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#![deny(clippy::disallowed_methods)]
7
8use std::borrow::Cow;
9use std::collections::{HashMap, HashSet};
10use std::sync::atomic::{AtomicBool, Ordering};
11use std::sync::{Arc, OnceLock, RwLock};
12
13use crate::crypto::os_random;
14use crate::crypto::sha256::sha256;
15use crate::storage::encryption::argon2id::{derive_key, Argon2Params};
16use crate::storage::engine::pager::Pager;
17
18use super::column_policy_gate::{ColumnAccessRequest, ColumnPolicyGate, ColumnPolicyOutcome};
19use super::enforcement_mode::{legacy_rbac_decision, PolicyEnforcementMode};
20use super::managed_policy::{ManagedPolicyDecision, ManagedPolicyGate, PolicyOp};
21use super::policies::{self as iam_policies, EvalContext, Policy, ResourceRef, SimulationOutcome};
22use super::privileges::{
23    check_grant, Action, AuthzContext, AuthzError, Grant, GrantPrincipal, GrantsView,
24    PermissionCache, Resource, UserAttributes,
25};
26use super::registry::ConfigRegistry;
27use super::vault::{KeyPair, Vault, VaultState};
28use super::{now_ms, ApiKey, AuthConfig, AuthError, Role, Session, User, UserId};
29use crate::runtime::control_events::{
30    ControlEvent, ControlEventConfig, ControlEventCtx, ControlEventLedger, EventKind, Outcome,
31    Sensitivity,
32};
33
34// ---------------------------------------------------------------------------
35// PrincipalRef + SimCtx — IAM policy attachments
36// ---------------------------------------------------------------------------
37
38/// Principal targeted by `attach_policy` / `detach_policy`.
39#[derive(Debug, Clone, PartialEq, Eq, Hash)]
40pub enum PrincipalRef {
41    User(UserId),
42    Group(String),
43}
44
45/// Reserved IAM group that every principal belongs to. Used by the
46/// GRANT-to-PUBLIC compatibility layer.
47pub const PUBLIC_IAM_GROUP: &str = "__public__";
48
49/// Optional context overrides for `simulate` — anything not set falls back
50/// to a default value when the kernel evaluates the request.
51#[derive(Debug, Clone, Default)]
52pub struct SimCtx {
53    pub current_tenant: Option<String>,
54    pub peer_ip: Option<std::net::IpAddr>,
55    pub mfa_present: bool,
56    pub now_ms: Option<u128>,
57}
58
59/// Control-event dependencies for audited IAM policy mutations.
60///
61/// The existing `put_policy` / `delete_policy` / attach / detach
62/// methods remain unaudited for bootstrap and synthetic GRANT internals.
63/// Public mutation surfaces that need evidence pass this context to the
64/// `*_with_control_events` siblings.
65pub struct PolicyMutationControl<'a> {
66    pub ctx: &'a ControlEventCtx<'a>,
67    pub ledger: &'a dyn ControlEventLedger,
68    pub config: ControlEventConfig,
69    pub registry: Option<&'a ConfigRegistry>,
70    pub actor: &'a UserId,
71    pub eval_ctx: &'a EvalContext,
72}
73
74/// Control-event dependencies for audited user lifecycle mutations.
75pub struct UserLifecycleControl<'a> {
76    pub ctx: &'a ControlEventCtx<'a>,
77    pub ledger: &'a dyn ControlEventLedger,
78    pub config: ControlEventConfig,
79}
80
81#[derive(Clone)]
82struct AuthStoreControlEvents {
83    ledger: Arc<dyn ControlEventLedger>,
84    config: ControlEventConfig,
85}
86
87// ---------------------------------------------------------------------------
88// BootstrapResult
89// ---------------------------------------------------------------------------
90
91/// Result of a successful bootstrap operation.
92///
93/// The `certificate` is the hex-encoded string the admin must save --
94/// it is the ONLY way to unseal the vault after a restart.
95pub struct BootstrapResult {
96    pub user: User,
97    pub api_key: ApiKey,
98    /// Certificate hex string.  `None` when vault is not configured.
99    pub certificate: Option<String>,
100}
101
102impl std::fmt::Debug for BootstrapResult {
103    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104        f.debug_struct("BootstrapResult")
105            .field("user", &self.user)
106            .field("api_key", &"<redacted>")
107            .field(
108                "certificate",
109                &self.certificate.as_ref().map(|_| "<redacted>"),
110            )
111            .finish()
112    }
113}
114
115// ---------------------------------------------------------------------------
116// AuthStore
117// ---------------------------------------------------------------------------
118
119/// Central in-process authority for auth state.
120///
121/// All mutations are guarded by `RwLock`s so the store is `Send + Sync`.
122pub struct AuthStore {
123    /// `(tenant_id, username) -> User`. Tenant scoping is built into the
124    /// key so `alice@acme` and `alice@globex` are distinct identities.
125    users: RwLock<HashMap<UserId, User>>,
126    sessions: RwLock<HashMap<String, Session>>,
127    counted_session_tokens: RwLock<HashSet<String>>,
128    /// key-string -> (owner UserId, role)
129    api_key_index: RwLock<HashMap<String, (UserId, Role)>>,
130    /// Once true, bootstrap() is permanently sealed.
131    bootstrapped: AtomicBool,
132    config: AuthConfig,
133    /// Optional encrypted vault for persisting auth state to pager pages.
134    vault: RwLock<Option<Vault>>,
135    /// Reference to the pager for vault page I/O.
136    pager: Option<Arc<Pager>>,
137    /// Called after each successful vault save. Vault pages are written to
138    /// the data file directly, outside the commit WAL, so a serverless WAL
139    /// archive must publish a generation to capture them.
140    vault_persist_hook: RwLock<Option<Arc<dyn Fn() + Send + Sync>>>,
141    /// Existing operator credential; bootstrap must preserve this seal.
142    provided_certificate: Option<String>,
143    /// Certificate-based keypair for token signing and vault seal.
144    /// Populated after bootstrap or after restoring from a sealed vault.
145    keypair: RwLock<Option<KeyPair>>,
146    /// Encrypted key-value store for arbitrary secrets.
147    /// Persisted to vault alongside users/api_keys.
148    vault_kv: RwLock<HashMap<String, String>>,
149    secret_key_init: std::sync::Mutex<()>,
150    /// Plain (non-encrypted) user key-value store for `$kv.*` / `SET KV`
151    /// (#1602). Deliberately isolated from `vault_kv` (encrypted secrets)
152    /// and from the runtime config store — three independent flat-maps,
153    /// no mixing. Backs the `kv:read` / `kv:write` IAM-gated resolver.
154    plain_kv: RwLock<HashMap<String, String>>,
155    /// Per-user GRANT rows. Persisted via `vault_kv` under the
156    /// `red.acl.grants.<tenant>/<user>` key prefix so existing snapshot
157    /// logic keeps working without modification. See `privileges` module
158    /// for the resolution algorithm.
159    grants: RwLock<HashMap<UserId, Vec<Grant>>>,
160    /// PUBLIC grants — apply to every authenticated principal.
161    public_grants: RwLock<Vec<Grant>>,
162    /// PG-style account attributes (`VALID UNTIL`, `CONNECTION LIMIT`,
163    /// `search_path`). Keyed by `UserId`. Persisted under
164    /// `red.acl.attrs.<tenant>/<user>`.
165    user_attributes: RwLock<HashMap<UserId, UserAttributes>>,
166    /// Live session count per user — used by `CONNECTION LIMIT`
167    /// enforcement on login. Bumped at authenticate, decremented at
168    /// session revoke / expiry.
169    session_count_by_user: RwLock<HashMap<UserId, u32>>,
170    /// Pre-resolved (resource, action) cache built per-user so the
171    /// hot path skips a linear scan of the user's grants on every
172    /// statement. Invalidated on GRANT / REVOKE / ALTER USER.
173    permission_cache: RwLock<HashMap<UserId, PermissionCache>>,
174    /// IAM-style policies, keyed by id. Persisted under
175    /// `red.iam.policies`. The kernel in `super::policies` owns the
176    /// Policy type — this map just deduplicates and shares.
177    policies: RwLock<HashMap<String, Arc<Policy>>>,
178    /// Per-user policy attachments — ordered list of policy ids.
179    /// Persisted under `red.iam.attachments.users`.
180    user_attachments: RwLock<HashMap<UserId, Vec<String>>>,
181    /// Per-group policy attachments. Users join groups through
182    /// `UserAttributes::groups`; effective policies resolve group
183    /// attachments before user-direct attachments.
184    group_attachments: RwLock<HashMap<String, Vec<String>>>,
185    /// Cached effective `Vec<Arc<Policy>>` per user. Invalidated on
186    /// any policy mutation that affects the user's attachments.
187    iam_effective_cache: RwLock<HashMap<UserId, Vec<Arc<Policy>>>>,
188    /// Once any IAM policy is installed, authorization switches to the
189    /// IAM evaluator and stays deny-by-default even if policies are
190    /// later deleted. Persisted under `red.iam.enabled`.
191    iam_authorization_enabled: AtomicBool,
192    /// Selects the fallback behaviour when the IAM evaluator returns
193    /// `DefaultDeny`. See [`PolicyEnforcementMode`] and #712 / S5A.
194    /// Default is [`PolicyEnforcementMode::default_existing_install`]
195    /// (`LegacyRbac`) so an existing install upgrading past #712
196    /// keeps its current authorization posture until the operator
197    /// flips it explicitly. The bootstrap path sets this to
198    /// `PolicyOnly` for fresh installs; the boot-time config loader
199    /// supersedes both when a `policy.enforcement_mode` key in `red.config`
200    /// value is present in the configured value store.
201    enforcement_mode: RwLock<PolicyEnforcementMode>,
202    /// Once-per-boot flag used by [`AuthStore::take_legacy_rbac_warn_once`]
203    /// to deliver exactly one `warn`-level log line when the store is
204    /// running under [`PolicyEnforcementMode::LegacyRbac`]. The boot
205    /// path checks the flag and, if it can claim it, emits the line.
206    legacy_rbac_boot_warn_emitted: AtomicBool,
207    /// `(tenant, role) → HashSet<CollectionId>` cache used by the AI
208    /// pipeline (issue #119). Distinct from `permission_cache`, which
209    /// is keyed by `UserId` and answers `(resource, action)` lookups —
210    /// this cache answers the inverse "what collections is this scope
211    /// allowed to read?" query that `AuthorizedSearch` uses to
212    /// pre-filter SEARCH SIMILAR / SEARCH CONTEXT candidates before any
213    /// similarity score is computed. Entries TTL out at 60s and are
214    /// invalidated explicitly on GRANT/REVOKE/CREATE POLICY/DROP
215    /// POLICY/DROP COLLECTION.
216    visible_collections_cache: super::scope_cache::AuthCache,
217    control_events: RwLock<Option<AuthStoreControlEvents>>,
218}
219
220/// RAII reservation for a long-lived wire connection. Dropping the lease
221/// releases exactly one CONNECTION LIMIT slot.
222pub struct ConnectionLease {
223    store: Arc<AuthStore>,
224    principal: UserId,
225}
226
227impl Drop for ConnectionLease {
228    fn drop(&mut self) {
229        self.store.decrement_session_count(&self.principal);
230    }
231}
232
233// Use fast-but-safe Argon2id params for auth hashing (smaller than the
234// default 64 MB so that user-management RPCs respond quickly).
235fn auth_argon2_params() -> Argon2Params {
236    Argon2Params {
237        m_cost: 4 * 1024, // 4 MB
238        t_cost: 3,
239        p: 1,
240        tag_len: 32,
241    }
242}
243
244fn policy_control_fields(
245    policy_id: &str,
246    policy: Option<&Policy>,
247    principal: Option<&PrincipalRef>,
248) -> HashMap<String, Sensitivity> {
249    let mut fields = HashMap::new();
250    fields.insert("policy_id".to_string(), Sensitivity::raw(policy_id));
251    if let Some(policy) = policy {
252        let effects = policy
253            .statements
254            .iter()
255            .map(|s| match s.effect {
256                iam_policies::Effect::Allow => "allow",
257                iam_policies::Effect::Deny => "deny",
258            })
259            .collect::<Vec<_>>()
260            .join(",");
261        let actions = policy
262            .statements
263            .iter()
264            .flat_map(|s| s.actions.iter())
265            .map(policy_action_pattern)
266            .collect::<Vec<_>>()
267            .join(",");
268        let resources = policy
269            .statements
270            .iter()
271            .flat_map(|s| s.resources.iter())
272            .map(policy_resource_pattern)
273            .collect::<Vec<_>>()
274            .join(",");
275        fields.insert("effect".to_string(), Sensitivity::raw(effects));
276        fields.insert("action".to_string(), Sensitivity::raw(actions));
277        fields.insert("resource".to_string(), Sensitivity::raw(resources));
278        if let Some(attrs) = policy_principal_attrs(policy) {
279            fields.insert("principal_attrs".to_string(), Sensitivity::raw(attrs));
280        }
281    }
282    if let Some(principal) = principal {
283        fields.insert(
284            "principal".to_string(),
285            Sensitivity::raw(policy_principal_label(principal)),
286        );
287    }
288    fields
289}
290
291fn policy_action_pattern(pattern: &iam_policies::ActionPattern) -> String {
292    match pattern {
293        iam_policies::ActionPattern::Exact(s) => s.clone(),
294        iam_policies::ActionPattern::Wildcard => "*".to_string(),
295        iam_policies::ActionPattern::Prefix(s) => format!("{s}:*"),
296    }
297}
298
299fn policy_resource_pattern(pattern: &iam_policies::ResourcePattern) -> String {
300    match pattern {
301        iam_policies::ResourcePattern::Exact { kind, name } => format!("{kind}:{name}"),
302        iam_policies::ResourcePattern::Glob(s) => s.clone(),
303        iam_policies::ResourcePattern::Wildcard => "*".to_string(),
304    }
305}
306
307fn policy_principal_attrs(policy: &Policy) -> Option<String> {
308    let mut attrs = Vec::new();
309    for statement in &policy.statements {
310        let Some(condition) = &statement.condition else {
311            continue;
312        };
313        if let Some(value) = condition.platform_scoped {
314            attrs.push(format!("platform_scoped={value}"));
315        }
316        if let Some(value) = condition.mfa {
317            attrs.push(format!("mfa={value}"));
318        }
319        if let Some(value) = condition.tenant_match {
320            attrs.push(format!("tenant_match={value}"));
321        }
322    }
323    if attrs.is_empty() {
324        None
325    } else {
326        Some(attrs.join(","))
327    }
328}
329
330fn policy_principal_label(principal: &PrincipalRef) -> String {
331    match principal {
332        PrincipalRef::User(uid) => format!("user:{uid}"),
333        PrincipalRef::Group(group) => format!("group:{group}"),
334    }
335}
336
337fn default_user_lifecycle_ctx<'a>() -> ControlEventCtx<'a> {
338    ControlEventCtx {
339        actor: crate::runtime::control_events::ActorRef::Anonymous,
340        scope: None,
341        request_id: None,
342        trace_id: None,
343    }
344}
345
346fn bootstrap_user_lifecycle_ctx<'a>() -> ControlEventCtx<'a> {
347    ControlEventCtx {
348        actor: crate::runtime::control_events::ActorRef::System("bootstrap"),
349        scope: None,
350        request_id: None,
351        trace_id: None,
352    }
353}
354
355fn user_resource(id: &UserId) -> String {
356    format!("user:{id}")
357}
358
359fn api_key_resource(api_key_id: &str) -> String {
360    format!("apikey:{api_key_id}")
361}
362
363/// Hex digest that identifies an API key in control events and, with the
364/// `rkh_` prefix, at rest. Accepts either the secret or the stored id, so
365/// every entry point can take whichever the caller holds.
366fn api_key_id(key: &str) -> String {
367    match key.strip_prefix("rkh_") {
368        Some(hex) => hex.to_string(),
369        None => hex::encode(sha256(key.as_bytes())),
370    }
371}
372
373/// Stored form of an API key: `rkh_<sha256(secret)>`. The secret is only
374/// ever compared by hashing it and looking the result up.
375pub(crate) fn api_key_credential_id(token: &str) -> String {
376    format!("rkh_{}", api_key_id(token))
377}
378
379fn password_evidence() -> Sensitivity {
380    Sensitivity::redacted()
381}
382
383fn user_control_fields(
384    id: &UserId,
385    role: Option<Role>,
386    enabled: Option<bool>,
387    include_password: bool,
388) -> HashMap<String, Sensitivity> {
389    let mut fields = HashMap::new();
390    fields.insert(
391        "username".to_string(),
392        Sensitivity::raw(id.username.clone()),
393    );
394    fields.insert(
395        "tenant_id".to_string(),
396        Sensitivity::raw(id.tenant.clone().unwrap_or_default()),
397    );
398    if let Some(role) = role {
399        fields.insert("role".to_string(), Sensitivity::raw(role.as_str()));
400    }
401    if let Some(enabled) = enabled {
402        fields.insert("enabled".to_string(), Sensitivity::raw(enabled.to_string()));
403    }
404    if include_password {
405        fields.insert("password".to_string(), password_evidence());
406    }
407    fields
408}
409
410fn api_key_control_fields(
411    id: &UserId,
412    role: Role,
413    api_key_id: &str,
414) -> HashMap<String, Sensitivity> {
415    let mut fields = user_control_fields(id, Some(role), None, false);
416    fields.insert("api_key_id".to_string(), Sensitivity::raw(api_key_id));
417    fields.insert("api_key".to_string(), Sensitivity::redacted());
418    fields
419}
420
421fn user_error_is_denied(err: &AuthError) -> bool {
422    !matches!(err, AuthError::Internal(_))
423}
424
425impl AuthStore {
426    // -----------------------------------------------------------------
427    // Construction
428    // -----------------------------------------------------------------
429
430    pub fn new(config: AuthConfig) -> Self {
431        Self {
432            users: RwLock::new(HashMap::new()),
433            sessions: RwLock::new(HashMap::new()),
434            counted_session_tokens: RwLock::new(HashSet::new()),
435            api_key_index: RwLock::new(HashMap::new()),
436            bootstrapped: AtomicBool::new(false),
437            config,
438            vault: RwLock::new(None),
439            pager: None,
440            vault_persist_hook: RwLock::new(None),
441            provided_certificate: None,
442            keypair: RwLock::new(None),
443            vault_kv: RwLock::new(HashMap::new()),
444            secret_key_init: std::sync::Mutex::new(()),
445            plain_kv: RwLock::new(HashMap::new()),
446            grants: RwLock::new(HashMap::new()),
447            public_grants: RwLock::new(Vec::new()),
448            user_attributes: RwLock::new(HashMap::new()),
449            session_count_by_user: RwLock::new(HashMap::new()),
450            permission_cache: RwLock::new(HashMap::new()),
451            policies: RwLock::new(HashMap::new()),
452            user_attachments: RwLock::new(HashMap::new()),
453            group_attachments: RwLock::new(HashMap::new()),
454            iam_effective_cache: RwLock::new(HashMap::new()),
455            iam_authorization_enabled: AtomicBool::new(false),
456            enforcement_mode: RwLock::new(PolicyEnforcementMode::default_existing_install()),
457            legacy_rbac_boot_warn_emitted: AtomicBool::new(false),
458            visible_collections_cache: super::scope_cache::AuthCache::new(
459                super::scope_cache::DEFAULT_TTL,
460            ),
461            control_events: RwLock::new(None),
462        }
463    }
464
465    pub fn configure_control_events(
466        &self,
467        ledger: Arc<dyn ControlEventLedger>,
468        config: ControlEventConfig,
469    ) {
470        *self
471            .control_events
472            .write()
473            .unwrap_or_else(|e| e.into_inner()) = Some(AuthStoreControlEvents { ledger, config });
474    }
475
476    fn configured_control_events(&self) -> Option<AuthStoreControlEvents> {
477        self.control_events
478            .read()
479            .unwrap_or_else(|e| e.into_inner())
480            .clone()
481    }
482
483    /// Create an `AuthStore` backed by encrypted vault pages inside the
484    /// main `.rdb` database file.
485    ///
486    /// If vault pages already exist, their contents are loaded and
487    /// restored into the in-memory store.  All subsequent mutations are
488    /// automatically persisted to the vault pages via the pager.
489    pub fn with_vault(config: AuthConfig, pager: Arc<Pager>) -> Result<Self, AuthError> {
490        let certificate = crate::utils::env_with_file_fallback("REDDB_CERTIFICATE");
491        let passphrase = crate::utils::env_with_file_fallback("REDDB_VAULT_PASSPHRASE");
492        match (certificate, passphrase) {
493            (Some(_), Some(_)) => Err(AuthError::Internal(
494                "set either REDDB_CERTIFICATE or REDDB_VAULT_PASSPHRASE, not both".into(),
495            )),
496            (None, Some(passphrase)) => Self::with_vault_passphrase(config, pager, &passphrase),
497            (certificate, None) => {
498                Self::with_vault_optional_certificate(config, pager, certificate.as_deref())
499            }
500        }
501    }
502
503    pub fn with_vault_certificate(
504        config: AuthConfig,
505        pager: Arc<Pager>,
506        certificate_hex: &str,
507    ) -> Result<Self, AuthError> {
508        Self::with_vault_optional_certificate(config, pager, Some(certificate_hex))
509    }
510
511    pub fn with_vault_passphrase(
512        config: AuthConfig,
513        pager: Arc<Pager>,
514        passphrase: &str,
515    ) -> Result<Self, AuthError> {
516        let mut store = Self::new(config);
517        let vault = Vault::with_passphrase(&pager, passphrase)?;
518        if let Some(state) = vault.load(&pager)? {
519            store.restore_from_vault(state);
520        }
521        *store.vault.write().map_err(lock_err)? = Some(vault);
522        store.pager = Some(pager);
523        Ok(store)
524    }
525
526    fn with_vault_optional_certificate(
527        config: AuthConfig,
528        pager: Arc<Pager>,
529        certificate_hex: Option<&str>,
530    ) -> Result<Self, AuthError> {
531        let mut store = Self::new(config);
532
533        // Restore persisted state if vault pages exist. A fresh database does
534        // not need a temporary seal: bootstrap generates the certificate and
535        // installs the first real vault atomically.
536        if Vault::has_saved_state(&pager) {
537            let vault = match certificate_hex {
538                Some(certificate) => Vault::with_certificate(&pager, certificate)?,
539                None => Vault::open(&pager)?,
540            };
541            if let Some(state) = vault.load(&pager)? {
542                store.restore_from_vault(state);
543            }
544            *store.vault.write().unwrap_or_else(|e| e.into_inner()) = Some(vault);
545        } else if let Some(certificate) = certificate_hex {
546            let vault = Vault::with_certificate(&pager, certificate)?;
547            *store.vault.write().unwrap_or_else(|e| e.into_inner()) = Some(vault);
548        }
549
550        store.pager = Some(pager);
551        store.provided_certificate =
552            certificate_hex.map(|certificate| certificate.trim().to_ascii_lowercase());
553        Ok(store)
554    }
555
556    pub fn config(&self) -> &AuthConfig {
557        &self.config
558    }
559
560    pub fn is_enabled(&self) -> bool {
561        self.config.enabled
562    }
563
564    /// Returns true when no users exist yet and bootstrap hasn't been sealed.
565    pub fn needs_bootstrap(&self) -> bool {
566        !self.bootstrapped.load(Ordering::Acquire)
567            && self.users.read().map(|u| u.is_empty()).unwrap_or(true)
568    }
569
570    /// Internal: read-locked lookup by `UserId`.
571    fn get_user_cloned(&self, id: &UserId) -> Option<User> {
572        self.users.read().ok().and_then(|m| m.get(id).cloned())
573    }
574
575    /// Whether bootstrap has already been performed (sealed).
576    pub fn is_bootstrapped(&self) -> bool {
577        self.bootstrapped.load(Ordering::Acquire)
578    }
579
580    /// Bootstrap the first admin user. One-shot, irreversible.
581    ///
582    /// Uses an atomic compare-exchange to guarantee that even under
583    /// concurrent calls, only the first one succeeds. Once sealed,
584    /// all subsequent calls fail immediately -- there is no undo.
585    ///
586    /// When a vault/pager is configured, a certificate-based keypair is
587    /// generated and the vault is re-encrypted with the certificate-derived
588    /// key.  The certificate hex string is returned in `BootstrapResult`
589    /// so the admin can save it.
590    pub fn bootstrap(&self, username: &str, password: &str) -> Result<BootstrapResult, AuthError> {
591        if let Some(configured) = self.configured_control_events() {
592            let ctx = bootstrap_user_lifecycle_ctx();
593            let control = UserLifecycleControl {
594                ctx: &ctx,
595                ledger: configured.ledger.as_ref(),
596                config: configured.config,
597            };
598            self.bootstrap_with_control_events_inner(username, password, &control)
599        } else {
600            self.bootstrap_unaudited(username, password)
601        }
602    }
603
604    /// Bootstrap while durably delivering a newly generated vault
605    /// certificate before the sealed vault is installed or persisted.
606    pub fn bootstrap_with_certificate_delivery(
607        &self,
608        username: &str,
609        password: &str,
610        mut deliver: impl FnMut(&str) -> Result<(), AuthError>,
611    ) -> Result<BootstrapResult, AuthError> {
612        let delivery: &mut dyn FnMut(&str) -> Result<(), AuthError> = &mut deliver;
613        if let Some(configured) = self.configured_control_events() {
614            let ctx = bootstrap_user_lifecycle_ctx();
615            let control = UserLifecycleControl {
616                ctx: &ctx,
617                ledger: configured.ledger.as_ref(),
618                config: configured.config,
619            };
620            self.bootstrap_with_control_events_inner_and_delivery(
621                username,
622                password,
623                &control,
624                Some(delivery),
625            )
626        } else {
627            self.bootstrap_unaudited_with_delivery(username, password, Some(delivery))
628        }
629    }
630
631    pub fn bootstrap_with_control_events(
632        &self,
633        username: &str,
634        password: &str,
635        ctx: &ControlEventCtx<'_>,
636        ledger: &dyn ControlEventLedger,
637        config: ControlEventConfig,
638    ) -> Result<BootstrapResult, AuthError> {
639        let system_ctx = ControlEventCtx {
640            actor: crate::runtime::control_events::ActorRef::System("bootstrap"),
641            scope: ctx.scope.clone(),
642            request_id: ctx.request_id.clone(),
643            trace_id: ctx.trace_id.clone(),
644        };
645        let control = UserLifecycleControl {
646            ctx: &system_ctx,
647            ledger,
648            config,
649        };
650        self.bootstrap_with_control_events_inner(username, password, &control)
651    }
652
653    /// Backwards-compatible bootstrap entry point for older callers
654    /// that used to ask for an operator-owned first admin. Authorization
655    /// is now policy-first, so this creates the same ordinary platform
656    /// admin as [`Self::bootstrap`].
657    pub fn bootstrap_system_admin(
658        &self,
659        username: &str,
660        password: &str,
661    ) -> Result<BootstrapResult, AuthError> {
662        self.bootstrap(username, password)
663    }
664
665    fn bootstrap_unaudited(
666        &self,
667        username: &str,
668        password: &str,
669    ) -> Result<BootstrapResult, AuthError> {
670        self.bootstrap_unaudited_with_delivery(username, password, None)
671    }
672
673    fn bootstrap_unaudited_with_delivery(
674        &self,
675        username: &str,
676        password: &str,
677        mut certificate_delivery: Option<&mut dyn FnMut(&str) -> Result<(), AuthError>>,
678    ) -> Result<BootstrapResult, AuthError> {
679        // Atomic seal: only the first caller wins.
680        if self
681            .bootstrapped
682            .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
683            .is_err()
684        {
685            return Err(AuthError::Forbidden(
686                "bootstrap already completed — sealed permanently".to_string(),
687            ));
688        }
689
690        // Double-check users are actually empty (belt and suspenders).
691        {
692            let users = self.users.read().map_err(lock_err)?;
693            if !users.is_empty() {
694                return Err(AuthError::Forbidden(
695                    "bootstrap already completed — users exist".to_string(),
696                ));
697            }
698        }
699
700        let user = self.create_user_in_tenant_unaudited(None, username, password, Role::Admin)?;
701        let key = self.create_api_key_in_tenant_unaudited(
702            None,
703            username,
704            "bootstrap",
705            Role::Admin,
706            None,
707        )?;
708
709        // Token signing gets a fresh master secret. Preserve an existing
710        // certificate/passphrase seal instead of replacing the operator's key.
711        let credential_result = (|| -> Result<Option<String>, AuthError> {
712            let certificate = if let Some(ref pager) = self.pager {
713                let keypair = KeyPair::generate();
714                let mut vault = self.vault.write().map_err(lock_err)?;
715                let certificate = if vault.is_none() {
716                    let certificate = keypair.certificate_hex();
717                    if let Some(deliver) = certificate_delivery.as_mut() {
718                        deliver(&certificate)?;
719                    }
720                    *vault = Some(Vault::with_certificate_bytes(pager, &keypair.certificate)?);
721                    Some(certificate)
722                } else {
723                    self.provided_certificate.clone()
724                };
725                *self.keypair.write().map_err(lock_err)? = Some(keypair);
726                drop(vault);
727                self.ensure_vault_secret_key_result()?;
728                certificate
729            } else {
730                None
731            };
732            *self.enforcement_mode.write().map_err(lock_err)? =
733                PolicyEnforcementMode::default_fresh_bootstrap();
734            self.vault_kv.write().map_err(lock_err)?.insert(
735                "red.config.policy.enforcement_mode".into(),
736                PolicyEnforcementMode::default_fresh_bootstrap()
737                    .as_str()
738                    .into(),
739            );
740            self.persist_to_vault_result()?;
741            Ok(certificate)
742        })();
743        let certificate = match credential_result {
744            Ok(certificate) => certificate,
745            Err(err) => {
746                self.rollback_bootstrap(&UserId::from_parts(None, username));
747                return Err(err);
748            }
749        };
750
751        Ok(BootstrapResult {
752            user,
753            api_key: key,
754            certificate,
755        })
756    }
757
758    fn bootstrap_with_control_events_inner(
759        &self,
760        username: &str,
761        password: &str,
762        control: &UserLifecycleControl<'_>,
763    ) -> Result<BootstrapResult, AuthError> {
764        self.bootstrap_with_control_events_inner_and_delivery(username, password, control, None)
765    }
766
767    fn bootstrap_with_control_events_inner_and_delivery(
768        &self,
769        username: &str,
770        password: &str,
771        control: &UserLifecycleControl<'_>,
772        certificate_delivery: Option<&mut dyn FnMut(&str) -> Result<(), AuthError>>,
773    ) -> Result<BootstrapResult, AuthError> {
774        let id = UserId::from_parts(None, username);
775        match self.bootstrap_unaudited_with_delivery(username, password, certificate_delivery) {
776            Ok(result) => {
777                let event_result = self.emit_user_lifecycle_allowed(
778                    control,
779                    EventKind::UserCreate,
780                    "user.create",
781                    &id,
782                    user_control_fields(&id, Some(Role::Admin), Some(true), true),
783                );
784                if let Err(err) = event_result {
785                    self.rollback_bootstrap(&id);
786                    return Err(err);
787                }
788                Ok(result)
789            }
790            Err(err) => {
791                self.emit_user_lifecycle_outcome(
792                    control,
793                    if user_error_is_denied(&err) {
794                        Outcome::Denied
795                    } else {
796                        Outcome::Error
797                    },
798                    EventKind::UserCreate,
799                    "user.create",
800                    &id,
801                    Some(err.to_string()),
802                    user_control_fields(&id, Some(Role::Admin), Some(true), true),
803                );
804                Err(err)
805            }
806        }
807    }
808
809    /// Auto-bootstrap from environment variables if no users exist.
810    ///
811    /// Checks `REDDB_USERNAME` and `REDDB_PASSWORD`. If both are set and
812    /// the user store is empty, creates the first admin user automatically.
813    /// This mirrors the Docker pattern (`MYSQL_ROOT_PASSWORD`, etc.).
814    ///
815    /// Returns `Some(BootstrapResult)` if bootstrapped, `None` if skipped.
816    pub fn bootstrap_from_env(&self) -> Option<BootstrapResult> {
817        if !self.needs_bootstrap() {
818            return None;
819        }
820
821        let username = crate::utils::env_with_file_fallback("REDDB_USERNAME")?;
822        let password = crate::utils::env_with_file_fallback("REDDB_PASSWORD")?;
823
824        if username.is_empty() || password.is_empty() {
825            return None;
826        }
827        let mut certificate_output = if self.bootstrap_requires_certificate_delivery() {
828            let Some(path) = crate::utils::env_with_file_fallback("REDDB_BOOTSTRAP_CERT_OUT")
829            else {
830                tracing::error!(
831                    target: "reddb::security",
832                    "env bootstrap requires REDDB_BOOTSTRAP_CERT_OUT when the vault is enabled; refusing to emit the certificate to logs"
833                );
834                return None;
835            };
836            let mut options = std::fs::OpenOptions::new();
837            options.write(true).create_new(true);
838            #[cfg(unix)]
839            {
840                use std::os::unix::fs::OpenOptionsExt;
841                options.mode(0o600);
842            }
843            let file = match options.open(&path) {
844                Ok(file) => file,
845                Err(error) => {
846                    tracing::error!(
847                        target: "reddb::security",
848                        path = %path,
849                        error = %error,
850                        "env bootstrap certificate output is not writable"
851                    );
852                    return None;
853                }
854            };
855            Some((path, file))
856        } else {
857            None
858        };
859
860        let mut certificate_staged = false;
861        let bootstrap_result = match certificate_output.as_mut() {
862            Some((path, file)) => {
863                self.bootstrap_with_certificate_delivery(&username, &password, |certificate| {
864                    use std::io::Write;
865                    writeln!(file, "{certificate}").map_err(|error| {
866                        AuthError::Internal(format!(
867                            "write bootstrap certificate {}: {error}",
868                            path
869                        ))
870                    })?;
871                    file.sync_all().map_err(|error| {
872                        AuthError::Internal(format!("sync bootstrap certificate {}: {error}", path))
873                    })?;
874                    certificate_staged = true;
875                    Ok(())
876                })
877            }
878            None => self.bootstrap(&username, &password),
879        };
880
881        match bootstrap_result {
882            Ok(result) => {
883                // F-04: `username` is REDDB_USERNAME — operator-supplied
884                // (env), but still routed through the LogField escaper
885                // because env strings cross trust boundaries in some
886                // deployment models (k8s downward API, Vault sidecar,
887                // external secret operator). See ADR 0010.
888                tracing::info!(
889                    username = %reddb_wire::audit_safe_log_field(&username),
890                    "bootstrapped admin user from REDDB_USERNAME/REDDB_PASSWORD"
891                );
892                if !certificate_staged {
893                    if let (Some(cert), Some((path, file))) =
894                        (result.certificate.as_deref(), certificate_output.as_mut())
895                    {
896                        use std::io::Write;
897                        if let Err(error) = writeln!(file, "{cert}").and_then(|()| file.sync_all())
898                        {
899                            tracing::error!(
900                                target: "reddb::security",
901                                path = %path,
902                                error = %error,
903                                "could not write the vault certificate"
904                            );
905                            return None;
906                        }
907                    }
908                }
909                if let Some((path, _)) = certificate_output {
910                    tracing::warn!(
911                        target: "reddb::security",
912                        path = %path,
913                        "vault certificate written — save it: the ONLY way to unseal after a restart"
914                    );
915                }
916                Some(result)
917            }
918            Err(e) => {
919                let output_path = certificate_output.as_ref().map(|(path, _)| path.clone());
920                drop(certificate_output);
921                if let Some(path) = output_path {
922                    let _ = std::fs::remove_file(path);
923                }
924                tracing::error!(err = %e, "env bootstrap failed");
925                None
926            }
927        }
928    }
929
930    // -----------------------------------------------------------------
931    // Vault persistence
932    // -----------------------------------------------------------------
933
934    /// Persist the current auth state to the vault pages (if configured).
935    pub(crate) fn persist_to_vault_result(&self) -> Result<(), AuthError> {
936        let vault_guard = self.vault.read().unwrap_or_else(|e| e.into_inner());
937        if let (Some(ref vault), Some(ref pager)) = (&*vault_guard, &self.pager) {
938            let state = self.snapshot();
939            vault.save(pager, &state)?;
940            let hook = self
941                .vault_persist_hook
942                .read()
943                .unwrap_or_else(|e| e.into_inner())
944                .clone();
945            if let Some(hook) = hook {
946                hook();
947            }
948        }
949        Ok(())
950    }
951
952    /// Install the callback run after every successful vault save.
953    pub fn set_vault_persist_hook(&self, hook: Arc<dyn Fn() + Send + Sync>) {
954        *self
955            .vault_persist_hook
956            .write()
957            .unwrap_or_else(|e| e.into_inner()) = Some(hook);
958    }
959
960    /// Persist the current auth state to the vault pages (if configured).
961    ///
962    /// Legacy auth mutations still treat in-memory state as authoritative.
963    /// New secret-management paths use the `try_` methods below so callers
964    /// get a hard error if the vault write fails.
965    fn persist_to_vault(&self) {
966        if let Err(e) = self.persist_to_vault_result() {
967            tracing::error!(err = %e, "vault persist failed");
968            // Issue #205 — vault persist is the secret-rotation
969            // serialization point: when this fails, freshly rotated
970            // credentials live only in memory and a process restart
971            // loses them. Operator-grade event so the operator can
972            // intervene before the next restart.
973            crate::telemetry::operator_event::OperatorEvent::SecretRotationFailed {
974                secret_ref: "auth_vault".to_string(),
975                error: e.to_string(),
976            }
977            .emit_global();
978        }
979    }
980
981    /// True when this store has an encrypted vault and pager wired in.
982    pub fn is_vault_backed(&self) -> bool {
983        self.pager.is_some()
984            && self
985                .vault
986                .read()
987                .map(|guard| guard.is_some())
988                .unwrap_or(false)
989    }
990
991    /// Whether first-admin bootstrap must mint and deliver a new certificate
992    /// before the vault can be activated. Passphrase-backed and already
993    /// credentialed vaults preserve their existing seal and need no output.
994    pub fn bootstrap_requires_certificate_delivery(&self) -> bool {
995        self.pager.is_some()
996            && self
997                .vault
998                .read()
999                .map(|vault| vault.is_none())
1000                .unwrap_or(true)
1001    }
1002
1003    // -----------------------------------------------------------------
1004    // Vault KV — encrypted key-value store for arbitrary secrets
1005    // -----------------------------------------------------------------
1006
1007    /// Read a value from the vault KV store. Returns `None` if not set.
1008    pub fn vault_kv_get(&self, key: &str) -> Option<String> {
1009        self.vault_kv
1010            .read()
1011            .ok()
1012            .and_then(|kv| kv.get(key).cloned())
1013    }
1014
1015    /// Snapshot vault KV values for statement-local secret resolution.
1016    pub fn vault_kv_snapshot(&self) -> HashMap<String, String> {
1017        self.vault_kv
1018            .read()
1019            .map(|kv| kv.clone())
1020            .unwrap_or_default()
1021    }
1022
1023    /// Export vault KV as an encrypted logical blob for JSONL dump/restore.
1024    /// Returns `None` when the vault has no KV entries.
1025    pub fn vault_kv_export_encrypted(&self) -> Result<Option<String>, AuthError> {
1026        if !self.is_vault_backed() {
1027            return Err(AuthError::Forbidden(
1028                "vault KV export requires an enabled, unsealed vault".to_string(),
1029            ));
1030        }
1031        let kv = self.vault_kv_snapshot();
1032        if kv.is_empty() {
1033            return Ok(None);
1034        }
1035
1036        let vault_guard = self.vault.read().map_err(lock_err)?;
1037        let vault = vault_guard.as_ref().ok_or_else(|| {
1038            AuthError::Forbidden("vault KV export requires an enabled, unsealed vault".to_string())
1039        })?;
1040        let state = VaultState {
1041            users: Vec::new(),
1042            api_keys: Vec::new(),
1043            bootstrapped: false,
1044            master_secret: None,
1045            kv,
1046        };
1047        Ok(Some(vault.seal_logical_export(&state)?))
1048    }
1049
1050    /// Merge imported vault KV entries and fail if the encrypted vault
1051    /// write cannot be made durable.
1052    pub fn vault_kv_try_import(
1053        &self,
1054        entries: HashMap<String, String>,
1055    ) -> Result<usize, AuthError> {
1056        if !self.is_vault_backed() {
1057            return Err(AuthError::Forbidden(
1058                "vault KV import requires an enabled, unsealed vault".to_string(),
1059            ));
1060        }
1061        if entries.is_empty() {
1062            return Ok(0);
1063        }
1064
1065        let mut previous = HashMap::new();
1066        {
1067            let mut kv = self.vault_kv.write().map_err(lock_err)?;
1068            for (key, value) in &entries {
1069                previous.insert(key.clone(), kv.insert(key.clone(), value.clone()));
1070            }
1071        }
1072
1073        if let Err(err) = self.persist_to_vault_result() {
1074            if let Ok(mut kv) = self.vault_kv.write() {
1075                for (key, old) in previous {
1076                    match old {
1077                        Some(value) => {
1078                            kv.insert(key, value);
1079                        }
1080                        None => {
1081                            kv.remove(&key);
1082                        }
1083                    }
1084                }
1085            }
1086            return Err(err);
1087        }
1088
1089        Ok(entries.len())
1090    }
1091
1092    /// Import false placeholders for secrets whose encrypted payload
1093    /// could not be decrypted during logical restore.
1094    pub fn vault_kv_try_import_placeholders(&self, keys: &[String]) -> Result<usize, AuthError> {
1095        let entries = keys
1096            .iter()
1097            .map(|key| (key.clone(), "false".to_string()))
1098            .collect();
1099        self.vault_kv_try_import(entries)
1100    }
1101
1102    /// Write a value to the vault KV store, persisting to disk.
1103    pub fn vault_kv_set(&self, key: String, value: String) {
1104        if let Ok(mut kv) = self.vault_kv.write() {
1105            kv.insert(key, value);
1106        }
1107        self.persist_to_vault();
1108    }
1109
1110    /// Write a value to the vault KV store and fail if the vault write
1111    /// cannot be made durable.
1112    pub fn vault_kv_try_set(&self, key: String, value: String) -> Result<(), AuthError> {
1113        if !self.is_vault_backed() {
1114            return Err(AuthError::Forbidden(
1115                "SET SECRET requires an enabled, unsealed vault".to_string(),
1116            ));
1117        }
1118
1119        let previous = {
1120            let mut kv = self.vault_kv.write().map_err(lock_err)?;
1121            kv.insert(key.clone(), value)
1122        };
1123
1124        if let Err(err) = self.persist_to_vault_result() {
1125            if let Ok(mut kv) = self.vault_kv.write() {
1126                match previous {
1127                    Some(value) => {
1128                        kv.insert(key, value);
1129                    }
1130                    None => {
1131                        kv.remove(&key);
1132                    }
1133                }
1134            }
1135            return Err(err);
1136        }
1137
1138        Ok(())
1139    }
1140
1141    /// Delete a value from the vault KV store. Returns true if it existed.
1142    pub fn vault_kv_delete(&self, key: &str) -> bool {
1143        let existed = self
1144            .vault_kv
1145            .write()
1146            .map(|mut kv| kv.remove(key).is_some())
1147            .unwrap_or(false);
1148        if existed {
1149            self.persist_to_vault();
1150        }
1151        existed
1152    }
1153
1154    /// Delete a value from the vault KV store and fail if the vault write
1155    /// cannot be made durable.
1156    pub fn vault_kv_try_delete(&self, key: &str) -> Result<bool, AuthError> {
1157        if !self.is_vault_backed() {
1158            return Err(AuthError::Forbidden(
1159                "DELETE SECRET requires an enabled, unsealed vault".to_string(),
1160            ));
1161        }
1162
1163        let removed = {
1164            let mut kv = self.vault_kv.write().map_err(lock_err)?;
1165            kv.remove(key)
1166        };
1167
1168        if removed.is_none() {
1169            return Ok(false);
1170        }
1171
1172        if let Err(err) = self.persist_to_vault_result() {
1173            if let Ok(mut kv) = self.vault_kv.write() {
1174                if let Some(value) = removed {
1175                    kv.insert(key.to_string(), value);
1176                }
1177            }
1178            return Err(err);
1179        }
1180
1181        Ok(true)
1182    }
1183
1184    /// List all keys in the vault KV store.
1185    pub fn vault_kv_keys(&self) -> Vec<String> {
1186        self.vault_kv
1187            .read()
1188            .map(|kv| kv.keys().cloned().collect())
1189            .unwrap_or_default()
1190    }
1191
1192    // -----------------------------------------------------------------
1193    // Plain KV — non-encrypted user key-value store (#1602)
1194    //
1195    // A sibling to the vault KV above, but stored in its own flat-map
1196    // with no encryption. Backs `$kv.*` / `SET KV` / `DELETE KV` and is
1197    // gated by `kv:read` / `kv:write` at the runtime layer. Kept fully
1198    // separate from `vault_kv` (secrets) and the config store.
1199    // -----------------------------------------------------------------
1200
1201    /// Read a value from the plain KV store. Returns `None` if not set.
1202    pub fn plain_kv_get(&self, key: &str) -> Option<String> {
1203        self.plain_kv
1204            .read()
1205            .ok()
1206            .and_then(|kv| kv.get(key).cloned())
1207    }
1208
1209    /// Snapshot plain KV values for statement-local resolution.
1210    pub fn plain_kv_snapshot(&self) -> HashMap<String, String> {
1211        self.plain_kv
1212            .read()
1213            .map(|kv| kv.clone())
1214            .unwrap_or_default()
1215    }
1216
1217    /// Write a value to the plain KV store.
1218    pub fn plain_kv_set(&self, key: String, value: String) {
1219        if let Ok(mut kv) = self.plain_kv.write() {
1220            kv.insert(key, value);
1221        }
1222    }
1223
1224    /// Delete a value from the plain KV store. Returns true if it existed.
1225    pub fn plain_kv_delete(&self, key: &str) -> bool {
1226        self.plain_kv
1227            .write()
1228            .map(|mut kv| kv.remove(key).is_some())
1229            .unwrap_or(false)
1230    }
1231
1232    /// List all keys in the plain KV store.
1233    pub fn plain_kv_keys(&self) -> Vec<String> {
1234        self.plain_kv
1235            .read()
1236            .map(|kv| kv.keys().cloned().collect())
1237            .unwrap_or_default()
1238    }
1239
1240    /// Convenience: get the 32-byte secret key for Value::Secret encryption.
1241    /// Generated on first boot and stored at `red.secret.aes_key`.
1242    pub fn vault_secret_key(&self) -> Option<[u8; 32]> {
1243        let hex_str = self.vault_kv_get("red.secret.aes_key")?;
1244        let bytes = hex::decode(hex_str).ok()?;
1245        if bytes.len() == 32 {
1246            let mut key = [0u8; 32];
1247            key.copy_from_slice(&bytes);
1248            Some(key)
1249        } else {
1250            None
1251        }
1252    }
1253
1254    /// Generate and store the AES-256 secret key on first boot if not present.
1255    pub fn ensure_vault_secret_key(&self) {
1256        if let Err(err) = self.ensure_vault_secret_key_result() {
1257            tracing::error!(error = %err, "vault secret key initialization failed");
1258        }
1259    }
1260
1261    pub(crate) fn ensure_vault_secret_key_result(&self) -> Result<(), AuthError> {
1262        let _guard = self.secret_key_init.lock().map_err(lock_err)?;
1263        if self.vault_secret_key().is_some() {
1264            return Ok(());
1265        }
1266        if self.vault_kv_get("red.secret.aes_key").is_some() {
1267            return Err(AuthError::Internal(
1268                "stored vault secret key is invalid".into(),
1269            ));
1270        }
1271        let value = hex::encode(random_bytes(32));
1272        if self.is_vault_backed() {
1273            self.vault_kv_try_set("red.secret.aes_key".into(), value)
1274        } else {
1275            self.vault_kv
1276                .write()
1277                .map_err(lock_err)?
1278                .insert("red.secret.aes_key".into(), value);
1279            Ok(())
1280        }
1281    }
1282
1283    /// Take a snapshot of the current auth state for vault serialization.
1284    fn snapshot(&self) -> VaultState {
1285        let users_guard = self.users.read().unwrap_or_else(|e| e.into_inner());
1286        let users: Vec<User> = users_guard.values().cloned().collect();
1287
1288        // Collect (owner UserId, api_key) pairs from all users so a
1289        // tenant-scoped owner can be reattached on restore.
1290        let mut api_keys = Vec::new();
1291        for user in &users {
1292            let owner = UserId::from_parts(user.tenant_id.as_deref(), &user.username);
1293            for key in &user.api_keys {
1294                api_keys.push((owner.clone(), key.clone()));
1295            }
1296        }
1297
1298        // Include the master secret if a keypair is loaded.
1299        let master_secret = self
1300            .keypair
1301            .read()
1302            .ok()
1303            .and_then(|guard| guard.as_ref().map(|kp| kp.master_secret.clone()));
1304
1305        let kv = self.vault_kv.read().map(|m| m.clone()).unwrap_or_default();
1306
1307        VaultState {
1308            users,
1309            api_keys,
1310            bootstrapped: self.bootstrapped.load(Ordering::Acquire),
1311            master_secret,
1312            kv,
1313        }
1314    }
1315
1316    /// Restore the in-memory auth state from a vault snapshot.
1317    fn restore_from_vault(&mut self, state: VaultState) {
1318        // Restore bootstrap seal.
1319        if state.bootstrapped {
1320            self.bootstrapped.store(true, Ordering::Release);
1321        }
1322
1323        // Restore keypair from master secret (if present).
1324        if let Some(secret) = state.master_secret {
1325            let kp = KeyPair::from_master_secret(secret);
1326            if let Ok(mut guard) = self.keypair.write() {
1327                *guard = Some(kp);
1328            }
1329        }
1330
1331        // Restore KV store.
1332        if let Ok(mut kv) = self.vault_kv.write() {
1333            *kv = state.kv;
1334        }
1335
1336        // Restore users.
1337        let mut users = self.users.write().unwrap_or_else(|e| e.into_inner());
1338        let mut idx = self
1339            .api_key_index
1340            .write()
1341            .unwrap_or_else(|e| e.into_inner());
1342
1343        for mut user in state.users {
1344            let id = UserId::from_parts(user.tenant_id.as_deref(), &user.username);
1345            // A vault written before keys were hashed at rest holds the
1346            // secret itself. Hash it on the way in; the next persist
1347            // rewrites the line and the secret is gone from disk.
1348            for key in &mut user.api_keys {
1349                if !key.key.starts_with("rkh_") {
1350                    key.key = api_key_credential_id(&key.key);
1351                }
1352            }
1353            // Register API keys in the index.
1354            for key in &user.api_keys {
1355                idx.insert(key.key.clone(), (id.clone(), key.role));
1356            }
1357            users.insert(id, user);
1358        }
1359        drop(idx);
1360        drop(users);
1361
1362        self.rehydrate_acl();
1363        self.rehydrate_iam();
1364    }
1365
1366    // -----------------------------------------------------------------
1367    // User management
1368    // -----------------------------------------------------------------
1369
1370    /// Create a new platform-scoped user (`tenant_id = None`).
1371    ///
1372    /// For tenant-scoped creation, use [`Self::create_user_in_tenant`].
1373    pub fn create_user(
1374        &self,
1375        username: &str,
1376        password: &str,
1377        role: Role,
1378    ) -> Result<User, AuthError> {
1379        self.create_user_in_tenant(None, username, password, role)
1380    }
1381
1382    pub fn create_user_with_control_events(
1383        &self,
1384        username: &str,
1385        password: &str,
1386        role: Role,
1387        ctx: &ControlEventCtx<'_>,
1388        ledger: &dyn ControlEventLedger,
1389        config: ControlEventConfig,
1390    ) -> Result<User, AuthError> {
1391        self.create_user_in_tenant_with_control_events(
1392            None, username, password, role, ctx, ledger, config,
1393        )
1394    }
1395
1396    /// Create a user under the given tenant scope. `tenant_id == None`
1397    /// produces a platform-wide user. `(tenant, username)` is the
1398    /// uniqueness key — the same `username` may exist independently
1399    /// under multiple tenants.
1400    pub fn create_user_in_tenant(
1401        &self,
1402        tenant_id: Option<&str>,
1403        username: &str,
1404        password: &str,
1405        role: Role,
1406    ) -> Result<User, AuthError> {
1407        if let Some(configured) = self.configured_control_events() {
1408            let ctx = default_user_lifecycle_ctx();
1409            let control = UserLifecycleControl {
1410                ctx: &ctx,
1411                ledger: configured.ledger.as_ref(),
1412                config: configured.config,
1413            };
1414            self.create_user_in_tenant_controlled(tenant_id, username, password, role, &control)
1415        } else {
1416            self.create_user_in_tenant_unaudited(tenant_id, username, password, role)
1417        }
1418    }
1419
1420    #[allow(clippy::too_many_arguments)]
1421    pub fn create_user_in_tenant_with_control_events(
1422        &self,
1423        tenant_id: Option<&str>,
1424        username: &str,
1425        password: &str,
1426        role: Role,
1427        ctx: &ControlEventCtx<'_>,
1428        ledger: &dyn ControlEventLedger,
1429        config: ControlEventConfig,
1430    ) -> Result<User, AuthError> {
1431        let control = UserLifecycleControl {
1432            ctx,
1433            ledger,
1434            config,
1435        };
1436        self.create_user_in_tenant_controlled(tenant_id, username, password, role, &control)
1437    }
1438
1439    pub fn create_admin_user(
1440        &self,
1441        username: &str,
1442        password: &str,
1443        role: Role,
1444        tenant_id: Option<&str>,
1445    ) -> Result<User, AuthError> {
1446        if let Some(configured) = self.configured_control_events() {
1447            let ctx = default_user_lifecycle_ctx();
1448            let control = UserLifecycleControl {
1449                ctx: &ctx,
1450                ledger: configured.ledger.as_ref(),
1451                config: configured.config,
1452            };
1453            self.create_user_in_tenant_controlled(tenant_id, username, password, role, &control)
1454        } else {
1455            self.create_user_in_tenant_unaudited(tenant_id, username, password, role)
1456        }
1457    }
1458
1459    fn create_user_in_tenant_unaudited(
1460        &self,
1461        tenant_id: Option<&str>,
1462        username: &str,
1463        password: &str,
1464        role: Role,
1465    ) -> Result<User, AuthError> {
1466        let id = UserId::from_parts(tenant_id, username);
1467        let mut users = self.users.write().map_err(lock_err)?;
1468        if users.contains_key(&id) {
1469            return Err(AuthError::UserExists(id.to_string()));
1470        }
1471
1472        let now = now_ms();
1473        let user = User {
1474            username: username.to_string(),
1475            tenant_id: tenant_id.map(|s| s.to_string()),
1476            password_hash: hash_password(password),
1477            scram_verifier: Some(make_scram_verifier(password)),
1478            role,
1479            api_keys: Vec::new(),
1480            created_at: now,
1481            updated_at: now,
1482            enabled: true,
1483        };
1484        users.insert(id, user.clone());
1485        drop(users); // release lock before vault I/O
1486        self.persist_to_vault();
1487        Ok(user)
1488    }
1489
1490    fn create_user_in_tenant_controlled(
1491        &self,
1492        tenant_id: Option<&str>,
1493        username: &str,
1494        password: &str,
1495        role: Role,
1496        control: &UserLifecycleControl<'_>,
1497    ) -> Result<User, AuthError> {
1498        let id = UserId::from_parts(tenant_id, username);
1499        match self.create_user_in_tenant_unaudited(tenant_id, username, password, role) {
1500            Ok(user) => {
1501                if let Err(err) = self.emit_user_lifecycle_allowed(
1502                    control,
1503                    EventKind::UserCreate,
1504                    "user.create",
1505                    &id,
1506                    user_control_fields(&id, Some(role), Some(true), true),
1507                ) {
1508                    self.rollback_create_user(&id);
1509                    return Err(err);
1510                }
1511                Ok(user)
1512            }
1513            Err(err) => {
1514                self.emit_user_lifecycle_outcome(
1515                    control,
1516                    if user_error_is_denied(&err) {
1517                        Outcome::Denied
1518                    } else {
1519                        Outcome::Error
1520                    },
1521                    EventKind::UserCreate,
1522                    "user.create",
1523                    &id,
1524                    Some(err.to_string()),
1525                    user_control_fields(&id, Some(role), Some(true), true),
1526                );
1527                Err(err)
1528            }
1529        }
1530    }
1531
1532    /// Look up a user's SCRAM verifier by full `UserId`.
1533    ///
1534    /// The wire handshake passes the tenant resolved from the session
1535    /// (or `None` for the bootstrap admin) so cross-tenant collisions
1536    /// never authenticate the wrong identity.
1537    pub fn lookup_scram_verifier(&self, id: &UserId) -> Option<crate::auth::scram::ScramVerifier> {
1538        // Synthetic platform-owner principal must never authenticate.
1539        if crate::auth::self_lock_guard::is_synthetic_principal(&id.username) {
1540            return None;
1541        }
1542        let users = self.users.read().ok()?;
1543        // A disabled account keeps its verifier (re-enable restores it)
1544        // but must not authenticate; returning `None` here makes the
1545        // handshake use the dummy verifier, so timing stays uniform.
1546        users
1547            .get(id)
1548            .filter(|u| u.enabled)
1549            .and_then(|u| u.scram_verifier.clone())
1550    }
1551
1552    /// Backwards-compatible shim for the v2 wire bootstrap path: looks
1553    /// up a user by username assuming the platform (`tenant=None`)
1554    /// scope. Use this only where the handshake hasn't yet learned the
1555    /// caller's tenant.
1556    pub fn lookup_scram_verifier_global(
1557        &self,
1558        username: &str,
1559    ) -> Option<crate::auth::scram::ScramVerifier> {
1560        self.lookup_scram_verifier(&UserId::platform(username))
1561    }
1562
1563    /// Return all users (password hashes redacted).
1564    ///
1565    /// The synthetic [`crate::auth::self_lock_guard::PLATFORM_OWNER_USERNAME`]
1566    /// principal is filtered out — it is a policy-graph anchor, not an
1567    /// operator-visible account.
1568    pub fn list_users(&self) -> Vec<User> {
1569        let users = match self.users.read() {
1570            Ok(g) => g,
1571            Err(_) => return Vec::new(),
1572        };
1573        users
1574            .values()
1575            .filter(|u| !crate::auth::self_lock_guard::is_synthetic_principal(&u.username))
1576            .map(|u| User {
1577                password_hash: String::new(), // redacted
1578                ..u.clone()
1579            })
1580            .collect()
1581    }
1582
1583    /// Return users restricted to a tenant scope.
1584    ///
1585    /// `tenant_filter`:
1586    ///   - `None` listing in `Some(None)` — only platform users
1587    ///   - `Some(Some("acme"))` — only users in tenant `acme`
1588    ///   - `None` argument — all users (admin-only callers)
1589    pub fn list_users_scoped(&self, tenant_filter: Option<Option<&str>>) -> Vec<User> {
1590        let users = match self.users.read() {
1591            Ok(g) => g,
1592            Err(_) => return Vec::new(),
1593        };
1594        users
1595            .values()
1596            .filter(|u| match tenant_filter {
1597                None => true,
1598                Some(t) => u.tenant_id.as_deref() == t,
1599            })
1600            .filter(|u| !crate::auth::self_lock_guard::is_synthetic_principal(&u.username))
1601            .map(|u| User {
1602                password_hash: String::new(), // redacted
1603                ..u.clone()
1604            })
1605            .collect()
1606    }
1607
1608    /// Resource shape used by IAM policies that govern user lifecycle
1609    /// mutations. Platform users are addressed as `user:<username>`;
1610    /// tenant users are addressed as `user:tenant/<tenant>/<username>`
1611    /// by the existing policy resource qualifier.
1612    pub fn user_lifecycle_resource(uid: &UserId) -> ResourceRef {
1613        let resource = ResourceRef::new("user", uid.username.clone());
1614        match &uid.tenant {
1615            Some(tenant) => resource.with_tenant(tenant.clone()),
1616            None => resource,
1617        }
1618    }
1619
1620    pub fn eval_context_for_principal(
1621        &self,
1622        principal: &UserId,
1623        role: Role,
1624        current_tenant: Option<String>,
1625    ) -> EvalContext {
1626        EvalContext {
1627            principal_tenant: principal.tenant.clone(),
1628            current_tenant,
1629            peer_ip: None,
1630            mfa_present: false,
1631            now_ms: now_ms(),
1632            principal_is_admin_role: role == Role::Admin,
1633            principal_is_platform_scoped: principal.tenant.is_none(),
1634        }
1635    }
1636
1637    /// Policy gate for user lifecycle mutations.
1638    ///
1639    /// This is intentionally separate from the store mutation methods:
1640    /// bootstrap and manifest loading can still seed users directly,
1641    /// while public surfaces must authorize `user:*` before calling the
1642    /// mutator. Explicit Deny wins even in `LegacyRbac` mode.
1643    pub fn check_user_lifecycle_authz(
1644        &self,
1645        actor: &UserId,
1646        actor_role: Role,
1647        action: &str,
1648        target: &UserId,
1649    ) -> bool {
1650        let resource = Self::user_lifecycle_resource(target);
1651        let ctx = self.eval_context_for_principal(actor, actor_role, target.tenant.clone());
1652        if actor.tenant.is_some() && actor.tenant != target.tenant {
1653            return false;
1654        }
1655        if self.has_explicit_user_lifecycle_deny(actor, actor_role, action, target) {
1656            return false;
1657        }
1658        actor_role.can_admin()
1659            || self.check_policy_authz_with_role(actor, action, &resource, &ctx, actor_role)
1660    }
1661
1662    /// Returns `true` only when an IAM policy explicitly denies the
1663    /// action on the target. `DefaultDeny` (no matching policy) is
1664    /// treated as permitted, so this is safe to call after the caller
1665    /// has already verified the actor's role — it only blocks protected
1666    /// principals (e.g. the cloud-preset `red_admin` guardrail).
1667    pub fn has_explicit_user_lifecycle_deny(
1668        &self,
1669        actor: &UserId,
1670        actor_role: Role,
1671        action: &str,
1672        target: &UserId,
1673    ) -> bool {
1674        let resource = Self::user_lifecycle_resource(target);
1675        let ctx = self.eval_context_for_principal(actor, actor_role, target.tenant.clone());
1676        let pols = self.effective_policies(actor);
1677        let refs: Vec<&Policy> = pols.iter().map(|p| p.as_ref()).collect();
1678        matches!(
1679            iam_policies::evaluate(&refs, action, &resource, &ctx),
1680            iam_policies::Decision::Deny { .. }
1681        )
1682    }
1683
1684    pub fn get_user(&self, tenant_id: Option<&str>, username: &str) -> Option<User> {
1685        let id = UserId::from_parts(tenant_id, username);
1686        self.get_user_cloned(&id).map(|u| User {
1687            password_hash: String::new(),
1688            ..u
1689        })
1690    }
1691
1692    /// Delete a platform-scoped user (`tenant_id = None`) and revoke
1693    /// all of their API keys + sessions.
1694    ///
1695    /// For tenant-scoped deletes, use [`Self::delete_user_in_tenant`].
1696    pub fn delete_user(&self, username: &str) -> Result<(), AuthError> {
1697        self.delete_user_in_tenant(None, username)
1698    }
1699
1700    pub fn delete_user_with_control_events(
1701        &self,
1702        username: &str,
1703        ctx: &ControlEventCtx<'_>,
1704        ledger: &dyn ControlEventLedger,
1705        config: ControlEventConfig,
1706    ) -> Result<(), AuthError> {
1707        self.delete_user_in_tenant_with_control_events(None, username, ctx, ledger, config)
1708    }
1709
1710    /// Delete a user identified by `(tenant_id, username)` and revoke
1711    /// all of their API keys + sessions.
1712    pub fn delete_user_in_tenant(
1713        &self,
1714        tenant_id: Option<&str>,
1715        username: &str,
1716    ) -> Result<(), AuthError> {
1717        if let Some(configured) = self.configured_control_events() {
1718            let ctx = default_user_lifecycle_ctx();
1719            let control = UserLifecycleControl {
1720                ctx: &ctx,
1721                ledger: configured.ledger.as_ref(),
1722                config: configured.config,
1723            };
1724            self.delete_user_in_tenant_controlled(tenant_id, username, &control)
1725        } else {
1726            self.delete_user_in_tenant_unaudited(tenant_id, username)
1727        }
1728    }
1729
1730    pub fn delete_user_in_tenant_with_control_events(
1731        &self,
1732        tenant_id: Option<&str>,
1733        username: &str,
1734        ctx: &ControlEventCtx<'_>,
1735        ledger: &dyn ControlEventLedger,
1736        config: ControlEventConfig,
1737    ) -> Result<(), AuthError> {
1738        let control = UserLifecycleControl {
1739            ctx,
1740            ledger,
1741            config,
1742        };
1743        self.delete_user_in_tenant_controlled(tenant_id, username, &control)
1744    }
1745
1746    fn delete_user_in_tenant_unaudited(
1747        &self,
1748        tenant_id: Option<&str>,
1749        username: &str,
1750    ) -> Result<(), AuthError> {
1751        let id = UserId::from_parts(tenant_id, username);
1752        let mut users = self.users.write().map_err(lock_err)?;
1753        let user = users
1754            .remove(&id)
1755            .ok_or_else(|| AuthError::UserNotFound(id.to_string()))?;
1756
1757        // Remove API key index entries.
1758        if let Ok(mut idx) = self.api_key_index.write() {
1759            for api_key in &user.api_keys {
1760                idx.remove(&api_key.key);
1761            }
1762        }
1763
1764        self.purge_sessions_for(&id);
1765
1766        self.persist_to_vault();
1767        Ok(())
1768    }
1769
1770    fn delete_user_in_tenant_controlled(
1771        &self,
1772        tenant_id: Option<&str>,
1773        username: &str,
1774        control: &UserLifecycleControl<'_>,
1775    ) -> Result<(), AuthError> {
1776        let id = UserId::from_parts(tenant_id, username);
1777        let rollback = self.user_delete_rollback_snapshot(&id, tenant_id, username);
1778        match self.delete_user_in_tenant_unaudited(tenant_id, username) {
1779            Ok(()) => {
1780                if let Err(err) = self.emit_user_lifecycle_allowed(
1781                    control,
1782                    EventKind::UserDelete,
1783                    "user.delete",
1784                    &id,
1785                    user_control_fields(&id, rollback.as_ref().map(|r| r.0.role), None, false),
1786                ) {
1787                    if let Some((user, sessions)) = rollback {
1788                        self.restore_deleted_user(&id, user, sessions);
1789                    }
1790                    return Err(err);
1791                }
1792                Ok(())
1793            }
1794            Err(err) => {
1795                self.emit_user_lifecycle_outcome(
1796                    control,
1797                    if user_error_is_denied(&err) {
1798                        Outcome::Denied
1799                    } else {
1800                        Outcome::Error
1801                    },
1802                    EventKind::UserDelete,
1803                    "user.delete",
1804                    &id,
1805                    Some(err.to_string()),
1806                    user_control_fields(&id, rollback.as_ref().map(|r| r.0.role), None, false),
1807                );
1808                Err(err)
1809            }
1810        }
1811    }
1812
1813    /// Change password (requires the old password). Defaults to
1814    /// platform tenant; use [`Self::change_password_in_tenant`] for
1815    /// scoped users.
1816    pub fn change_password(
1817        &self,
1818        username: &str,
1819        old_password: &str,
1820        new_password: &str,
1821    ) -> Result<(), AuthError> {
1822        self.change_password_in_tenant(None, username, old_password, new_password)
1823    }
1824
1825    pub fn change_password_with_control_events(
1826        &self,
1827        username: &str,
1828        old_password: &str,
1829        new_password: &str,
1830        ctx: &ControlEventCtx<'_>,
1831        ledger: &dyn ControlEventLedger,
1832        config: ControlEventConfig,
1833    ) -> Result<(), AuthError> {
1834        self.change_password_in_tenant_with_control_events(
1835            None,
1836            username,
1837            old_password,
1838            new_password,
1839            ctx,
1840            ledger,
1841            config,
1842        )
1843    }
1844
1845    #[allow(clippy::too_many_arguments)]
1846    pub fn change_password_in_tenant(
1847        &self,
1848        tenant_id: Option<&str>,
1849        username: &str,
1850        old_password: &str,
1851        new_password: &str,
1852    ) -> Result<(), AuthError> {
1853        if let Some(configured) = self.configured_control_events() {
1854            let ctx = default_user_lifecycle_ctx();
1855            let control = UserLifecycleControl {
1856                ctx: &ctx,
1857                ledger: configured.ledger.as_ref(),
1858                config: configured.config,
1859            };
1860            self.change_password_in_tenant_controlled(
1861                tenant_id,
1862                username,
1863                old_password,
1864                new_password,
1865                &control,
1866            )
1867        } else {
1868            self.change_password_in_tenant_unaudited(
1869                tenant_id,
1870                username,
1871                old_password,
1872                new_password,
1873            )
1874        }
1875    }
1876
1877    #[allow(clippy::too_many_arguments)]
1878    pub fn change_password_in_tenant_with_control_events(
1879        &self,
1880        tenant_id: Option<&str>,
1881        username: &str,
1882        old_password: &str,
1883        new_password: &str,
1884        ctx: &ControlEventCtx<'_>,
1885        ledger: &dyn ControlEventLedger,
1886        config: ControlEventConfig,
1887    ) -> Result<(), AuthError> {
1888        let control = UserLifecycleControl {
1889            ctx,
1890            ledger,
1891            config,
1892        };
1893        self.change_password_in_tenant_controlled(
1894            tenant_id,
1895            username,
1896            old_password,
1897            new_password,
1898            &control,
1899        )
1900    }
1901
1902    fn change_password_in_tenant_unaudited(
1903        &self,
1904        tenant_id: Option<&str>,
1905        username: &str,
1906        old_password: &str,
1907        new_password: &str,
1908    ) -> Result<(), AuthError> {
1909        let id = UserId::from_parts(tenant_id, username);
1910        let mut users = self.users.write().map_err(lock_err)?;
1911        let user = users
1912            .get_mut(&id)
1913            .ok_or_else(|| AuthError::UserNotFound(id.to_string()))?;
1914
1915        if !verify_password(old_password, &user.password_hash) {
1916            return Err(AuthError::InvalidCredentials);
1917        }
1918
1919        user.password_hash = hash_password(new_password);
1920        user.scram_verifier = Some(make_scram_verifier(new_password));
1921        user.updated_at = now_ms();
1922        drop(users); // release lock before vault I/O
1923        self.persist_to_vault();
1924        Ok(())
1925    }
1926
1927    /// Administrative password reset (`ALTER USER … PASSWORD '…'`): no
1928    /// old-password check. Rehashes, regenerates the SCRAM verifier and
1929    /// revokes every live session of the account so a rotated credential
1930    /// cannot keep an existing session alive. Callers gate authorization.
1931    pub fn set_password_by_admin(&self, id: &UserId, new_password: &str) -> Result<(), AuthError> {
1932        if new_password.is_empty() {
1933            return Err(AuthError::Forbidden("password cannot be empty".to_string()));
1934        }
1935        {
1936            let mut users = self.users.write().map_err(lock_err)?;
1937            let user = users
1938                .get_mut(id)
1939                .ok_or_else(|| AuthError::UserNotFound(id.to_string()))?;
1940            user.password_hash = hash_password(new_password);
1941            user.scram_verifier = Some(make_scram_verifier(new_password));
1942            user.updated_at = now_ms();
1943        }
1944        self.purge_sessions_for(id);
1945        self.persist_to_vault();
1946        Ok(())
1947    }
1948
1949    fn change_password_in_tenant_controlled(
1950        &self,
1951        tenant_id: Option<&str>,
1952        username: &str,
1953        old_password: &str,
1954        new_password: &str,
1955        control: &UserLifecycleControl<'_>,
1956    ) -> Result<(), AuthError> {
1957        let id = UserId::from_parts(tenant_id, username);
1958        let previous = self.get_user_cloned(&id);
1959        match self.change_password_in_tenant_unaudited(
1960            tenant_id,
1961            username,
1962            old_password,
1963            new_password,
1964        ) {
1965            Ok(()) => {
1966                if let Err(err) = self.emit_user_lifecycle_allowed(
1967                    control,
1968                    EventKind::UserUpdate,
1969                    "user.update",
1970                    &id,
1971                    user_control_fields(
1972                        &id,
1973                        previous.as_ref().map(|u| u.role),
1974                        previous.as_ref().map(|u| u.enabled),
1975                        true,
1976                    ),
1977                ) {
1978                    self.restore_user_snapshot(&id, previous);
1979                    return Err(err);
1980                }
1981                Ok(())
1982            }
1983            Err(err) => {
1984                self.emit_user_lifecycle_outcome(
1985                    control,
1986                    if user_error_is_denied(&err) {
1987                        Outcome::Denied
1988                    } else {
1989                        Outcome::Error
1990                    },
1991                    EventKind::UserUpdate,
1992                    "user.update",
1993                    &id,
1994                    Some(err.to_string()),
1995                    user_control_fields(
1996                        &id,
1997                        previous.as_ref().map(|u| u.role),
1998                        previous.as_ref().map(|u| u.enabled),
1999                        true,
2000                    ),
2001                );
2002                Err(err)
2003            }
2004        }
2005    }
2006
2007    /// Change a user's role (admin-only operation). Defaults to platform
2008    /// tenant; use [`Self::change_role_in_tenant`] for scoped users.
2009    pub fn change_role(&self, username: &str, new_role: Role) -> Result<(), AuthError> {
2010        self.change_role_in_tenant(None, username, new_role)
2011    }
2012
2013    pub fn change_role_in_tenant(
2014        &self,
2015        tenant_id: Option<&str>,
2016        username: &str,
2017        new_role: Role,
2018    ) -> Result<(), AuthError> {
2019        if let Some(configured) = self.configured_control_events() {
2020            let ctx = default_user_lifecycle_ctx();
2021            let control = UserLifecycleControl {
2022                ctx: &ctx,
2023                ledger: configured.ledger.as_ref(),
2024                config: configured.config,
2025            };
2026            self.change_role_in_tenant_controlled(tenant_id, username, new_role, &control)
2027        } else {
2028            self.change_role_in_tenant_unaudited(tenant_id, username, new_role)
2029        }
2030    }
2031
2032    pub fn change_role_in_tenant_with_control_events(
2033        &self,
2034        tenant_id: Option<&str>,
2035        username: &str,
2036        new_role: Role,
2037        ctx: &ControlEventCtx<'_>,
2038        ledger: &dyn ControlEventLedger,
2039        config: ControlEventConfig,
2040    ) -> Result<(), AuthError> {
2041        let control = UserLifecycleControl {
2042            ctx,
2043            ledger,
2044            config,
2045        };
2046        self.change_role_in_tenant_controlled(tenant_id, username, new_role, &control)
2047    }
2048
2049    fn change_role_in_tenant_unaudited(
2050        &self,
2051        tenant_id: Option<&str>,
2052        username: &str,
2053        new_role: Role,
2054    ) -> Result<(), AuthError> {
2055        let id = UserId::from_parts(tenant_id, username);
2056        let mut users = self.users.write().map_err(lock_err)?;
2057        let user = users
2058            .get_mut(&id)
2059            .ok_or_else(|| AuthError::UserNotFound(id.to_string()))?;
2060
2061        let prior_role = user.role;
2062        user.role = new_role;
2063        user.updated_at = now_ms();
2064
2065        // Issue #205 — promotion to Admin is an operator-grade event:
2066        // the new role grants destructive capabilities (DROP, ALTER,
2067        // GRANT) that an operator must observe out-of-band even when
2068        // the auth path itself is healthy.
2069        if new_role == Role::Admin && prior_role != Role::Admin {
2070            crate::telemetry::operator_event::OperatorEvent::AdminCapabilityGranted {
2071                granted_to: id.to_string(),
2072                capability: "Role::Admin".to_string(),
2073                granted_by: "auth_store::change_role".to_string(),
2074            }
2075            .emit_global();
2076        }
2077
2078        // Downgrade any API keys that now exceed the user's role.
2079        for key in &mut user.api_keys {
2080            if key.role > new_role {
2081                key.role = new_role;
2082            }
2083        }
2084
2085        // Update the api_key_index as well.
2086        if let Ok(mut idx) = self.api_key_index.write() {
2087            for key in &user.api_keys {
2088                if let Some(entry) = idx.get_mut(&key.key) {
2089                    entry.1 = key.role;
2090                }
2091            }
2092        }
2093
2094        // Sessions snapshot the role at login. A change in either direction
2095        // must not keep riding on a token minted under the old one — a
2096        // demotion would otherwise stay ineffective for the session TTL.
2097        if prior_role != new_role {
2098            self.purge_sessions_for(&id);
2099        }
2100
2101        self.persist_to_vault();
2102        Ok(())
2103    }
2104
2105    fn change_role_in_tenant_controlled(
2106        &self,
2107        tenant_id: Option<&str>,
2108        username: &str,
2109        new_role: Role,
2110        control: &UserLifecycleControl<'_>,
2111    ) -> Result<(), AuthError> {
2112        let id = UserId::from_parts(tenant_id, username);
2113        let previous = self.get_user_cloned(&id);
2114        match self.change_role_in_tenant_unaudited(tenant_id, username, new_role) {
2115            Ok(()) => {
2116                if let Err(err) = self.emit_user_lifecycle_allowed(
2117                    control,
2118                    EventKind::UserUpdate,
2119                    "user.update",
2120                    &id,
2121                    user_control_fields(
2122                        &id,
2123                        Some(new_role),
2124                        previous.as_ref().map(|u| u.enabled),
2125                        false,
2126                    ),
2127                ) {
2128                    self.restore_user_snapshot(&id, previous);
2129                    return Err(err);
2130                }
2131                Ok(())
2132            }
2133            Err(err) => {
2134                self.emit_user_lifecycle_outcome(
2135                    control,
2136                    if user_error_is_denied(&err) {
2137                        Outcome::Denied
2138                    } else {
2139                        Outcome::Error
2140                    },
2141                    EventKind::UserUpdate,
2142                    "user.update",
2143                    &id,
2144                    Some(err.to_string()),
2145                    user_control_fields(
2146                        &id,
2147                        Some(new_role),
2148                        previous.as_ref().map(|u| u.enabled),
2149                        false,
2150                    ),
2151                );
2152                Err(err)
2153            }
2154        }
2155    }
2156
2157    // -----------------------------------------------------------------
2158    // Authentication (login)
2159    // -----------------------------------------------------------------
2160
2161    /// Verify credentials for a platform-tenant user (`tenant_id = None`)
2162    /// and create a session. For tenant-scoped login use
2163    /// [`Self::authenticate_in_tenant`].
2164    ///
2165    /// When a keypair is available (certificate-based seal), session tokens
2166    /// are signed with the master secret so the server can verify they were
2167    /// genuinely issued by this vault instance.
2168    pub fn authenticate(&self, username: &str, password: &str) -> Result<Session, AuthError> {
2169        self.authenticate_in_tenant(None, username, password)
2170    }
2171
2172    /// Verify credentials for `(tenant_id, username, password)` and
2173    /// create a session. Tenant-aware: `alice@acme` and `alice@globex`
2174    /// authenticate independently.
2175    ///
2176    /// Every outcome is recorded in the control-event ledger when one is
2177    /// configured: login was the one credential decision with no chained
2178    /// trace, so a brute-force run or a login from a freshly re-enabled
2179    /// account was invisible to an audit of the store. Under a
2180    /// compliance-mode ledger a login that cannot be recorded is refused.
2181    pub fn authenticate_in_tenant(
2182        &self,
2183        tenant_id: Option<&str>,
2184        username: &str,
2185        password: &str,
2186    ) -> Result<Session, AuthError> {
2187        let id = UserId::from_parts(tenant_id, username);
2188        match self.authenticate_in_tenant_unaudited(tenant_id, username, password) {
2189            Ok(session) => {
2190                if let Err(err) = self.emit_auth_event(
2191                    EventKind::AuthLogin,
2192                    Outcome::Allowed,
2193                    &id,
2194                    Some(session.role),
2195                    None,
2196                ) {
2197                    if let Ok(mut sessions) = self.sessions.write() {
2198                        sessions.remove(&session.token);
2199                    }
2200                    return Err(err);
2201                }
2202                Ok(session)
2203            }
2204            Err(err) => {
2205                let outcome = if matches!(err, AuthError::InvalidCredentials) {
2206                    Outcome::Denied
2207                } else {
2208                    Outcome::Error
2209                };
2210                // Already refusing; a ledger failure cannot make it worse.
2211                let _ = self.emit_auth_event(
2212                    EventKind::AuthLoginFailed,
2213                    outcome,
2214                    &id,
2215                    None,
2216                    Some(&err.to_string()),
2217                );
2218                Err(err)
2219            }
2220        }
2221    }
2222
2223    /// Record one authentication decision. `Err` only when the ledger is
2224    /// configured to require persistence and refused the event.
2225    fn emit_auth_event(
2226        &self,
2227        kind: EventKind,
2228        outcome: Outcome,
2229        id: &UserId,
2230        role: Option<Role>,
2231        reason: Option<&str>,
2232    ) -> Result<(), AuthError> {
2233        let Some(configured) = self.configured_control_events() else {
2234            return Ok(());
2235        };
2236        let ctx = ControlEventCtx {
2237            actor: crate::runtime::control_events::ActorRef::User(id),
2238            scope: id.tenant.as_deref().map(Cow::Borrowed),
2239            request_id: None,
2240            trace_id: None,
2241        };
2242        let mut fields: HashMap<String, Sensitivity> = HashMap::new();
2243        fields.insert("principal".to_string(), Sensitivity::raw(id.to_string()));
2244        if let Some(role) = role {
2245            fields.insert("role".to_string(), Sensitivity::raw(role.as_str()));
2246        }
2247        let event = ControlEvent {
2248            kind,
2249            outcome,
2250            action: Cow::Borrowed(kind.as_str()),
2251            resource: Some(format!("principal:{id}")),
2252            reason: reason.map(str::to_string),
2253            matched_policy_id: None,
2254            fields,
2255        };
2256        match configured.ledger.emit(&ctx, event) {
2257            Ok(_) => Ok(()),
2258            Err(err) if configured.config.require_persistence() => Err(AuthError::Internal(
2259                format!("control-event ledger refused {}: {err}", kind.as_str()),
2260            )),
2261            Err(err) => {
2262                tracing::warn!(
2263                    target: "reddb::security",
2264                    kind = kind.as_str(),
2265                    error = %err,
2266                    "control-event ledger refused an auth event"
2267                );
2268                Ok(())
2269            }
2270        }
2271    }
2272
2273    fn authenticate_in_tenant_unaudited(
2274        &self,
2275        tenant_id: Option<&str>,
2276        username: &str,
2277        password: &str,
2278    ) -> Result<Session, AuthError> {
2279        // Initialize once on the first login, regardless of whether the
2280        // principal exists. Subsequent missing/disabled-account attempts use
2281        // this verifier instead of returning before production-cost Argon2.
2282        let dummy_hash = dummy_password_hash();
2283        // The synthetic platform-owner principal exists only as a
2284        // policy-graph anchor (see `crate::auth::self_lock_guard`); it
2285        // must never authenticate via any transport.
2286        if crate::auth::self_lock_guard::is_synthetic_principal(username) {
2287            let _ = verify_password(password, dummy_hash);
2288            return Err(AuthError::InvalidCredentials);
2289        }
2290        let id = UserId::from_parts(tenant_id, username);
2291        let users = self.users.read().map_err(lock_err)?;
2292        let (stored_hash, account_enabled) = match users.get(&id) {
2293            Some(user) => (user.password_hash.clone(), user.enabled),
2294            None => (dummy_hash.to_string(), false),
2295        };
2296        let password_matches = verify_password(password, &stored_hash);
2297        if !account_enabled || !password_matches {
2298            return Err(AuthError::InvalidCredentials);
2299        }
2300
2301        let user = users
2302            .get(&id)
2303            .expect("an enabled account came from the user map");
2304
2305        // Generate token: signed if keypair is available, random otherwise.
2306        let token = match self.keypair.read().ok().and_then(|g| {
2307            g.as_ref().map(|kp| {
2308                let token_id = random_hex(16);
2309                let sig = kp.sign(format!("session:{}", token_id).as_bytes());
2310                // Take first 16 bytes of signature for compact token.
2311                format!("rs_{}{}", token_id, hex::encode(&sig[..16]))
2312            })
2313        }) {
2314            Some(signed_token) => signed_token,
2315            None => generate_session_token(),
2316        };
2317
2318        let now = now_ms();
2319        let session = Session {
2320            token,
2321            username: username.to_string(),
2322            tenant_id: user.tenant_id.clone(),
2323            role: user.role,
2324            created_at: now,
2325            expires_at: now + (self.config.session_ttl_secs as u128 * 1000),
2326        };
2327
2328        drop(users); // release read lock before acquiring write
2329
2330        let mut sessions = self.sessions.write().map_err(lock_err)?;
2331        sessions.insert(session.token.clone(), session.clone());
2332        drop(sessions);
2333
2334        // Transparently upgrade a hash produced by the retired in-tree KDF.
2335        // This is the only point where the verified plaintext is in hand.
2336        if password_hash_needs_upgrade(&stored_hash) {
2337            let upgraded = hash_password(password);
2338            let mut rehashed = false;
2339            if let Ok(mut users) = self.users.write() {
2340                if let Some(user) = users.get_mut(&id) {
2341                    // Skip if a concurrent password change already moved it.
2342                    if user.password_hash == stored_hash {
2343                        user.password_hash = upgraded;
2344                        rehashed = true;
2345                    }
2346                }
2347            }
2348            if rehashed {
2349                self.persist_to_vault();
2350            }
2351        }
2352
2353        Ok(session)
2354    }
2355
2356    // -----------------------------------------------------------------
2357    // Token validation
2358    // -----------------------------------------------------------------
2359
2360    /// Validate a token (session or API key).
2361    ///
2362    /// Returns `(username, role)` if valid, `None` otherwise. Tenant
2363    /// scope is dropped here for compatibility with the bulk of the
2364    /// existing caller surface (routing, gRPC control, redwire). Use
2365    /// [`Self::validate_token_full`] when the caller needs the
2366    /// resolved `UserId` (e.g. to pin `CURRENT_TENANT()`).
2367    pub fn validate_token(&self, token: &str) -> Option<(String, Role)> {
2368        self.validate_token_full(token)
2369            .map(|(id, role)| (id.username, role))
2370    }
2371
2372    /// Tenant-aware token validation. Returns the resolved `UserId`
2373    /// (which carries the tenant) and the granted `Role`.
2374    pub fn validate_token_full(&self, token: &str) -> Option<(UserId, Role)> {
2375        let resolved = self.resolve_token_unchecked(token)?;
2376        // Every credential is re-checked against the live user record so
2377        // `ALTER USER … DISABLE` / `VALID UNTIL` take effect immediately for
2378        // sessions and API keys, not only at password login.
2379        if !self.principal_is_active(&resolved.0) {
2380            return None;
2381        }
2382        Some(resolved)
2383    }
2384
2385    /// Token → `(UserId, Role)` without consulting the owning user record.
2386    fn resolve_token_unchecked(&self, token: &str) -> Option<(UserId, Role)> {
2387        // Try session tokens first.
2388        if token.starts_with("rs_") {
2389            if let Ok(sessions) = self.sessions.read() {
2390                if let Some(session) = sessions.get(token) {
2391                    let now = now_ms();
2392                    if now < session.expires_at {
2393                        return Some((
2394                            UserId::from_parts(session.tenant_id.as_deref(), &session.username),
2395                            session.role,
2396                        ));
2397                    }
2398                }
2399            }
2400            return None;
2401        }
2402
2403        // Try API keys: the index is keyed by the credential id, so the
2404        // presented secret is hashed and never compared as text.
2405        if token.starts_with("rk_") {
2406            let id = api_key_credential_id(token);
2407            let (owner, role) = self
2408                .api_key_index
2409                .read()
2410                .ok()
2411                .and_then(|idx| idx.get(&id).cloned())?;
2412            if self.api_key_expired(&owner, &id) {
2413                return None;
2414            }
2415            return Some((owner, role));
2416        }
2417
2418        None
2419    }
2420
2421    /// Whether the key `id` owned by `owner` has passed its `expires_at`.
2422    /// A key the owner no longer lists counts as expired.
2423    fn api_key_expired(&self, owner: &UserId, id: &str) -> bool {
2424        let Ok(users) = self.users.read() else {
2425            return true;
2426        };
2427        users
2428            .get(owner)
2429            .and_then(|user| user.api_keys.iter().find(|key| key.key == id))
2430            .map(|key| key.expires_at.is_some_and(|deadline| now_ms() >= deadline))
2431            .unwrap_or(true)
2432    }
2433
2434    /// The current role of `id` when the account is active, else `None`.
2435    ///
2436    /// Callers holding a long-lived credential (the browser refresh cookie)
2437    /// use this to re-derive the principal's role at use time rather than
2438    /// trusting a role captured when the credential was minted.
2439    pub fn active_user_role(&self, id: &UserId) -> Option<Role> {
2440        if !self.principal_is_active(id) {
2441            return None;
2442        }
2443        self.users.read().ok()?.get(id).map(|user| user.role)
2444    }
2445
2446    /// Whether `id` names an enabled account whose `VALID UNTIL` (if any)
2447    /// has not passed. Unknown accounts are inactive.
2448    fn principal_is_active(&self, id: &UserId) -> bool {
2449        let enabled = match self.users.read() {
2450            Ok(users) => users.get(id).map(|u| u.enabled).unwrap_or(false),
2451            Err(_) => false,
2452        };
2453        if !enabled {
2454            return false;
2455        }
2456        match self.user_attributes(id).valid_until {
2457            Some(deadline) => now_ms() < deadline,
2458            None => true,
2459        }
2460    }
2461
2462    // -----------------------------------------------------------------
2463    // API Key management
2464    // -----------------------------------------------------------------
2465
2466    /// Create a persistent API key for a platform-tenant user.
2467    ///
2468    /// For tenant-scoped users use [`Self::create_api_key_in_tenant`].
2469    pub fn create_api_key(
2470        &self,
2471        username: &str,
2472        name: &str,
2473        role: Role,
2474    ) -> Result<ApiKey, AuthError> {
2475        self.create_api_key_in_tenant(None, username, name, role)
2476    }
2477
2478    pub fn create_api_key_with_control_events(
2479        &self,
2480        username: &str,
2481        name: &str,
2482        role: Role,
2483        ctx: &ControlEventCtx<'_>,
2484        ledger: &dyn ControlEventLedger,
2485        config: ControlEventConfig,
2486    ) -> Result<ApiKey, AuthError> {
2487        self.create_api_key_in_tenant_with_control_events(
2488            None, username, name, role, ctx, ledger, config,
2489        )
2490    }
2491
2492    pub fn create_api_key_in_tenant(
2493        &self,
2494        tenant_id: Option<&str>,
2495        username: &str,
2496        name: &str,
2497        role: Role,
2498    ) -> Result<ApiKey, AuthError> {
2499        self.create_api_key_in_tenant_expiring(tenant_id, username, name, role, None)
2500    }
2501
2502    /// Create an API key that stops validating at `expires_at` (ms since
2503    /// epoch). The returned value carries the secret; nothing else does.
2504    pub fn create_api_key_in_tenant_expiring(
2505        &self,
2506        tenant_id: Option<&str>,
2507        username: &str,
2508        name: &str,
2509        role: Role,
2510        expires_at: Option<u128>,
2511    ) -> Result<ApiKey, AuthError> {
2512        if let Some(configured) = self.configured_control_events() {
2513            let ctx = default_user_lifecycle_ctx();
2514            let control = UserLifecycleControl {
2515                ctx: &ctx,
2516                ledger: configured.ledger.as_ref(),
2517                config: configured.config,
2518            };
2519            self.create_api_key_in_tenant_controlled(
2520                tenant_id, username, name, role, expires_at, &control,
2521            )
2522        } else {
2523            self.create_api_key_in_tenant_unaudited(tenant_id, username, name, role, expires_at)
2524        }
2525    }
2526
2527    #[allow(clippy::too_many_arguments)]
2528    pub fn create_api_key_in_tenant_with_control_events(
2529        &self,
2530        tenant_id: Option<&str>,
2531        username: &str,
2532        name: &str,
2533        role: Role,
2534        ctx: &ControlEventCtx<'_>,
2535        ledger: &dyn ControlEventLedger,
2536        config: ControlEventConfig,
2537    ) -> Result<ApiKey, AuthError> {
2538        let control = UserLifecycleControl {
2539            ctx,
2540            ledger,
2541            config,
2542        };
2543        self.create_api_key_in_tenant_controlled(tenant_id, username, name, role, None, &control)
2544    }
2545
2546    fn create_api_key_in_tenant_unaudited(
2547        &self,
2548        tenant_id: Option<&str>,
2549        username: &str,
2550        name: &str,
2551        role: Role,
2552        expires_at: Option<u128>,
2553    ) -> Result<ApiKey, AuthError> {
2554        let id = UserId::from_parts(tenant_id, username);
2555        let mut users = self.users.write().map_err(lock_err)?;
2556        let user = users
2557            .get_mut(&id)
2558            .ok_or_else(|| AuthError::UserNotFound(id.to_string()))?;
2559
2560        // The key's role cannot exceed the user's role.
2561        if role > user.role {
2562            return Err(AuthError::RoleExceeded {
2563                requested: role,
2564                ceiling: user.role,
2565            });
2566        }
2567
2568        let secret = generate_api_key();
2569        let stored = ApiKey {
2570            key: api_key_credential_id(&secret),
2571            name: name.to_string(),
2572            role,
2573            created_at: now_ms(),
2574            expires_at,
2575        };
2576
2577        user.api_keys.push(stored.clone());
2578        user.updated_at = now_ms();
2579
2580        // Update the index.
2581        if let Ok(mut idx) = self.api_key_index.write() {
2582            idx.insert(stored.key.clone(), (id.clone(), stored.role));
2583        }
2584
2585        drop(users); // release lock before vault I/O
2586        self.persist_to_vault();
2587        // The secret leaves the store exactly once, here.
2588        Ok(ApiKey {
2589            key: secret,
2590            ..stored
2591        })
2592    }
2593
2594    fn create_api_key_in_tenant_controlled(
2595        &self,
2596        tenant_id: Option<&str>,
2597        username: &str,
2598        name: &str,
2599        role: Role,
2600        expires_at: Option<u128>,
2601        control: &UserLifecycleControl<'_>,
2602    ) -> Result<ApiKey, AuthError> {
2603        let id = UserId::from_parts(tenant_id, username);
2604        match self.create_api_key_in_tenant_unaudited(tenant_id, username, name, role, expires_at) {
2605            Ok(api_key) => {
2606                let key_id = api_key_id(&api_key.key);
2607                if let Err(err) = self.emit_api_key_allowed(
2608                    control,
2609                    EventKind::ApiKeyCreate,
2610                    "apikey.create",
2611                    &key_id,
2612                    api_key_control_fields(&id, role, &key_id),
2613                ) {
2614                    self.rollback_create_api_key(&id, &api_key.key);
2615                    return Err(err);
2616                }
2617                Ok(api_key)
2618            }
2619            Err(err) => {
2620                self.emit_user_lifecycle_outcome(
2621                    control,
2622                    if user_error_is_denied(&err) {
2623                        Outcome::Denied
2624                    } else {
2625                        Outcome::Error
2626                    },
2627                    EventKind::ApiKeyCreate,
2628                    "apikey.create",
2629                    &id,
2630                    Some(err.to_string()),
2631                    user_control_fields(&id, Some(role), None, false),
2632                );
2633                Err(err)
2634            }
2635        }
2636    }
2637
2638    /// Resolve the tenant-aware owner of an API key without exposing its record.
2639    pub fn api_key_owner(&self, key: &str) -> Option<UserId> {
2640        let key_id = api_key_credential_id(key);
2641        self.api_key_index
2642            .read()
2643            .ok()
2644            .and_then(|index| index.get(&key_id).map(|(id, _)| id.clone()))
2645    }
2646
2647    /// Revoke (delete) an API key.
2648    pub fn revoke_api_key(&self, key: &str) -> Result<(), AuthError> {
2649        if let Some(configured) = self.configured_control_events() {
2650            let ctx = default_user_lifecycle_ctx();
2651            let control = UserLifecycleControl {
2652                ctx: &ctx,
2653                ledger: configured.ledger.as_ref(),
2654                config: configured.config,
2655            };
2656            self.revoke_api_key_controlled(key, &control)
2657        } else {
2658            self.revoke_api_key_unaudited(key)
2659        }
2660    }
2661
2662    pub fn revoke_api_key_with_control_events(
2663        &self,
2664        key: &str,
2665        ctx: &ControlEventCtx<'_>,
2666        ledger: &dyn ControlEventLedger,
2667        config: ControlEventConfig,
2668    ) -> Result<(), AuthError> {
2669        let control = UserLifecycleControl {
2670            ctx,
2671            ledger,
2672            config,
2673        };
2674        self.revoke_api_key_controlled(key, &control)
2675    }
2676
2677    fn revoke_api_key_unaudited(&self, key: &str) -> Result<(), AuthError> {
2678        let key_id = api_key_credential_id(key);
2679        let key = key_id.as_str();
2680        let mut users = self.users.write().map_err(lock_err)?;
2681
2682        // Find which user owns this key (look up by the api_key_index
2683        // first; fall back to a scan for legacy state restored before
2684        // the index was reseeded).
2685        let owner_id: UserId = {
2686            if let Ok(idx) = self.api_key_index.read() {
2687                if let Some((id, _)) = idx.get(key) {
2688                    id.clone()
2689                } else {
2690                    return Err(AuthError::KeyNotFound(key.to_string()));
2691                }
2692            } else {
2693                let owner = users
2694                    .iter()
2695                    .find(|(_, u)| u.api_keys.iter().any(|k| k.key == key));
2696                match owner {
2697                    Some((id, _)) => id.clone(),
2698                    None => return Err(AuthError::KeyNotFound(key.to_string())),
2699                }
2700            }
2701        };
2702
2703        let user = users
2704            .get_mut(&owner_id)
2705            .ok_or_else(|| AuthError::KeyNotFound(key.to_string()))?;
2706        user.api_keys.retain(|k| k.key != key);
2707        user.updated_at = now_ms();
2708
2709        // Remove from index.
2710        if let Ok(mut idx) = self.api_key_index.write() {
2711            idx.remove(key);
2712        }
2713
2714        self.persist_to_vault();
2715        Ok(())
2716    }
2717
2718    fn revoke_api_key_controlled(
2719        &self,
2720        key: &str,
2721        control: &UserLifecycleControl<'_>,
2722    ) -> Result<(), AuthError> {
2723        let key_id = api_key_id(key);
2724        let rollback = self.api_key_rollback_snapshot(key);
2725        let id = rollback
2726            .as_ref()
2727            .map(|r| r.0.clone())
2728            .unwrap_or_else(|| UserId::from_parts(None, ""));
2729        let role = rollback.as_ref().map(|r| r.1.role).unwrap_or(Role::Read);
2730        match self.revoke_api_key_unaudited(key) {
2731            Ok(()) => {
2732                if let Err(err) = self.emit_api_key_allowed(
2733                    control,
2734                    EventKind::ApiKeyRevoke,
2735                    "apikey.revoke",
2736                    &key_id,
2737                    api_key_control_fields(&id, role, &key_id),
2738                ) {
2739                    if let Some((owner, api_key)) = rollback {
2740                        self.restore_api_key(&owner, api_key);
2741                    }
2742                    return Err(err);
2743                }
2744                Ok(())
2745            }
2746            Err(err) => {
2747                self.emit_user_lifecycle_outcome(
2748                    control,
2749                    if user_error_is_denied(&err) {
2750                        Outcome::Denied
2751                    } else {
2752                        Outcome::Error
2753                    },
2754                    EventKind::ApiKeyRevoke,
2755                    "apikey.revoke",
2756                    &id,
2757                    Some(err.to_string()),
2758                    api_key_control_fields(&id, role, &key_id),
2759                );
2760                Err(err)
2761            }
2762        }
2763    }
2764
2765    // -----------------------------------------------------------------
2766    // Session management
2767    // -----------------------------------------------------------------
2768
2769    /// Revoke a session token.
2770    pub fn revoke_session(&self, token: &str) {
2771        if let Some(session) = self.remove_session_without_count(token) {
2772            if self.take_counted_session(token) {
2773                let uid = UserId::from_parts(session.tenant_id.as_deref(), &session.username);
2774                self.decrement_session_count(&uid);
2775            }
2776        }
2777    }
2778
2779    fn remove_session_without_count(&self, token: &str) -> Option<Session> {
2780        self.sessions.write().ok()?.remove(token)
2781    }
2782
2783    fn take_counted_session(&self, token: &str) -> bool {
2784        self.counted_session_tokens
2785            .write()
2786            .map(|mut tokens| tokens.remove(token))
2787            .unwrap_or(false)
2788    }
2789
2790    /// Purge expired sessions (housekeeping).
2791    pub fn purge_expired_sessions(&self) -> usize {
2792        let now = now_ms();
2793        if let Ok(mut sessions) = self.sessions.write() {
2794            let expired: Vec<Session> = sessions
2795                .values()
2796                .filter(|session| session.expires_at <= now)
2797                .cloned()
2798                .collect();
2799            sessions.retain(|_, session| session.expires_at > now);
2800            drop(sessions);
2801            for session in &expired {
2802                if self.take_counted_session(&session.token) {
2803                    let uid = UserId::from_parts(session.tenant_id.as_deref(), &session.username);
2804                    self.decrement_session_count(&uid);
2805                }
2806            }
2807            return expired.len();
2808        }
2809        0
2810    }
2811
2812    // -----------------------------------------------------------------
2813    // Granular RBAC — GRANT / REVOKE
2814    //
2815    // The privilege engine lives in `super::privileges`. These helpers
2816    // are the AuthStore facade: they keep an in-memory map of grants per
2817    // user (plus a `public_grants` list), persist additions/removals to
2818    // the existing `vault_kv` store, and rebuild the per-user
2819    // `PermissionCache` so the hot path stays O(1).
2820    //
2821    // Persistence design: rather than extend the snapshot/restore
2822    // pipeline (Agent #2's territory) we serialise grants and account
2823    // attributes to the vault KV store. That gives us atomic write +
2824    // encrypted-at-rest semantics for free without touching the
2825    // existing USER/KEY/KV serializer paths. On restart `rehydrate_acl`
2826    // reads these KV entries back into the in-memory maps.
2827    // -----------------------------------------------------------------
2828
2829    /// Persist a grant. Returns `Forbidden` when the granting user is
2830    /// not Admin or attempts a cross-tenant grant.
2831    pub fn grant(
2832        &self,
2833        granter: &UserId,
2834        granter_role: Role,
2835        principal: GrantPrincipal,
2836        resource: Resource,
2837        actions: Vec<Action>,
2838        with_grant_option: bool,
2839        tenant: Option<String>,
2840    ) -> Result<(), AuthError> {
2841        if granter_role != Role::Admin {
2842            return Err(AuthError::Forbidden(format!(
2843                "GRANT requires Admin role; granter `{}` has `{:?}`",
2844                granter, granter_role
2845            )));
2846        }
2847
2848        // Cross-tenant guard: a tenant-scoped admin cannot mint grants
2849        // outside their tenant. Platform admin (tenant=None) may grant
2850        // anywhere.
2851        if granter.tenant.is_some() && granter.tenant != tenant {
2852            return Err(AuthError::Forbidden(format!(
2853                "cross-tenant GRANT denied: granter tenant `{:?}` != grant tenant `{:?}`",
2854                granter.tenant, tenant
2855            )));
2856        }
2857
2858        let mut actions_set = std::collections::BTreeSet::new();
2859        for a in actions {
2860            actions_set.insert(a);
2861        }
2862        let g = Grant {
2863            principal: principal.clone(),
2864            resource,
2865            actions: actions_set,
2866            with_grant_option,
2867            granted_by: granter.to_string(),
2868            granted_at: now_ms(),
2869            tenant,
2870            columns: None,
2871        };
2872
2873        match &principal {
2874            GrantPrincipal::User(uid) => {
2875                self.grants
2876                    .write()
2877                    .unwrap_or_else(|e| e.into_inner())
2878                    .entry(uid.clone())
2879                    .or_default()
2880                    .push(g.clone());
2881                self.invalidate_permission_cache(Some(uid));
2882            }
2883            GrantPrincipal::Public => {
2884                self.public_grants
2885                    .write()
2886                    .unwrap_or_else(|e| e.into_inner())
2887                    .push(g.clone());
2888                self.invalidate_permission_cache(None);
2889            }
2890            GrantPrincipal::Group(_) => {
2891                return Err(AuthError::Forbidden(
2892                    "GROUP principals are not yet supported; use a USER or PUBLIC".to_string(),
2893                ));
2894            }
2895        }
2896
2897        // Issue #119: a fresh grant changes the visible-collections set
2898        // for `(tenant, role)` callers under the same tenant. Drop those
2899        // cache entries so the next AI command sees the new SELECT
2900        // privilege immediately.
2901        self.invalidate_visible_collections_for_tenant(g.tenant.as_deref());
2902
2903        self.persist_acl_to_kv();
2904        Ok(())
2905    }
2906
2907    /// Drop matching grants from a principal. Returns the number of
2908    /// grants removed.
2909    pub fn revoke(
2910        &self,
2911        granter: &UserId,
2912        granter_role: Role,
2913        principal: &GrantPrincipal,
2914        resource: &Resource,
2915        actions: &[Action],
2916    ) -> Result<usize, AuthError> {
2917        if granter_role != Role::Admin {
2918            return Err(AuthError::Forbidden(format!(
2919                "REVOKE requires Admin role; granter `{}` has `{:?}`",
2920                granter, granter_role
2921            )));
2922        }
2923
2924        // Cross-tenant guard, mirroring GRANT: a tenant-scoped admin can only
2925        // touch grants of principals in its own tenant. The target tenant
2926        // comes from the statement text, so without this a tenant admin could
2927        // strip another tenant's grants. Platform admin (tenant=None) may
2928        // revoke anywhere.
2929        if let GrantPrincipal::User(uid) = principal {
2930            if granter.tenant.is_some() && granter.tenant != uid.tenant {
2931                return Err(AuthError::Forbidden(format!(
2932                    "cross-tenant REVOKE denied: granter tenant `{:?}` != principal tenant `{:?}`",
2933                    granter.tenant, uid.tenant
2934                )));
2935            }
2936        }
2937
2938        let removed = match principal {
2939            GrantPrincipal::User(uid) => {
2940                let mut g = self.grants.write().unwrap_or_else(|e| e.into_inner());
2941                let before = g.get(uid).map(|v| v.len()).unwrap_or(0);
2942                if let Some(list) = g.get_mut(uid) {
2943                    list.retain(|gr| {
2944                        !(gr.resource == *resource
2945                            && (actions.iter().any(|a| gr.actions.contains(a))
2946                                || (gr.actions.contains(&Action::All) && !actions.is_empty())))
2947                    });
2948                }
2949                let after = g.get(uid).map(|v| v.len()).unwrap_or(0);
2950                drop(g);
2951                self.invalidate_permission_cache(Some(uid));
2952                before - after
2953            }
2954            GrantPrincipal::Public => {
2955                let mut p = self
2956                    .public_grants
2957                    .write()
2958                    .unwrap_or_else(|e| e.into_inner());
2959                let before = p.len();
2960                p.retain(|gr| {
2961                    !(gr.resource == *resource
2962                        && (actions.iter().any(|a| gr.actions.contains(a))
2963                            || (gr.actions.contains(&Action::All) && !actions.is_empty())))
2964                });
2965                let after = p.len();
2966                drop(p);
2967                self.invalidate_permission_cache(None);
2968                before - after
2969            }
2970            GrantPrincipal::Group(_) => 0,
2971        };
2972
2973        if removed > 0 {
2974            // Issue #119: REVOKE may shrink the visible-collections set
2975            // for any `(tenant, role)` slot. We don't know the exact
2976            // tenant when the principal is `Public`, so a `Public`
2977            // revoke clears the whole cache; user revokes scope to the
2978            // user's tenant.
2979            match principal {
2980                GrantPrincipal::User(uid) => {
2981                    self.invalidate_visible_collections_for_tenant(uid.tenant.as_deref());
2982                }
2983                GrantPrincipal::Public | GrantPrincipal::Group(_) => {
2984                    self.invalidate_visible_collections_cache();
2985                }
2986            }
2987            self.persist_acl_to_kv();
2988        }
2989        Ok(removed)
2990    }
2991
2992    /// Compute the set of collection ids a given `(tenant, role)`
2993    /// scope can read, consulting the explicit grant table. The result
2994    /// is cached for `super::scope_cache::DEFAULT_TTL` (60s) and
2995    /// invalidated on every GRANT/REVOKE/policy/collection mutation
2996    /// that could change the answer.
2997    ///
2998    /// `all_collections` is the full list of collection ids known to
2999    /// the storage layer. The runtime hands it in so this module stays
3000    /// decoupled from the storage crate. Each collection passes through
3001    /// `check_grant(SELECT)` under a synthetic `(principal, role,
3002    /// tenant)` view. The cache key includes principal because direct
3003    /// grants can differ between users that share the same tenant and
3004    /// role.
3005    pub fn visible_collections_for_scope(
3006        &self,
3007        tenant: Option<&str>,
3008        role: Role,
3009        principal: &str,
3010        all_collections: &[String],
3011    ) -> std::collections::HashSet<String> {
3012        let key = super::scope_cache::ScopeKey::new(tenant, principal, role);
3013        if let Some(hit) = self.visible_collections_cache.get(&key) {
3014            return hit;
3015        }
3016        // Slow path: walk every collection through `check_grant`. We
3017        // build the AuthzContext once, then reuse it per resource.
3018        let ctx = AuthzContext {
3019            principal,
3020            effective_role: role,
3021            tenant,
3022        };
3023        let mut visible = std::collections::HashSet::new();
3024        for collection in all_collections {
3025            let resource = Resource::table_from_name(collection);
3026            if self.check_grant(&ctx, Action::Select, &resource).is_ok() {
3027                visible.insert(collection.clone());
3028            }
3029        }
3030        self.visible_collections_cache.insert(key, visible.clone());
3031        visible
3032    }
3033
3034    /// Stats probe required by issue #119 — exposes hit/miss counts and
3035    /// invalidations for the visible-collections cache so metrics
3036    /// pipelines can compute a hit rate.
3037    pub fn auth_cache_stats(&self) -> super::scope_cache::AuthCacheStats {
3038        self.visible_collections_cache.stats()
3039    }
3040
3041    /// Drop every cached `(tenant, role)` entry. Called from CREATE
3042    /// POLICY / DROP POLICY / DROP COLLECTION paths where the affected
3043    /// tenant set is unknown.
3044    pub fn invalidate_visible_collections_cache(&self) {
3045        self.visible_collections_cache.invalidate_all();
3046    }
3047
3048    /// Drop cached entries for one tenant. Called from GRANT / REVOKE
3049    /// where the principal's tenant is known.
3050    pub fn invalidate_visible_collections_for_tenant(&self, tenant: Option<&str>) {
3051        self.visible_collections_cache.invalidate_tenant(tenant);
3052    }
3053
3054    /// Snapshot of every grant the principal effectively has, including
3055    /// `Public` grants. Audit / introspection helper.
3056    pub fn effective_grants(&self, uid: &UserId) -> Vec<Grant> {
3057        let mut out = Vec::new();
3058        if let Ok(g) = self.grants.read() {
3059            if let Some(list) = g.get(uid) {
3060                out.extend(list.iter().cloned());
3061            }
3062        }
3063        if let Ok(p) = self.public_grants.read() {
3064            out.extend(p.iter().cloned());
3065        }
3066        out
3067    }
3068
3069    /// Run a privilege check using the in-memory grant tables. Returns
3070    /// `Ok(())` on allow, `Err(AuthzError)` on deny.
3071    pub fn check_grant(
3072        &self,
3073        ctx: &AuthzContext<'_>,
3074        action: Action,
3075        resource: &Resource,
3076    ) -> Result<(), AuthzError> {
3077        if ctx.effective_role == Role::Admin {
3078            return Ok(());
3079        }
3080
3081        let uid = UserId::from_parts(ctx.tenant, ctx.principal);
3082
3083        // Fast path: per-user pre-resolved cache.
3084        if let Ok(cache) = self.permission_cache.read() {
3085            if let Some(pc) = cache.get(&uid) {
3086                if pc.allows(resource, action) {
3087                    return Ok(());
3088                }
3089            }
3090        }
3091
3092        // Slow path: linear scan + rebuild cache as a side-effect.
3093        let user_grants = self
3094            .grants
3095            .read()
3096            .ok()
3097            .and_then(|g| g.get(&uid).cloned())
3098            .unwrap_or_default();
3099        let any_user_grants = self
3100            .grants
3101            .read()
3102            .ok()
3103            .map(|g| g.values().any(|list| !list.is_empty()))
3104            .unwrap_or(false);
3105        let public_grants = self
3106            .public_grants
3107            .read()
3108            .ok()
3109            .map(|p| p.clone())
3110            .unwrap_or_default();
3111        if user_grants.is_empty() && public_grants.is_empty() && any_user_grants {
3112            return Err(AuthzError::PermissionDenied {
3113                action,
3114                resource: resource.clone(),
3115                principal: ctx.principal.to_string(),
3116            });
3117        }
3118        let view = GrantsView {
3119            user_grants: &user_grants,
3120            public_grants: &public_grants,
3121        };
3122        let result = check_grant(ctx, action, resource, &view);
3123
3124        if result.is_ok() {
3125            let pc = PermissionCache::build(&user_grants, &public_grants);
3126            if let Ok(mut cache) = self.permission_cache.write() {
3127                cache.insert(uid, pc);
3128            }
3129        }
3130        result
3131    }
3132
3133    // -----------------------------------------------------------------
3134    // ALTER USER attributes (VALID UNTIL, CONNECTION LIMIT, etc.)
3135    // -----------------------------------------------------------------
3136
3137    /// Replace the attribute record for `uid`.
3138    pub fn set_user_attributes(
3139        &self,
3140        uid: &UserId,
3141        attrs: UserAttributes,
3142    ) -> Result<(), AuthError> {
3143        let users = self.users.read().map_err(lock_err)?;
3144        if !users.contains_key(uid) {
3145            return Err(AuthError::UserNotFound(uid.to_string()));
3146        }
3147        drop(users);
3148
3149        self.user_attributes
3150            .write()
3151            .unwrap_or_else(|e| e.into_inner())
3152            .insert(uid.clone(), attrs);
3153        self.invalidate_iam_cache(Some(uid));
3154        self.persist_acl_to_kv();
3155        Ok(())
3156    }
3157
3158    /// Read the attributes for `uid`. Returns `Default::default()` for
3159    /// users that have never been altered.
3160    pub fn user_attributes(&self, uid: &UserId) -> UserAttributes {
3161        self.user_attributes
3162            .read()
3163            .ok()
3164            .and_then(|m| m.get(uid).cloned())
3165            .unwrap_or_default()
3166    }
3167
3168    pub fn add_user_to_group(&self, uid: &UserId, group: &str) -> Result<(), AuthError> {
3169        if group.trim().is_empty() {
3170            return Err(AuthError::Forbidden("group name cannot be empty".into()));
3171        }
3172        let mut attrs = self.user_attributes(uid);
3173        if !attrs.groups.iter().any(|g| g == group) {
3174            attrs.groups.push(group.to_string());
3175            attrs.groups.sort();
3176        }
3177        self.set_user_attributes(uid, attrs)
3178    }
3179
3180    pub fn remove_user_from_group(&self, uid: &UserId, group: &str) -> Result<(), AuthError> {
3181        let mut attrs = self.user_attributes(uid);
3182        attrs.groups.retain(|g| g != group);
3183        self.set_user_attributes(uid, attrs)
3184    }
3185
3186    /// Toggle `User.enabled` without rotating credentials.
3187    pub fn set_user_enabled(&self, uid: &UserId, enabled: bool) -> Result<(), AuthError> {
3188        if let Some(configured) = self.configured_control_events() {
3189            let ctx = default_user_lifecycle_ctx();
3190            let control = UserLifecycleControl {
3191                ctx: &ctx,
3192                ledger: configured.ledger.as_ref(),
3193                config: configured.config,
3194            };
3195            self.set_user_enabled_controlled(uid, enabled, &control)
3196        } else {
3197            self.set_user_enabled_unaudited(uid, enabled)
3198        }
3199    }
3200
3201    pub fn disable_user(
3202        &self,
3203        username: &str,
3204        ctx: &ControlEventCtx<'_>,
3205        ledger: &dyn ControlEventLedger,
3206        config: ControlEventConfig,
3207    ) -> Result<(), AuthError> {
3208        self.disable_user_in_tenant(None, username, ctx, ledger, config)
3209    }
3210
3211    pub fn disable_user_in_tenant(
3212        &self,
3213        tenant_id: Option<&str>,
3214        username: &str,
3215        ctx: &ControlEventCtx<'_>,
3216        ledger: &dyn ControlEventLedger,
3217        config: ControlEventConfig,
3218    ) -> Result<(), AuthError> {
3219        let uid = UserId::from_parts(tenant_id, username);
3220        let control = UserLifecycleControl {
3221            ctx,
3222            ledger,
3223            config,
3224        };
3225        self.set_user_enabled_controlled(&uid, false, &control)
3226    }
3227
3228    fn set_user_enabled_unaudited(&self, uid: &UserId, enabled: bool) -> Result<(), AuthError> {
3229        let mut users = self.users.write().map_err(lock_err)?;
3230        let user = users
3231            .get_mut(uid)
3232            .ok_or_else(|| AuthError::UserNotFound(uid.to_string()))?;
3233        user.enabled = enabled;
3234        user.updated_at = now_ms();
3235        drop(users);
3236        if !enabled {
3237            self.purge_sessions_for(uid);
3238        }
3239        self.persist_to_vault();
3240        Ok(())
3241    }
3242
3243    /// Drop every live session belonging to `uid` (tenant + username match
3244    /// so a same-named user in another tenant is untouched).
3245    fn purge_sessions_for(&self, uid: &UserId) {
3246        if let Ok(mut sessions) = self.sessions.write() {
3247            let tokens: Vec<String> = sessions
3248                .iter()
3249                .filter(|(_, session)| {
3250                    session.username == uid.username && session.tenant_id == uid.tenant
3251                })
3252                .map(|(token, _)| token.clone())
3253                .collect();
3254            for token in &tokens {
3255                sessions.remove(token);
3256            }
3257            drop(sessions);
3258            for token in tokens {
3259                if self.take_counted_session(&token) {
3260                    self.decrement_session_count(uid);
3261                }
3262            }
3263        }
3264    }
3265
3266    fn set_user_enabled_controlled(
3267        &self,
3268        uid: &UserId,
3269        enabled: bool,
3270        control: &UserLifecycleControl<'_>,
3271    ) -> Result<(), AuthError> {
3272        let previous = self.get_user_cloned(uid);
3273        let kind = if enabled {
3274            EventKind::UserUpdate
3275        } else {
3276            EventKind::UserDisable
3277        };
3278        let action = if enabled {
3279            "user.update"
3280        } else {
3281            "user.disable"
3282        };
3283        match self.set_user_enabled_unaudited(uid, enabled) {
3284            Ok(()) => {
3285                if let Err(err) = self.emit_user_lifecycle_allowed(
3286                    control,
3287                    kind,
3288                    action,
3289                    uid,
3290                    user_control_fields(
3291                        uid,
3292                        previous.as_ref().map(|u| u.role),
3293                        Some(enabled),
3294                        false,
3295                    ),
3296                ) {
3297                    self.restore_user_snapshot(uid, previous);
3298                    return Err(err);
3299                }
3300                Ok(())
3301            }
3302            Err(err) => {
3303                self.emit_user_lifecycle_outcome(
3304                    control,
3305                    if user_error_is_denied(&err) {
3306                        Outcome::Denied
3307                    } else {
3308                        Outcome::Error
3309                    },
3310                    kind,
3311                    action,
3312                    uid,
3313                    Some(err.to_string()),
3314                    user_control_fields(
3315                        uid,
3316                        previous.as_ref().map(|u| u.role),
3317                        Some(enabled),
3318                        false,
3319                    ),
3320                );
3321                Err(err)
3322            }
3323        }
3324    }
3325
3326    fn emit_user_lifecycle_allowed(
3327        &self,
3328        control: &UserLifecycleControl<'_>,
3329        kind: EventKind,
3330        action: &'static str,
3331        id: &UserId,
3332        fields: HashMap<String, Sensitivity>,
3333    ) -> Result<(), AuthError> {
3334        self.emit_user_lifecycle_event(control, Outcome::Allowed, kind, action, id, None, fields)
3335    }
3336
3337    fn emit_api_key_allowed(
3338        &self,
3339        control: &UserLifecycleControl<'_>,
3340        kind: EventKind,
3341        action: &'static str,
3342        api_key_id: &str,
3343        fields: HashMap<String, Sensitivity>,
3344    ) -> Result<(), AuthError> {
3345        self.emit_control_event(
3346            control,
3347            Outcome::Allowed,
3348            kind,
3349            action,
3350            Some(api_key_resource(api_key_id)),
3351            None,
3352            fields,
3353        )
3354    }
3355
3356    #[allow(clippy::too_many_arguments)]
3357    fn emit_user_lifecycle_outcome(
3358        &self,
3359        control: &UserLifecycleControl<'_>,
3360        outcome: Outcome,
3361        kind: EventKind,
3362        action: &'static str,
3363        id: &UserId,
3364        reason: Option<String>,
3365        fields: HashMap<String, Sensitivity>,
3366    ) {
3367        let _ = self.emit_user_lifecycle_event(control, outcome, kind, action, id, reason, fields);
3368    }
3369
3370    #[allow(clippy::too_many_arguments)]
3371    fn emit_user_lifecycle_event(
3372        &self,
3373        control: &UserLifecycleControl<'_>,
3374        outcome: Outcome,
3375        kind: EventKind,
3376        action: &'static str,
3377        id: &UserId,
3378        reason: Option<String>,
3379        fields: HashMap<String, Sensitivity>,
3380    ) -> Result<(), AuthError> {
3381        self.emit_control_event(
3382            control,
3383            outcome,
3384            kind,
3385            action,
3386            Some(user_resource(id)),
3387            reason,
3388            fields,
3389        )
3390    }
3391
3392    #[allow(clippy::too_many_arguments)]
3393    fn emit_control_event(
3394        &self,
3395        control: &UserLifecycleControl<'_>,
3396        outcome: Outcome,
3397        kind: EventKind,
3398        action: &'static str,
3399        resource: Option<String>,
3400        reason: Option<String>,
3401        fields: HashMap<String, Sensitivity>,
3402    ) -> Result<(), AuthError> {
3403        let event = ControlEvent {
3404            kind,
3405            outcome,
3406            action: Cow::Borrowed(action),
3407            resource,
3408            reason,
3409            matched_policy_id: None,
3410            fields,
3411        };
3412        match control.ledger.emit(control.ctx, event) {
3413            Ok(_) => Ok(()),
3414            Err(err) if control.config.require_persistence() => {
3415                Err(AuthError::Internal(err.to_string()))
3416            }
3417            Err(_) => Ok(()),
3418        }
3419    }
3420
3421    fn rollback_create_user(&self, id: &UserId) {
3422        let removed = self
3423            .users
3424            .write()
3425            .unwrap_or_else(|e| e.into_inner())
3426            .remove(id);
3427        if let Some(user) = removed {
3428            self.remove_api_key_index_entries(&user);
3429        }
3430        self.persist_to_vault();
3431    }
3432
3433    fn rollback_bootstrap(&self, id: &UserId) {
3434        self.bootstrapped.store(false, Ordering::Release);
3435        self.rollback_create_user(id);
3436    }
3437
3438    fn restore_user_snapshot(&self, id: &UserId, previous: Option<User>) {
3439        match previous {
3440            Some(user) => {
3441                self.users
3442                    .write()
3443                    .unwrap_or_else(|e| e.into_inner())
3444                    .insert(id.clone(), user.clone());
3445                self.index_user_api_keys(id, &user);
3446            }
3447            None => {
3448                self.rollback_create_user(id);
3449                return;
3450            }
3451        }
3452        self.persist_to_vault();
3453    }
3454
3455    fn user_delete_rollback_snapshot(
3456        &self,
3457        id: &UserId,
3458        tenant_id: Option<&str>,
3459        username: &str,
3460    ) -> Option<(User, Vec<(String, Session)>)> {
3461        let user = self.get_user_cloned(id)?;
3462        let sessions = self
3463            .sessions
3464            .read()
3465            .map(|sessions| {
3466                sessions
3467                    .iter()
3468                    .filter(|(_, session)| {
3469                        session.username == username && session.tenant_id.as_deref() == tenant_id
3470                    })
3471                    .map(|(token, session)| (token.clone(), session.clone()))
3472                    .collect()
3473            })
3474            .unwrap_or_default();
3475        Some((user, sessions))
3476    }
3477
3478    fn restore_deleted_user(&self, id: &UserId, user: User, sessions: Vec<(String, Session)>) {
3479        self.users
3480            .write()
3481            .unwrap_or_else(|e| e.into_inner())
3482            .insert(id.clone(), user.clone());
3483        self.index_user_api_keys(id, &user);
3484        if !sessions.is_empty() {
3485            let mut guard = self.sessions.write().unwrap_or_else(|e| e.into_inner());
3486            for (token, session) in sessions {
3487                guard.insert(token, session);
3488            }
3489        }
3490        self.persist_to_vault();
3491    }
3492
3493    fn rollback_create_api_key(&self, id: &UserId, key: &str) {
3494        let key_id = api_key_credential_id(key);
3495        let key = key_id.as_str();
3496        if let Ok(mut users) = self.users.write() {
3497            if let Some(user) = users.get_mut(id) {
3498                user.api_keys.retain(|api_key| api_key.key != key);
3499                user.updated_at = now_ms();
3500            }
3501        }
3502        if let Ok(mut idx) = self.api_key_index.write() {
3503            idx.remove(key);
3504        }
3505        self.persist_to_vault();
3506    }
3507
3508    fn api_key_rollback_snapshot(&self, key: &str) -> Option<(UserId, ApiKey)> {
3509        let key = api_key_credential_id(key);
3510        let users = self.users.read().ok()?;
3511        users.iter().find_map(|(id, user)| {
3512            user.api_keys
3513                .iter()
3514                .find(|api_key| api_key.key == key)
3515                .cloned()
3516                .map(|api_key| (id.clone(), api_key))
3517        })
3518    }
3519
3520    fn restore_api_key(&self, id: &UserId, api_key: ApiKey) {
3521        if let Ok(mut users) = self.users.write() {
3522            if let Some(user) = users.get_mut(id) {
3523                if !user
3524                    .api_keys
3525                    .iter()
3526                    .any(|candidate| candidate.key == api_key.key)
3527                {
3528                    user.api_keys.push(api_key.clone());
3529                    user.updated_at = now_ms();
3530                }
3531            }
3532        }
3533        if let Ok(mut idx) = self.api_key_index.write() {
3534            idx.insert(api_key.key.clone(), (id.clone(), api_key.role));
3535        }
3536        self.persist_to_vault();
3537    }
3538
3539    fn remove_api_key_index_entries(&self, user: &User) {
3540        if let Ok(mut idx) = self.api_key_index.write() {
3541            for api_key in &user.api_keys {
3542                idx.remove(&api_key.key);
3543            }
3544        }
3545    }
3546
3547    fn index_user_api_keys(&self, id: &UserId, user: &User) {
3548        if let Ok(mut idx) = self.api_key_index.write() {
3549            for api_key in &user.api_keys {
3550                idx.insert(api_key.key.clone(), (id.clone(), api_key.role));
3551            }
3552        }
3553    }
3554
3555    // -----------------------------------------------------------------
3556    // Login-side enforcement (HTTP path)
3557    // -----------------------------------------------------------------
3558
3559    /// Authenticate with VALID UNTIL / CONNECTION LIMIT enforcement.
3560    /// Wraps `authenticate_in_tenant` and additionally:
3561    ///   * rejects logins after `valid_until`,
3562    ///   * rejects logins when the live session count would exceed the
3563    ///     `connection_limit` attribute.
3564    pub fn authenticate_with_attrs(
3565        &self,
3566        tenant_id: Option<&str>,
3567        username: &str,
3568        password: &str,
3569    ) -> Result<Session, AuthError> {
3570        let uid = UserId::from_parts(tenant_id, username);
3571        let session = self.authenticate_active(tenant_id, username, password)?;
3572        if let Err(error) = self.reserve_connection_slot(&uid) {
3573            self.remove_session_without_count(&session.token);
3574            return Err(error);
3575        }
3576        let mut tokens = self.counted_session_tokens.write().map_err(|_| {
3577            self.remove_session_without_count(&session.token);
3578            self.decrement_session_count(&uid);
3579            AuthError::Internal("session admission lock poisoned".to_string())
3580        })?;
3581        tokens.insert(session.token.clone());
3582        Ok(session)
3583    }
3584
3585    /// Authenticate a stateless/token login while enforcing account expiry.
3586    /// CONNECTION LIMIT is reserved for live wire leases, not for merely
3587    /// issuing a reusable bearer token.
3588    pub fn authenticate_active(
3589        &self,
3590        tenant_id: Option<&str>,
3591        username: &str,
3592        password: &str,
3593    ) -> Result<Session, AuthError> {
3594        let uid = UserId::from_parts(tenant_id, username);
3595        if let Some(deadline) = self.user_attributes(&uid).valid_until {
3596            if now_ms() >= deadline {
3597                return Err(AuthError::Forbidden(format!(
3598                    "account `{uid}` expired (VALID UNTIL exceeded)"
3599                )));
3600            }
3601        }
3602        self.authenticate_in_tenant(tenant_id, username, password)
3603    }
3604
3605    /// Authenticate a wire connection and hold its admission slot until the
3606    /// returned lease is dropped at EOF/Bye/error.
3607    pub fn authenticate_connection(
3608        self: &Arc<Self>,
3609        tenant_id: Option<&str>,
3610        username: &str,
3611        password: &str,
3612    ) -> Result<(Session, ConnectionLease), AuthError> {
3613        let session = self.authenticate_active(tenant_id, username, password)?;
3614        let principal = UserId::from_parts(tenant_id, username);
3615        if let Err(error) = self.reserve_connection_slot(&principal) {
3616            self.remove_session_without_count(&session.token);
3617            return Err(error);
3618        }
3619        // PG password authentication needs the verified identity but does not
3620        // expose a bearer token. Remove the transient login session so its TTL
3621        // and revocation lifecycle cannot release the socket-owned lease.
3622        self.remove_session_without_count(&session.token);
3623        let lease = ConnectionLease {
3624            store: Arc::clone(self),
3625            principal,
3626        };
3627        Ok((session, lease))
3628    }
3629
3630    /// Reserve a slot after a non-password proof (SCRAM, API key, session,
3631    /// or a locally mapped OAuth principal) has already been validated.
3632    pub fn acquire_connection_lease(
3633        self: &Arc<Self>,
3634        principal: &UserId,
3635    ) -> Result<ConnectionLease, AuthError> {
3636        if !self.principal_is_active(principal) {
3637            return Err(AuthError::InvalidCredentials);
3638        }
3639        self.reserve_connection_slot(principal)?;
3640        Ok(ConnectionLease {
3641            store: Arc::clone(self),
3642            principal: principal.clone(),
3643        })
3644    }
3645
3646    fn reserve_connection_slot(&self, uid: &UserId) -> Result<(), AuthError> {
3647        let attrs = self.user_attributes(uid);
3648        if let Some(deadline) = attrs.valid_until {
3649            if now_ms() >= deadline {
3650                return Err(AuthError::Forbidden(format!(
3651                    "account `{uid}` expired (VALID UNTIL exceeded)"
3652                )));
3653            }
3654        }
3655        let mut counts = self
3656            .session_count_by_user
3657            .write()
3658            .map_err(|_| AuthError::Internal("connection admission lock poisoned".to_string()))?;
3659        let current = counts.get(uid).copied().unwrap_or(0);
3660        if let Some(limit) = attrs.connection_limit {
3661            if current >= limit {
3662                return Err(AuthError::Forbidden(format!(
3663                    "account `{uid}` exceeded CONNECTION LIMIT ({limit})"
3664                )));
3665            }
3666        }
3667        counts.insert(uid.clone(), current.saturating_add(1));
3668        Ok(())
3669    }
3670
3671    /// Decrement the live-session count for `uid`. Call from session
3672    /// revoke / expiry paths so CONNECTION LIMIT stays accurate.
3673    pub fn decrement_session_count(&self, uid: &UserId) {
3674        if let Ok(mut counts) = self.session_count_by_user.write() {
3675            if let Some(c) = counts.get_mut(uid) {
3676                *c = c.saturating_sub(1);
3677            }
3678        }
3679    }
3680
3681    // -----------------------------------------------------------------
3682    // ACL persistence — vault_kv backed
3683    // -----------------------------------------------------------------
3684
3685    /// Re-read the ACL state from `vault_kv`. Call after vault load /
3686    /// restore so the in-memory maps reflect the persisted data.
3687    pub fn rehydrate_acl(&self) {
3688        let kv_snapshot: Vec<(String, String)> = self
3689            .vault_kv
3690            .read()
3691            .map(|kv| {
3692                kv.iter()
3693                    .filter(|(k, _)| {
3694                        k.starts_with("red.acl.grants.")
3695                            || k.starts_with("red.acl.attrs.")
3696                            || k == &"red.acl.public_grants"
3697                    })
3698                    .map(|(k, v)| (k.clone(), v.clone()))
3699                    .collect()
3700            })
3701            .unwrap_or_default();
3702
3703        for (k, v) in kv_snapshot {
3704            if k == "red.acl.public_grants" {
3705                if let Some(parsed) = decode_grants_blob(&v) {
3706                    *self
3707                        .public_grants
3708                        .write()
3709                        .unwrap_or_else(|e| e.into_inner()) = parsed;
3710                }
3711            } else if let Some(suffix) = k.strip_prefix("red.acl.grants.") {
3712                if let Some(uid) = decode_uid(suffix) {
3713                    if let Some(mut parsed) = decode_grants_blob(&v) {
3714                        // Restore the principal field — the on-disk
3715                        // line stores only resource+action shape.
3716                        for g in parsed.iter_mut() {
3717                            g.principal = GrantPrincipal::User(uid.clone());
3718                        }
3719                        self.grants
3720                            .write()
3721                            .unwrap_or_else(|e| e.into_inner())
3722                            .insert(uid, parsed);
3723                    }
3724                }
3725            } else if let Some(suffix) = k.strip_prefix("red.acl.attrs.") {
3726                if let Some(uid) = decode_uid(suffix) {
3727                    if let Some(parsed) = decode_attrs_blob(&v) {
3728                        self.user_attributes
3729                            .write()
3730                            .unwrap_or_else(|e| e.into_inner())
3731                            .insert(uid, parsed);
3732                    }
3733                }
3734            }
3735        }
3736
3737        self.permission_cache
3738            .write()
3739            .unwrap_or_else(|e| e.into_inner())
3740            .clear();
3741    }
3742
3743    /// Snapshot every ACL change back into the vault KV store.
3744    fn persist_acl_to_kv(&self) {
3745        let public = self
3746            .public_grants
3747            .read()
3748            .ok()
3749            .map(|p| encode_grants_blob(&p))
3750            .unwrap_or_default();
3751        self.vault_kv_set("red.acl.public_grants".to_string(), public);
3752
3753        let snapshot: Vec<(UserId, Vec<Grant>)> = self
3754            .grants
3755            .read()
3756            .ok()
3757            .map(|g| g.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
3758            .unwrap_or_default();
3759        for (uid, list) in snapshot {
3760            let key = format!("red.acl.grants.{}", encode_uid(&uid));
3761            let val = encode_grants_blob(&list);
3762            self.vault_kv_set(key, val);
3763        }
3764
3765        let attrs_snapshot: Vec<(UserId, UserAttributes)> = self
3766            .user_attributes
3767            .read()
3768            .ok()
3769            .map(|m| m.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
3770            .unwrap_or_default();
3771        for (uid, attrs) in attrs_snapshot {
3772            let key = format!("red.acl.attrs.{}", encode_uid(&uid));
3773            let val = encode_attrs_blob(&attrs);
3774            self.vault_kv_set(key, val);
3775        }
3776    }
3777
3778    fn invalidate_permission_cache(&self, uid: Option<&UserId>) {
3779        if let Ok(mut cache) = self.permission_cache.write() {
3780            match uid {
3781                Some(u) => {
3782                    cache.remove(u);
3783                }
3784                None => cache.clear(),
3785            }
3786        }
3787    }
3788
3789    // -----------------------------------------------------------------
3790    // IAM policies — put / delete / attach / detach / simulate
3791    //
3792    // The kernel in `super::policies` owns the Policy type and the
3793    // evaluator. AuthStore handles persistence + per-user cache + the
3794    // GRANT translation layer (synthetic `_grant_*` policies).
3795    // -----------------------------------------------------------------
3796
3797    pub fn put_policy_with_control_events(
3798        &self,
3799        p: Policy,
3800        control: &PolicyMutationControl<'_>,
3801    ) -> Result<(), AuthError> {
3802        let policy_id = p.id.clone();
3803        let kind = if self.get_policy(&policy_id).is_some() {
3804            EventKind::PolicyUpdate
3805        } else {
3806            EventKind::PolicyCreate
3807        };
3808
3809        if p.id.starts_with("_grant_") || p.id.starts_with("_default_") {
3810            let err = AuthError::Forbidden(format!("policy id `{}` is reserved", p.id));
3811            self.emit_policy_error(
3812                control,
3813                kind,
3814                "policy:put",
3815                &policy_id,
3816                Some(&p),
3817                None,
3818                &err,
3819            );
3820            return Err(err);
3821        }
3822
3823        if let Some(ManagedPolicyDecision::Deny {
3824            entry_id,
3825            matched_action,
3826            matched_resource,
3827            reason,
3828            ..
3829        }) = self.managed_policy_decision(&policy_id, PolicyOp::Put, control)
3830        {
3831            self.emit_policy_denied(
3832                control,
3833                kind,
3834                "policy:put",
3835                &policy_id,
3836                Some(&p),
3837                None,
3838                &reason.to_string(),
3839                Some(entry_id),
3840                Some((matched_action, matched_resource)),
3841            );
3842            return Err(Self::managed_policy_error(&policy_id, &reason.to_string()));
3843        }
3844
3845        let previous = self.get_policy(&policy_id);
3846        let was_enabled = self.iam_authorization_enabled();
3847        match self.put_policy_internal(p.clone()) {
3848            Ok(()) => match self.emit_policy_allowed(
3849                control,
3850                kind,
3851                "policy:put",
3852                &policy_id,
3853                Some(&p),
3854                None,
3855                None,
3856            ) {
3857                Ok(()) => Ok(()),
3858                Err(err) => {
3859                    self.restore_policy_put(&policy_id, previous, was_enabled);
3860                    Err(err)
3861                }
3862            },
3863            Err(err) => {
3864                self.emit_policy_error(
3865                    control,
3866                    kind,
3867                    "policy:put",
3868                    &policy_id,
3869                    Some(&p),
3870                    None,
3871                    &err,
3872                );
3873                Err(err)
3874            }
3875        }
3876    }
3877
3878    pub fn delete_policy_with_control_events(
3879        &self,
3880        id: &str,
3881        control: &PolicyMutationControl<'_>,
3882    ) -> Result<(), AuthError> {
3883        let existing = self.get_policy(id);
3884        if let Some(ManagedPolicyDecision::Deny {
3885            entry_id,
3886            matched_action,
3887            matched_resource,
3888            reason,
3889            ..
3890        }) = self.managed_policy_decision(id, PolicyOp::Drop, control)
3891        {
3892            self.emit_policy_denied(
3893                control,
3894                EventKind::PolicyDelete,
3895                "policy:drop",
3896                id,
3897                existing.as_deref(),
3898                None,
3899                &reason.to_string(),
3900                Some(entry_id),
3901                Some((matched_action, matched_resource)),
3902            );
3903            return Err(Self::managed_policy_error(id, &reason.to_string()));
3904        }
3905
3906        let user_attachments = self
3907            .user_attachments
3908            .read()
3909            .map(|m| m.clone())
3910            .unwrap_or_default();
3911        let group_attachments = self
3912            .group_attachments
3913            .read()
3914            .map(|m| m.clone())
3915            .unwrap_or_default();
3916        let was_enabled = self.iam_authorization_enabled();
3917        match self.delete_policy(id) {
3918            Ok(()) => match self.emit_policy_allowed(
3919                control,
3920                EventKind::PolicyDelete,
3921                "policy:drop",
3922                id,
3923                existing.as_deref(),
3924                None,
3925                None,
3926            ) {
3927                Ok(()) => Ok(()),
3928                Err(err) => {
3929                    if let Some(policy) = existing {
3930                        self.restore_policy_delete(
3931                            id,
3932                            policy,
3933                            user_attachments,
3934                            group_attachments,
3935                            was_enabled,
3936                        );
3937                    }
3938                    Err(err)
3939                }
3940            },
3941            Err(err) => {
3942                self.emit_policy_error(
3943                    control,
3944                    EventKind::PolicyDelete,
3945                    "policy:drop",
3946                    id,
3947                    existing.as_deref(),
3948                    None,
3949                    &err,
3950                );
3951                Err(err)
3952            }
3953        }
3954    }
3955
3956    pub fn attach_policy_with_control_events(
3957        &self,
3958        principal: PrincipalRef,
3959        policy_id: &str,
3960        control: &PolicyMutationControl<'_>,
3961    ) -> Result<(), AuthError> {
3962        let existing = self.get_policy(policy_id);
3963        if let Some(ManagedPolicyDecision::Deny {
3964            entry_id,
3965            matched_action,
3966            matched_resource,
3967            reason,
3968            ..
3969        }) = self.managed_policy_decision(policy_id, PolicyOp::Attach, control)
3970        {
3971            self.emit_policy_denied(
3972                control,
3973                EventKind::PolicyAttach,
3974                "policy:attach",
3975                policy_id,
3976                existing.as_deref(),
3977                Some(&principal),
3978                &reason.to_string(),
3979                Some(entry_id),
3980                Some((matched_action, matched_resource)),
3981            );
3982            return Err(Self::managed_policy_error(policy_id, &reason.to_string()));
3983        }
3984
3985        if let Some(err_msg) = self.check_self_lock_invariant_for_attach(policy_id) {
3986            self.emit_policy_denied(
3987                control,
3988                EventKind::PolicyAttach,
3989                "policy:attach",
3990                policy_id,
3991                existing.as_deref(),
3992                Some(&principal),
3993                &err_msg,
3994                None,
3995                None,
3996            );
3997            return Err(AuthError::Forbidden(err_msg));
3998        }
3999
4000        let user_attachments = self
4001            .user_attachments
4002            .read()
4003            .map(|m| m.clone())
4004            .unwrap_or_default();
4005        let group_attachments = self
4006            .group_attachments
4007            .read()
4008            .map(|m| m.clone())
4009            .unwrap_or_default();
4010        match self.attach_policy(principal.clone(), policy_id) {
4011            Ok(()) => match self.emit_policy_allowed(
4012                control,
4013                EventKind::PolicyAttach,
4014                "policy:attach",
4015                policy_id,
4016                existing.as_deref(),
4017                Some(&principal),
4018                None,
4019            ) {
4020                Ok(()) => Ok(()),
4021                Err(err) => {
4022                    self.restore_policy_attachments(user_attachments, group_attachments);
4023                    Err(err)
4024                }
4025            },
4026            Err(err) => {
4027                self.emit_policy_error(
4028                    control,
4029                    EventKind::PolicyAttach,
4030                    "policy:attach",
4031                    policy_id,
4032                    existing.as_deref(),
4033                    Some(&principal),
4034                    &err,
4035                );
4036                Err(err)
4037            }
4038        }
4039    }
4040
4041    pub fn detach_policy_with_control_events(
4042        &self,
4043        principal: PrincipalRef,
4044        policy_id: &str,
4045        control: &PolicyMutationControl<'_>,
4046    ) -> Result<(), AuthError> {
4047        let existing = self.get_policy(policy_id);
4048        if let Some(ManagedPolicyDecision::Deny {
4049            entry_id,
4050            matched_action,
4051            matched_resource,
4052            reason,
4053            ..
4054        }) = self.managed_policy_decision(policy_id, PolicyOp::Detach, control)
4055        {
4056            self.emit_policy_denied(
4057                control,
4058                EventKind::PolicyDetach,
4059                "policy:detach",
4060                policy_id,
4061                existing.as_deref(),
4062                Some(&principal),
4063                &reason.to_string(),
4064                Some(entry_id),
4065                Some((matched_action, matched_resource)),
4066            );
4067            return Err(Self::managed_policy_error(policy_id, &reason.to_string()));
4068        }
4069        let Some(existing_policy) = existing else {
4070            let err = AuthError::Forbidden(format!("policy `{policy_id}` not found"));
4071            self.emit_policy_error(
4072                control,
4073                EventKind::PolicyDetach,
4074                "policy:detach",
4075                policy_id,
4076                None,
4077                Some(&principal),
4078                &err,
4079            );
4080            return Err(err);
4081        };
4082
4083        let user_attachments = self
4084            .user_attachments
4085            .read()
4086            .map(|m| m.clone())
4087            .unwrap_or_default();
4088        let group_attachments = self
4089            .group_attachments
4090            .read()
4091            .map(|m| m.clone())
4092            .unwrap_or_default();
4093        match self.detach_policy(principal.clone(), policy_id) {
4094            Ok(()) => match self.emit_policy_allowed(
4095                control,
4096                EventKind::PolicyDetach,
4097                "policy:detach",
4098                policy_id,
4099                Some(existing_policy.as_ref()),
4100                Some(&principal),
4101                None,
4102            ) {
4103                Ok(()) => Ok(()),
4104                Err(err) => {
4105                    self.restore_policy_attachments(user_attachments, group_attachments);
4106                    Err(err)
4107                }
4108            },
4109            Err(err) => {
4110                self.emit_policy_error(
4111                    control,
4112                    EventKind::PolicyDetach,
4113                    "policy:detach",
4114                    policy_id,
4115                    Some(existing_policy.as_ref()),
4116                    Some(&principal),
4117                    &err,
4118                );
4119                Err(err)
4120            }
4121        }
4122    }
4123
4124    fn managed_policy_decision(
4125        &self,
4126        policy_id: &str,
4127        op: PolicyOp,
4128        control: &PolicyMutationControl<'_>,
4129    ) -> Option<ManagedPolicyDecision> {
4130        control.registry.map(|registry| {
4131            ManagedPolicyGate::new(registry).check_mutation(
4132                self,
4133                control.actor,
4134                control.eval_ctx,
4135                policy_id,
4136                op,
4137            )
4138        })
4139    }
4140
4141    /// Run the [`crate::auth::self_lock_guard`] invariant against the
4142    /// current policy set. Returns `Some(error_message)` when an attach
4143    /// must be refused, `None` when the system would remain unlockable.
4144    ///
4145    /// `_policy_id` is informational — the invariant is on the full
4146    /// graph and doesn't currently special-case the new entry.
4147    fn check_self_lock_invariant_for_attach(&self, _policy_id: &str) -> Option<String> {
4148        use crate::auth::self_lock_guard::{
4149            check_self_lock_invariant, format_block_error, InvariantOutcome,
4150        };
4151        let policies: Vec<Arc<Policy>> = match self.policies.read() {
4152            Ok(map) => map.values().cloned().collect(),
4153            Err(_) => return None,
4154        };
4155        let outcome = check_self_lock_invariant(&policies);
4156        match &outcome {
4157            InvariantOutcome::Ok => None,
4158            InvariantOutcome::Blocked { .. } => format_block_error(&outcome),
4159        }
4160    }
4161
4162    fn managed_policy_error(policy_id: &str, reason: &str) -> AuthError {
4163        AuthError::Forbidden(format!(
4164            "managed policy mutation blocked for `{policy_id}`: {reason}"
4165        ))
4166    }
4167
4168    fn emit_policy_allowed(
4169        &self,
4170        control: &PolicyMutationControl<'_>,
4171        kind: EventKind,
4172        action: &'static str,
4173        policy_id: &str,
4174        policy: Option<&Policy>,
4175        principal: Option<&PrincipalRef>,
4176        matched_policy_id: Option<String>,
4177    ) -> Result<(), AuthError> {
4178        let event = ControlEvent {
4179            kind,
4180            outcome: Outcome::Allowed,
4181            action: std::borrow::Cow::Borrowed(action),
4182            resource: Some(format!("policy:{policy_id}")),
4183            reason: None,
4184            matched_policy_id,
4185            fields: policy_control_fields(policy_id, policy, principal),
4186        };
4187        match control.ledger.emit(control.ctx, event) {
4188            Ok(_) => Ok(()),
4189            Err(err) if control.config.require_persistence() => {
4190                Err(AuthError::Internal(err.to_string()))
4191            }
4192            Err(_) => Ok(()),
4193        }
4194    }
4195
4196    #[allow(clippy::too_many_arguments)]
4197    fn emit_policy_denied(
4198        &self,
4199        control: &PolicyMutationControl<'_>,
4200        kind: EventKind,
4201        action: &'static str,
4202        policy_id: &str,
4203        policy: Option<&Policy>,
4204        principal: Option<&PrincipalRef>,
4205        reason: &str,
4206        matched_policy_id: Option<String>,
4207        matched: Option<(String, String)>,
4208    ) {
4209        let mut fields = policy_control_fields(policy_id, policy, principal);
4210        if let Some((matched_action, matched_resource)) = matched {
4211            fields.insert(
4212                "matched_action".to_string(),
4213                Sensitivity::raw(matched_action),
4214            );
4215            fields.insert(
4216                "matched_resource".to_string(),
4217                Sensitivity::raw(matched_resource),
4218            );
4219        }
4220        let event = ControlEvent {
4221            kind,
4222            outcome: Outcome::Denied,
4223            action: std::borrow::Cow::Borrowed(action),
4224            resource: Some(format!("policy:{policy_id}")),
4225            reason: Some(reason.to_string()),
4226            matched_policy_id,
4227            fields,
4228        };
4229        let _ = control.ledger.emit(control.ctx, event);
4230    }
4231
4232    fn emit_policy_error(
4233        &self,
4234        control: &PolicyMutationControl<'_>,
4235        kind: EventKind,
4236        action: &'static str,
4237        policy_id: &str,
4238        policy: Option<&Policy>,
4239        principal: Option<&PrincipalRef>,
4240        err: &AuthError,
4241    ) {
4242        let event = ControlEvent {
4243            kind,
4244            outcome: Outcome::Error,
4245            action: std::borrow::Cow::Borrowed(action),
4246            resource: Some(format!("policy:{policy_id}")),
4247            reason: Some(err.to_string()),
4248            matched_policy_id: None,
4249            fields: policy_control_fields(policy_id, policy, principal),
4250        };
4251        let _ = control.ledger.emit(control.ctx, event);
4252    }
4253
4254    fn restore_policy_put(
4255        &self,
4256        policy_id: &str,
4257        previous: Option<Arc<Policy>>,
4258        was_enabled: bool,
4259    ) {
4260        let mut policies = self.policies.write().unwrap_or_else(|e| e.into_inner());
4261        match previous {
4262            Some(policy) => {
4263                policies.insert(policy_id.to_string(), policy);
4264            }
4265            None => {
4266                policies.remove(policy_id);
4267            }
4268        }
4269        drop(policies);
4270        self.iam_authorization_enabled
4271            .store(was_enabled, Ordering::Release);
4272        self.iam_effective_cache
4273            .write()
4274            .unwrap_or_else(|e| e.into_inner())
4275            .clear();
4276        self.invalidate_visible_collections_cache();
4277        self.persist_iam_to_kv();
4278    }
4279
4280    fn restore_policy_delete(
4281        &self,
4282        policy_id: &str,
4283        policy: Arc<Policy>,
4284        user_attachments: HashMap<UserId, Vec<String>>,
4285        group_attachments: HashMap<String, Vec<String>>,
4286        was_enabled: bool,
4287    ) {
4288        self.policies
4289            .write()
4290            .unwrap_or_else(|e| e.into_inner())
4291            .insert(policy_id.to_string(), policy);
4292        self.restore_policy_attachments(user_attachments, group_attachments);
4293        self.iam_authorization_enabled
4294            .store(was_enabled, Ordering::Release);
4295        self.persist_iam_to_kv();
4296    }
4297
4298    fn restore_policy_attachments(
4299        &self,
4300        user_attachments: HashMap<UserId, Vec<String>>,
4301        group_attachments: HashMap<String, Vec<String>>,
4302    ) {
4303        *self
4304            .user_attachments
4305            .write()
4306            .unwrap_or_else(|e| e.into_inner()) = user_attachments;
4307        *self
4308            .group_attachments
4309            .write()
4310            .unwrap_or_else(|e| e.into_inner()) = group_attachments;
4311        self.iam_effective_cache
4312            .write()
4313            .unwrap_or_else(|e| e.into_inner())
4314            .clear();
4315        self.invalidate_visible_collections_cache();
4316        self.persist_iam_to_kv();
4317    }
4318
4319    /// Insert or replace a policy by id. Rejects synthetic ids
4320    /// (`_grant_*` / `_default_*`) so callers can't hand-write them
4321    /// from the public API. Use `put_policy_internal` for synthetic
4322    /// inserts.
4323    pub fn put_policy(&self, p: Policy) -> Result<(), AuthError> {
4324        if p.id.starts_with("_grant_") || p.id.starts_with("_default_") {
4325            return Err(AuthError::Forbidden(format!(
4326                "policy id `{}` is reserved",
4327                p.id
4328            )));
4329        }
4330        self.put_policy_internal(p)
4331    }
4332
4333    /// Internal put bypassing the synthetic-namespace guard. Used by
4334    /// the GRANT translation layer; exposed publicly so integration
4335    /// tests can register synthetic `_grant_*` policies without going
4336    /// through the SQL frontend.
4337    pub fn put_policy_internal(&self, p: Policy) -> Result<(), AuthError> {
4338        p.validate()
4339            .map_err(|e| AuthError::Forbidden(format!("invalid policy `{}`: {e}", p.id)))?;
4340        let id = p.id.clone();
4341        self.policies
4342            .write()
4343            .unwrap_or_else(|e| e.into_inner())
4344            .insert(id, Arc::new(p));
4345        self.iam_authorization_enabled
4346            .store(true, Ordering::Release);
4347        self.iam_effective_cache
4348            .write()
4349            .unwrap_or_else(|e| e.into_inner())
4350            .clear();
4351        // Issue #119: a policy mutation can change the visible-
4352        // collections answer for any (tenant, role); we don't know
4353        // which up-front, so blow the whole cache.
4354        self.invalidate_visible_collections_cache();
4355        self.persist_iam_to_kv();
4356        Ok(())
4357    }
4358
4359    /// Whether the IAM evaluator should be authoritative for runtime
4360    /// authorization. This flips on the first policy write and remains
4361    /// on after deletes so dropping all policies leaves the instance in
4362    /// default-deny rather than silently returning to role fallback.
4363    pub fn iam_authorization_enabled(&self) -> bool {
4364        self.iam_authorization_enabled.load(Ordering::Acquire)
4365    }
4366
4367    /// Remove a policy and any attachments referencing it.
4368    pub fn delete_policy(&self, id: &str) -> Result<(), AuthError> {
4369        let removed = self
4370            .policies
4371            .write()
4372            .unwrap_or_else(|e| e.into_inner())
4373            .remove(id)
4374            .is_some();
4375        if !removed {
4376            return Err(AuthError::Forbidden(format!("policy `{id}` not found")));
4377        }
4378        // Detach from every user / group.
4379        if let Ok(mut ua) = self.user_attachments.write() {
4380            for ids in ua.values_mut() {
4381                ids.retain(|p| p != id);
4382            }
4383            ua.retain(|_, v| !v.is_empty());
4384        }
4385        if let Ok(mut ga) = self.group_attachments.write() {
4386            for ids in ga.values_mut() {
4387                ids.retain(|p| p != id);
4388            }
4389            ga.retain(|_, v| !v.is_empty());
4390        }
4391        self.iam_effective_cache
4392            .write()
4393            .unwrap_or_else(|e| e.into_inner())
4394            .clear();
4395        // Issue #119: dropping a policy can shrink any caller's visible
4396        // set; clear the (tenant, role) cache so AI commands re-resolve.
4397        self.invalidate_visible_collections_cache();
4398        self.persist_iam_to_kv();
4399        Ok(())
4400    }
4401
4402    /// List all policies (id-sorted for deterministic output).
4403    pub fn list_policies(&self) -> Vec<Arc<Policy>> {
4404        let map = match self.policies.read() {
4405            Ok(g) => g,
4406            Err(_) => return Vec::new(),
4407        };
4408        let mut out: Vec<Arc<Policy>> = map.values().cloned().collect();
4409        out.sort_by(|a, b| a.id.cmp(&b.id));
4410        out
4411    }
4412
4413    /// Fetch a single policy by id.
4414    pub fn get_policy(&self, id: &str) -> Option<Arc<Policy>> {
4415        self.policies.read().ok().and_then(|m| m.get(id).cloned())
4416    }
4417
4418    /// List policies directly attached to a group.
4419    pub fn group_policies(&self, group: &str) -> Vec<Arc<Policy>> {
4420        let policies = self.policies.read();
4421        let attachments = self.group_attachments.read();
4422        let mut out = Vec::new();
4423        if let (Ok(p_map), Ok(ga_map)) = (policies, attachments) {
4424            if let Some(ids) = ga_map.get(group) {
4425                for id in ids {
4426                    if let Some(p) = p_map.get(id) {
4427                        out.push(p.clone());
4428                    }
4429                }
4430            }
4431        }
4432        out.sort_by(|a, b| a.id.cmp(&b.id));
4433        out
4434    }
4435
4436    /// Delete synthetic policies produced by SQL GRANT translation.
4437    /// REVOKE uses this to keep the IAM lane and the legacy grant table
4438    /// in lock-step.
4439    pub fn delete_synthetic_grant_policies(
4440        &self,
4441        principal: &GrantPrincipal,
4442        resource: &Resource,
4443        actions: &[Action],
4444    ) -> usize {
4445        let attached = match principal {
4446            GrantPrincipal::User(uid) => self
4447                .user_attachments
4448                .read()
4449                .ok()
4450                .and_then(|m| m.get(uid).cloned())
4451                .unwrap_or_default(),
4452            GrantPrincipal::Group(group) => self
4453                .group_attachments
4454                .read()
4455                .ok()
4456                .and_then(|m| m.get(group).cloned())
4457                .unwrap_or_default(),
4458            GrantPrincipal::Public => self
4459                .group_attachments
4460                .read()
4461                .ok()
4462                .and_then(|m| m.get(PUBLIC_IAM_GROUP).cloned())
4463                .unwrap_or_default(),
4464        };
4465        if attached.is_empty() {
4466            return 0;
4467        }
4468
4469        let mut delete_ids = Vec::new();
4470        if let Ok(policies) = self.policies.read() {
4471            for id in attached {
4472                let Some(policy) = policies.get(&id) else {
4473                    continue;
4474                };
4475                if !policy.id.starts_with("_grant_") {
4476                    continue;
4477                }
4478                if synthetic_grant_matches(policy, resource, actions) {
4479                    delete_ids.push(policy.id.clone());
4480                }
4481            }
4482        }
4483
4484        let mut deleted = 0usize;
4485        for id in delete_ids {
4486            if self.delete_policy(&id).is_ok() {
4487                deleted += 1;
4488            }
4489        }
4490        deleted
4491    }
4492
4493    /// Apply the `REDDB_POLICY_BREAK_GLASS` recovery path: install or
4494    /// refresh the unlock policy, ensure the synthetic platform-owner
4495    /// user record exists, rebind the unlock policy to it, and emit a
4496    /// `policy.break_glass` audit event. Idempotent across reboots.
4497    ///
4498    /// `boot_ts_ms` is recorded in the audit event so operators can
4499    /// correlate the recovery with the boot transcript.
4500    pub fn apply_policy_break_glass(&self, boot_ts_ms: u128) -> Result<(), AuthError> {
4501        use crate::auth::self_lock_guard::{
4502            break_glass_audit_fields, unlock_policy, PLATFORM_OWNER_UNLOCK_POLICY_ID,
4503            PLATFORM_OWNER_USERNAME,
4504        };
4505
4506        // (1) Install or refresh the unlock policy. `put_policy_internal`
4507        // bypasses the synthetic-namespace guard, lets us replace any
4508        // tampered persisted copy, and persists to vault on success.
4509        let policy = unlock_policy();
4510        self.put_policy_internal(policy)?;
4511
4512        // (2) Ensure the synthetic platform-owner user record exists.
4513        // We bypass the public user-creation API to keep this user
4514        // immutable, disabled, and absent from operator listings even
4515        // if our filter ever regresses.
4516        let owner_id = UserId::platform(PLATFORM_OWNER_USERNAME);
4517        {
4518            let mut users = self.users.write().unwrap_or_else(|e| e.into_inner());
4519            users.entry(owner_id.clone()).or_insert_with(|| User {
4520                username: PLATFORM_OWNER_USERNAME.to_string(),
4521                tenant_id: None,
4522                // No usable password; even if `authenticate` were
4523                // wired to accept the principal it would fail
4524                // verification. Defence in depth: `enabled = false`
4525                // and the username filter both block it.
4526                password_hash: String::new(),
4527                scram_verifier: None,
4528                role: Role::Admin,
4529                api_keys: Vec::new(),
4530                created_at: boot_ts_ms,
4531                updated_at: boot_ts_ms,
4532                enabled: false,
4533            });
4534        }
4535
4536        // (3) Rebind the unlock policy to the synthetic principal.
4537        // `attach_policy` is idempotent (the helper checks for an
4538        // existing binding before appending).
4539        self.attach_policy(
4540            PrincipalRef::User(owner_id.clone()),
4541            PLATFORM_OWNER_UNLOCK_POLICY_ID,
4542        )?;
4543
4544        // (4) Emit a loud audit event. If the control-event ledger
4545        // isn't configured (e.g. unit tests without runtime wiring),
4546        // log a warn and proceed — recovery must not depend on audit
4547        // wiring being live.
4548        let fields_raw = break_glass_audit_fields(boot_ts_ms);
4549        let mut fields: HashMap<String, Sensitivity> = HashMap::new();
4550        for (k, v) in fields_raw {
4551            fields.insert(k, Sensitivity::raw(v));
4552        }
4553        if let Some(configured) = self.configured_control_events() {
4554            let ctx = ControlEventCtx {
4555                actor: crate::runtime::control_events::ActorRef::System("break_glass"),
4556                scope: None,
4557                request_id: None,
4558                trace_id: None,
4559            };
4560            let event = ControlEvent {
4561                kind: EventKind::PolicyBreakGlass,
4562                outcome: Outcome::Allowed,
4563                action: std::borrow::Cow::Borrowed("policy:break_glass"),
4564                resource: Some(format!("policy:{PLATFORM_OWNER_UNLOCK_POLICY_ID}")),
4565                reason: Some("REDDB_POLICY_BREAK_GLASS=1 at boot".into()),
4566                matched_policy_id: None,
4567                fields,
4568            };
4569            let _ = configured.ledger.emit(&ctx, event);
4570        }
4571        tracing::warn!(
4572            policy_id = PLATFORM_OWNER_UNLOCK_POLICY_ID,
4573            principal = PLATFORM_OWNER_USERNAME,
4574            boot_ts_ms = %boot_ts_ms,
4575            "REDDB_POLICY_BREAK_GLASS=1 — installed/refreshed platform-owner unlock policy and rebound to synthetic principal"
4576        );
4577        Ok(())
4578    }
4579
4580    /// Attach a policy to a user or group. Returns an error if the
4581    /// policy id doesn't exist.
4582    pub fn attach_policy(&self, principal: PrincipalRef, policy_id: &str) -> Result<(), AuthError> {
4583        if !self
4584            .policies
4585            .read()
4586            .map(|m| m.contains_key(policy_id))
4587            .unwrap_or(false)
4588        {
4589            return Err(AuthError::Forbidden(format!(
4590                "policy `{policy_id}` not found"
4591            )));
4592        }
4593        match &principal {
4594            PrincipalRef::User(uid) => {
4595                let mut ua = self
4596                    .user_attachments
4597                    .write()
4598                    .unwrap_or_else(|e| e.into_inner());
4599                let list = ua.entry(uid.clone()).or_default();
4600                if !list.iter().any(|p| p == policy_id) {
4601                    list.push(policy_id.to_string());
4602                }
4603                drop(ua);
4604                self.invalidate_iam_cache(Some(uid));
4605            }
4606            PrincipalRef::Group(g) => {
4607                let mut ga = self
4608                    .group_attachments
4609                    .write()
4610                    .unwrap_or_else(|e| e.into_inner());
4611                let list = ga.entry(g.clone()).or_default();
4612                if !list.iter().any(|p| p == policy_id) {
4613                    list.push(policy_id.to_string());
4614                }
4615                drop(ga);
4616                self.invalidate_iam_cache(None);
4617            }
4618        }
4619        self.persist_iam_to_kv();
4620        Ok(())
4621    }
4622
4623    /// Remove a policy attachment from a user or group.
4624    pub fn detach_policy(&self, principal: PrincipalRef, policy_id: &str) -> Result<(), AuthError> {
4625        match &principal {
4626            PrincipalRef::User(uid) => {
4627                if let Ok(mut ua) = self.user_attachments.write() {
4628                    if let Some(list) = ua.get_mut(uid) {
4629                        list.retain(|p| p != policy_id);
4630                        if list.is_empty() {
4631                            ua.remove(uid);
4632                        }
4633                    }
4634                }
4635                self.invalidate_iam_cache(Some(uid));
4636            }
4637            PrincipalRef::Group(g) => {
4638                if let Ok(mut ga) = self.group_attachments.write() {
4639                    if let Some(list) = ga.get_mut(g) {
4640                        list.retain(|p| p != policy_id);
4641                        if list.is_empty() {
4642                            ga.remove(g);
4643                        }
4644                    }
4645                }
4646                self.invalidate_iam_cache(None);
4647            }
4648        }
4649        self.persist_iam_to_kv();
4650        Ok(())
4651    }
4652
4653    /// Resolve the ordered list of effective policies for a user:
4654    /// group attachments first (least specific), then user
4655    /// attachments (most specific). Cached per user.
4656    pub fn effective_policies(&self, user: &UserId) -> Vec<Arc<Policy>> {
4657        if let Ok(cache) = self.iam_effective_cache.read() {
4658            if let Some(hit) = cache.get(user) {
4659                return hit.clone();
4660            }
4661        }
4662        let policies = self.policies.read();
4663        let user_attachments = self.user_attachments.read();
4664        let group_attachments = self.group_attachments.read();
4665        let mut groups = self
4666            .user_attributes
4667            .read()
4668            .ok()
4669            .and_then(|m| m.get(user).map(|attrs| attrs.groups.clone()))
4670            .unwrap_or_default();
4671        groups.insert(0, PUBLIC_IAM_GROUP.to_string());
4672        let mut out: Vec<Arc<Policy>> = Vec::new();
4673        if let (Ok(p_map), Ok(ua_map), Ok(ga_map)) = (policies, user_attachments, group_attachments)
4674        {
4675            for group in groups {
4676                if let Some(ids) = ga_map.get(&group) {
4677                    for id in ids {
4678                        if let Some(p) = p_map.get(id) {
4679                            out.push(p.clone());
4680                        }
4681                    }
4682                }
4683            }
4684            if let Some(ids) = ua_map.get(user) {
4685                for id in ids {
4686                    if let Some(p) = p_map.get(id) {
4687                        out.push(p.clone());
4688                    }
4689                }
4690            }
4691        }
4692        if let Ok(mut cache) = self.iam_effective_cache.write() {
4693            cache.insert(user.clone(), out.clone());
4694        }
4695        out
4696    }
4697
4698    /// Run the policy simulator for a principal. Synthesises an
4699    /// `EvalContext` from the user record + caller-supplied extras.
4700    pub fn simulate(
4701        &self,
4702        principal: &UserId,
4703        action: &str,
4704        resource: &ResourceRef,
4705        ctx_extras: SimCtx,
4706    ) -> SimulationOutcome {
4707        let user_role = self
4708            .users
4709            .read()
4710            .ok()
4711            .and_then(|u| u.get(principal).map(|u| u.role));
4712        let principal_is_admin_role = user_role == Some(Role::Admin);
4713        let now = ctx_extras.now_ms.unwrap_or_else(now_ms);
4714        let ctx = EvalContext {
4715            principal_tenant: principal.tenant.clone(),
4716            current_tenant: ctx_extras.current_tenant,
4717            peer_ip: ctx_extras.peer_ip,
4718            mfa_present: ctx_extras.mfa_present,
4719            now_ms: now,
4720            principal_is_admin_role,
4721            principal_is_platform_scoped: principal.tenant.is_none(),
4722        };
4723        let pols = self.effective_policies(principal);
4724        let refs: Vec<&Policy> = pols.iter().map(|p| p.as_ref()).collect();
4725        iam_policies::simulate(&refs, action, resource, &ctx)
4726    }
4727
4728    /// Production hot-path policy evaluation. Returns `true` on Allow
4729    /// / AdminBypass, `false` on Deny / DefaultDeny.
4730    ///
4731    /// This entry point is **strict**: it never consults the
4732    /// [`PolicyEnforcementMode`] fallback. Governance APIs that gate
4733    /// admin-tier mutations (managed-config writes, registry
4734    /// supersedes, managed-policy lifecycle) call this so they cannot
4735    /// accidentally pick up the lenient `LegacyRbac` posture. Runtime
4736    /// hot-path callers that should respect the mode call
4737    /// [`AuthStore::check_policy_authz_with_role`] instead.
4738    pub fn check_policy_authz(
4739        &self,
4740        principal: &UserId,
4741        action: &str,
4742        resource: &ResourceRef,
4743        ctx: &EvalContext,
4744    ) -> bool {
4745        let pols = self.effective_policies(principal);
4746        let refs: Vec<&Policy> = pols.iter().map(|p| p.as_ref()).collect();
4747        let decision = iam_policies::evaluate(&refs, action, resource, ctx);
4748        matches!(
4749            decision,
4750            iam_policies::Decision::Allow { .. } | iam_policies::Decision::AdminBypass
4751        )
4752    }
4753
4754    /// Mode-aware policy evaluation for runtime SQL/HTTP/wire surfaces.
4755    ///
4756    /// Returns `true` on `Allow`/`AdminBypass`, `false` on an explicit
4757    /// `Deny`. On `DefaultDeny` (no statement matched) the result
4758    /// depends on the active [`PolicyEnforcementMode`]:
4759    ///
4760    /// * `LegacyRbac` — defer to
4761    ///   [`legacy_rbac_decision`][super::enforcement_mode::legacy_rbac_decision]
4762    ///   using the caller's `role`. This preserves the pre-#712
4763    ///   behaviour where a principal with no attached policy is gated
4764    ///   only by their role.
4765    /// * `PolicyOnly` — return `false`. A principal needs an explicit
4766    ///   matching `Allow` to be authorized.
4767    ///
4768    /// An explicit `Deny` always wins, irrespective of mode and role.
4769    pub fn check_policy_authz_with_role(
4770        &self,
4771        principal: &UserId,
4772        action: &str,
4773        resource: &ResourceRef,
4774        ctx: &EvalContext,
4775        role: Role,
4776    ) -> bool {
4777        let pols = self.effective_policies(principal);
4778        let refs: Vec<&Policy> = pols.iter().map(|p| p.as_ref()).collect();
4779        let decision = iam_policies::evaluate(&refs, action, resource, ctx);
4780        match decision {
4781            iam_policies::Decision::Allow { .. } | iam_policies::Decision::AdminBypass => true,
4782            iam_policies::Decision::Deny { .. } => false,
4783            iam_policies::Decision::DefaultDeny => match self.enforcement_mode() {
4784                PolicyEnforcementMode::LegacyRbac => legacy_rbac_decision(role, action),
4785                PolicyEnforcementMode::PolicyOnly => false,
4786            },
4787        }
4788    }
4789
4790    // -----------------------------------------------------------------
4791    // PolicyEnforcementMode (#712)
4792    // -----------------------------------------------------------------
4793
4794    /// Read the active enforcement mode. Cheap (a single `RwLock` read);
4795    /// safe to call on the hot path.
4796    pub fn enforcement_mode(&self) -> PolicyEnforcementMode {
4797        *self
4798            .enforcement_mode
4799            .read()
4800            .unwrap_or_else(|e| e.into_inner())
4801    }
4802
4803    /// Overwrite the active enforcement mode and persist it to the
4804    /// vault KV so the new value survives a restart. Returns the
4805    /// previous value so callers logging a transition (e.g. the
4806    /// boot-time loader, the S5B migration command) can record the
4807    /// before/after.
4808    pub fn set_enforcement_mode(&self, mode: PolicyEnforcementMode) -> PolicyEnforcementMode {
4809        let prev = {
4810            let mut guard = self
4811                .enforcement_mode
4812                .write()
4813                .unwrap_or_else(|e| e.into_inner());
4814            let prev = *guard;
4815            *guard = mode;
4816            prev
4817        };
4818        self.vault_kv_set(
4819            "red.config.policy.enforcement_mode".to_string(),
4820            mode.as_str().to_string(),
4821        );
4822        prev
4823    }
4824
4825    /// Claim the "emit the one-time legacy-RBAC boot warning" token.
4826    /// Returns `true` on the first call after construction (or after a
4827    /// process restart) **iff** the active mode is `LegacyRbac`;
4828    /// returns `false` on every subsequent call so the boot path can
4829    /// guarantee the warning is logged at most once per boot.
4830    pub fn take_legacy_rbac_warn_once(&self) -> bool {
4831        if self.enforcement_mode() != PolicyEnforcementMode::LegacyRbac {
4832            return false;
4833        }
4834        !self
4835            .legacy_rbac_boot_warn_emitted
4836            .swap(true, Ordering::AcqRel)
4837    }
4838
4839    /// Evaluate a resolved table projection through the column policy
4840    /// gate. Query paths should pass already-resolved column names; this
4841    /// helper intentionally does not parse SQL projection syntax.
4842    pub fn check_column_projection_authz(
4843        &self,
4844        principal: &UserId,
4845        request: &ColumnAccessRequest,
4846        ctx: &EvalContext,
4847    ) -> ColumnPolicyOutcome {
4848        let pols = self.effective_policies(principal);
4849        let refs: Vec<&Policy> = pols.iter().map(|p| p.as_ref()).collect();
4850        ColumnPolicyGate::new(&refs).evaluate(request, ctx)
4851    }
4852
4853    fn invalidate_iam_cache(&self, uid: Option<&UserId>) {
4854        if let Ok(mut cache) = self.iam_effective_cache.write() {
4855            match uid {
4856                Some(u) => {
4857                    cache.remove(u);
4858                }
4859                None => cache.clear(),
4860            }
4861        }
4862    }
4863
4864    /// Drop every effective-policy cache entry. Called from execution
4865    /// paths that mutate policies/attachments without knowing which
4866    /// users will be affected.
4867    pub fn invalidate_all_iam_cache(&self) {
4868        self.invalidate_iam_cache(None);
4869    }
4870
4871    // -----------------------------------------------------------------
4872    // IAM persistence — vault_kv backed under `red.iam.*` keys
4873    // -----------------------------------------------------------------
4874
4875    /// Reload IAM state (policies + attachments) from the vault KV.
4876    /// Replaces the legacy `rehydrate_acl` reader — pre-1.0 we drop
4877    /// the old `red.acl.*` blob format entirely.
4878    pub fn rehydrate_iam(&self) {
4879        let mut enabled = self
4880            .vault_kv_get("red.iam.enabled")
4881            .map(|v| v == "true")
4882            .unwrap_or(false);
4883        // Policies — single JSON object keyed by id.
4884        if let Some(blob) = self.vault_kv_get("red.iam.policies") {
4885            if let Ok(val) = crate::serde_json::from_str::<crate::serde_json::Value>(&blob) {
4886                if let Some(obj) = val.as_object() {
4887                    let mut map = HashMap::new();
4888                    for (id, body) in obj.iter() {
4889                        let s = body.to_string_compact();
4890                        if let Ok(p) = Policy::from_json_str(&s) {
4891                            map.insert(id.clone(), Arc::new(p));
4892                        }
4893                    }
4894                    if !map.is_empty() {
4895                        enabled = true;
4896                    }
4897                    *self.policies.write().unwrap_or_else(|e| e.into_inner()) = map;
4898                }
4899            }
4900        }
4901        // User attachments.
4902        if let Some(blob) = self.vault_kv_get("red.iam.attachments.users") {
4903            if let Ok(val) = crate::serde_json::from_str::<crate::serde_json::Value>(&blob) {
4904                if let Some(obj) = val.as_object() {
4905                    let mut map: HashMap<UserId, Vec<String>> = HashMap::new();
4906                    for (encoded_uid, ids_v) in obj.iter() {
4907                        let Some(uid) = decode_uid(encoded_uid) else {
4908                            continue;
4909                        };
4910                        if let Some(arr) = ids_v.as_array() {
4911                            let ids: Vec<String> = arr
4912                                .iter()
4913                                .filter_map(|v| v.as_str().map(|s| s.to_string()))
4914                                .collect();
4915                            map.insert(uid, ids);
4916                        }
4917                    }
4918                    *self
4919                        .user_attachments
4920                        .write()
4921                        .unwrap_or_else(|e| e.into_inner()) = map;
4922                }
4923            }
4924        }
4925        // Group attachments.
4926        if let Some(blob) = self.vault_kv_get("red.iam.attachments.groups") {
4927            if let Ok(val) = crate::serde_json::from_str::<crate::serde_json::Value>(&blob) {
4928                if let Some(obj) = val.as_object() {
4929                    let mut map: HashMap<String, Vec<String>> = HashMap::new();
4930                    for (g, ids_v) in obj.iter() {
4931                        if let Some(arr) = ids_v.as_array() {
4932                            let ids: Vec<String> = arr
4933                                .iter()
4934                                .filter_map(|v| v.as_str().map(|s| s.to_string()))
4935                                .collect();
4936                            map.insert(g.clone(), ids);
4937                        }
4938                    }
4939                    *self
4940                        .group_attachments
4941                        .write()
4942                        .unwrap_or_else(|e| e.into_inner()) = map;
4943                }
4944            }
4945        }
4946        self.iam_authorization_enabled
4947            .store(enabled, Ordering::Release);
4948        self.invalidate_iam_cache(None);
4949
4950        // #712 / S5A: load persisted enforcement mode, if any. Absence
4951        // of the key means an existing install upgrading past #712 —
4952        // stay on the lenient default written at construction time.
4953        // Fresh installs receive `PolicyOnly` via the bootstrap path
4954        // (`mark_bootstrap_complete`) before the first restart, so this
4955        // hydrate path picks it up on every subsequent boot.
4956        if let Some(stored) = self.vault_kv_get("red.config.policy.enforcement_mode") {
4957            if let Some(mode) = PolicyEnforcementMode::parse(&stored) {
4958                *self
4959                    .enforcement_mode
4960                    .write()
4961                    .unwrap_or_else(|e| e.into_inner()) = mode;
4962            }
4963        }
4964
4965        // #712 / S5A: legacy_rbac is a transitional posture; emit one
4966        // boot-time warning so operators see the migration nudge in
4967        // their logs. The flag inside take_legacy_rbac_warn_once
4968        // guarantees we don't spam reload cycles.
4969        if self.take_legacy_rbac_warn_once() {
4970            tracing::warn!(
4971                target: "reddb::auth::enforcement_mode",
4972                mode = "legacy_rbac",
4973                hard_version = crate::auth::enforcement_mode::POLICY_ONLY_HARD_VERSION,
4974                "policy enforcement_mode=legacy_rbac (transitional). Run \
4975                 `MIGRATE POLICY MODE TO 'policy_only'` (next slice S5B) \
4976                 before {} to flip this install over to the strict posture.",
4977                crate::auth::enforcement_mode::POLICY_ONLY_HARD_VERSION,
4978            );
4979        }
4980    }
4981
4982    /// Snapshot policies + attachments into the vault KV. Called
4983    /// after every mutation.
4984    fn persist_iam_to_kv(&self) {
4985        let enabled = if self.iam_authorization_enabled() {
4986            "true"
4987        } else {
4988            "false"
4989        };
4990        self.vault_kv_set("red.iam.enabled".to_string(), enabled.to_string());
4991
4992        // Policies: `{ "<id>": <policy_json>, ... }`
4993        let policies_obj = {
4994            let map = self.policies.read().unwrap_or_else(|e| e.into_inner());
4995            let mut obj = crate::serde_json::Map::new();
4996            for (id, p) in map.iter() {
4997                let s = p.to_json_string();
4998                if let Ok(v) = crate::serde_json::from_str::<crate::serde_json::Value>(&s) {
4999                    obj.insert(id.clone(), v);
5000                }
5001            }
5002            crate::serde_json::Value::Object(obj).to_string_compact()
5003        };
5004        self.vault_kv_set("red.iam.policies".to_string(), policies_obj);
5005
5006        // User attachments: `{ "<encoded_uid>": [ "<policy_id>", ... ], ... }`
5007        let users_obj = {
5008            let map = self
5009                .user_attachments
5010                .read()
5011                .unwrap_or_else(|e| e.into_inner());
5012            let mut obj = crate::serde_json::Map::new();
5013            for (uid, ids) in map.iter() {
5014                let arr = crate::serde_json::Value::Array(
5015                    ids.iter()
5016                        .map(|s| crate::serde_json::Value::String(s.clone()))
5017                        .collect(),
5018                );
5019                obj.insert(encode_uid(uid), arr);
5020            }
5021            crate::serde_json::Value::Object(obj).to_string_compact()
5022        };
5023        self.vault_kv_set("red.iam.attachments.users".to_string(), users_obj);
5024
5025        // Group attachments.
5026        let groups_obj = {
5027            let map = self
5028                .group_attachments
5029                .read()
5030                .unwrap_or_else(|e| e.into_inner());
5031            let mut obj = crate::serde_json::Map::new();
5032            for (g, ids) in map.iter() {
5033                let arr = crate::serde_json::Value::Array(
5034                    ids.iter()
5035                        .map(|s| crate::serde_json::Value::String(s.clone()))
5036                        .collect(),
5037                );
5038                obj.insert(g.clone(), arr);
5039            }
5040            crate::serde_json::Value::Object(obj).to_string_compact()
5041        };
5042        self.vault_kv_set("red.iam.attachments.groups".to_string(), groups_obj);
5043    }
5044}
5045
5046fn synthetic_grant_matches(policy: &Policy, resource: &Resource, actions: &[Action]) -> bool {
5047    policy.statements.iter().any(|st| {
5048        st.effect == crate::auth::policies::Effect::Allow
5049            && st.condition.is_none()
5050            && grant_actions_overlap(&st.actions, actions)
5051            && grant_resource_matches(&st.resources, resource)
5052    })
5053}
5054
5055fn grant_actions_overlap(
5056    patterns: &[crate::auth::policies::ActionPattern],
5057    actions: &[Action],
5058) -> bool {
5059    if actions.contains(&Action::All) {
5060        return true;
5061    }
5062    patterns.iter().any(|pat| match pat {
5063        crate::auth::policies::ActionPattern::Wildcard => true,
5064        crate::auth::policies::ActionPattern::Exact(s) => {
5065            actions.iter().any(|a| s.eq_ignore_ascii_case(a.as_str()))
5066        }
5067        crate::auth::policies::ActionPattern::Prefix(_) => false,
5068    })
5069}
5070
5071fn grant_resource_matches(
5072    patterns: &[crate::auth::policies::ResourcePattern],
5073    resource: &Resource,
5074) -> bool {
5075    let expected = grant_resource_pattern(resource);
5076    patterns.iter().any(|pat| pat == &expected)
5077}
5078
5079fn grant_resource_pattern(resource: &Resource) -> crate::auth::policies::ResourcePattern {
5080    use crate::auth::policies::ResourcePattern;
5081
5082    match resource {
5083        Resource::Database => ResourcePattern::Glob("table:*".to_string()),
5084        Resource::Schema(s) => ResourcePattern::Glob(format!("table:{s}.*")),
5085        Resource::Table { schema, table } => ResourcePattern::Exact {
5086            kind: "table".to_string(),
5087            name: match schema {
5088                Some(s) => format!("{s}.{table}"),
5089                None => table.clone(),
5090            },
5091        },
5092        Resource::Function { schema, name } => ResourcePattern::Exact {
5093            kind: "function".to_string(),
5094            name: match schema {
5095                Some(s) => format!("{s}.{name}"),
5096                None => name.clone(),
5097            },
5098        },
5099    }
5100}
5101
5102// ===========================================================================
5103// ACL serialization helpers — line-oriented, human-readable so an
5104// operator inspecting the vault dump can spot misconfigurations.
5105//
5106// Format (one record per line):
5107//   GRANT|<resource>|<actions_csv>|<with_grant_option>|<tenant_or_*>|<granted_by>|<granted_at>
5108//   ATTR|<valid_until>|<connection_limit>|<search_path>
5109//
5110// Resources are encoded as:
5111//   db                          → Database
5112//   schema:<name>               → Schema(name)
5113//   table:<schema_or_*>:<name>  → Table { schema, table }
5114//   func:<schema_or_*>:<name>   → Function { schema, name }
5115// ===========================================================================
5116
5117fn encode_uid(uid: &UserId) -> String {
5118    match &uid.tenant {
5119        Some(t) => format!("{}/{}", t, uid.username),
5120        None => format!("*/{}", uid.username),
5121    }
5122}
5123
5124fn decode_uid(s: &str) -> Option<UserId> {
5125    let (tenant, username) = s.split_once('/')?;
5126    Some(if tenant == "*" {
5127        UserId::platform(username)
5128    } else {
5129        UserId::scoped(tenant, username)
5130    })
5131}
5132
5133fn encode_resource(r: &Resource) -> String {
5134    match r {
5135        Resource::Database => "db".into(),
5136        Resource::Schema(s) => format!("schema:{}", s),
5137        Resource::Table { schema, table } => {
5138            format!("table:{}:{}", schema.as_deref().unwrap_or("*"), table)
5139        }
5140        Resource::Function { schema, name } => {
5141            format!("func:{}:{}", schema.as_deref().unwrap_or("*"), name)
5142        }
5143    }
5144}
5145
5146fn decode_resource(s: &str) -> Option<Resource> {
5147    if s == "db" {
5148        return Some(Resource::Database);
5149    }
5150    if let Some(rest) = s.strip_prefix("schema:") {
5151        return Some(Resource::Schema(rest.to_string()));
5152    }
5153    if let Some(rest) = s.strip_prefix("table:") {
5154        let (schema, table) = rest.split_once(':')?;
5155        return Some(Resource::Table {
5156            schema: if schema == "*" {
5157                None
5158            } else {
5159                Some(schema.to_string())
5160            },
5161            table: table.to_string(),
5162        });
5163    }
5164    if let Some(rest) = s.strip_prefix("func:") {
5165        let (schema, name) = rest.split_once(':')?;
5166        return Some(Resource::Function {
5167            schema: if schema == "*" {
5168                None
5169            } else {
5170                Some(schema.to_string())
5171            },
5172            name: name.to_string(),
5173        });
5174    }
5175    None
5176}
5177
5178fn encode_grants_blob(grants: &[Grant]) -> String {
5179    let mut out = String::new();
5180    for g in grants {
5181        let actions: Vec<&str> = g.actions.iter().map(|a| a.as_str()).collect();
5182        out.push_str(&format!(
5183            "GRANT|{}|{}|{}|{}|{}|{}\n",
5184            encode_resource(&g.resource),
5185            actions.join(","),
5186            g.with_grant_option,
5187            g.tenant.as_deref().unwrap_or("*"),
5188            g.granted_by,
5189            g.granted_at,
5190        ));
5191    }
5192    out
5193}
5194
5195fn decode_grants_blob(s: &str) -> Option<Vec<Grant>> {
5196    let mut out = Vec::new();
5197    for line in s.lines() {
5198        if line.is_empty() {
5199            continue;
5200        }
5201        let parts: Vec<&str> = line.split('|').collect();
5202        if parts.len() != 7 || parts[0] != "GRANT" {
5203            return None;
5204        }
5205        let resource = decode_resource(parts[1])?;
5206        let mut actions = std::collections::BTreeSet::new();
5207        for token in parts[2].split(',') {
5208            if let Some(a) = Action::from_keyword(token) {
5209                actions.insert(a);
5210            }
5211        }
5212        let with_grant_option = parts[3] == "true";
5213        let tenant = if parts[4] == "*" {
5214            None
5215        } else {
5216            Some(parts[4].to_string())
5217        };
5218        let granted_by = parts[5].to_string();
5219        let granted_at: u128 = parts[6].parse().unwrap_or(0);
5220        out.push(Grant {
5221            // Principal field is reconstructed by the loader from the
5222            // storage-key prefix; default to `Public` here.
5223            principal: GrantPrincipal::Public,
5224            resource,
5225            actions,
5226            with_grant_option,
5227            granted_by,
5228            granted_at,
5229            tenant,
5230            columns: None,
5231        });
5232    }
5233    Some(out)
5234}
5235
5236fn encode_attrs_blob(a: &UserAttributes) -> String {
5237    let valid = a
5238        .valid_until
5239        .map(|t| t.to_string())
5240        .unwrap_or_else(|| "*".into());
5241    let limit = a
5242        .connection_limit
5243        .map(|l| l.to_string())
5244        .unwrap_or_else(|| "*".into());
5245    let path = a.search_path.clone().unwrap_or_else(|| "*".into());
5246    let groups = if a.groups.is_empty() {
5247        "*".to_string()
5248    } else {
5249        a.groups.join(",")
5250    };
5251    format!("ATTR|{}|{}|{}|{}\n", valid, limit, path, groups)
5252}
5253
5254fn decode_attrs_blob(s: &str) -> Option<UserAttributes> {
5255    let line = s.lines().next()?;
5256    let parts: Vec<&str> = line.split('|').collect();
5257    if !(parts.len() == 4 || parts.len() == 5) || parts[0] != "ATTR" {
5258        return None;
5259    }
5260    let groups = if parts.get(4).copied().unwrap_or("*") == "*" {
5261        Vec::new()
5262    } else {
5263        parts[4]
5264            .split(',')
5265            .filter(|g| !g.is_empty())
5266            .map(|g| g.to_string())
5267            .collect()
5268    };
5269    Some(UserAttributes {
5270        valid_until: if parts[1] == "*" {
5271            None
5272        } else {
5273            parts[1].parse().ok()
5274        },
5275        connection_limit: if parts[2] == "*" {
5276            None
5277        } else {
5278            parts[2].parse().ok()
5279        },
5280        search_path: if parts[3] == "*" {
5281            None
5282        } else {
5283            Some(parts[3].to_string())
5284        },
5285        groups,
5286    })
5287}
5288
5289// ===========================================================================
5290// Password hashing
5291// ===========================================================================
5292
5293/// Derive a SCRAM-SHA-256 verifier for a fresh user / password
5294/// rotation. Salt is 16 random bytes; iter is the engine default
5295/// (`scram::DEFAULT_ITER`). Stored alongside the Argon2 password
5296/// hash so HTTP login + v2 SCRAM can both authenticate the same
5297/// user.
5298fn make_scram_verifier(password: &str) -> crate::auth::scram::ScramVerifier {
5299    let salt = random_bytes(16);
5300    crate::auth::scram::ScramVerifier::from_password(
5301        password,
5302        salt,
5303        crate::auth::scram::DEFAULT_ITER,
5304    )
5305}
5306
5307/// Argon2id cost parameters for password hashing, at the OWASP floor
5308/// (19 MiB, t=2, p=1). The previous in-tree KDF ran at 4 MiB / t=3, which
5309/// is below that floor; the parameters are encoded in the PHC string so
5310/// they can be raised again without another format change.
5311const PASSWORD_M_COST_KIB: u32 = 19 * 1024;
5312const PASSWORD_T_COST: u32 = 2;
5313const PASSWORD_P_COST: u32 = 1;
5314const PASSWORD_TAG_LEN: usize = 32;
5315
5316static DUMMY_PASSWORD_HASH: OnceLock<String> = OnceLock::new();
5317
5318fn dummy_password_hash() -> &'static str {
5319    DUMMY_PASSWORD_HASH
5320        .get_or_init(|| hash_password("reddb-invalid-login-dummy"))
5321        .as_str()
5322}
5323
5324fn password_hasher() -> argon2::Argon2<'static> {
5325    let params = argon2::Params::new(
5326        PASSWORD_M_COST_KIB,
5327        PASSWORD_T_COST,
5328        PASSWORD_P_COST,
5329        Some(PASSWORD_TAG_LEN),
5330    )
5331    .expect("Argon2id parameters are constant and valid");
5332    argon2::Argon2::new(argon2::Algorithm::Argon2id, argon2::Version::V0x13, params)
5333}
5334
5335/// Hash a password with Argon2id (RFC 9106) via the RustCrypto `argon2`
5336/// crate, encoded as a PHC string:
5337/// `$argon2id$v=19$m=19456,t=2,p=1$<salt_b64>$<hash_b64>`.
5338///
5339/// The previous in-tree implementation was not RFC 9106 — its `G` mixing
5340/// function added the block indices where the specification calls for the
5341/// `2·lo32(a)·lo32(b)` term, and its compression function was ad hoc — so
5342/// its memory-hardness was unknown. Hashes in the old
5343/// `argon2id$<salt_hex>$<hash_hex>` form still verify (see
5344/// [`verify_password`]) and are transparently upgraded on the owner's next
5345/// successful login.
5346pub(crate) fn hash_password(password: &str) -> String {
5347    use argon2::PasswordHasher;
5348    // The salt comes from the OS CSPRNG inside the hasher and, like
5349    // `random_bytes`, fails closed rather than degrading.
5350    password_hasher()
5351        .hash_password(password.as_bytes())
5352        .expect("Argon2id hashing cannot fail for valid parameters and a working CSPRNG")
5353        .to_string()
5354}
5355
5356/// Whether `stored_hash` was produced by the retired in-tree KDF and should
5357/// be re-hashed the next time its owner authenticates.
5358pub(crate) fn password_hash_needs_upgrade(stored_hash: &str) -> bool {
5359    stored_hash.starts_with("argon2id$")
5360}
5361
5362/// Verify a password against either encoding: the current PHC string, or a
5363/// legacy `argon2id$<salt_hex>$<hash_hex>` produced by the retired in-tree
5364/// KDF. Legacy hashes stay verifiable so an upgrade does not lock every
5365/// account out; [`password_hash_needs_upgrade`] drives the rehash.
5366pub(crate) fn verify_password(password: &str, stored_hash: &str) -> bool {
5367    if let Some(rest) = stored_hash.strip_prefix("argon2id$") {
5368        return verify_legacy_password(password, rest);
5369    }
5370    use argon2::{PasswordHash, PasswordVerifier};
5371    let Ok(parsed) = stored_hash.parse::<PasswordHash>() else {
5372        return false;
5373    };
5374    password_hasher()
5375        .verify_password(password.as_bytes(), &parsed)
5376        .is_ok()
5377}
5378
5379/// Verify against the retired in-tree KDF, whose stored form is
5380/// `<salt_hex>$<hash_hex>` (the `argon2id$` prefix is already stripped).
5381fn verify_legacy_password(password: &str, salt_and_hash: &str) -> bool {
5382    let Some((salt_hex, hash_hex)) = salt_and_hash.split_once('$') else {
5383        return false;
5384    };
5385    let (Ok(salt), Ok(expected)) = (hex::decode(salt_hex), hex::decode(hash_hex)) else {
5386        return false;
5387    };
5388    let computed = derive_key(password.as_bytes(), &salt, &auth_argon2_params());
5389    constant_time_eq(&computed, &expected)
5390}
5391
5392/// Constant-time byte comparison — one implementation for the crate.
5393fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
5394    crate::crypto::constant_time_eq(a, b)
5395}
5396
5397// ===========================================================================
5398// Token generation
5399// ===========================================================================
5400
5401fn generate_session_token() -> String {
5402    format!("rs_{}", hex::encode(random_bytes(32)))
5403}
5404
5405fn generate_api_key() -> String {
5406    format!("rk_{}", hex::encode(random_bytes(32)))
5407}
5408
5409/// Generate `n` random bytes and return as a hex string.
5410fn random_hex(n: usize) -> String {
5411    hex::encode(random_bytes(n))
5412}
5413
5414/// Generate `n` cryptographically random bytes using the OS CSPRNG,
5415/// then mix with SHA-256 for domain separation.
5416pub(crate) fn random_bytes(n: usize) -> Vec<u8> {
5417    let mut buf = vec![0u8; n.max(32)];
5418    // Fail closed: these bytes become session tokens, API keys, salts and
5419    // AES-GCM nonces. A predictable fallback (the old time-derived seed)
5420    // is strictly worse than refusing the operation.
5421    if let Err(err) = os_random::fill_bytes(&mut buf) {
5422        panic!("OS CSPRNG unavailable; refusing to generate credential material: {err}");
5423    }
5424    // SHA-256 mix to ensure uniform distribution.
5425    let digest = sha256(&buf);
5426    if n <= 32 {
5427        digest[..n].to_vec()
5428    } else {
5429        // Chain SHA-256 for longer outputs (unusual but supported).
5430        let mut out = Vec::with_capacity(n);
5431        let mut prev = digest;
5432        while out.len() < n {
5433            out.extend_from_slice(&prev[..std::cmp::min(32, n - out.len())]);
5434            prev = sha256(&prev);
5435        }
5436        out
5437    }
5438}
5439
5440// ===========================================================================
5441// Helpers
5442// ===========================================================================
5443
5444fn lock_err<T>(_: T) -> AuthError {
5445    AuthError::Internal("lock poisoned".to_string())
5446}
5447
5448// ===========================================================================
5449// Tests
5450// ===========================================================================
5451
5452#[cfg(test)]
5453mod tests {
5454    use super::*;
5455
5456    fn test_config() -> AuthConfig {
5457        AuthConfig {
5458            enabled: true,
5459            session_ttl_secs: 60,
5460            require_auth: true,
5461            auto_encrypt_storage: false,
5462            vault_enabled: false,
5463            cert: Default::default(),
5464            oauth: Default::default(),
5465        }
5466    }
5467
5468    #[test]
5469    fn test_create_and_list_users() {
5470        let store = AuthStore::new(test_config());
5471        store.create_user("alice", "pass1", Role::Admin).unwrap();
5472        store.create_user("bob", "pass2", Role::Read).unwrap();
5473
5474        let users = store.list_users();
5475        assert_eq!(users.len(), 2);
5476        // Password hashes should be redacted.
5477        for u in &users {
5478            assert!(u.password_hash.is_empty());
5479        }
5480    }
5481
5482    #[test]
5483    fn test_create_duplicate_user() {
5484        let store = AuthStore::new(test_config());
5485        store.create_user("alice", "pass", Role::Admin).unwrap();
5486        let err = store.create_user("alice", "pass2", Role::Read).unwrap_err();
5487        assert!(matches!(err, AuthError::UserExists(_)));
5488    }
5489
5490    struct RecordingLedger(std::sync::Mutex<Vec<(String, String)>>);
5491
5492    impl crate::runtime::control_events::ControlEventLedger for RecordingLedger {
5493        fn emit(
5494            &self,
5495            _ctx: &ControlEventCtx<'_>,
5496            event: ControlEvent,
5497        ) -> Result<
5498            crate::runtime::control_events::EventId,
5499            crate::runtime::control_events::ControlEventError,
5500        > {
5501            self.0.lock().unwrap().push((
5502                event.kind.as_str().to_string(),
5503                event.outcome.as_str().to_string(),
5504            ));
5505            Ok(crate::runtime::control_events::EventId("evt".to_string()))
5506        }
5507    }
5508
5509    #[test]
5510    fn logins_land_in_the_control_event_ledger() {
5511        let store = AuthStore::new(test_config());
5512        store.create_user("dave", "pw", Role::Read).unwrap();
5513        let ledger = std::sync::Arc::new(RecordingLedger(std::sync::Mutex::new(Vec::new())));
5514        store.configure_control_events(
5515            ledger.clone(),
5516            crate::runtime::control_events::ControlEventConfig::default(),
5517        );
5518        store.authenticate("dave", "pw").expect("login");
5519        store
5520            .authenticate("dave", "nope")
5521            .expect_err("bad password");
5522        store
5523            .authenticate("nobody", "pw")
5524            .expect_err("unknown user");
5525        let seen = ledger.0.lock().unwrap().clone();
5526        let allowed = Outcome::Allowed.as_str().to_string();
5527        let denied = Outcome::Denied.as_str().to_string();
5528        assert!(
5529            seen.contains(&("auth.login".to_string(), allowed)),
5530            "success not recorded: {seen:?}"
5531        );
5532        assert_eq!(
5533            seen.iter()
5534                .filter(|(k, o)| k == "auth.login_failed" && *o == denied)
5535                .count(),
5536            2,
5537            "both refusals must be recorded: {seen:?}"
5538        );
5539    }
5540
5541    #[test]
5542    fn api_keys_are_hashed_at_rest_and_expire() {
5543        let store = AuthStore::new(test_config());
5544        store.create_user("erin", "pw", Role::Write).unwrap();
5545        let key = store
5546            .create_api_key_in_tenant_expiring(None, "erin", "ci", Role::Read, Some(now_ms() + 60))
5547            .unwrap();
5548        assert!(key.key.starts_with("rk_"));
5549
5550        let stored = store
5551            .users
5552            .read()
5553            .unwrap()
5554            .get(&UserId::from_parts(None, "erin"))
5555            .unwrap()
5556            .api_keys[0]
5557            .clone();
5558        assert!(stored.key.starts_with("rkh_"), "{}", stored.key);
5559        assert_ne!(stored.key, key.key, "the secret must not be stored");
5560        assert_eq!(stored.key, api_key_credential_id(&key.key));
5561
5562        assert!(store.validate_token(&key.key).is_some());
5563        std::thread::sleep(std::time::Duration::from_millis(80));
5564        assert!(
5565            store.validate_token(&key.key).is_none(),
5566            "an expired key must not validate"
5567        );
5568
5569        // Revocation accepts the stored id as well as the secret.
5570        store.revoke_api_key(&stored.key).unwrap();
5571        assert!(store.revoke_api_key(&key.key).is_err());
5572    }
5573
5574    #[test]
5575    fn revoke_is_clamped_to_the_granter_tenant() {
5576        use crate::auth::privileges::{Action, GrantPrincipal, Resource};
5577        let store = AuthStore::new(test_config());
5578        let acme_admin = UserId::from_parts(Some("acme"), "adm");
5579        let globex_user = UserId::from_parts(Some("globex"), "u");
5580        let err = store
5581            .revoke(
5582                &acme_admin,
5583                Role::Admin,
5584                &GrantPrincipal::User(globex_user),
5585                &Resource::table_from_name("orders"),
5586                &[Action::Select],
5587            )
5588            .expect_err("a tenant admin must not touch another tenant's grants");
5589        assert!(err.to_string().contains("cross-tenant"), "{err}");
5590        // Platform admin may.
5591        store
5592            .revoke(
5593                &UserId::from_parts(None, "platform"),
5594                Role::Admin,
5595                &GrantPrincipal::User(UserId::from_parts(Some("globex"), "u")),
5596                &Resource::table_from_name("orders"),
5597                &[Action::Select],
5598            )
5599            .expect("platform admin revokes anywhere");
5600    }
5601
5602    #[test]
5603    fn role_change_revokes_sessions_minted_under_the_old_role() {
5604        let store = AuthStore::new(test_config());
5605        store.create_user("carol", "pw", Role::Write).unwrap();
5606        let session = store.authenticate("carol", "pw").unwrap();
5607        assert!(store.validate_token(&session.token).is_some());
5608        store.change_role("carol", Role::Read).unwrap();
5609        assert!(
5610            store.validate_token(&session.token).is_none(),
5611            "a demotion must not keep riding on the old session"
5612        );
5613    }
5614
5615    #[test]
5616    fn test_authenticate_and_validate() {
5617        let store = AuthStore::new(test_config());
5618        store.create_user("alice", "secret", Role::Write).unwrap();
5619
5620        let session = store.authenticate("alice", "secret").unwrap();
5621        assert!(session.token.starts_with("rs_"));
5622
5623        let (username, role) = store.validate_token(&session.token).unwrap();
5624        assert_eq!(username, "alice");
5625        assert_eq!(role, Role::Write);
5626    }
5627
5628    #[test]
5629    fn test_authenticate_wrong_password() {
5630        let store = AuthStore::new(test_config());
5631        store.create_user("alice", "secret", Role::Read).unwrap();
5632
5633        let err = store.authenticate("alice", "wrong").unwrap_err();
5634        assert!(matches!(err, AuthError::InvalidCredentials));
5635    }
5636
5637    #[test]
5638    fn unknown_disabled_and_wrong_password_logins_share_the_public_error() {
5639        let store = AuthStore::new(test_config());
5640        store.create_user("alice", "secret", Role::Read).unwrap();
5641        store.create_user("disabled", "secret", Role::Read).unwrap();
5642        store
5643            .set_user_enabled(&UserId::platform("disabled"), false)
5644            .unwrap();
5645
5646        for result in [
5647            store.authenticate("unknown", "secret"),
5648            store.authenticate("alice", "wrong"),
5649            store.authenticate("disabled", "secret"),
5650        ] {
5651            assert!(matches!(result, Err(AuthError::InvalidCredentials)));
5652        }
5653    }
5654
5655    #[test]
5656    fn test_api_key_lifecycle() {
5657        let store = AuthStore::new(test_config());
5658        store.create_user("alice", "pass", Role::Admin).unwrap();
5659
5660        let key = store
5661            .create_api_key("alice", "ci-token", Role::Write)
5662            .unwrap();
5663        assert!(key.key.starts_with("rk_"));
5664
5665        let (username, role) = store.validate_token(&key.key).unwrap();
5666        assert_eq!(username, "alice");
5667        assert_eq!(role, Role::Write);
5668
5669        store.revoke_api_key(&key.key).unwrap();
5670        assert!(store.validate_token(&key.key).is_none());
5671    }
5672
5673    #[test]
5674    fn test_api_key_role_exceeded() {
5675        let store = AuthStore::new(test_config());
5676        store.create_user("bob", "pass", Role::Read).unwrap();
5677
5678        let err = store
5679            .create_api_key("bob", "escalate", Role::Admin)
5680            .unwrap_err();
5681        assert!(matches!(err, AuthError::RoleExceeded { .. }));
5682    }
5683
5684    #[test]
5685    fn test_change_password() {
5686        let store = AuthStore::new(test_config());
5687        store.create_user("alice", "old", Role::Write).unwrap();
5688
5689        store.change_password("alice", "old", "new").unwrap();
5690
5691        // Old password should fail.
5692        assert!(store.authenticate("alice", "old").is_err());
5693        // New password should succeed.
5694        assert!(store.authenticate("alice", "new").is_ok());
5695    }
5696
5697    #[test]
5698    fn test_change_role() {
5699        let store = AuthStore::new(test_config());
5700        store.create_user("alice", "pass", Role::Admin).unwrap();
5701        store.create_api_key("alice", "key1", Role::Admin).unwrap();
5702
5703        store.change_role("alice", Role::Read).unwrap();
5704
5705        // User's role should be Read now.
5706        let users = store.list_users();
5707        let alice = users.iter().find(|u| u.username == "alice").unwrap();
5708        assert_eq!(alice.role, Role::Read);
5709
5710        // API keys should have been downgraded.
5711        assert_eq!(alice.api_keys[0].role, Role::Read);
5712    }
5713
5714    #[test]
5715    fn test_admin_user_mutations_are_policy_controlled_not_flag_guarded() {
5716        let store = AuthStore::new(test_config());
5717        store
5718            .create_admin_user("system", "pass", Role::Admin, None)
5719            .unwrap();
5720
5721        let uid = UserId::platform("system");
5722        store.change_password("system", "pass", "new").unwrap();
5723        store.change_role("system", Role::Read).unwrap();
5724        store.set_user_enabled(&uid, false).unwrap();
5725
5726        let key = store
5727            .create_api_key("system", "rotation", Role::Read)
5728            .unwrap();
5729        // The account is disabled at this point: every credential it owns
5730        // must stop validating, API keys included (they used to be resolved
5731        // straight from the index without consulting the user record).
5732        assert!(store.validate_token(&key.key).is_none());
5733        store.set_user_enabled(&uid, true).unwrap();
5734        assert!(store.validate_token(&key.key).is_some());
5735        store.revoke_api_key(&key.key).unwrap();
5736        assert!(store.validate_token(&key.key).is_none());
5737        store.delete_user("system").unwrap();
5738    }
5739
5740    #[test]
5741    fn test_user_lifecycle_deny_policy_blocks_cloud_admin_deletion() {
5742        use crate::auth::policies::Policy;
5743
5744        let store = AuthStore::new(test_config());
5745        store
5746            .create_user("cloud-admin", "pass", Role::Admin)
5747            .unwrap();
5748        store
5749            .create_user("customer-admin", "pass", Role::Admin)
5750            .unwrap();
5751
5752        store
5753            .put_policy(
5754                Policy::from_json_str(
5755                    r#"{
5756                        "id": "customer-admin-allow-all",
5757                        "version": 1,
5758                        "statements": [{
5759                            "effect": "allow",
5760                            "actions": ["*"],
5761                            "resources": ["*"]
5762                        }]
5763                    }"#,
5764                )
5765                .unwrap(),
5766            )
5767            .unwrap();
5768        store
5769            .put_policy(
5770                Policy::from_json_str(
5771                    r#"{
5772                        "id": "cloud-admin-protection",
5773                        "version": 1,
5774                        "statements": [{
5775                            "effect": "deny",
5776                            "actions": [
5777                                "user:delete",
5778                                "user:disable",
5779                                "user:password:change",
5780                                "user:role:update"
5781                            ],
5782                            "resources": ["user:cloud-admin"]
5783                        }]
5784                    }"#,
5785                )
5786                .unwrap(),
5787            )
5788            .unwrap();
5789        let customer = UserId::platform("customer-admin");
5790        store
5791            .attach_policy(
5792                PrincipalRef::User(customer.clone()),
5793                "customer-admin-allow-all",
5794            )
5795            .unwrap();
5796        store
5797            .attach_policy(
5798                PrincipalRef::User(customer.clone()),
5799                "cloud-admin-protection",
5800            )
5801            .unwrap();
5802
5803        let cloud_admin = UserId::platform("cloud-admin");
5804        assert!(!store.check_user_lifecycle_authz(
5805            &customer,
5806            Role::Admin,
5807            "user:delete",
5808            &cloud_admin,
5809        ));
5810        assert!(!store.check_user_lifecycle_authz(
5811            &customer,
5812            Role::Admin,
5813            "user:disable",
5814            &cloud_admin,
5815        ));
5816        assert!(!store.check_user_lifecycle_authz(
5817            &customer,
5818            Role::Admin,
5819            "user:password:change",
5820            &cloud_admin,
5821        ));
5822        assert!(!store.check_user_lifecycle_authz(
5823            &customer,
5824            Role::Admin,
5825            "user:role:update",
5826            &cloud_admin,
5827        ));
5828
5829        let another_user = UserId::platform("someone-else");
5830        assert!(store.check_user_lifecycle_authz(
5831            &customer,
5832            Role::Admin,
5833            "user:delete",
5834            &another_user,
5835        ));
5836    }
5837
5838    #[test]
5839    fn admin_user_lifecycle_keeps_role_baseline_in_policy_only_mode() {
5840        let store = AuthStore::new(test_config());
5841        store.set_enforcement_mode(PolicyEnforcementMode::PolicyOnly);
5842        store.create_user("admin", "pass", Role::Admin).unwrap();
5843        store.create_user("alice", "pass", Role::Read).unwrap();
5844
5845        assert!(store.check_user_lifecycle_authz(
5846            &UserId::platform("admin"),
5847            Role::Admin,
5848            "user:update",
5849            &UserId::platform("alice"),
5850        ));
5851    }
5852
5853    #[test]
5854    fn test_regular_user_mutations_still_work() {
5855        let store = AuthStore::new(test_config());
5856        store.create_user("alice", "old", Role::Admin).unwrap();
5857
5858        let uid = UserId::platform("alice");
5859        store.set_user_enabled(&uid, false).unwrap();
5860        assert!(matches!(
5861            store.authenticate("alice", "old"),
5862            Err(AuthError::InvalidCredentials)
5863        ));
5864
5865        store.set_user_enabled(&uid, true).unwrap();
5866        store.change_password("alice", "old", "new").unwrap();
5867        store.change_role("alice", Role::Read).unwrap();
5868        store.delete_user("alice").unwrap();
5869        assert!(matches!(
5870            store.authenticate("alice", "new"),
5871            Err(AuthError::InvalidCredentials)
5872        ));
5873    }
5874
5875    #[test]
5876    fn test_delete_user() {
5877        let store = AuthStore::new(test_config());
5878        store.create_user("alice", "pass", Role::Admin).unwrap();
5879        let key = store.create_api_key("alice", "key1", Role::Read).unwrap();
5880        let session = store.authenticate("alice", "pass").unwrap();
5881
5882        store.delete_user("alice").unwrap();
5883
5884        assert!(store.validate_token(&key.key).is_none());
5885        assert!(store.validate_token(&session.token).is_none());
5886        assert!(store.list_users().is_empty());
5887    }
5888
5889    #[test]
5890    fn test_revoke_session() {
5891        let store = AuthStore::new(test_config());
5892        store.create_user("alice", "pass", Role::Read).unwrap();
5893        let session = store.authenticate("alice", "pass").unwrap();
5894
5895        store.revoke_session(&session.token);
5896        assert!(store.validate_token(&session.token).is_none());
5897    }
5898
5899    #[test]
5900    fn test_password_hash_format() {
5901        // PHC string: `$argon2id$v=19$m=19456,t=2,p=1$<salt_b64>$<hash_b64>`.
5902        // Encoding the parameters is what lets the cost be raised later
5903        // without another format change — the retired in-tree form stored
5904        // only salt and tag, so its 4 MiB / t=3 cost was frozen.
5905        let hash = hash_password("test");
5906        assert!(
5907            hash.starts_with("$argon2id$v=19$"),
5908            "expected a PHC-encoded Argon2id hash, got: {hash}"
5909        );
5910        assert!(
5911            hash.contains(&format!(
5912                "m={PASSWORD_M_COST_KIB},t={PASSWORD_T_COST},p={PASSWORD_P_COST}"
5913            )),
5914            "the PHC string must carry the cost parameters: {hash}"
5915        );
5916        assert!(verify_password("test", &hash));
5917        assert!(!verify_password("wrong", &hash));
5918        assert!(
5919            !password_hash_needs_upgrade(&hash),
5920            "a freshly minted hash must not be flagged for upgrade"
5921        );
5922    }
5923
5924    #[test]
5925    fn legacy_password_hashes_still_verify_and_upgrade_on_login() {
5926        // Records written by the retired in-tree KDF must keep verifying —
5927        // otherwise the upgrade locks every existing account out — and must
5928        // be re-hashed with the real KDF once the plaintext is in hand.
5929        let legacy = {
5930            let salt = random_bytes(16);
5931            let hash = derive_key(b"hunter2", &salt, &auth_argon2_params());
5932            format!("argon2id${}${}", hex::encode(&salt), hex::encode(&hash))
5933        };
5934        assert!(verify_password("hunter2", &legacy));
5935        assert!(!verify_password("wrong", &legacy));
5936        assert!(password_hash_needs_upgrade(&legacy));
5937
5938        let store = AuthStore::new(test_config());
5939        store
5940            .create_user("erin", "placeholder", Role::Write)
5941            .unwrap();
5942        {
5943            let mut users = store.users.write().unwrap();
5944            users
5945                .get_mut(&UserId::platform("erin"))
5946                .unwrap()
5947                .password_hash = legacy.clone();
5948        }
5949
5950        store
5951            .authenticate("erin", "hunter2")
5952            .expect("a legacy hash must still authenticate");
5953
5954        let stored = store
5955            .users
5956            .read()
5957            .unwrap()
5958            .get(&UserId::platform("erin"))
5959            .unwrap()
5960            .password_hash
5961            .clone();
5962        assert!(
5963            stored.starts_with("$argon2id$v=19$"),
5964            "a successful login must upgrade the stored hash, got: {stored}"
5965        );
5966        assert!(store.authenticate("erin", "hunter2").is_ok());
5967    }
5968
5969    #[test]
5970    fn test_constant_time_eq() {
5971        assert!(constant_time_eq(b"hello", b"hello"));
5972        assert!(!constant_time_eq(b"hello", b"world"));
5973        assert!(!constant_time_eq(b"short", b"longer"));
5974    }
5975
5976    #[test]
5977    fn test_bootstrap_seals_permanently() {
5978        let store = AuthStore::new(test_config());
5979
5980        assert!(store.needs_bootstrap());
5981        assert!(!store.is_bootstrapped());
5982
5983        // First bootstrap succeeds
5984        let result = store.bootstrap("admin", "secret");
5985        assert!(result.is_ok());
5986        let br = result.unwrap();
5987        assert_eq!(br.user.username, "admin");
5988        assert_eq!(br.user.role, Role::Admin);
5989        assert!(br.api_key.key.starts_with("rk_"));
5990        // No vault configured, so no certificate.
5991        assert!(br.certificate.is_none());
5992
5993        // Sealed now
5994        assert!(!store.needs_bootstrap());
5995        assert!(store.is_bootstrapped());
5996
5997        // Second bootstrap fails -- sealed permanently
5998        let result = store.bootstrap("admin2", "secret2");
5999        assert!(result.is_err());
6000        let err = result.unwrap_err();
6001        assert!(err.to_string().contains("sealed permanently"));
6002
6003        // Only 1 user exists (the first one)
6004        assert_eq!(store.list_users().len(), 1);
6005        assert_eq!(store.list_users()[0].username, "admin");
6006    }
6007
6008    #[test]
6009    fn certificate_delivery_failure_precedes_vault_activation() {
6010        use crate::storage::engine::pager::PagerConfig;
6011        use std::sync::atomic::{AtomicU64, Ordering as AtomicOrdering};
6012
6013        static COUNTER: AtomicU64 = AtomicU64::new(0);
6014        let id = COUNTER.fetch_add(1, AtomicOrdering::Relaxed);
6015        let directory = std::env::temp_dir().join(format!(
6016            "reddb-auth-delivery-failure-{}-{id}",
6017            std::process::id()
6018        ));
6019        std::fs::create_dir_all(&directory).expect("temp directory");
6020        let pager = Arc::new(
6021            Pager::open(directory.join("test.rdb"), PagerConfig::default()).expect("pager"),
6022        );
6023        let mut config = test_config();
6024        config.vault_enabled = true;
6025        let store = AuthStore::with_vault_optional_certificate(config, Arc::clone(&pager), None)
6026            .expect("fresh vault store");
6027
6028        let error = store
6029            .bootstrap_with_certificate_delivery("admin", "secret", |_| {
6030                Err(AuthError::Internal(
6031                    "simulated delivery failure".to_string(),
6032                ))
6033            })
6034            .expect_err("delivery failure must abort bootstrap");
6035        assert!(error.to_string().contains("simulated delivery failure"));
6036        assert!(store.needs_bootstrap());
6037        assert!(store.list_users().is_empty());
6038        assert!(!Vault::has_saved_state(&pager));
6039
6040        drop(store);
6041        drop(pager);
6042        let _ = std::fs::remove_dir_all(directory);
6043    }
6044
6045    #[test]
6046    fn test_bootstrap_after_manual_user_creation() {
6047        let store = AuthStore::new(test_config());
6048
6049        // Create a user manually first
6050        store.create_user("existing", "pass", Role::Read).unwrap();
6051
6052        // Bootstrap sees the seal hasn't been set but users exist
6053        // The atomic seal fires first, then the users check catches it
6054        assert!(!store.needs_bootstrap()); // users exist → false
6055    }
6056
6057    // ---------------------------------------------------------------
6058    // Tenant scoping
6059    // ---------------------------------------------------------------
6060
6061    #[test]
6062    fn test_same_username_two_tenants_distinct() {
6063        let store = AuthStore::new(test_config());
6064        store
6065            .create_user_in_tenant(Some("acme"), "alice", "pw-acme", Role::Write)
6066            .unwrap();
6067        store
6068            .create_user_in_tenant(Some("globex"), "alice", "pw-globex", Role::Read)
6069            .unwrap();
6070
6071        // Two distinct users.
6072        let users = store.list_users();
6073        assert_eq!(users.len(), 2);
6074
6075        // Each verifies its own password under its own tenant.
6076        assert!(store
6077            .authenticate_in_tenant(Some("acme"), "alice", "pw-acme")
6078            .is_ok());
6079        assert!(store
6080            .authenticate_in_tenant(Some("globex"), "alice", "pw-globex")
6081            .is_ok());
6082
6083        // Cross-tenant credentials are rejected.
6084        assert!(store
6085            .authenticate_in_tenant(Some("acme"), "alice", "pw-globex")
6086            .is_err());
6087        assert!(store
6088            .authenticate_in_tenant(Some("globex"), "alice", "pw-acme")
6089            .is_err());
6090    }
6091
6092    #[test]
6093    fn test_session_carries_tenant() {
6094        let store = AuthStore::new(test_config());
6095        store
6096            .create_user_in_tenant(Some("acme"), "alice", "pw", Role::Admin)
6097            .unwrap();
6098        let session = store
6099            .authenticate_in_tenant(Some("acme"), "alice", "pw")
6100            .unwrap();
6101        assert_eq!(session.tenant_id.as_deref(), Some("acme"));
6102
6103        let (id, role) = store.validate_token_full(&session.token).unwrap();
6104        assert_eq!(id.tenant.as_deref(), Some("acme"));
6105        assert_eq!(id.username, "alice");
6106        assert_eq!(role, Role::Admin);
6107    }
6108
6109    #[test]
6110    fn test_platform_user_has_no_tenant() {
6111        let store = AuthStore::new(test_config());
6112        store.create_user("admin", "pw", Role::Admin).unwrap();
6113        let session = store.authenticate("admin", "pw").unwrap();
6114        assert!(session.tenant_id.is_none());
6115
6116        let (id, _) = store.validate_token_full(&session.token).unwrap();
6117        assert!(id.tenant.is_none());
6118    }
6119
6120    #[test]
6121    fn test_lookup_scram_verifier_global_resolves_platform() {
6122        let store = AuthStore::new(test_config());
6123        store.create_user("admin", "pw", Role::Admin).unwrap();
6124        store
6125            .create_user_in_tenant(Some("acme"), "admin", "pw", Role::Admin)
6126            .unwrap();
6127
6128        // The global helper picks the platform-tenant user only.
6129        let v = store.lookup_scram_verifier_global("admin");
6130        assert!(v.is_some());
6131
6132        // The tenant-scoped user has its own verifier.
6133        let v_acme = store.lookup_scram_verifier(&UserId::scoped("acme", "admin"));
6134        assert!(v_acme.is_some());
6135
6136        // The two verifiers carry independent salts.
6137        assert_ne!(v.unwrap().salt, v_acme.unwrap().salt);
6138    }
6139
6140    #[test]
6141    fn test_delete_in_tenant_does_not_touch_other_tenant() {
6142        let store = AuthStore::new(test_config());
6143        store
6144            .create_user_in_tenant(Some("acme"), "alice", "pw", Role::Admin)
6145            .unwrap();
6146        store
6147            .create_user_in_tenant(Some("globex"), "alice", "pw", Role::Admin)
6148            .unwrap();
6149
6150        store.delete_user_in_tenant(Some("acme"), "alice").unwrap();
6151
6152        // Globex still alive.
6153        assert!(store
6154            .authenticate_in_tenant(Some("globex"), "alice", "pw")
6155            .is_ok());
6156        // Acme gone.
6157        assert!(store
6158            .authenticate_in_tenant(Some("acme"), "alice", "pw")
6159            .is_err());
6160    }
6161
6162    #[test]
6163    fn test_user_id_display() {
6164        assert_eq!(UserId::platform("admin").to_string(), "admin");
6165        assert_eq!(UserId::scoped("acme", "alice").to_string(), "acme/alice");
6166    }
6167
6168    // -----------------------------------------------------------------
6169    // PolicyEnforcementMode wiring (#712 / S5A)
6170    // -----------------------------------------------------------------
6171
6172    fn enforcement_eval_ctx(role: Role) -> EvalContext {
6173        EvalContext {
6174            principal_tenant: None,
6175            current_tenant: None,
6176            peer_ip: None,
6177            mfa_present: false,
6178            now_ms: 1_700_000_000_000,
6179            principal_is_admin_role: role == Role::Admin,
6180            principal_is_platform_scoped: true,
6181        }
6182    }
6183
6184    /// Helper: install a single unrelated allow policy so the IAM
6185    /// path is the authoritative one — without any installed policy
6186    /// the auth flow short-circuits before we ever consult the mode.
6187    fn install_unrelated_policy(store: &AuthStore) {
6188        store
6189            .put_policy(
6190                Policy::from_json_str(
6191                    r#"{"id":"p-unrelated","version":1,"statements":[{"effect":"allow","actions":["select"],"resources":["table:public.other"]}]}"#,
6192                )
6193                .unwrap(),
6194            )
6195            .unwrap();
6196    }
6197
6198    #[test]
6199    fn enforcement_mode_default_for_new_store_is_legacy_rbac() {
6200        // Pre-bootstrap construction = "existing install" path.
6201        // Defaulting to LegacyRbac preserves pre-#712 behaviour on
6202        // upgrade so an operator that has not yet attached IAM
6203        // policies does not lose access after the upgrade.
6204        let store = AuthStore::new(test_config());
6205        assert_eq!(store.enforcement_mode(), PolicyEnforcementMode::LegacyRbac);
6206    }
6207
6208    #[test]
6209    fn enforcement_mode_set_round_trips_and_returns_previous() {
6210        let store = AuthStore::new(test_config());
6211        let prev = store.set_enforcement_mode(PolicyEnforcementMode::PolicyOnly);
6212        assert_eq!(prev, PolicyEnforcementMode::LegacyRbac);
6213        assert_eq!(store.enforcement_mode(), PolicyEnforcementMode::PolicyOnly);
6214        let prev = store.set_enforcement_mode(PolicyEnforcementMode::LegacyRbac);
6215        assert_eq!(prev, PolicyEnforcementMode::PolicyOnly);
6216    }
6217
6218    #[test]
6219    fn policy_only_mode_treats_no_matching_policy_as_deny() {
6220        // Acceptance #2: in `policy_only` mode a principal with no
6221        // matching policy is denied even when the action's role
6222        // floor would otherwise have allowed it.
6223        let store = AuthStore::new(test_config());
6224        store.create_user("alice", "p", Role::Admin).unwrap();
6225        let uid = UserId::platform("alice");
6226        install_unrelated_policy(&store);
6227        store.set_enforcement_mode(PolicyEnforcementMode::PolicyOnly);
6228
6229        let resource = ResourceRef::new("table", "public.t");
6230        // Even Role::Admin is denied — DefaultDeny is the deciding
6231        // signal in `policy_only`, regardless of role.
6232        assert!(!store.check_policy_authz_with_role(
6233            &uid,
6234            "select",
6235            &resource,
6236            &enforcement_eval_ctx(Role::Admin),
6237            Role::Admin,
6238        ));
6239    }
6240
6241    #[test]
6242    fn legacy_rbac_mode_falls_back_to_role_decision() {
6243        // Acceptance #3: in `legacy_rbac` mode the same principal
6244        // falls through to the role-based decision. `select` requires
6245        // only `Read`, so all three roles satisfy it; a write verb
6246        // requires `Write`, so `Read` does not.
6247        let store = AuthStore::new(test_config());
6248        store.create_user("alice", "p", Role::Read).unwrap();
6249        let uid = UserId::platform("alice");
6250        install_unrelated_policy(&store);
6251        store.set_enforcement_mode(PolicyEnforcementMode::LegacyRbac);
6252
6253        let table = ResourceRef::new("table", "public.t");
6254        // Read role + select action: allowed via the legacy fallback.
6255        assert!(store.check_policy_authz_with_role(
6256            &uid,
6257            "select",
6258            &table,
6259            &enforcement_eval_ctx(Role::Read),
6260            Role::Read,
6261        ));
6262        // Read role + insert action: legacy decision says no.
6263        assert!(!store.check_policy_authz_with_role(
6264            &uid,
6265            "insert",
6266            &table,
6267            &enforcement_eval_ctx(Role::Read),
6268            Role::Read,
6269        ));
6270        // Admin role + insert action: legacy decision says yes.
6271        assert!(store.check_policy_authz_with_role(
6272            &uid,
6273            "insert",
6274            &table,
6275            &enforcement_eval_ctx(Role::Admin),
6276            Role::Admin,
6277        ));
6278    }
6279
6280    #[test]
6281    fn explicit_deny_wins_irrespective_of_mode_or_role() {
6282        // Even in `legacy_rbac` with an Admin role, an explicit
6283        // matching Deny statement always denies. The mode only
6284        // influences the `DefaultDeny` arm, never an explicit one.
6285        let store = AuthStore::new(test_config());
6286        store.create_user("alice", "p", Role::Admin).unwrap();
6287        let uid = UserId::platform("alice");
6288        store
6289            .put_policy(
6290                Policy::from_json_str(
6291                    r#"{"id":"p-deny-select","version":1,"statements":[{"effect":"deny","actions":["select"],"resources":["table:public.t"]}]}"#,
6292                )
6293                .unwrap(),
6294            )
6295            .unwrap();
6296        store
6297            .attach_policy(PrincipalRef::User(uid.clone()), "p-deny-select")
6298            .unwrap();
6299
6300        let resource = ResourceRef::new("table", "public.t");
6301        for mode in [
6302            PolicyEnforcementMode::LegacyRbac,
6303            PolicyEnforcementMode::PolicyOnly,
6304        ] {
6305            store.set_enforcement_mode(mode);
6306            assert!(
6307                !store.check_policy_authz_with_role(
6308                    &uid,
6309                    "select",
6310                    &resource,
6311                    &enforcement_eval_ctx(Role::Admin),
6312                    Role::Admin,
6313                ),
6314                "explicit deny must win under mode {mode:?}"
6315            );
6316        }
6317    }
6318
6319    #[test]
6320    fn explicit_allow_wins_irrespective_of_mode_or_role() {
6321        // Symmetric guarantee: an explicit Allow is honoured even in
6322        // `policy_only` mode for a role that the legacy fallback
6323        // would have rejected (Read role + admin-tier action).
6324        let store = AuthStore::new(test_config());
6325        store.create_user("alice", "p", Role::Read).unwrap();
6326        let uid = UserId::platform("alice");
6327        store
6328            .put_policy(
6329                Policy::from_json_str(
6330                    r#"{"id":"p-allow-create","version":1,"statements":[{"effect":"allow","actions":["create"],"resources":["table:public.t"]}]}"#,
6331                )
6332                .unwrap(),
6333            )
6334            .unwrap();
6335        store
6336            .attach_policy(PrincipalRef::User(uid.clone()), "p-allow-create")
6337            .unwrap();
6338        store.set_enforcement_mode(PolicyEnforcementMode::PolicyOnly);
6339
6340        let resource = ResourceRef::new("table", "public.t");
6341        assert!(store.check_policy_authz_with_role(
6342            &uid,
6343            "create",
6344            &resource,
6345            &enforcement_eval_ctx(Role::Read),
6346            Role::Read,
6347        ));
6348    }
6349
6350    #[test]
6351    fn take_legacy_rbac_warn_once_is_at_most_once_per_boot() {
6352        let store = AuthStore::new(test_config());
6353        // Default mode = LegacyRbac, so the first call wins the token.
6354        assert!(store.take_legacy_rbac_warn_once());
6355        // Every subsequent call is a no-op for the lifetime of this
6356        // process / AuthStore — that is the "once per boot" guarantee.
6357        for _ in 0..3 {
6358            assert!(!store.take_legacy_rbac_warn_once());
6359        }
6360    }
6361
6362    #[test]
6363    fn take_legacy_rbac_warn_once_is_silent_under_policy_only() {
6364        // Acceptance #5 phrases the warning as "Boot in legacy_rbac
6365        // mode emits exactly one warn entry per boot" — implicitly,
6366        // `policy_only` boots emit zero. The token must not be
6367        // claimable when the mode is strict so the boot path stays
6368        // quiet.
6369        let store = AuthStore::new(test_config());
6370        store.set_enforcement_mode(PolicyEnforcementMode::PolicyOnly);
6371        assert!(!store.take_legacy_rbac_warn_once());
6372        // And, importantly, switching back to LegacyRbac later does
6373        // not "owe" us a warning — the token was never claimed under
6374        // policy_only, so it is still available the first time the
6375        // mode is legacy_rbac.
6376        store.set_enforcement_mode(PolicyEnforcementMode::LegacyRbac);
6377        assert!(store.take_legacy_rbac_warn_once());
6378        assert!(!store.take_legacy_rbac_warn_once());
6379    }
6380
6381    #[test]
6382    fn strict_check_policy_authz_ignores_enforcement_mode() {
6383        // Governance APIs (managed_config, registry, managed_policy)
6384        // call the strict `check_policy_authz` — it must return
6385        // `false` on DefaultDeny regardless of mode so the lenient
6386        // posture cannot accidentally elevate an admin-tier mutation.
6387        let store = AuthStore::new(test_config());
6388        store.create_user("alice", "p", Role::Admin).unwrap();
6389        let uid = UserId::platform("alice");
6390        install_unrelated_policy(&store);
6391        store.set_enforcement_mode(PolicyEnforcementMode::LegacyRbac);
6392
6393        let resource = ResourceRef::new("table", "public.t");
6394        assert!(!store.check_policy_authz(
6395            &uid,
6396            "select",
6397            &resource,
6398            &enforcement_eval_ctx(Role::Admin),
6399        ));
6400    }
6401
6402    #[test]
6403    fn disabling_a_user_invalidates_its_api_keys_and_sessions() {
6404        let store = AuthStore::new(test_config());
6405        store.create_user("carol", "pw", Role::Write).unwrap();
6406        let key = store
6407            .create_api_key("carol", "ci", Role::Write)
6408            .unwrap()
6409            .key;
6410        let session = store.authenticate("carol", "pw").unwrap();
6411        assert!(store.validate_token(&key).is_some());
6412        assert!(store.validate_token(&session.token).is_some());
6413
6414        let uid = UserId::platform("carol");
6415        store.set_user_enabled(&uid, false).unwrap();
6416
6417        // API keys resolved straight from the index and never consulted the
6418        // user record, so a disabled (or offboarded) account kept a working
6419        // credential forever.
6420        assert!(
6421            store.validate_token(&key).is_none(),
6422            "an API key must stop working the moment its owner is disabled"
6423        );
6424        assert!(
6425            store.validate_token(&session.token).is_none(),
6426            "live sessions must not survive disabling the account"
6427        );
6428        assert!(
6429            store.lookup_scram_verifier(&uid).is_none(),
6430            "SCRAM must not authenticate a disabled account"
6431        );
6432    }
6433
6434    #[test]
6435    fn admin_password_reset_applies_and_revokes_sessions() {
6436        let store = AuthStore::new(test_config());
6437        store.create_user("dave", "old", Role::Write).unwrap();
6438        let session = store.authenticate("dave", "old").unwrap();
6439
6440        store
6441            .set_password_by_admin(&UserId::platform("dave"), "rotated")
6442            .expect("admin reset");
6443
6444        assert!(
6445            store.authenticate("dave", "old").is_err(),
6446            "the old password must stop working after a reset"
6447        );
6448        assert!(
6449            store.authenticate("dave", "rotated").is_ok(),
6450            "the new password must work after a reset"
6451        );
6452        assert!(
6453            store.validate_token(&session.token).is_none(),
6454            "a password rotation must revoke live sessions"
6455        );
6456    }
6457}