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        let id = UserId::from_parts(tenant_id, username);
709        let mut users = self.users.write().map_err(lock_err)?;
710        if users.contains_key(&id) {
711            return Err(AuthError::UserExists(id.to_string()));
712        }
713
714        let now = now_ms();
715        let user = User {
716            username: username.to_string(),
717            tenant_id: tenant_id.map(|s| s.to_string()),
718            password_hash: hash_password(password),
719            scram_verifier: Some(make_scram_verifier(password)),
720            role,
721            api_keys: Vec::new(),
722            created_at: now,
723            updated_at: now,
724            enabled: true,
725        };
726        users.insert(id, user.clone());
727        drop(users); // release lock before vault I/O
728        self.persist_to_vault();
729        Ok(user)
730    }
731
732    /// Look up a user's SCRAM verifier by full `UserId`.
733    ///
734    /// The wire handshake passes the tenant resolved from the session
735    /// (or `None` for the bootstrap admin) so cross-tenant collisions
736    /// never authenticate the wrong identity.
737    pub fn lookup_scram_verifier(&self, id: &UserId) -> Option<crate::auth::scram::ScramVerifier> {
738        let users = self.users.read().ok()?;
739        users.get(id).and_then(|u| u.scram_verifier.clone())
740    }
741
742    /// Backwards-compatible shim for the v2 wire bootstrap path: looks
743    /// up a user by username assuming the platform (`tenant=None`)
744    /// scope. Use this only where the handshake hasn't yet learned the
745    /// caller's tenant.
746    pub fn lookup_scram_verifier_global(
747        &self,
748        username: &str,
749    ) -> Option<crate::auth::scram::ScramVerifier> {
750        self.lookup_scram_verifier(&UserId::platform(username))
751    }
752
753    /// Return all users (password hashes redacted).
754    pub fn list_users(&self) -> Vec<User> {
755        let users = match self.users.read() {
756            Ok(g) => g,
757            Err(_) => return Vec::new(),
758        };
759        users
760            .values()
761            .map(|u| User {
762                password_hash: String::new(), // redacted
763                ..u.clone()
764            })
765            .collect()
766    }
767
768    /// Return users restricted to a tenant scope.
769    ///
770    /// `tenant_filter`:
771    ///   - `None` listing in `Some(None)` — only platform users
772    ///   - `Some(Some("acme"))` — only users in tenant `acme`
773    ///   - `None` argument — all users (admin-only callers)
774    pub fn list_users_scoped(&self, tenant_filter: Option<Option<&str>>) -> Vec<User> {
775        let users = match self.users.read() {
776            Ok(g) => g,
777            Err(_) => return Vec::new(),
778        };
779        users
780            .values()
781            .filter(|u| match tenant_filter {
782                None => true,
783                Some(t) => u.tenant_id.as_deref() == t,
784            })
785            .map(|u| User {
786                password_hash: String::new(), // redacted
787                ..u.clone()
788            })
789            .collect()
790    }
791
792    /// Look up a single user by `(tenant, username)`. Password hash
793    /// is redacted.
794    pub fn get_user(&self, tenant_id: Option<&str>, username: &str) -> Option<User> {
795        let id = UserId::from_parts(tenant_id, username);
796        self.get_user_cloned(&id).map(|u| User {
797            password_hash: String::new(),
798            ..u
799        })
800    }
801
802    /// Delete a platform-scoped user (`tenant_id = None`) and revoke
803    /// all of their API keys + sessions.
804    ///
805    /// For tenant-scoped deletes, use [`Self::delete_user_in_tenant`].
806    pub fn delete_user(&self, username: &str) -> Result<(), AuthError> {
807        self.delete_user_in_tenant(None, username)
808    }
809
810    /// Delete a user identified by `(tenant_id, username)` and revoke
811    /// all of their API keys + sessions.
812    pub fn delete_user_in_tenant(
813        &self,
814        tenant_id: Option<&str>,
815        username: &str,
816    ) -> Result<(), AuthError> {
817        let id = UserId::from_parts(tenant_id, username);
818        let mut users = self.users.write().map_err(lock_err)?;
819        let user = users
820            .remove(&id)
821            .ok_or_else(|| AuthError::UserNotFound(id.to_string()))?;
822
823        // Remove API key index entries.
824        if let Ok(mut idx) = self.api_key_index.write() {
825            for api_key in &user.api_keys {
826                idx.remove(&api_key.key);
827            }
828        }
829
830        // Remove sessions belonging to this user (match on tenant+username
831        // so we don't tear down a same-named user in another tenant).
832        if let Ok(mut sessions) = self.sessions.write() {
833            sessions
834                .retain(|_, s| !(s.username == username && s.tenant_id.as_deref() == tenant_id));
835        }
836
837        self.persist_to_vault();
838        Ok(())
839    }
840
841    /// Change password (requires the old password). Defaults to
842    /// platform tenant; use [`Self::change_password_in_tenant`] for
843    /// scoped users.
844    pub fn change_password(
845        &self,
846        username: &str,
847        old_password: &str,
848        new_password: &str,
849    ) -> Result<(), AuthError> {
850        self.change_password_in_tenant(None, username, old_password, new_password)
851    }
852
853    pub fn change_password_in_tenant(
854        &self,
855        tenant_id: Option<&str>,
856        username: &str,
857        old_password: &str,
858        new_password: &str,
859    ) -> Result<(), AuthError> {
860        let id = UserId::from_parts(tenant_id, username);
861        let mut users = self.users.write().map_err(lock_err)?;
862        let user = users
863            .get_mut(&id)
864            .ok_or_else(|| AuthError::UserNotFound(id.to_string()))?;
865
866        if !verify_password(old_password, &user.password_hash) {
867            return Err(AuthError::InvalidCredentials);
868        }
869
870        user.password_hash = hash_password(new_password);
871        user.scram_verifier = Some(make_scram_verifier(new_password));
872        user.updated_at = now_ms();
873        drop(users); // release lock before vault I/O
874        self.persist_to_vault();
875        Ok(())
876    }
877
878    /// Change a user's role (admin-only operation). Defaults to platform
879    /// tenant; use [`Self::change_role_in_tenant`] for scoped users.
880    pub fn change_role(&self, username: &str, new_role: Role) -> Result<(), AuthError> {
881        self.change_role_in_tenant(None, username, new_role)
882    }
883
884    pub fn change_role_in_tenant(
885        &self,
886        tenant_id: Option<&str>,
887        username: &str,
888        new_role: Role,
889    ) -> Result<(), AuthError> {
890        let id = UserId::from_parts(tenant_id, username);
891        let mut users = self.users.write().map_err(lock_err)?;
892        let user = users
893            .get_mut(&id)
894            .ok_or_else(|| AuthError::UserNotFound(id.to_string()))?;
895
896        let prior_role = user.role;
897        user.role = new_role;
898        user.updated_at = now_ms();
899
900        // Issue #205 — promotion to Admin is an operator-grade event:
901        // the new role grants destructive capabilities (DROP, ALTER,
902        // GRANT) that an operator must observe out-of-band even when
903        // the auth path itself is healthy.
904        if new_role == Role::Admin && prior_role != Role::Admin {
905            crate::telemetry::operator_event::OperatorEvent::AdminCapabilityGranted {
906                granted_to: id.to_string(),
907                capability: "Role::Admin".to_string(),
908                granted_by: "auth_store::change_role".to_string(),
909            }
910            .emit_global();
911        }
912
913        // Downgrade any API keys that now exceed the user's role.
914        for key in &mut user.api_keys {
915            if key.role > new_role {
916                key.role = new_role;
917            }
918        }
919
920        // Update the api_key_index as well.
921        if let Ok(mut idx) = self.api_key_index.write() {
922            for key in &user.api_keys {
923                if let Some(entry) = idx.get_mut(&key.key) {
924                    entry.1 = key.role;
925                }
926            }
927        }
928
929        self.persist_to_vault();
930        Ok(())
931    }
932
933    // -----------------------------------------------------------------
934    // Authentication (login)
935    // -----------------------------------------------------------------
936
937    /// Verify credentials for a platform-tenant user (`tenant_id = None`)
938    /// and create a session. For tenant-scoped login use
939    /// [`Self::authenticate_in_tenant`].
940    ///
941    /// When a keypair is available (certificate-based seal), session tokens
942    /// are signed with the master secret so the server can verify they were
943    /// genuinely issued by this vault instance.
944    pub fn authenticate(&self, username: &str, password: &str) -> Result<Session, AuthError> {
945        self.authenticate_in_tenant(None, username, password)
946    }
947
948    /// Verify credentials for `(tenant_id, username, password)` and
949    /// create a session. Tenant-aware: `alice@acme` and `alice@globex`
950    /// authenticate independently.
951    pub fn authenticate_in_tenant(
952        &self,
953        tenant_id: Option<&str>,
954        username: &str,
955        password: &str,
956    ) -> Result<Session, AuthError> {
957        let id = UserId::from_parts(tenant_id, username);
958        let users = self.users.read().map_err(lock_err)?;
959        let user = users.get(&id).ok_or(AuthError::InvalidCredentials)?;
960
961        if !user.enabled {
962            return Err(AuthError::InvalidCredentials);
963        }
964
965        if !verify_password(password, &user.password_hash) {
966            return Err(AuthError::InvalidCredentials);
967        }
968
969        // Generate token: signed if keypair is available, random otherwise.
970        let token = match self.keypair.read().ok().and_then(|g| {
971            g.as_ref().map(|kp| {
972                let token_id = random_hex(16);
973                let sig = kp.sign(format!("session:{}", token_id).as_bytes());
974                // Take first 16 bytes of signature for compact token.
975                format!("rs_{}{}", token_id, hex::encode(&sig[..16]))
976            })
977        }) {
978            Some(signed_token) => signed_token,
979            None => generate_session_token(),
980        };
981
982        let now = now_ms();
983        let session = Session {
984            token,
985            username: username.to_string(),
986            tenant_id: user.tenant_id.clone(),
987            role: user.role,
988            created_at: now,
989            expires_at: now + (self.config.session_ttl_secs as u128 * 1000),
990        };
991
992        drop(users); // release read lock before acquiring write
993
994        let mut sessions = self.sessions.write().map_err(lock_err)?;
995        sessions.insert(session.token.clone(), session.clone());
996        Ok(session)
997    }
998
999    // -----------------------------------------------------------------
1000    // Token validation
1001    // -----------------------------------------------------------------
1002
1003    /// Validate a token (session or API key).
1004    ///
1005    /// Returns `(username, role)` if valid, `None` otherwise. Tenant
1006    /// scope is dropped here for compatibility with the bulk of the
1007    /// existing caller surface (routing, gRPC control, redwire). Use
1008    /// [`Self::validate_token_full`] when the caller needs the
1009    /// resolved `UserId` (e.g. to pin `CURRENT_TENANT()`).
1010    pub fn validate_token(&self, token: &str) -> Option<(String, Role)> {
1011        self.validate_token_full(token)
1012            .map(|(id, role)| (id.username, role))
1013    }
1014
1015    /// Tenant-aware token validation. Returns the resolved `UserId`
1016    /// (which carries the tenant) and the granted `Role`.
1017    pub fn validate_token_full(&self, token: &str) -> Option<(UserId, Role)> {
1018        // Try session tokens first.
1019        if token.starts_with("rs_") {
1020            if let Ok(sessions) = self.sessions.read() {
1021                if let Some(session) = sessions.get(token) {
1022                    let now = now_ms();
1023                    if now < session.expires_at {
1024                        return Some((
1025                            UserId::from_parts(session.tenant_id.as_deref(), &session.username),
1026                            session.role,
1027                        ));
1028                    }
1029                }
1030            }
1031            return None;
1032        }
1033
1034        // Try API keys.
1035        if token.starts_with("rk_") {
1036            if let Ok(idx) = self.api_key_index.read() {
1037                return idx.get(token).cloned();
1038            }
1039            return None;
1040        }
1041
1042        None
1043    }
1044
1045    // -----------------------------------------------------------------
1046    // API Key management
1047    // -----------------------------------------------------------------
1048
1049    /// Create a persistent API key for a platform-tenant user.
1050    ///
1051    /// For tenant-scoped users use [`Self::create_api_key_in_tenant`].
1052    pub fn create_api_key(
1053        &self,
1054        username: &str,
1055        name: &str,
1056        role: Role,
1057    ) -> Result<ApiKey, AuthError> {
1058        self.create_api_key_in_tenant(None, username, name, role)
1059    }
1060
1061    pub fn create_api_key_in_tenant(
1062        &self,
1063        tenant_id: Option<&str>,
1064        username: &str,
1065        name: &str,
1066        role: Role,
1067    ) -> Result<ApiKey, AuthError> {
1068        let id = UserId::from_parts(tenant_id, username);
1069        let mut users = self.users.write().map_err(lock_err)?;
1070        let user = users
1071            .get_mut(&id)
1072            .ok_or_else(|| AuthError::UserNotFound(id.to_string()))?;
1073
1074        // The key's role cannot exceed the user's role.
1075        if role > user.role {
1076            return Err(AuthError::RoleExceeded {
1077                requested: role,
1078                ceiling: user.role,
1079            });
1080        }
1081
1082        let api_key = ApiKey {
1083            key: generate_api_key(),
1084            name: name.to_string(),
1085            role,
1086            created_at: now_ms(),
1087        };
1088
1089        user.api_keys.push(api_key.clone());
1090        user.updated_at = now_ms();
1091
1092        // Update the index.
1093        if let Ok(mut idx) = self.api_key_index.write() {
1094            idx.insert(api_key.key.clone(), (id.clone(), api_key.role));
1095        }
1096
1097        drop(users); // release lock before vault I/O
1098        self.persist_to_vault();
1099        Ok(api_key)
1100    }
1101
1102    /// Revoke (delete) an API key.
1103    pub fn revoke_api_key(&self, key: &str) -> Result<(), AuthError> {
1104        let mut users = self.users.write().map_err(lock_err)?;
1105
1106        // Find which user owns this key (look up by the api_key_index
1107        // first; fall back to a scan for legacy state restored before
1108        // the index was reseeded).
1109        let owner_id: UserId = {
1110            if let Ok(idx) = self.api_key_index.read() {
1111                if let Some((id, _)) = idx.get(key) {
1112                    id.clone()
1113                } else {
1114                    return Err(AuthError::KeyNotFound(key.to_string()));
1115                }
1116            } else {
1117                let owner = users
1118                    .iter()
1119                    .find(|(_, u)| u.api_keys.iter().any(|k| k.key == key));
1120                match owner {
1121                    Some((id, _)) => id.clone(),
1122                    None => return Err(AuthError::KeyNotFound(key.to_string())),
1123                }
1124            }
1125        };
1126
1127        let user = users
1128            .get_mut(&owner_id)
1129            .ok_or_else(|| AuthError::KeyNotFound(key.to_string()))?;
1130        user.api_keys.retain(|k| k.key != key);
1131        user.updated_at = now_ms();
1132
1133        // Remove from index.
1134        if let Ok(mut idx) = self.api_key_index.write() {
1135            idx.remove(key);
1136        }
1137
1138        self.persist_to_vault();
1139        Ok(())
1140    }
1141
1142    // -----------------------------------------------------------------
1143    // Session management
1144    // -----------------------------------------------------------------
1145
1146    /// Revoke a session token.
1147    pub fn revoke_session(&self, token: &str) {
1148        if let Ok(mut sessions) = self.sessions.write() {
1149            sessions.remove(token);
1150        }
1151    }
1152
1153    /// Purge expired sessions (housekeeping).
1154    pub fn purge_expired_sessions(&self) -> usize {
1155        let now = now_ms();
1156        if let Ok(mut sessions) = self.sessions.write() {
1157            let before = sessions.len();
1158            sessions.retain(|_, s| s.expires_at > now);
1159            return before - sessions.len();
1160        }
1161        0
1162    }
1163
1164    // -----------------------------------------------------------------
1165    // Granular RBAC — GRANT / REVOKE
1166    //
1167    // The privilege engine lives in `super::privileges`. These helpers
1168    // are the AuthStore facade: they keep an in-memory map of grants per
1169    // user (plus a `public_grants` list), persist additions/removals to
1170    // the existing `vault_kv` store, and rebuild the per-user
1171    // `PermissionCache` so the hot path stays O(1).
1172    //
1173    // Persistence design: rather than extend the snapshot/restore
1174    // pipeline (Agent #2's territory) we serialise grants and account
1175    // attributes to the vault KV store. That gives us atomic write +
1176    // encrypted-at-rest semantics for free without touching the
1177    // existing USER/KEY/KV serializer paths. On restart `rehydrate_acl`
1178    // reads these KV entries back into the in-memory maps.
1179    // -----------------------------------------------------------------
1180
1181    /// Persist a grant. Returns `Forbidden` when the granting user is
1182    /// not Admin or attempts a cross-tenant grant.
1183    pub fn grant(
1184        &self,
1185        granter: &UserId,
1186        granter_role: Role,
1187        principal: GrantPrincipal,
1188        resource: Resource,
1189        actions: Vec<Action>,
1190        with_grant_option: bool,
1191        tenant: Option<String>,
1192    ) -> Result<(), AuthError> {
1193        if granter_role != Role::Admin {
1194            return Err(AuthError::Forbidden(format!(
1195                "GRANT requires Admin role; granter `{}` has `{:?}`",
1196                granter, granter_role
1197            )));
1198        }
1199
1200        // Cross-tenant guard: a tenant-scoped admin cannot mint grants
1201        // outside their tenant. Platform admin (tenant=None) may grant
1202        // anywhere.
1203        if granter.tenant.is_some() && granter.tenant != tenant {
1204            return Err(AuthError::Forbidden(format!(
1205                "cross-tenant GRANT denied: granter tenant `{:?}` != grant tenant `{:?}`",
1206                granter.tenant, tenant
1207            )));
1208        }
1209
1210        let mut actions_set = std::collections::BTreeSet::new();
1211        for a in actions {
1212            actions_set.insert(a);
1213        }
1214        let g = Grant {
1215            principal: principal.clone(),
1216            resource,
1217            actions: actions_set,
1218            with_grant_option,
1219            granted_by: granter.to_string(),
1220            granted_at: now_ms(),
1221            tenant,
1222            columns: None,
1223        };
1224
1225        match &principal {
1226            GrantPrincipal::User(uid) => {
1227                self.grants
1228                    .write()
1229                    .unwrap_or_else(|e| e.into_inner())
1230                    .entry(uid.clone())
1231                    .or_default()
1232                    .push(g.clone());
1233                self.invalidate_permission_cache(Some(uid));
1234            }
1235            GrantPrincipal::Public => {
1236                self.public_grants
1237                    .write()
1238                    .unwrap_or_else(|e| e.into_inner())
1239                    .push(g.clone());
1240                self.invalidate_permission_cache(None);
1241            }
1242            GrantPrincipal::Group(_) => {
1243                return Err(AuthError::Forbidden(
1244                    "GROUP principals are not yet supported; use a USER or PUBLIC".to_string(),
1245                ));
1246            }
1247        }
1248
1249        // Issue #119: a fresh grant changes the visible-collections set
1250        // for `(tenant, role)` callers under the same tenant. Drop those
1251        // cache entries so the next AI command sees the new SELECT
1252        // privilege immediately.
1253        self.invalidate_visible_collections_for_tenant(g.tenant.as_deref());
1254
1255        self.persist_acl_to_kv();
1256        Ok(())
1257    }
1258
1259    /// Drop matching grants from a principal. Returns the number of
1260    /// grants removed.
1261    pub fn revoke(
1262        &self,
1263        granter_role: Role,
1264        principal: &GrantPrincipal,
1265        resource: &Resource,
1266        actions: &[Action],
1267    ) -> Result<usize, AuthError> {
1268        if granter_role != Role::Admin {
1269            return Err(AuthError::Forbidden(format!(
1270                "REVOKE requires Admin role; granter has `{:?}`",
1271                granter_role
1272            )));
1273        }
1274
1275        let removed = match principal {
1276            GrantPrincipal::User(uid) => {
1277                let mut g = self.grants.write().unwrap_or_else(|e| e.into_inner());
1278                let before = g.get(uid).map(|v| v.len()).unwrap_or(0);
1279                if let Some(list) = g.get_mut(uid) {
1280                    list.retain(|gr| {
1281                        !(gr.resource == *resource
1282                            && (actions.iter().any(|a| gr.actions.contains(a))
1283                                || (gr.actions.contains(&Action::All) && !actions.is_empty())))
1284                    });
1285                }
1286                let after = g.get(uid).map(|v| v.len()).unwrap_or(0);
1287                drop(g);
1288                self.invalidate_permission_cache(Some(uid));
1289                before - after
1290            }
1291            GrantPrincipal::Public => {
1292                let mut p = self
1293                    .public_grants
1294                    .write()
1295                    .unwrap_or_else(|e| e.into_inner());
1296                let before = p.len();
1297                p.retain(|gr| {
1298                    !(gr.resource == *resource
1299                        && (actions.iter().any(|a| gr.actions.contains(a))
1300                            || (gr.actions.contains(&Action::All) && !actions.is_empty())))
1301                });
1302                let after = p.len();
1303                drop(p);
1304                self.invalidate_permission_cache(None);
1305                before - after
1306            }
1307            GrantPrincipal::Group(_) => 0,
1308        };
1309
1310        if removed > 0 {
1311            // Issue #119: REVOKE may shrink the visible-collections set
1312            // for any `(tenant, role)` slot. We don't know the exact
1313            // tenant when the principal is `Public`, so a `Public`
1314            // revoke clears the whole cache; user revokes scope to the
1315            // user's tenant.
1316            match principal {
1317                GrantPrincipal::User(uid) => {
1318                    self.invalidate_visible_collections_for_tenant(uid.tenant.as_deref());
1319                }
1320                GrantPrincipal::Public | GrantPrincipal::Group(_) => {
1321                    self.invalidate_visible_collections_cache();
1322                }
1323            }
1324            self.persist_acl_to_kv();
1325        }
1326        Ok(removed)
1327    }
1328
1329    /// Compute the set of collection ids a given `(tenant, role)`
1330    /// scope can read, consulting the explicit grant table. The result
1331    /// is cached for `super::scope_cache::DEFAULT_TTL` (60s) and
1332    /// invalidated on every GRANT/REVOKE/policy/collection mutation
1333    /// that could change the answer.
1334    ///
1335    /// `all_collections` is the full list of collection ids known to
1336    /// the storage layer. The runtime hands it in so this module stays
1337    /// decoupled from the storage crate. Each collection passes through
1338    /// `check_grant(SELECT)` under a synthetic `(principal, role,
1339    /// tenant)` view.
1340    ///
1341    /// Why `(tenant, role)` and not `UserId`: the AI pipeline gates
1342    /// rows by RLS and grant scope, both of which key off the role +
1343    /// tenant pair, not the bare username. Two users that share a
1344    /// tenant + role share a cache slot, dropping the steady-state
1345    /// memory cost.
1346    pub fn visible_collections_for_scope(
1347        &self,
1348        tenant: Option<&str>,
1349        role: Role,
1350        principal: &str,
1351        all_collections: &[String],
1352    ) -> std::collections::HashSet<String> {
1353        let key = super::scope_cache::ScopeKey::new(tenant, role);
1354        if let Some(hit) = self.visible_collections_cache.get(&key) {
1355            return hit;
1356        }
1357        // Slow path: walk every collection through `check_grant`. We
1358        // build the AuthzContext once, then reuse it per resource.
1359        let ctx = AuthzContext {
1360            principal,
1361            effective_role: role,
1362            tenant,
1363        };
1364        let mut visible = std::collections::HashSet::new();
1365        for collection in all_collections {
1366            let resource = Resource::table_from_name(collection);
1367            if self.check_grant(&ctx, Action::Select, &resource).is_ok() {
1368                visible.insert(collection.clone());
1369            }
1370        }
1371        self.visible_collections_cache.insert(key, visible.clone());
1372        visible
1373    }
1374
1375    /// Stats probe required by issue #119 — exposes hit/miss counts and
1376    /// invalidations for the visible-collections cache so metrics
1377    /// pipelines can compute a hit rate.
1378    pub fn auth_cache_stats(&self) -> super::scope_cache::AuthCacheStats {
1379        self.visible_collections_cache.stats()
1380    }
1381
1382    /// Drop every cached `(tenant, role)` entry. Called from CREATE
1383    /// POLICY / DROP POLICY / DROP COLLECTION paths where the affected
1384    /// tenant set is unknown.
1385    pub fn invalidate_visible_collections_cache(&self) {
1386        self.visible_collections_cache.invalidate_all();
1387    }
1388
1389    /// Drop cached entries for one tenant. Called from GRANT / REVOKE
1390    /// where the principal's tenant is known.
1391    pub fn invalidate_visible_collections_for_tenant(&self, tenant: Option<&str>) {
1392        self.visible_collections_cache.invalidate_tenant(tenant);
1393    }
1394
1395    /// Snapshot of every grant the principal effectively has, including
1396    /// `Public` grants. Audit / introspection helper.
1397    pub fn effective_grants(&self, uid: &UserId) -> Vec<Grant> {
1398        let mut out = Vec::new();
1399        if let Ok(g) = self.grants.read() {
1400            if let Some(list) = g.get(uid) {
1401                out.extend(list.iter().cloned());
1402            }
1403        }
1404        if let Ok(p) = self.public_grants.read() {
1405            out.extend(p.iter().cloned());
1406        }
1407        out
1408    }
1409
1410    /// Run a privilege check using the in-memory grant tables. Returns
1411    /// `Ok(())` on allow, `Err(AuthzError)` on deny.
1412    pub fn check_grant(
1413        &self,
1414        ctx: &AuthzContext<'_>,
1415        action: Action,
1416        resource: &Resource,
1417    ) -> Result<(), AuthzError> {
1418        if ctx.effective_role == Role::Admin {
1419            return Ok(());
1420        }
1421
1422        let uid = UserId::from_parts(ctx.tenant, ctx.principal);
1423
1424        // Fast path: per-user pre-resolved cache.
1425        if let Ok(cache) = self.permission_cache.read() {
1426            if let Some(pc) = cache.get(&uid) {
1427                if pc.allows(resource, action) {
1428                    return Ok(());
1429                }
1430            }
1431        }
1432
1433        // Slow path: linear scan + rebuild cache as a side-effect.
1434        let user_grants = self
1435            .grants
1436            .read()
1437            .ok()
1438            .and_then(|g| g.get(&uid).cloned())
1439            .unwrap_or_default();
1440        let any_user_grants = self
1441            .grants
1442            .read()
1443            .ok()
1444            .map(|g| g.values().any(|list| !list.is_empty()))
1445            .unwrap_or(false);
1446        let public_grants = self
1447            .public_grants
1448            .read()
1449            .ok()
1450            .map(|p| p.clone())
1451            .unwrap_or_default();
1452        if user_grants.is_empty() && public_grants.is_empty() && any_user_grants {
1453            return Err(AuthzError::PermissionDenied {
1454                action,
1455                resource: resource.clone(),
1456                principal: ctx.principal.to_string(),
1457            });
1458        }
1459        let view = GrantsView {
1460            user_grants: &user_grants,
1461            public_grants: &public_grants,
1462        };
1463        let result = check_grant(ctx, action, resource, &view);
1464
1465        if result.is_ok() {
1466            let pc = PermissionCache::build(&user_grants, &public_grants);
1467            if let Ok(mut cache) = self.permission_cache.write() {
1468                cache.insert(uid, pc);
1469            }
1470        }
1471        result
1472    }
1473
1474    // -----------------------------------------------------------------
1475    // ALTER USER attributes (VALID UNTIL, CONNECTION LIMIT, etc.)
1476    // -----------------------------------------------------------------
1477
1478    /// Replace the attribute record for `uid`.
1479    pub fn set_user_attributes(
1480        &self,
1481        uid: &UserId,
1482        attrs: UserAttributes,
1483    ) -> Result<(), AuthError> {
1484        let users = self.users.read().map_err(lock_err)?;
1485        if !users.contains_key(uid) {
1486            return Err(AuthError::UserNotFound(uid.to_string()));
1487        }
1488        drop(users);
1489
1490        self.user_attributes
1491            .write()
1492            .unwrap_or_else(|e| e.into_inner())
1493            .insert(uid.clone(), attrs);
1494        self.invalidate_iam_cache(Some(uid));
1495        self.persist_acl_to_kv();
1496        Ok(())
1497    }
1498
1499    /// Read the attributes for `uid`. Returns `Default::default()` for
1500    /// users that have never been altered.
1501    pub fn user_attributes(&self, uid: &UserId) -> UserAttributes {
1502        self.user_attributes
1503            .read()
1504            .ok()
1505            .and_then(|m| m.get(uid).cloned())
1506            .unwrap_or_default()
1507    }
1508
1509    pub fn add_user_to_group(&self, uid: &UserId, group: &str) -> Result<(), AuthError> {
1510        if group.trim().is_empty() {
1511            return Err(AuthError::Forbidden("group name cannot be empty".into()));
1512        }
1513        let mut attrs = self.user_attributes(uid);
1514        if !attrs.groups.iter().any(|g| g == group) {
1515            attrs.groups.push(group.to_string());
1516            attrs.groups.sort();
1517        }
1518        self.set_user_attributes(uid, attrs)
1519    }
1520
1521    pub fn remove_user_from_group(&self, uid: &UserId, group: &str) -> Result<(), AuthError> {
1522        let mut attrs = self.user_attributes(uid);
1523        attrs.groups.retain(|g| g != group);
1524        self.set_user_attributes(uid, attrs)
1525    }
1526
1527    /// Toggle `User.enabled` without rotating credentials.
1528    pub fn set_user_enabled(&self, uid: &UserId, enabled: bool) -> Result<(), AuthError> {
1529        let mut users = self.users.write().map_err(lock_err)?;
1530        let user = users
1531            .get_mut(uid)
1532            .ok_or_else(|| AuthError::UserNotFound(uid.to_string()))?;
1533        user.enabled = enabled;
1534        user.updated_at = now_ms();
1535        drop(users);
1536        self.persist_to_vault();
1537        Ok(())
1538    }
1539
1540    // -----------------------------------------------------------------
1541    // Login-side enforcement (HTTP path)
1542    // -----------------------------------------------------------------
1543
1544    /// Authenticate with VALID UNTIL / CONNECTION LIMIT enforcement.
1545    /// Wraps `authenticate_in_tenant` and additionally:
1546    ///   * rejects logins after `valid_until`,
1547    ///   * rejects logins when the live session count would exceed the
1548    ///     `connection_limit` attribute.
1549    pub fn authenticate_with_attrs(
1550        &self,
1551        tenant_id: Option<&str>,
1552        username: &str,
1553        password: &str,
1554    ) -> Result<Session, AuthError> {
1555        let uid = UserId::from_parts(tenant_id, username);
1556        let attrs = self.user_attributes(&uid);
1557
1558        if let Some(deadline) = attrs.valid_until {
1559            if now_ms() >= deadline {
1560                return Err(AuthError::Forbidden(format!(
1561                    "account `{}` expired (VALID UNTIL exceeded)",
1562                    uid
1563                )));
1564            }
1565        }
1566
1567        if let Some(limit) = attrs.connection_limit {
1568            let current = self
1569                .session_count_by_user
1570                .read()
1571                .ok()
1572                .and_then(|m| m.get(&uid).copied())
1573                .unwrap_or(0);
1574            if current >= limit {
1575                return Err(AuthError::Forbidden(format!(
1576                    "account `{}` exceeded CONNECTION LIMIT ({})",
1577                    uid, limit
1578                )));
1579            }
1580        }
1581
1582        let session = self.authenticate_in_tenant(tenant_id, username, password)?;
1583
1584        if let Ok(mut counts) = self.session_count_by_user.write() {
1585            *counts.entry(uid).or_insert(0) += 1;
1586        }
1587        Ok(session)
1588    }
1589
1590    /// Decrement the live-session count for `uid`. Call from session
1591    /// revoke / expiry paths so CONNECTION LIMIT stays accurate.
1592    pub fn decrement_session_count(&self, uid: &UserId) {
1593        if let Ok(mut counts) = self.session_count_by_user.write() {
1594            if let Some(c) = counts.get_mut(uid) {
1595                *c = c.saturating_sub(1);
1596            }
1597        }
1598    }
1599
1600    // -----------------------------------------------------------------
1601    // ACL persistence — vault_kv backed
1602    // -----------------------------------------------------------------
1603
1604    /// Re-read the ACL state from `vault_kv`. Call after vault load /
1605    /// restore so the in-memory maps reflect the persisted data.
1606    pub fn rehydrate_acl(&self) {
1607        let kv_snapshot: Vec<(String, String)> = self
1608            .vault_kv
1609            .read()
1610            .map(|kv| {
1611                kv.iter()
1612                    .filter(|(k, _)| {
1613                        k.starts_with("red.acl.grants.")
1614                            || k.starts_with("red.acl.attrs.")
1615                            || k == &"red.acl.public_grants"
1616                    })
1617                    .map(|(k, v)| (k.clone(), v.clone()))
1618                    .collect()
1619            })
1620            .unwrap_or_default();
1621
1622        for (k, v) in kv_snapshot {
1623            if k == "red.acl.public_grants" {
1624                if let Some(parsed) = decode_grants_blob(&v) {
1625                    *self
1626                        .public_grants
1627                        .write()
1628                        .unwrap_or_else(|e| e.into_inner()) = parsed;
1629                }
1630            } else if let Some(suffix) = k.strip_prefix("red.acl.grants.") {
1631                if let Some(uid) = decode_uid(suffix) {
1632                    if let Some(mut parsed) = decode_grants_blob(&v) {
1633                        // Restore the principal field — the on-disk
1634                        // line stores only resource+action shape.
1635                        for g in parsed.iter_mut() {
1636                            g.principal = GrantPrincipal::User(uid.clone());
1637                        }
1638                        self.grants
1639                            .write()
1640                            .unwrap_or_else(|e| e.into_inner())
1641                            .insert(uid, parsed);
1642                    }
1643                }
1644            } else if let Some(suffix) = k.strip_prefix("red.acl.attrs.") {
1645                if let Some(uid) = decode_uid(suffix) {
1646                    if let Some(parsed) = decode_attrs_blob(&v) {
1647                        self.user_attributes
1648                            .write()
1649                            .unwrap_or_else(|e| e.into_inner())
1650                            .insert(uid, parsed);
1651                    }
1652                }
1653            }
1654        }
1655
1656        self.permission_cache
1657            .write()
1658            .unwrap_or_else(|e| e.into_inner())
1659            .clear();
1660    }
1661
1662    /// Snapshot every ACL change back into the vault KV store.
1663    fn persist_acl_to_kv(&self) {
1664        let public = self
1665            .public_grants
1666            .read()
1667            .ok()
1668            .map(|p| encode_grants_blob(&p))
1669            .unwrap_or_default();
1670        self.vault_kv_set("red.acl.public_grants".to_string(), public);
1671
1672        let snapshot: Vec<(UserId, Vec<Grant>)> = self
1673            .grants
1674            .read()
1675            .ok()
1676            .map(|g| g.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
1677            .unwrap_or_default();
1678        for (uid, list) in snapshot {
1679            let key = format!("red.acl.grants.{}", encode_uid(&uid));
1680            let val = encode_grants_blob(&list);
1681            self.vault_kv_set(key, val);
1682        }
1683
1684        let attrs_snapshot: Vec<(UserId, UserAttributes)> = self
1685            .user_attributes
1686            .read()
1687            .ok()
1688            .map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
1689            .unwrap_or_default();
1690        for (uid, attrs) in attrs_snapshot {
1691            let key = format!("red.acl.attrs.{}", encode_uid(&uid));
1692            let val = encode_attrs_blob(&attrs);
1693            self.vault_kv_set(key, val);
1694        }
1695    }
1696
1697    fn invalidate_permission_cache(&self, uid: Option<&UserId>) {
1698        if let Ok(mut cache) = self.permission_cache.write() {
1699            match uid {
1700                Some(u) => {
1701                    cache.remove(u);
1702                }
1703                None => cache.clear(),
1704            }
1705        }
1706    }
1707
1708    // -----------------------------------------------------------------
1709    // IAM policies — put / delete / attach / detach / simulate
1710    //
1711    // The kernel in `super::policies` owns the Policy type and the
1712    // evaluator. AuthStore handles persistence + per-user cache + the
1713    // GRANT translation layer (synthetic `_grant_*` policies).
1714    // -----------------------------------------------------------------
1715
1716    /// Insert or replace a policy by id. Rejects synthetic ids
1717    /// (`_grant_*` / `_default_*`) so callers can't hand-write them
1718    /// from the public API. Use `put_policy_internal` for synthetic
1719    /// inserts.
1720    pub fn put_policy(&self, p: Policy) -> Result<(), AuthError> {
1721        if p.id.starts_with("_grant_") || p.id.starts_with("_default_") {
1722            return Err(AuthError::Forbidden(format!(
1723                "policy id `{}` is reserved",
1724                p.id
1725            )));
1726        }
1727        self.put_policy_internal(p)
1728    }
1729
1730    /// Internal put bypassing the synthetic-namespace guard. Used by
1731    /// the GRANT translation layer; exposed publicly so integration
1732    /// tests can register synthetic `_grant_*` policies without going
1733    /// through the SQL frontend.
1734    pub fn put_policy_internal(&self, p: Policy) -> Result<(), AuthError> {
1735        p.validate()
1736            .map_err(|e| AuthError::Forbidden(format!("invalid policy `{}`: {e}", p.id)))?;
1737        let id = p.id.clone();
1738        self.policies
1739            .write()
1740            .unwrap_or_else(|e| e.into_inner())
1741            .insert(id, Arc::new(p));
1742        self.iam_authorization_enabled
1743            .store(true, Ordering::Release);
1744        self.iam_effective_cache
1745            .write()
1746            .unwrap_or_else(|e| e.into_inner())
1747            .clear();
1748        // Issue #119: a policy mutation can change the visible-
1749        // collections answer for any (tenant, role); we don't know
1750        // which up-front, so blow the whole cache.
1751        self.invalidate_visible_collections_cache();
1752        self.persist_iam_to_kv();
1753        Ok(())
1754    }
1755
1756    /// Whether the IAM evaluator should be authoritative for runtime
1757    /// authorization. This flips on the first policy write and remains
1758    /// on after deletes so dropping all policies leaves the instance in
1759    /// default-deny rather than silently returning to role fallback.
1760    pub fn iam_authorization_enabled(&self) -> bool {
1761        self.iam_authorization_enabled.load(Ordering::Acquire)
1762    }
1763
1764    /// Remove a policy and any attachments referencing it.
1765    pub fn delete_policy(&self, id: &str) -> Result<(), AuthError> {
1766        let removed = self
1767            .policies
1768            .write()
1769            .unwrap_or_else(|e| e.into_inner())
1770            .remove(id)
1771            .is_some();
1772        if !removed {
1773            return Err(AuthError::Forbidden(format!("policy `{id}` not found")));
1774        }
1775        // Detach from every user / group.
1776        if let Ok(mut ua) = self.user_attachments.write() {
1777            for ids in ua.values_mut() {
1778                ids.retain(|p| p != id);
1779            }
1780            ua.retain(|_, v| !v.is_empty());
1781        }
1782        if let Ok(mut ga) = self.group_attachments.write() {
1783            for ids in ga.values_mut() {
1784                ids.retain(|p| p != id);
1785            }
1786            ga.retain(|_, v| !v.is_empty());
1787        }
1788        self.iam_effective_cache
1789            .write()
1790            .unwrap_or_else(|e| e.into_inner())
1791            .clear();
1792        // Issue #119: dropping a policy can shrink any caller's visible
1793        // set; clear the (tenant, role) cache so AI commands re-resolve.
1794        self.invalidate_visible_collections_cache();
1795        self.persist_iam_to_kv();
1796        Ok(())
1797    }
1798
1799    /// List all policies (id-sorted for deterministic output).
1800    pub fn list_policies(&self) -> Vec<Arc<Policy>> {
1801        let map = match self.policies.read() {
1802            Ok(g) => g,
1803            Err(_) => return Vec::new(),
1804        };
1805        let mut out: Vec<Arc<Policy>> = map.values().cloned().collect();
1806        out.sort_by(|a, b| a.id.cmp(&b.id));
1807        out
1808    }
1809
1810    /// Fetch a single policy by id.
1811    pub fn get_policy(&self, id: &str) -> Option<Arc<Policy>> {
1812        self.policies.read().ok().and_then(|m| m.get(id).cloned())
1813    }
1814
1815    /// List policies directly attached to a group.
1816    pub fn group_policies(&self, group: &str) -> Vec<Arc<Policy>> {
1817        let policies = self.policies.read();
1818        let attachments = self.group_attachments.read();
1819        let mut out = Vec::new();
1820        if let (Ok(p_map), Ok(ga_map)) = (policies, attachments) {
1821            if let Some(ids) = ga_map.get(group) {
1822                for id in ids {
1823                    if let Some(p) = p_map.get(id) {
1824                        out.push(p.clone());
1825                    }
1826                }
1827            }
1828        }
1829        out.sort_by(|a, b| a.id.cmp(&b.id));
1830        out
1831    }
1832
1833    /// Delete synthetic policies produced by SQL GRANT translation.
1834    /// REVOKE uses this to keep the IAM lane and the legacy grant table
1835    /// in lock-step.
1836    pub fn delete_synthetic_grant_policies(
1837        &self,
1838        principal: &GrantPrincipal,
1839        resource: &Resource,
1840        actions: &[Action],
1841    ) -> usize {
1842        let attached = match principal {
1843            GrantPrincipal::User(uid) => self
1844                .user_attachments
1845                .read()
1846                .ok()
1847                .and_then(|m| m.get(uid).cloned())
1848                .unwrap_or_default(),
1849            GrantPrincipal::Group(group) => self
1850                .group_attachments
1851                .read()
1852                .ok()
1853                .and_then(|m| m.get(group).cloned())
1854                .unwrap_or_default(),
1855            GrantPrincipal::Public => self
1856                .group_attachments
1857                .read()
1858                .ok()
1859                .and_then(|m| m.get(PUBLIC_IAM_GROUP).cloned())
1860                .unwrap_or_default(),
1861        };
1862        if attached.is_empty() {
1863            return 0;
1864        }
1865
1866        let mut delete_ids = Vec::new();
1867        if let Ok(policies) = self.policies.read() {
1868            for id in attached {
1869                let Some(policy) = policies.get(&id) else {
1870                    continue;
1871                };
1872                if !policy.id.starts_with("_grant_") {
1873                    continue;
1874                }
1875                if synthetic_grant_matches(policy, resource, actions) {
1876                    delete_ids.push(policy.id.clone());
1877                }
1878            }
1879        }
1880
1881        let mut deleted = 0usize;
1882        for id in delete_ids {
1883            if self.delete_policy(&id).is_ok() {
1884                deleted += 1;
1885            }
1886        }
1887        deleted
1888    }
1889
1890    /// Attach a policy to a user or group. Returns an error if the
1891    /// policy id doesn't exist.
1892    pub fn attach_policy(&self, principal: PrincipalRef, policy_id: &str) -> Result<(), AuthError> {
1893        if !self
1894            .policies
1895            .read()
1896            .map(|m| m.contains_key(policy_id))
1897            .unwrap_or(false)
1898        {
1899            return Err(AuthError::Forbidden(format!(
1900                "policy `{policy_id}` not found"
1901            )));
1902        }
1903        match &principal {
1904            PrincipalRef::User(uid) => {
1905                let mut ua = self
1906                    .user_attachments
1907                    .write()
1908                    .unwrap_or_else(|e| e.into_inner());
1909                let list = ua.entry(uid.clone()).or_default();
1910                if !list.iter().any(|p| p == policy_id) {
1911                    list.push(policy_id.to_string());
1912                }
1913                drop(ua);
1914                self.invalidate_iam_cache(Some(uid));
1915            }
1916            PrincipalRef::Group(g) => {
1917                let mut ga = self
1918                    .group_attachments
1919                    .write()
1920                    .unwrap_or_else(|e| e.into_inner());
1921                let list = ga.entry(g.clone()).or_default();
1922                if !list.iter().any(|p| p == policy_id) {
1923                    list.push(policy_id.to_string());
1924                }
1925                drop(ga);
1926                self.invalidate_iam_cache(None);
1927            }
1928        }
1929        self.persist_iam_to_kv();
1930        Ok(())
1931    }
1932
1933    /// Remove a policy attachment from a user or group.
1934    pub fn detach_policy(&self, principal: PrincipalRef, policy_id: &str) -> Result<(), AuthError> {
1935        match &principal {
1936            PrincipalRef::User(uid) => {
1937                if let Ok(mut ua) = self.user_attachments.write() {
1938                    if let Some(list) = ua.get_mut(uid) {
1939                        list.retain(|p| p != policy_id);
1940                        if list.is_empty() {
1941                            ua.remove(uid);
1942                        }
1943                    }
1944                }
1945                self.invalidate_iam_cache(Some(uid));
1946            }
1947            PrincipalRef::Group(g) => {
1948                if let Ok(mut ga) = self.group_attachments.write() {
1949                    if let Some(list) = ga.get_mut(g) {
1950                        list.retain(|p| p != policy_id);
1951                        if list.is_empty() {
1952                            ga.remove(g);
1953                        }
1954                    }
1955                }
1956                self.invalidate_iam_cache(None);
1957            }
1958        }
1959        self.persist_iam_to_kv();
1960        Ok(())
1961    }
1962
1963    /// Resolve the ordered list of effective policies for a user:
1964    /// group attachments first (least specific), then user
1965    /// attachments (most specific). Cached per user.
1966    pub fn effective_policies(&self, user: &UserId) -> Vec<Arc<Policy>> {
1967        if let Ok(cache) = self.iam_effective_cache.read() {
1968            if let Some(hit) = cache.get(user) {
1969                return hit.clone();
1970            }
1971        }
1972        let policies = self.policies.read();
1973        let user_attachments = self.user_attachments.read();
1974        let group_attachments = self.group_attachments.read();
1975        let mut groups = self
1976            .user_attributes
1977            .read()
1978            .ok()
1979            .and_then(|m| m.get(user).map(|attrs| attrs.groups.clone()))
1980            .unwrap_or_default();
1981        groups.insert(0, PUBLIC_IAM_GROUP.to_string());
1982        let mut out: Vec<Arc<Policy>> = Vec::new();
1983        if let (Ok(p_map), Ok(ua_map), Ok(ga_map)) = (policies, user_attachments, group_attachments)
1984        {
1985            for group in groups {
1986                if let Some(ids) = ga_map.get(&group) {
1987                    for id in ids {
1988                        if let Some(p) = p_map.get(id) {
1989                            out.push(p.clone());
1990                        }
1991                    }
1992                }
1993            }
1994            if let Some(ids) = ua_map.get(user) {
1995                for id in ids {
1996                    if let Some(p) = p_map.get(id) {
1997                        out.push(p.clone());
1998                    }
1999                }
2000            }
2001        }
2002        if let Ok(mut cache) = self.iam_effective_cache.write() {
2003            cache.insert(user.clone(), out.clone());
2004        }
2005        out
2006    }
2007
2008    /// Run the policy simulator for a principal. Synthesises an
2009    /// `EvalContext` from the user record + caller-supplied extras.
2010    pub fn simulate(
2011        &self,
2012        principal: &UserId,
2013        action: &str,
2014        resource: &ResourceRef,
2015        ctx_extras: SimCtx,
2016    ) -> SimulationOutcome {
2017        let user_role = self
2018            .users
2019            .read()
2020            .ok()
2021            .and_then(|u| u.get(principal).map(|u| u.role));
2022        let principal_is_admin_role = user_role == Some(Role::Admin);
2023        let now = ctx_extras.now_ms.unwrap_or_else(now_ms);
2024        let ctx = EvalContext {
2025            principal_tenant: principal.tenant.clone(),
2026            current_tenant: ctx_extras.current_tenant,
2027            peer_ip: ctx_extras.peer_ip,
2028            mfa_present: ctx_extras.mfa_present,
2029            now_ms: now,
2030            principal_is_admin_role,
2031        };
2032        let pols = self.effective_policies(principal);
2033        let refs: Vec<&Policy> = pols.iter().map(|p| p.as_ref()).collect();
2034        iam_policies::simulate(&refs, action, resource, &ctx)
2035    }
2036
2037    /// Production hot-path policy evaluation. Returns `true` on Allow
2038    /// / AdminBypass, `false` on Deny / DefaultDeny.
2039    pub fn check_policy_authz(
2040        &self,
2041        principal: &UserId,
2042        action: &str,
2043        resource: &ResourceRef,
2044        ctx: &EvalContext,
2045    ) -> bool {
2046        let pols = self.effective_policies(principal);
2047        let refs: Vec<&Policy> = pols.iter().map(|p| p.as_ref()).collect();
2048        let decision = iam_policies::evaluate(&refs, action, resource, ctx);
2049        matches!(
2050            decision,
2051            iam_policies::Decision::Allow { .. } | iam_policies::Decision::AdminBypass
2052        )
2053    }
2054
2055    /// Evaluate a resolved table projection through the column policy
2056    /// gate. Query paths should pass already-resolved column names; this
2057    /// helper intentionally does not parse SQL projection syntax.
2058    pub fn check_column_projection_authz(
2059        &self,
2060        principal: &UserId,
2061        request: &ColumnAccessRequest,
2062        ctx: &EvalContext,
2063    ) -> ColumnPolicyOutcome {
2064        let pols = self.effective_policies(principal);
2065        let refs: Vec<&Policy> = pols.iter().map(|p| p.as_ref()).collect();
2066        ColumnPolicyGate::new(&refs).evaluate(request, ctx)
2067    }
2068
2069    fn invalidate_iam_cache(&self, uid: Option<&UserId>) {
2070        if let Ok(mut cache) = self.iam_effective_cache.write() {
2071            match uid {
2072                Some(u) => {
2073                    cache.remove(u);
2074                }
2075                None => cache.clear(),
2076            }
2077        }
2078    }
2079
2080    /// Drop every effective-policy cache entry. Called from execution
2081    /// paths that mutate policies/attachments without knowing which
2082    /// users will be affected.
2083    pub fn invalidate_all_iam_cache(&self) {
2084        self.invalidate_iam_cache(None);
2085    }
2086
2087    // -----------------------------------------------------------------
2088    // IAM persistence — vault_kv backed under `red.iam.*` keys
2089    // -----------------------------------------------------------------
2090
2091    /// Reload IAM state (policies + attachments) from the vault KV.
2092    /// Replaces the legacy `rehydrate_acl` reader — pre-1.0 we drop
2093    /// the old `red.acl.*` blob format entirely.
2094    pub fn rehydrate_iam(&self) {
2095        let mut enabled = self
2096            .vault_kv_get("red.iam.enabled")
2097            .map(|v| v == "true")
2098            .unwrap_or(false);
2099        // Policies — single JSON object keyed by id.
2100        if let Some(blob) = self.vault_kv_get("red.iam.policies") {
2101            if let Ok(val) = crate::serde_json::from_str::<crate::serde_json::Value>(&blob) {
2102                if let Some(obj) = val.as_object() {
2103                    let mut map = HashMap::new();
2104                    for (id, body) in obj.iter() {
2105                        let s = body.to_string_compact();
2106                        if let Ok(p) = Policy::from_json_str(&s) {
2107                            map.insert(id.clone(), Arc::new(p));
2108                        }
2109                    }
2110                    if !map.is_empty() {
2111                        enabled = true;
2112                    }
2113                    *self.policies.write().unwrap_or_else(|e| e.into_inner()) = map;
2114                }
2115            }
2116        }
2117        // User attachments.
2118        if let Some(blob) = self.vault_kv_get("red.iam.attachments.users") {
2119            if let Ok(val) = crate::serde_json::from_str::<crate::serde_json::Value>(&blob) {
2120                if let Some(obj) = val.as_object() {
2121                    let mut map: HashMap<UserId, Vec<String>> = HashMap::new();
2122                    for (encoded_uid, ids_v) in obj.iter() {
2123                        let Some(uid) = decode_uid(encoded_uid) else {
2124                            continue;
2125                        };
2126                        if let Some(arr) = ids_v.as_array() {
2127                            let ids: Vec<String> = arr
2128                                .iter()
2129                                .filter_map(|v| v.as_str().map(|s| s.to_string()))
2130                                .collect();
2131                            map.insert(uid, ids);
2132                        }
2133                    }
2134                    *self
2135                        .user_attachments
2136                        .write()
2137                        .unwrap_or_else(|e| e.into_inner()) = map;
2138                }
2139            }
2140        }
2141        // Group attachments.
2142        if let Some(blob) = self.vault_kv_get("red.iam.attachments.groups") {
2143            if let Ok(val) = crate::serde_json::from_str::<crate::serde_json::Value>(&blob) {
2144                if let Some(obj) = val.as_object() {
2145                    let mut map: HashMap<String, Vec<String>> = HashMap::new();
2146                    for (g, ids_v) in obj.iter() {
2147                        if let Some(arr) = ids_v.as_array() {
2148                            let ids: Vec<String> = arr
2149                                .iter()
2150                                .filter_map(|v| v.as_str().map(|s| s.to_string()))
2151                                .collect();
2152                            map.insert(g.clone(), ids);
2153                        }
2154                    }
2155                    *self
2156                        .group_attachments
2157                        .write()
2158                        .unwrap_or_else(|e| e.into_inner()) = map;
2159                }
2160            }
2161        }
2162        self.iam_authorization_enabled
2163            .store(enabled, Ordering::Release);
2164        self.invalidate_iam_cache(None);
2165    }
2166
2167    /// Snapshot policies + attachments into the vault KV. Called
2168    /// after every mutation.
2169    fn persist_iam_to_kv(&self) {
2170        let enabled = if self.iam_authorization_enabled() {
2171            "true"
2172        } else {
2173            "false"
2174        };
2175        self.vault_kv_set("red.iam.enabled".to_string(), enabled.to_string());
2176
2177        // Policies: `{ "<id>": <policy_json>, ... }`
2178        let policies_obj = {
2179            let map = self.policies.read().unwrap_or_else(|e| e.into_inner());
2180            let mut obj = crate::serde_json::Map::new();
2181            for (id, p) in map.iter() {
2182                let s = p.to_json_string();
2183                if let Ok(v) = crate::serde_json::from_str::<crate::serde_json::Value>(&s) {
2184                    obj.insert(id.clone(), v);
2185                }
2186            }
2187            crate::serde_json::Value::Object(obj).to_string_compact()
2188        };
2189        self.vault_kv_set("red.iam.policies".to_string(), policies_obj);
2190
2191        // User attachments: `{ "<encoded_uid>": [ "<policy_id>", ... ], ... }`
2192        let users_obj = {
2193            let map = self
2194                .user_attachments
2195                .read()
2196                .unwrap_or_else(|e| e.into_inner());
2197            let mut obj = crate::serde_json::Map::new();
2198            for (uid, ids) in map.iter() {
2199                let arr = crate::serde_json::Value::Array(
2200                    ids.iter()
2201                        .map(|s| crate::serde_json::Value::String(s.clone()))
2202                        .collect(),
2203                );
2204                obj.insert(encode_uid(uid), arr);
2205            }
2206            crate::serde_json::Value::Object(obj).to_string_compact()
2207        };
2208        self.vault_kv_set("red.iam.attachments.users".to_string(), users_obj);
2209
2210        // Group attachments.
2211        let groups_obj = {
2212            let map = self
2213                .group_attachments
2214                .read()
2215                .unwrap_or_else(|e| e.into_inner());
2216            let mut obj = crate::serde_json::Map::new();
2217            for (g, ids) in map.iter() {
2218                let arr = crate::serde_json::Value::Array(
2219                    ids.iter()
2220                        .map(|s| crate::serde_json::Value::String(s.clone()))
2221                        .collect(),
2222                );
2223                obj.insert(g.clone(), arr);
2224            }
2225            crate::serde_json::Value::Object(obj).to_string_compact()
2226        };
2227        self.vault_kv_set("red.iam.attachments.groups".to_string(), groups_obj);
2228    }
2229}
2230
2231fn synthetic_grant_matches(policy: &Policy, resource: &Resource, actions: &[Action]) -> bool {
2232    policy.statements.iter().any(|st| {
2233        st.effect == crate::auth::policies::Effect::Allow
2234            && st.condition.is_none()
2235            && grant_actions_overlap(&st.actions, actions)
2236            && grant_resource_matches(&st.resources, resource)
2237    })
2238}
2239
2240fn grant_actions_overlap(
2241    patterns: &[crate::auth::policies::ActionPattern],
2242    actions: &[Action],
2243) -> bool {
2244    if actions.contains(&Action::All) {
2245        return true;
2246    }
2247    patterns.iter().any(|pat| match pat {
2248        crate::auth::policies::ActionPattern::Wildcard => true,
2249        crate::auth::policies::ActionPattern::Exact(s) => {
2250            actions.iter().any(|a| s.eq_ignore_ascii_case(a.as_str()))
2251        }
2252        crate::auth::policies::ActionPattern::Prefix(_) => false,
2253    })
2254}
2255
2256fn grant_resource_matches(
2257    patterns: &[crate::auth::policies::ResourcePattern],
2258    resource: &Resource,
2259) -> bool {
2260    let expected = grant_resource_pattern(resource);
2261    patterns.iter().any(|pat| pat == &expected)
2262}
2263
2264fn grant_resource_pattern(resource: &Resource) -> crate::auth::policies::ResourcePattern {
2265    use crate::auth::policies::ResourcePattern;
2266
2267    match resource {
2268        Resource::Database => ResourcePattern::Glob("table:*".to_string()),
2269        Resource::Schema(s) => ResourcePattern::Glob(format!("table:{s}.*")),
2270        Resource::Table { schema, table } => ResourcePattern::Exact {
2271            kind: "table".to_string(),
2272            name: match schema {
2273                Some(s) => format!("{s}.{table}"),
2274                None => table.clone(),
2275            },
2276        },
2277        Resource::Function { schema, name } => ResourcePattern::Exact {
2278            kind: "function".to_string(),
2279            name: match schema {
2280                Some(s) => format!("{s}.{name}"),
2281                None => name.clone(),
2282            },
2283        },
2284    }
2285}
2286
2287// ===========================================================================
2288// ACL serialization helpers — line-oriented, human-readable so an
2289// operator inspecting the vault dump can spot misconfigurations.
2290//
2291// Format (one record per line):
2292//   GRANT|<resource>|<actions_csv>|<with_grant_option>|<tenant_or_*>|<granted_by>|<granted_at>
2293//   ATTR|<valid_until>|<connection_limit>|<search_path>
2294//
2295// Resources are encoded as:
2296//   db                          → Database
2297//   schema:<name>               → Schema(name)
2298//   table:<schema_or_*>:<name>  → Table { schema, table }
2299//   func:<schema_or_*>:<name>   → Function { schema, name }
2300// ===========================================================================
2301
2302fn encode_uid(uid: &UserId) -> String {
2303    match &uid.tenant {
2304        Some(t) => format!("{}/{}", t, uid.username),
2305        None => format!("*/{}", uid.username),
2306    }
2307}
2308
2309fn decode_uid(s: &str) -> Option<UserId> {
2310    let (tenant, username) = s.split_once('/')?;
2311    Some(if tenant == "*" {
2312        UserId::platform(username)
2313    } else {
2314        UserId::scoped(tenant, username)
2315    })
2316}
2317
2318fn encode_resource(r: &Resource) -> String {
2319    match r {
2320        Resource::Database => "db".into(),
2321        Resource::Schema(s) => format!("schema:{}", s),
2322        Resource::Table { schema, table } => {
2323            format!("table:{}:{}", schema.as_deref().unwrap_or("*"), table)
2324        }
2325        Resource::Function { schema, name } => {
2326            format!("func:{}:{}", schema.as_deref().unwrap_or("*"), name)
2327        }
2328    }
2329}
2330
2331fn decode_resource(s: &str) -> Option<Resource> {
2332    if s == "db" {
2333        return Some(Resource::Database);
2334    }
2335    if let Some(rest) = s.strip_prefix("schema:") {
2336        return Some(Resource::Schema(rest.to_string()));
2337    }
2338    if let Some(rest) = s.strip_prefix("table:") {
2339        let (schema, table) = rest.split_once(':')?;
2340        return Some(Resource::Table {
2341            schema: if schema == "*" {
2342                None
2343            } else {
2344                Some(schema.to_string())
2345            },
2346            table: table.to_string(),
2347        });
2348    }
2349    if let Some(rest) = s.strip_prefix("func:") {
2350        let (schema, name) = rest.split_once(':')?;
2351        return Some(Resource::Function {
2352            schema: if schema == "*" {
2353                None
2354            } else {
2355                Some(schema.to_string())
2356            },
2357            name: name.to_string(),
2358        });
2359    }
2360    None
2361}
2362
2363fn encode_grants_blob(grants: &[Grant]) -> String {
2364    let mut out = String::new();
2365    for g in grants {
2366        let actions: Vec<&str> = g.actions.iter().map(|a| a.as_str()).collect();
2367        out.push_str(&format!(
2368            "GRANT|{}|{}|{}|{}|{}|{}\n",
2369            encode_resource(&g.resource),
2370            actions.join(","),
2371            g.with_grant_option,
2372            g.tenant.as_deref().unwrap_or("*"),
2373            g.granted_by,
2374            g.granted_at,
2375        ));
2376    }
2377    out
2378}
2379
2380fn decode_grants_blob(s: &str) -> Option<Vec<Grant>> {
2381    let mut out = Vec::new();
2382    for line in s.lines() {
2383        if line.is_empty() {
2384            continue;
2385        }
2386        let parts: Vec<&str> = line.split('|').collect();
2387        if parts.len() != 7 || parts[0] != "GRANT" {
2388            return None;
2389        }
2390        let resource = decode_resource(parts[1])?;
2391        let mut actions = std::collections::BTreeSet::new();
2392        for token in parts[2].split(',') {
2393            if let Some(a) = Action::from_keyword(token) {
2394                actions.insert(a);
2395            }
2396        }
2397        let with_grant_option = parts[3] == "true";
2398        let tenant = if parts[4] == "*" {
2399            None
2400        } else {
2401            Some(parts[4].to_string())
2402        };
2403        let granted_by = parts[5].to_string();
2404        let granted_at: u128 = parts[6].parse().unwrap_or(0);
2405        out.push(Grant {
2406            // Principal field is reconstructed by the loader from the
2407            // storage-key prefix; default to `Public` here.
2408            principal: GrantPrincipal::Public,
2409            resource,
2410            actions,
2411            with_grant_option,
2412            granted_by,
2413            granted_at,
2414            tenant,
2415            columns: None,
2416        });
2417    }
2418    Some(out)
2419}
2420
2421fn encode_attrs_blob(a: &UserAttributes) -> String {
2422    let valid = a
2423        .valid_until
2424        .map(|t| t.to_string())
2425        .unwrap_or_else(|| "*".into());
2426    let limit = a
2427        .connection_limit
2428        .map(|l| l.to_string())
2429        .unwrap_or_else(|| "*".into());
2430    let path = a.search_path.clone().unwrap_or_else(|| "*".into());
2431    let groups = if a.groups.is_empty() {
2432        "*".to_string()
2433    } else {
2434        a.groups.join(",")
2435    };
2436    format!("ATTR|{}|{}|{}|{}\n", valid, limit, path, groups)
2437}
2438
2439fn decode_attrs_blob(s: &str) -> Option<UserAttributes> {
2440    let line = s.lines().next()?;
2441    let parts: Vec<&str> = line.split('|').collect();
2442    if !(parts.len() == 4 || parts.len() == 5) || parts[0] != "ATTR" {
2443        return None;
2444    }
2445    let groups = if parts.get(4).copied().unwrap_or("*") == "*" {
2446        Vec::new()
2447    } else {
2448        parts[4]
2449            .split(',')
2450            .filter(|g| !g.is_empty())
2451            .map(|g| g.to_string())
2452            .collect()
2453    };
2454    Some(UserAttributes {
2455        valid_until: if parts[1] == "*" {
2456            None
2457        } else {
2458            parts[1].parse().ok()
2459        },
2460        connection_limit: if parts[2] == "*" {
2461            None
2462        } else {
2463            parts[2].parse().ok()
2464        },
2465        search_path: if parts[3] == "*" {
2466            None
2467        } else {
2468            Some(parts[3].to_string())
2469        },
2470        groups,
2471    })
2472}
2473
2474// ===========================================================================
2475// Password hashing
2476// ===========================================================================
2477
2478/// Derive a SCRAM-SHA-256 verifier for a fresh user / password
2479/// rotation. Salt is 16 random bytes; iter is the engine default
2480/// (`scram::DEFAULT_ITER`). Stored alongside the Argon2 password
2481/// hash so HTTP login + v2 SCRAM can both authenticate the same
2482/// user.
2483fn make_scram_verifier(password: &str) -> crate::auth::scram::ScramVerifier {
2484    let salt = random_bytes(16);
2485    crate::auth::scram::ScramVerifier::from_password(
2486        password,
2487        salt,
2488        crate::auth::scram::DEFAULT_ITER,
2489    )
2490}
2491
2492/// Hash a password using Argon2id.
2493///
2494/// Format: `argon2id$<salt_hex>$<hash_hex>`
2495pub(crate) fn hash_password(password: &str) -> String {
2496    let salt = random_bytes(16);
2497    let params = auth_argon2_params();
2498    let hash = derive_key(password.as_bytes(), &salt, &params);
2499    format!("argon2id${}${}", hex::encode(&salt), hex::encode(&hash))
2500}
2501
2502/// Verify a password against a stored `argon2id$<salt>$<hash>` string.
2503pub(crate) fn verify_password(password: &str, stored_hash: &str) -> bool {
2504    let parts: Vec<&str> = stored_hash.splitn(3, '$').collect();
2505    if parts.len() != 3 || parts[0] != "argon2id" {
2506        return false;
2507    }
2508
2509    let salt = match hex::decode(parts[1]) {
2510        Ok(s) => s,
2511        Err(_) => return false,
2512    };
2513
2514    let expected_hash = match hex::decode(parts[2]) {
2515        Ok(h) => h,
2516        Err(_) => return false,
2517    };
2518
2519    let params = auth_argon2_params();
2520    let computed = derive_key(password.as_bytes(), &salt, &params);
2521    constant_time_eq(&computed, &expected_hash)
2522}
2523
2524/// Constant-time byte comparison to avoid timing side-channels.
2525fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
2526    if a.len() != b.len() {
2527        return false;
2528    }
2529    let mut diff: u8 = 0;
2530    for (x, y) in a.iter().zip(b.iter()) {
2531        diff |= x ^ y;
2532    }
2533    diff == 0
2534}
2535
2536// ===========================================================================
2537// Token generation
2538// ===========================================================================
2539
2540fn generate_session_token() -> String {
2541    format!("rs_{}", hex::encode(random_bytes(32)))
2542}
2543
2544fn generate_api_key() -> String {
2545    format!("rk_{}", hex::encode(random_bytes(32)))
2546}
2547
2548/// Generate `n` random bytes and return as a hex string.
2549fn random_hex(n: usize) -> String {
2550    hex::encode(random_bytes(n))
2551}
2552
2553/// Generate `n` cryptographically random bytes using the OS CSPRNG,
2554/// then mix with SHA-256 for domain separation.
2555pub(crate) fn random_bytes(n: usize) -> Vec<u8> {
2556    let mut buf = vec![0u8; n.max(32)];
2557    if os_random::fill_bytes(&mut buf).is_err() {
2558        // Fallback: use system time and pointers as entropy (best-effort).
2559        let seed = now_ms().to_le_bytes();
2560        for (i, byte) in buf.iter_mut().enumerate() {
2561            *byte = seed[i % seed.len()] ^ (i as u8);
2562        }
2563    }
2564    // SHA-256 mix to ensure uniform distribution.
2565    let digest = sha256(&buf);
2566    if n <= 32 {
2567        digest[..n].to_vec()
2568    } else {
2569        // Chain SHA-256 for longer outputs (unusual but supported).
2570        let mut out = Vec::with_capacity(n);
2571        let mut prev = digest;
2572        while out.len() < n {
2573            out.extend_from_slice(&prev[..std::cmp::min(32, n - out.len())]);
2574            prev = sha256(&prev);
2575        }
2576        out
2577    }
2578}
2579
2580// ===========================================================================
2581// Helpers
2582// ===========================================================================
2583
2584fn lock_err<T>(_: T) -> AuthError {
2585    AuthError::Internal("lock poisoned".to_string())
2586}
2587
2588// ===========================================================================
2589// Tests
2590// ===========================================================================
2591
2592#[cfg(test)]
2593mod tests {
2594    use super::*;
2595
2596    fn test_config() -> AuthConfig {
2597        AuthConfig {
2598            enabled: true,
2599            session_ttl_secs: 60,
2600            require_auth: true,
2601            auto_encrypt_storage: false,
2602            vault_enabled: false,
2603            cert: Default::default(),
2604            oauth: Default::default(),
2605        }
2606    }
2607
2608    #[test]
2609    fn test_create_and_list_users() {
2610        let store = AuthStore::new(test_config());
2611        store.create_user("alice", "pass1", Role::Admin).unwrap();
2612        store.create_user("bob", "pass2", Role::Read).unwrap();
2613
2614        let users = store.list_users();
2615        assert_eq!(users.len(), 2);
2616        // Password hashes should be redacted.
2617        for u in &users {
2618            assert!(u.password_hash.is_empty());
2619        }
2620    }
2621
2622    #[test]
2623    fn test_create_duplicate_user() {
2624        let store = AuthStore::new(test_config());
2625        store.create_user("alice", "pass", Role::Admin).unwrap();
2626        let err = store.create_user("alice", "pass2", Role::Read).unwrap_err();
2627        assert!(matches!(err, AuthError::UserExists(_)));
2628    }
2629
2630    #[test]
2631    fn test_authenticate_and_validate() {
2632        let store = AuthStore::new(test_config());
2633        store.create_user("alice", "secret", Role::Write).unwrap();
2634
2635        let session = store.authenticate("alice", "secret").unwrap();
2636        assert!(session.token.starts_with("rs_"));
2637
2638        let (username, role) = store.validate_token(&session.token).unwrap();
2639        assert_eq!(username, "alice");
2640        assert_eq!(role, Role::Write);
2641    }
2642
2643    #[test]
2644    fn test_authenticate_wrong_password() {
2645        let store = AuthStore::new(test_config());
2646        store.create_user("alice", "secret", Role::Read).unwrap();
2647
2648        let err = store.authenticate("alice", "wrong").unwrap_err();
2649        assert!(matches!(err, AuthError::InvalidCredentials));
2650    }
2651
2652    #[test]
2653    fn test_api_key_lifecycle() {
2654        let store = AuthStore::new(test_config());
2655        store.create_user("alice", "pass", Role::Admin).unwrap();
2656
2657        let key = store
2658            .create_api_key("alice", "ci-token", Role::Write)
2659            .unwrap();
2660        assert!(key.key.starts_with("rk_"));
2661
2662        let (username, role) = store.validate_token(&key.key).unwrap();
2663        assert_eq!(username, "alice");
2664        assert_eq!(role, Role::Write);
2665
2666        store.revoke_api_key(&key.key).unwrap();
2667        assert!(store.validate_token(&key.key).is_none());
2668    }
2669
2670    #[test]
2671    fn test_api_key_role_exceeded() {
2672        let store = AuthStore::new(test_config());
2673        store.create_user("bob", "pass", Role::Read).unwrap();
2674
2675        let err = store
2676            .create_api_key("bob", "escalate", Role::Admin)
2677            .unwrap_err();
2678        assert!(matches!(err, AuthError::RoleExceeded { .. }));
2679    }
2680
2681    #[test]
2682    fn test_change_password() {
2683        let store = AuthStore::new(test_config());
2684        store.create_user("alice", "old", Role::Write).unwrap();
2685
2686        store.change_password("alice", "old", "new").unwrap();
2687
2688        // Old password should fail.
2689        assert!(store.authenticate("alice", "old").is_err());
2690        // New password should succeed.
2691        assert!(store.authenticate("alice", "new").is_ok());
2692    }
2693
2694    #[test]
2695    fn test_change_role() {
2696        let store = AuthStore::new(test_config());
2697        store.create_user("alice", "pass", Role::Admin).unwrap();
2698        store.create_api_key("alice", "key1", Role::Admin).unwrap();
2699
2700        store.change_role("alice", Role::Read).unwrap();
2701
2702        // User's role should be Read now.
2703        let users = store.list_users();
2704        let alice = users.iter().find(|u| u.username == "alice").unwrap();
2705        assert_eq!(alice.role, Role::Read);
2706
2707        // API keys should have been downgraded.
2708        assert_eq!(alice.api_keys[0].role, Role::Read);
2709    }
2710
2711    #[test]
2712    fn test_delete_user() {
2713        let store = AuthStore::new(test_config());
2714        store.create_user("alice", "pass", Role::Admin).unwrap();
2715        let key = store.create_api_key("alice", "key1", Role::Read).unwrap();
2716        let session = store.authenticate("alice", "pass").unwrap();
2717
2718        store.delete_user("alice").unwrap();
2719
2720        assert!(store.validate_token(&key.key).is_none());
2721        assert!(store.validate_token(&session.token).is_none());
2722        assert!(store.list_users().is_empty());
2723    }
2724
2725    #[test]
2726    fn test_revoke_session() {
2727        let store = AuthStore::new(test_config());
2728        store.create_user("alice", "pass", Role::Read).unwrap();
2729        let session = store.authenticate("alice", "pass").unwrap();
2730
2731        store.revoke_session(&session.token);
2732        assert!(store.validate_token(&session.token).is_none());
2733    }
2734
2735    #[test]
2736    fn test_password_hash_format() {
2737        let hash = hash_password("test");
2738        assert!(hash.starts_with("argon2id$"));
2739        let parts: Vec<&str> = hash.splitn(3, '$').collect();
2740        assert_eq!(parts.len(), 3);
2741        // Salt is 16 bytes = 32 hex chars.
2742        assert_eq!(parts[1].len(), 32);
2743        // Hash is 32 bytes = 64 hex chars.
2744        assert_eq!(parts[2].len(), 64);
2745    }
2746
2747    #[test]
2748    fn test_constant_time_eq() {
2749        assert!(constant_time_eq(b"hello", b"hello"));
2750        assert!(!constant_time_eq(b"hello", b"world"));
2751        assert!(!constant_time_eq(b"short", b"longer"));
2752    }
2753
2754    #[test]
2755    fn test_bootstrap_seals_permanently() {
2756        let store = AuthStore::new(test_config());
2757
2758        assert!(store.needs_bootstrap());
2759        assert!(!store.is_bootstrapped());
2760
2761        // First bootstrap succeeds
2762        let result = store.bootstrap("admin", "secret");
2763        assert!(result.is_ok());
2764        let br = result.unwrap();
2765        assert_eq!(br.user.username, "admin");
2766        assert_eq!(br.user.role, Role::Admin);
2767        assert!(br.api_key.key.starts_with("rk_"));
2768        // No vault configured, so no certificate.
2769        assert!(br.certificate.is_none());
2770
2771        // Sealed now
2772        assert!(!store.needs_bootstrap());
2773        assert!(store.is_bootstrapped());
2774
2775        // Second bootstrap fails -- sealed permanently
2776        let result = store.bootstrap("admin2", "secret2");
2777        assert!(result.is_err());
2778        let err = result.unwrap_err();
2779        assert!(err.to_string().contains("sealed permanently"));
2780
2781        // Only 1 user exists (the first one)
2782        assert_eq!(store.list_users().len(), 1);
2783        assert_eq!(store.list_users()[0].username, "admin");
2784    }
2785
2786    #[test]
2787    fn test_bootstrap_after_manual_user_creation() {
2788        let store = AuthStore::new(test_config());
2789
2790        // Create a user manually first
2791        store.create_user("existing", "pass", Role::Read).unwrap();
2792
2793        // Bootstrap sees the seal hasn't been set but users exist
2794        // The atomic seal fires first, then the users check catches it
2795        assert!(!store.needs_bootstrap()); // users exist → false
2796    }
2797
2798    // ---------------------------------------------------------------
2799    // Tenant scoping
2800    // ---------------------------------------------------------------
2801
2802    #[test]
2803    fn test_same_username_two_tenants_distinct() {
2804        let store = AuthStore::new(test_config());
2805        store
2806            .create_user_in_tenant(Some("acme"), "alice", "pw-acme", Role::Write)
2807            .unwrap();
2808        store
2809            .create_user_in_tenant(Some("globex"), "alice", "pw-globex", Role::Read)
2810            .unwrap();
2811
2812        // Two distinct users.
2813        let users = store.list_users();
2814        assert_eq!(users.len(), 2);
2815
2816        // Each verifies its own password under its own tenant.
2817        assert!(store
2818            .authenticate_in_tenant(Some("acme"), "alice", "pw-acme")
2819            .is_ok());
2820        assert!(store
2821            .authenticate_in_tenant(Some("globex"), "alice", "pw-globex")
2822            .is_ok());
2823
2824        // Cross-tenant credentials are rejected.
2825        assert!(store
2826            .authenticate_in_tenant(Some("acme"), "alice", "pw-globex")
2827            .is_err());
2828        assert!(store
2829            .authenticate_in_tenant(Some("globex"), "alice", "pw-acme")
2830            .is_err());
2831    }
2832
2833    #[test]
2834    fn test_session_carries_tenant() {
2835        let store = AuthStore::new(test_config());
2836        store
2837            .create_user_in_tenant(Some("acme"), "alice", "pw", Role::Admin)
2838            .unwrap();
2839        let session = store
2840            .authenticate_in_tenant(Some("acme"), "alice", "pw")
2841            .unwrap();
2842        assert_eq!(session.tenant_id.as_deref(), Some("acme"));
2843
2844        let (id, role) = store.validate_token_full(&session.token).unwrap();
2845        assert_eq!(id.tenant.as_deref(), Some("acme"));
2846        assert_eq!(id.username, "alice");
2847        assert_eq!(role, Role::Admin);
2848    }
2849
2850    #[test]
2851    fn test_platform_user_has_no_tenant() {
2852        let store = AuthStore::new(test_config());
2853        store.create_user("admin", "pw", Role::Admin).unwrap();
2854        let session = store.authenticate("admin", "pw").unwrap();
2855        assert!(session.tenant_id.is_none());
2856
2857        let (id, _) = store.validate_token_full(&session.token).unwrap();
2858        assert!(id.tenant.is_none());
2859    }
2860
2861    #[test]
2862    fn test_lookup_scram_verifier_global_resolves_platform() {
2863        let store = AuthStore::new(test_config());
2864        store.create_user("admin", "pw", Role::Admin).unwrap();
2865        store
2866            .create_user_in_tenant(Some("acme"), "admin", "pw", Role::Admin)
2867            .unwrap();
2868
2869        // The global helper picks the platform-tenant user only.
2870        let v = store.lookup_scram_verifier_global("admin");
2871        assert!(v.is_some());
2872
2873        // The tenant-scoped user has its own verifier.
2874        let v_acme = store.lookup_scram_verifier(&UserId::scoped("acme", "admin"));
2875        assert!(v_acme.is_some());
2876
2877        // The two verifiers carry independent salts.
2878        assert_ne!(v.unwrap().salt, v_acme.unwrap().salt);
2879    }
2880
2881    #[test]
2882    fn test_delete_in_tenant_does_not_touch_other_tenant() {
2883        let store = AuthStore::new(test_config());
2884        store
2885            .create_user_in_tenant(Some("acme"), "alice", "pw", Role::Admin)
2886            .unwrap();
2887        store
2888            .create_user_in_tenant(Some("globex"), "alice", "pw", Role::Admin)
2889            .unwrap();
2890
2891        store.delete_user_in_tenant(Some("acme"), "alice").unwrap();
2892
2893        // Globex still alive.
2894        assert!(store
2895            .authenticate_in_tenant(Some("globex"), "alice", "pw")
2896            .is_ok());
2897        // Acme gone.
2898        assert!(store
2899            .authenticate_in_tenant(Some("acme"), "alice", "pw")
2900            .is_err());
2901    }
2902
2903    #[test]
2904    fn test_user_id_display() {
2905        assert_eq!(UserId::platform("admin").to_string(), "admin");
2906        assert_eq!(UserId::scoped("acme", "alice").to_string(), "acme/alice");
2907    }
2908}