1#![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#[derive(Debug, Clone, PartialEq, Eq, Hash)]
40pub enum PrincipalRef {
41 User(UserId),
42 Group(String),
43}
44
45pub const PUBLIC_IAM_GROUP: &str = "__public__";
48
49#[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
59pub 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
74pub 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
87pub struct BootstrapResult {
96 pub user: User,
97 pub api_key: ApiKey,
98 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
115pub struct AuthStore {
123 users: RwLock<HashMap<UserId, User>>,
126 sessions: RwLock<HashMap<String, Session>>,
127 counted_session_tokens: RwLock<HashSet<String>>,
128 api_key_index: RwLock<HashMap<String, (UserId, Role)>>,
130 bootstrapped: AtomicBool,
132 config: AuthConfig,
133 vault: RwLock<Option<Vault>>,
135 pager: Option<Arc<Pager>>,
137 vault_persist_hook: RwLock<Option<Arc<dyn Fn() + Send + Sync>>>,
141 provided_certificate: Option<String>,
143 keypair: RwLock<Option<KeyPair>>,
146 vault_kv: RwLock<HashMap<String, String>>,
149 secret_key_init: std::sync::Mutex<()>,
150 plain_kv: RwLock<HashMap<String, String>>,
155 grants: RwLock<HashMap<UserId, Vec<Grant>>>,
160 public_grants: RwLock<Vec<Grant>>,
162 user_attributes: RwLock<HashMap<UserId, UserAttributes>>,
166 session_count_by_user: RwLock<HashMap<UserId, u32>>,
170 permission_cache: RwLock<HashMap<UserId, PermissionCache>>,
174 policies: RwLock<HashMap<String, Arc<Policy>>>,
178 user_attachments: RwLock<HashMap<UserId, Vec<String>>>,
181 group_attachments: RwLock<HashMap<String, Vec<String>>>,
185 iam_effective_cache: RwLock<HashMap<UserId, Vec<Arc<Policy>>>>,
188 iam_authorization_enabled: AtomicBool,
192 enforcement_mode: RwLock<PolicyEnforcementMode>,
202 legacy_rbac_boot_warn_emitted: AtomicBool,
207 visible_collections_cache: super::scope_cache::AuthCache,
217 control_events: RwLock<Option<AuthStoreControlEvents>>,
218}
219
220pub 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
233fn auth_argon2_params() -> Argon2Params {
236 Argon2Params {
237 m_cost: 4 * 1024, 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
363fn 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
373pub(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 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 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 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 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 fn get_user_cloned(&self, id: &UserId) -> Option<User> {
572 self.users.read().ok().and_then(|m| m.get(id).cloned())
573 }
574
575 pub fn is_bootstrapped(&self) -> bool {
577 self.bootstrapped.load(Ordering::Acquire)
578 }
579
580 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 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 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 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 {
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 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 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 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 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 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 fn persist_to_vault(&self) {
966 if let Err(e) = self.persist_to_vault_result() {
967 tracing::error!(err = %e, "vault persist failed");
968 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 fn restore_from_vault(&mut self, state: VaultState) {
1318 if state.bootstrapped {
1320 self.bootstrapped.store(true, Ordering::Release);
1321 }
1322
1323 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 if let Ok(mut kv) = self.vault_kv.write() {
1333 *kv = state.kv;
1334 }
1335
1336 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 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 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 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 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); 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 pub fn lookup_scram_verifier(&self, id: &UserId) -> Option<crate::auth::scram::ScramVerifier> {
1538 if crate::auth::self_lock_guard::is_synthetic_principal(&id.username) {
1540 return None;
1541 }
1542 let users = self.users.read().ok()?;
1543 users
1547 .get(id)
1548 .filter(|u| u.enabled)
1549 .and_then(|u| u.scram_verifier.clone())
1550 }
1551
1552 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 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(), ..u.clone()
1579 })
1580 .collect()
1581 }
1582
1583 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(), ..u.clone()
1604 })
1605 .collect()
1606 }
1607
1608 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 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 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 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 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 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 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); self.persist_to_vault();
1924 Ok(())
1925 }
1926
1927 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 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 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 for key in &mut user.api_keys {
2080 if key.role > new_role {
2081 key.role = new_role;
2082 }
2083 }
2084
2085 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 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 pub fn authenticate(&self, username: &str, password: &str) -> Result<Session, AuthError> {
2169 self.authenticate_in_tenant(None, username, password)
2170 }
2171
2172 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 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 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 let dummy_hash = dummy_password_hash();
2283 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 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 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); let mut sessions = self.sessions.write().map_err(lock_err)?;
2331 sessions.insert(session.token.clone(), session.clone());
2332 drop(sessions);
2333
2334 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 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 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 pub fn validate_token_full(&self, token: &str) -> Option<(UserId, Role)> {
2375 let resolved = self.resolve_token_unchecked(token)?;
2376 if !self.principal_is_active(&resolved.0) {
2380 return None;
2381 }
2382 Some(resolved)
2383 }
2384
2385 fn resolve_token_unchecked(&self, token: &str) -> Option<(UserId, Role)> {
2387 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 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 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 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 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 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 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 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 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); self.persist_to_vault();
2587 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 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 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 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 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 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 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 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 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 self.invalidate_visible_collections_for_tenant(g.tenant.as_deref());
2902
2903 self.persist_acl_to_kv();
2904 Ok(())
2905 }
2906
2907 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 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 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 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 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 pub fn auth_cache_stats(&self) -> super::scope_cache::AuthCacheStats {
3038 self.visible_collections_cache.stats()
3039 }
3040
3041 pub fn invalidate_visible_collections_cache(&self) {
3045 self.visible_collections_cache.invalidate_all();
3046 }
3047
3048 pub fn invalidate_visible_collections_for_tenant(&self, tenant: Option<&str>) {
3051 self.visible_collections_cache.invalidate_tenant(tenant);
3052 }
3053
3054 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 self.invalidate_visible_collections_cache();
4355 self.persist_iam_to_kv();
4356 Ok(())
4357 }
4358
4359 pub fn iam_authorization_enabled(&self) -> bool {
4364 self.iam_authorization_enabled.load(Ordering::Acquire)
4365 }
4366
4367 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 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 self.invalidate_visible_collections_cache();
4398 self.persist_iam_to_kv();
4399 Ok(())
4400 }
4401
4402 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 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 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 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 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 let policy = unlock_policy();
4510 self.put_policy_internal(policy)?;
4511
4512 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 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 self.attach_policy(
4540 PrincipalRef::User(owner_id.clone()),
4541 PLATFORM_OWNER_UNLOCK_POLICY_ID,
4542 )?;
4543
4544 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 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 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 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 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 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 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 pub fn enforcement_mode(&self) -> PolicyEnforcementMode {
4797 *self
4798 .enforcement_mode
4799 .read()
4800 .unwrap_or_else(|e| e.into_inner())
4801 }
4802
4803 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 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 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 pub fn invalidate_all_iam_cache(&self) {
4868 self.invalidate_iam_cache(None);
4869 }
4870
4871 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 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 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 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 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 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 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 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 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 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
5102fn 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: 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
5289fn 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
5307const 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
5335pub(crate) fn hash_password(password: &str) -> String {
5347 use argon2::PasswordHasher;
5348 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
5356pub(crate) fn password_hash_needs_upgrade(stored_hash: &str) -> bool {
5359 stored_hash.starts_with("argon2id$")
5360}
5361
5362pub(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
5379fn 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
5392fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
5394 crate::crypto::constant_time_eq(a, b)
5395}
5396
5397fn 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
5409fn random_hex(n: usize) -> String {
5411 hex::encode(random_bytes(n))
5412}
5413
5414pub(crate) fn random_bytes(n: usize) -> Vec<u8> {
5417 let mut buf = vec![0u8; n.max(32)];
5418 if let Err(err) = os_random::fill_bytes(&mut buf) {
5422 panic!("OS CSPRNG unavailable; refusing to generate credential material: {err}");
5423 }
5424 let digest = sha256(&buf);
5426 if n <= 32 {
5427 digest[..n].to_vec()
5428 } else {
5429 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
5440fn lock_err<T>(_: T) -> AuthError {
5445 AuthError::Internal("lock poisoned".to_string())
5446}
5447
5448#[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 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 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 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 assert!(store.authenticate("alice", "old").is_err());
5693 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 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 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 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 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 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 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 assert!(br.certificate.is_none());
5992
5993 assert!(!store.needs_bootstrap());
5995 assert!(store.is_bootstrapped());
5996
5997 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 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 store.create_user("existing", "pass", Role::Read).unwrap();
6051
6052 assert!(!store.needs_bootstrap()); }
6056
6057 #[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 let users = store.list_users();
6073 assert_eq!(users.len(), 2);
6074
6075 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 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 let v = store.lookup_scram_verifier_global("admin");
6130 assert!(v.is_some());
6131
6132 let v_acme = store.lookup_scram_verifier(&UserId::scoped("acme", "admin"));
6134 assert!(v_acme.is_some());
6135
6136 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 assert!(store
6154 .authenticate_in_tenant(Some("globex"), "alice", "pw")
6155 .is_ok());
6156 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 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 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 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 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 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 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 assert!(store.check_policy_authz_with_role(
6256 &uid,
6257 "select",
6258 &table,
6259 &enforcement_eval_ctx(Role::Read),
6260 Role::Read,
6261 ));
6262 assert!(!store.check_policy_authz_with_role(
6264 &uid,
6265 "insert",
6266 &table,
6267 &enforcement_eval_ctx(Role::Read),
6268 Role::Read,
6269 ));
6270 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 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 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 assert!(store.take_legacy_rbac_warn_once());
6355 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 let store = AuthStore::new(test_config());
6370 store.set_enforcement_mode(PolicyEnforcementMode::PolicyOnly);
6371 assert!(!store.take_legacy_rbac_warn_once());
6372 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 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 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}