1use crate::error::{Error, Result, is_err_config_not_found};
16use crate::is_iam_first_cluster_node_local;
17use crate::sys::{get_claims_from_token_with_secret, get_claims_from_token_with_secret_allow_missing_exp};
18use crate::{
19 cache::{Cache, CacheEntity, LockedCache},
20 error::{Error as IamError, is_err_no_such_group, is_err_no_such_policy, is_err_no_such_user},
21 store::{GroupInfo, MappedPolicy, Store, UserType, object::IAM_CONFIG_PREFIX},
22 sys::{
23 MAX_SVCSESSION_POLICY_SIZE, SESSION_POLICY_NAME, SESSION_POLICY_NAME_EXTRACTED, SITE_REPLICATOR_CLAIM,
24 SITE_REPLICATOR_SERVICE_ACCOUNT, STATUS_DISABLED, STATUS_ENABLED, UpdateServiceAccountOpts,
25 },
26};
27use futures::future::join_all;
28use rustfs_credentials::{Credentials, EMBEDDED_POLICY_TYPE, INHERITED_POLICY_TYPE};
29use rustfs_madmin::{AccountStatus, AddOrUpdateUserReq, GroupDesc};
30use rustfs_policy::{
31 arn::ARN,
32 auth::{self, UserIdentity, is_secret_key_valid, jwt_sign},
33 format::Format,
34 policy::{Policy, PolicyDoc, default::DEFAULT_POLICIES, iam_policy_claim_name_sa},
35};
36use rustfs_utils::{get_env_opt_str, path::path_join_buf};
37use serde::{Deserialize, Serialize};
38use serde_json::Value;
39use std::sync::atomic::{AtomicU8, AtomicU64};
40use std::{
41 collections::{HashMap, HashSet},
42 sync::{
43 Arc,
44 atomic::{AtomicBool, AtomicI64, Ordering},
45 },
46 time::Duration,
47};
48use time::OffsetDateTime;
49use tokio::{
50 select,
51 sync::{
52 mpsc,
53 mpsc::{Receiver, Sender},
54 },
55};
56use tracing::warn;
57use tracing::{debug, error};
58
59const IAM_FORMAT_FILE: &str = "format.json";
60const IAM_FORMAT_VERSION_1: i32 = 1;
61#[cfg(not(test))]
62const INITIAL_LOAD_RETRY_DELAY: Duration = Duration::from_secs(1);
63#[cfg(test)]
64const INITIAL_LOAD_RETRY_DELAY: Duration = Duration::from_millis(1);
65#[cfg(not(test))]
66const TEMP_USER_PERSISTENCE_VERIFY_RETRY_DELAY: Duration = Duration::from_millis(200);
67#[cfg(test)]
68const TEMP_USER_PERSISTENCE_VERIFY_RETRY_DELAY: Duration = Duration::from_millis(1);
69const TEMP_USER_PERSISTENCE_VERIFY_MAX_RETRIES: usize = 5;
70
71#[derive(Serialize, Deserialize)]
72struct IAMFormat {
73 version: i32,
74}
75
76impl IAMFormat {
77 fn new_version_1() -> Self {
78 IAMFormat {
79 version: IAM_FORMAT_VERSION_1,
80 }
81 }
82}
83
84fn get_iam_format_file_path() -> String {
85 path_join_buf(&[&IAM_CONFIG_PREFIX, IAM_FORMAT_FILE])
86}
87
88#[repr(u8)]
89#[derive(Debug, PartialEq)]
90pub enum IamState {
91 Uninitialized = 0,
92 Loading = 1,
93 Ready = 2,
94 Error = 3,
95}
96
97pub struct IamCache<T> {
98 pub cache: Cache,
99 pub api: T,
100 pub state: Arc<AtomicU8>,
101 pub loading: Arc<AtomicBool>,
102 pub roles: HashMap<ARN, Vec<String>>,
103 pub send_chan: Sender<i64>,
104 pub last_timestamp: AtomicI64,
105 pub sync_failures: AtomicU64,
106 pub sync_successes: AtomicU64,
107 pub last_sync_duration_millis: AtomicU64,
108}
109
110#[derive(Debug, Clone, Copy, Default)]
111pub struct IamSyncMetricsSnapshot {
112 pub last_sync_duration_millis: u64,
113 pub since_last_sync_millis: u64,
114 pub sync_failures: u64,
115 pub sync_successes: u64,
116}
117
118impl<T> IamCache<T>
119where
120 T: Store,
121{
122 async fn verify_temp_user_persistence(&self, access_key: &str) -> Result<()> {
123 for attempt in 0..=TEMP_USER_PERSISTENCE_VERIFY_MAX_RETRIES {
124 match self.api.load_user_identity(access_key, UserType::Sts).await {
125 Ok(_) => return Ok(()),
126 Err(err)
127 if attempt < TEMP_USER_PERSISTENCE_VERIFY_MAX_RETRIES
128 && (is_err_no_such_user(&err) || is_err_config_not_found(&err)) =>
129 {
130 warn!(
131 access_key,
132 attempt = attempt + 1,
133 max_retries = TEMP_USER_PERSISTENCE_VERIFY_MAX_RETRIES,
134 error = ?err,
135 "temporary IAM user not yet visible after save; retrying persistence verification"
136 );
137 tokio::time::sleep(TEMP_USER_PERSISTENCE_VERIFY_RETRY_DELAY).await;
138 }
139 Err(err) => return Err(err),
140 }
141 }
142
143 unreachable!("temp-user persistence verification loop should return on success or terminal error")
144 }
145
146 pub(crate) async fn new(api: T) -> Result<Arc<Self>> {
153 let (sender, receiver) = mpsc::channel::<i64>(100);
154
155 let sys = Arc::new(Self {
156 api,
157 cache: Cache::default(),
158 state: Arc::new(AtomicU8::new(IamState::Uninitialized as u8)),
159 loading: Arc::new(AtomicBool::new(false)),
160 send_chan: sender,
161 roles: HashMap::new(),
162 last_timestamp: AtomicI64::new(0),
163 sync_failures: AtomicU64::new(0),
164 sync_successes: AtomicU64::new(0),
165 last_sync_duration_millis: AtomicU64::new(0),
166 });
167
168 sys.clone().init(receiver).await?;
169 Ok(sys)
170 }
171
172 async fn init(self: Arc<Self>, receiver: Receiver<i64>) -> Result<()> {
174 self.state.store(IamState::Loading as u8, Ordering::SeqCst);
175 self.clone().save_iam_formatter().await?;
177
178 const MAX_RETRIES: usize = 3;
180 let mut load_error = None;
181 for attempt in 0..MAX_RETRIES {
182 if let Err(e) = self.clone().load().await {
183 if attempt == MAX_RETRIES - 1 {
184 self.state.store(IamState::Error as u8, Ordering::SeqCst);
185 warn!(
186 attempts = MAX_RETRIES,
187 error = ?e,
188 "IAM initial load failed"
189 );
190 load_error = Some(e);
191 } else {
192 warn!(attempt = attempt + 1, max_attempts = MAX_RETRIES, "IAM load retry scheduled");
193 tokio::time::sleep(INITIAL_LOAD_RETRY_DELAY).await;
194 }
195 } else {
196 break;
197 }
198 }
199
200 if let Some(err) = load_error {
201 return Err(err);
202 }
203
204 self.state.store(IamState::Ready as u8, Ordering::SeqCst);
205 debug!(state = "ready", "IAM manager ready");
206
207 let skip_background_task = get_env_opt_str("RUSTFS_SKIP_BACKGROUND_TASK").is_some();
210
211 if !skip_background_task {
212 tokio::spawn({
214 let s = Arc::clone(&self);
215 async move {
216 let ticker = tokio::time::interval(Duration::from_secs(120));
217 tokio::pin!(ticker, receiver);
218 loop {
219 select! {
220 _ = ticker.tick() => {
221 debug!(source = "ticker", "IAM reload tick");
222 if let Err(err) =s.clone().load().await{
223 warn!(source = "ticker", error = ?err, "IAM reload failed");
224 }
225 },
226 i = receiver.recv() => {
227 debug!(source = "receiver", "IAM reload signal received");
228 match i {
229 Some(t) => {
230 let last = s.last_timestamp.load(Ordering::Relaxed);
231 if last <= t {
232 debug!(source = "receiver", "IAM reload accepted");
233 if let Err(err) =s.clone().load().await{
234 warn!(source = "receiver", error = ?err, "IAM reload failed");
235 }
236 ticker.reset();
237 }
238 },
239 None => return,
240 }
241 }
242 }
243 }
244 }
245 });
246 }
247
248 Ok(())
249 }
250
251 pub fn is_ready(&self) -> bool {
253 self.state.load(Ordering::SeqCst) == IamState::Ready as u8
254 }
255
256 async fn _notify(&self) {
257 self.send_chan.send(OffsetDateTime::now_utc().unix_timestamp()).await.unwrap();
258 }
259
260 async fn load(self: Arc<Self>) -> Result<()> {
261 let started_at = std::time::Instant::now();
262 match self.api.load_all(&self.cache).await {
263 Ok(()) => {
264 self.last_timestamp
265 .store(OffsetDateTime::now_utc().unix_timestamp(), Ordering::Relaxed);
266 self.sync_successes.fetch_add(1, Ordering::Relaxed);
267 self.last_sync_duration_millis
268 .store(started_at.elapsed().as_millis().min(u128::from(u64::MAX)) as u64, Ordering::Relaxed);
269 Ok(())
270 }
271 Err(err) => {
272 self.sync_failures.fetch_add(1, Ordering::Relaxed);
273 Err(err)
274 }
275 }
276 }
277
278 pub fn sync_metrics_snapshot(&self) -> IamSyncMetricsSnapshot {
279 let now_secs = OffsetDateTime::now_utc().unix_timestamp();
280 let last_sync_secs = self.last_timestamp.load(Ordering::Relaxed);
281 let since_last_sync_millis = if last_sync_secs > 0 && now_secs >= last_sync_secs {
282 ((now_secs - last_sync_secs) as u64).saturating_mul(1000)
283 } else {
284 0
285 };
286
287 IamSyncMetricsSnapshot {
288 last_sync_duration_millis: self.last_sync_duration_millis.load(Ordering::Relaxed),
289 since_last_sync_millis,
290 sync_failures: self.sync_failures.load(Ordering::Relaxed),
291 sync_successes: self.sync_successes.load(Ordering::Relaxed),
292 }
293 }
294
295 pub async fn load_user(&self, access_key: &str) -> Result<()> {
296 let sts_mutation_lock = self.cache.sts_account_mutation_lock(access_key);
297 let _sts_mutation_guard = sts_mutation_lock.lock().await;
298 let mut users_map: HashMap<String, UserIdentity> = HashMap::new();
299 let mut user_policy_map = HashMap::new();
300 let mut sts_users_map = HashMap::new();
301 let mut sts_policy_map = HashMap::new();
302 let mut policy_docs_map = HashMap::new();
303
304 match self.api.load_user(access_key, UserType::Svc, &mut users_map).await {
305 Ok(()) => {}
306 Err(err) if is_err_no_such_user(&err) => {}
307 Err(err) => return Err(err),
308 }
309
310 let parent_user = users_map.get(access_key).map(|svc| svc.credentials.parent_user.clone());
311
312 if let Some(parent_user) = parent_user {
313 match self.api.load_user(&parent_user, UserType::Reg, &mut users_map).await {
314 Ok(()) => {}
315 Err(err) if is_err_no_such_user(&err) => {}
316 Err(err) => return Err(err),
317 }
318 let _ = self
319 .api
320 .load_mapped_policy(&parent_user, UserType::Reg, false, &mut user_policy_map)
321 .await;
322 } else {
323 match self.api.load_user(access_key, UserType::Reg, &mut users_map).await {
324 Ok(()) => {}
325 Err(err) if is_err_no_such_user(&err) => {}
326 Err(err) => return Err(err),
327 }
328 if users_map.contains_key(access_key) {
329 let _ = self
330 .api
331 .load_mapped_policy(access_key, UserType::Reg, false, &mut user_policy_map)
332 .await;
333 }
334
335 match self.api.load_user(access_key, UserType::Sts, &mut sts_users_map).await {
336 Ok(()) => {}
337 Err(err) if is_err_no_such_user(&err) => {}
338 Err(err) => return Err(err),
339 }
340
341 let has_sts_user = sts_users_map.get(access_key);
342
343 if let Some(parent) = has_sts_user.map(|sts| sts.credentials.parent_user.clone()) {
344 let _ = self
345 .api
346 .load_mapped_policy(&parent, UserType::Sts, false, &mut sts_policy_map)
347 .await;
348
349 if let Some(plc) = sts_policy_map.get(&parent) {
350 for p in plc.to_slice().iter() {
351 if !policy_docs_map.contains_key(p) {
352 let _ = self.api.load_policy_doc(p, &mut policy_docs_map).await;
353 }
354 }
355 }
356 }
357 }
358
359 for plc in user_policy_map.values() {
360 for p in plc.to_slice().iter() {
361 if !policy_docs_map.contains_key(p) {
362 let _ = self.api.load_policy_doc(p, &mut policy_docs_map).await;
363 }
364 }
365 }
366
367 self.cache.with_write_lock(|cache| {
368 let now = OffsetDateTime::now_utc();
369 for (key, user) in users_map.iter() {
370 cache.add_or_update_user(key, user, now);
371 }
372 for (key, user_policy) in user_policy_map.iter() {
373 cache.add_or_update_user_policy(key, user_policy, now);
374 }
375 for (key, sts_user) in sts_users_map.iter() {
376 cache.add_or_update_sts_account(key, sts_user, now);
377 }
378 for (key, sts_policy) in sts_policy_map.iter() {
379 cache.add_or_update_sts_policy(key, sts_policy, now);
380 }
381 for (key, policy_doc) in policy_docs_map.iter() {
382 cache.add_or_update_policy_doc(key, policy_doc, now);
383 }
384 });
385
386 Ok(())
387 }
388
389 #[tracing::instrument(level = "debug", skip(self))]
390 async fn save_iam_formatter(self: Arc<Self>) -> Result<()> {
391 let path = get_iam_format_file_path();
392
393 let iam_fmt: Format = match self.api.load_iam_config(&path).await {
394 Ok(v) => v,
395 Err(err) => {
396 if !is_err_config_not_found(&err) {
397 return Err(err);
398 }
399
400 Format::default()
401 }
402 };
403
404 if iam_fmt.version >= IAM_FORMAT_VERSION_1 {
405 return Ok(());
406 }
407
408 if !is_iam_first_cluster_node_local().await {
409 return Ok(());
410 }
411
412 self.api.save_iam_config(IAMFormat::new_version_1(), path).await
413 }
414 pub async fn get_user(&self, access_key: &str) -> Option<UserIdentity> {
415 let cache = self.cache.snapshot();
416 cache
417 .users
418 .get(access_key)
419 .cloned()
420 .or_else(|| cache.sts_accounts.get(access_key).cloned())
421 }
422
423 pub async fn get_mapped_policy(&self, name: &str, is_group: bool) -> Option<MappedPolicy> {
424 let cache = self.cache.snapshot();
425 if is_group {
426 cache.group_policies.get(name).cloned()
427 } else {
428 cache.user_policies.get(name).cloned()
429 }
430 }
431
432 pub async fn get_mapped_policy_record(&self, name: &str, user_type: UserType, is_group: bool) -> Option<MappedPolicy> {
436 let cache = self.cache.snapshot();
437 if is_group {
438 cache.group_policies.get(name).cloned()
439 } else if user_type == UserType::Sts {
440 cache.sts_policies.get(name).cloned()
441 } else {
442 cache.user_policies.get(name).cloned()
443 }
444 }
445
446 pub async fn get_group_info(&self, name: &str) -> Option<GroupInfo> {
450 self.cache.snapshot().groups.get(name).cloned()
451 }
452
453 pub async fn get_policy(&self, name: &str) -> Result<Policy> {
454 if name.is_empty() {
455 return Err(Error::InvalidArgument);
456 }
457
458 let policies = MappedPolicy::new(name).to_slice();
459 let cache = self.cache.snapshot();
460 let policy_docs = Arc::clone(&cache.policy_docs);
461 drop(cache);
462
463 let mut to_merge = Vec::new();
464 for policy in policies {
465 if policy.is_empty() {
466 continue;
467 }
468
469 let v = policy_docs.get(&policy).cloned().ok_or(Error::NoSuchPolicy)?;
470
471 to_merge.push(v.policy);
472 }
473
474 if to_merge.is_empty() {
475 return Err(Error::NoSuchPolicy);
476 }
477
478 Ok(Policy::merge_policies(to_merge))
479 }
480
481 pub async fn get_policy_doc(&self, name: &str) -> Result<PolicyDoc> {
482 if name.is_empty() {
483 return Err(Error::InvalidArgument);
484 }
485
486 self.cache
487 .snapshot()
488 .policy_docs
489 .get(name)
490 .cloned()
491 .ok_or(Error::NoSuchPolicy)
492 }
493
494 pub async fn delete_policy(&self, name: &str, is_from_notify: bool) -> Result<()> {
495 if name.is_empty() {
496 return Err(Error::InvalidArgument);
497 }
498
499 if is_from_notify {
500 let cache = self.cache.snapshot();
501 let user_policy_cache = Arc::clone(&cache.user_policies);
502 let group_policy_cache = Arc::clone(&cache.group_policies);
503 let users_cache = Arc::clone(&cache.users);
504
505 let mut users = Vec::new();
506 let mut stale_user_policies = Vec::new();
507 user_policy_cache.iter().for_each(|(k, v)| {
508 if !users_cache.contains_key(k) {
509 stale_user_policies.push(k.to_owned());
510 return;
511 }
512
513 if v.policy_set().contains(name) {
514 users.push(k.to_owned());
515 }
516 });
517
518 let mut groups = Vec::new();
519 group_policy_cache.iter().for_each(|(k, v)| {
520 if v.policy_set().contains(name) {
521 groups.push(k.to_owned());
522 }
523 });
524
525 if !stale_user_policies.is_empty() {
526 self.cache.with_write_lock(|cache| {
527 let now = OffsetDateTime::now_utc();
528 for user in stale_user_policies.iter() {
529 cache.delete_user_policy(user, now);
530 }
531 });
532 }
533
534 if !users.is_empty() || !groups.is_empty() {
535 return Err(Error::PolicyInUse);
536 }
537
538 if let Err(err) = self.api.delete_policy_doc(name).await {
539 if !is_err_no_such_policy(&err) {
544 return Err(err);
545 }
546
547 }
550 }
551
552 self.cache.delete_policy_doc(name, OffsetDateTime::now_utc());
553
554 Ok(())
555 }
556
557 pub async fn set_policy(&self, name: &str, policy: Policy) -> Result<OffsetDateTime> {
558 self.set_policy_at(name, policy, OffsetDateTime::now_utc()).await
559 }
560
561 pub async fn set_policy_at(&self, name: &str, policy: Policy, updated_at: OffsetDateTime) -> Result<OffsetDateTime> {
569 if name.is_empty() || policy.is_empty() {
570 return Err(Error::InvalidArgument);
571 }
572
573 let cache = self.cache.snapshot();
574 let policy_doc = cache
575 .policy_docs
576 .get(name)
577 .map(|v| {
578 let mut p = v.clone();
579 p.update_at(policy.clone(), updated_at);
580 p
581 })
582 .unwrap_or_else(|| PolicyDoc::new_at(policy, updated_at));
583
584 self.api.save_policy_doc(name, policy_doc.clone()).await?;
585
586 self.cache
587 .add_or_update_policy_doc(name, &policy_doc, OffsetDateTime::now_utc());
588
589 Ok(updated_at)
590 }
591
592 pub async fn list_policies(&self, bucket_name: &str) -> Result<HashMap<String, Policy>> {
593 let mut m = HashMap::new();
594
595 self.api.load_policy_docs(&mut m).await?;
596 set_default_canned_policies(&mut m);
597
598 let policy_docs_cache = CacheEntity::new(m.clone());
599
600 self.cache
601 .with_write_lock(|cache| cache.replace_policy_docs(policy_docs_cache));
602
603 let items: Vec<_> = m.into_iter().map(|(k, v)| (k, v.policy)).collect();
604
605 let futures: Vec<_> = items.iter().map(|(_, policy)| policy.match_resource(bucket_name)).collect();
606
607 let results = join_all(futures).await;
608
609 let filtered = items
610 .into_iter()
611 .zip(results)
612 .filter_map(|((k, policy), matches)| {
613 if bucket_name.is_empty() || matches {
614 Some((k, policy))
615 } else {
616 None
617 }
618 })
619 .collect();
620
621 Ok(filtered)
622 }
623
624 #[deprecated(
626 since = "1.0.0",
627 note = "use list_policies instead; this alias will be removed in the next breaking release"
628 )]
629 pub async fn list_polices(&self, bucket_name: &str) -> Result<HashMap<String, Policy>> {
630 self.list_policies(bucket_name).await
631 }
632
633 pub async fn merge_policies(&self, name: &str) -> (String, Policy) {
634 let mut policies = Vec::new();
635 let mut to_merge = Vec::new();
636 let mut miss_policies = Vec::new();
637 let cache = self.cache.snapshot();
638 let policy_docs = Arc::clone(&cache.policy_docs);
639 drop(cache);
640
641 for policy in MappedPolicy::new(name).to_slice() {
642 if policy.is_empty() {
643 continue;
644 }
645
646 if let Some(v) = policy_docs.get(&policy).cloned() {
647 policies.push(policy);
648 to_merge.push(v.policy);
649 } else {
650 miss_policies.push(policy);
651 }
652 }
653
654 if !miss_policies.is_empty() {
655 let mut m = HashMap::new();
656 for policy in miss_policies {
657 let _ = self.api.load_policy_doc(&policy, &mut m).await;
658 }
659
660 self.cache.with_write_lock(|cache| {
661 let now = OffsetDateTime::now_utc();
662 for (k, v) in m.iter() {
663 cache.add_or_update_policy_doc(k, v, now);
664 policies.push(k.clone());
665 to_merge.push(v.policy.clone());
666 }
667 });
668 }
669
670 (policies.join(","), Policy::merge_policies(to_merge))
671 }
672
673 pub async fn list_policy_docs(&self, bucket_name: &str) -> Result<HashMap<String, PolicyDoc>> {
674 let mut m = HashMap::new();
675
676 self.api.load_policy_docs(&mut m).await?;
677 set_default_canned_policies(&mut m);
678
679 let policy_docs_cache = CacheEntity::new(m.clone());
680
681 self.cache
682 .with_write_lock(|cache| cache.replace_policy_docs(policy_docs_cache));
683
684 let items: Vec<_> = m.into_iter().collect();
685
686 let futures: Vec<_> = items
687 .iter()
688 .map(|(_, policy_doc)| policy_doc.policy.match_resource(bucket_name))
689 .collect();
690
691 let results = join_all(futures).await;
692
693 let filtered = items
694 .into_iter()
695 .zip(results)
696 .filter_map(|((k, policy_doc), matches)| {
697 if bucket_name.is_empty() || matches {
698 Some((k, policy_doc))
699 } else {
700 None
701 }
702 })
703 .collect();
704
705 Ok(filtered)
706 }
707
708 pub async fn list_policy_docs_internal(&self, bucket_name: &str) -> Result<HashMap<String, PolicyDoc>> {
709 let cache = self.cache.snapshot();
710 let items: Vec<_> = cache.policy_docs.iter().map(|(k, v)| (k.clone(), v.clone())).collect();
711
712 let futures: Vec<_> = items
713 .iter()
714 .map(|(_, policy_doc)| policy_doc.policy.match_resource(bucket_name))
715 .collect();
716
717 let results = join_all(futures).await;
718
719 let ret = items
720 .into_iter()
721 .zip(results)
722 .filter_map(|((k, policy_doc), matches)| {
723 if bucket_name.is_empty() || matches {
724 Some((k, policy_doc))
725 } else {
726 None
727 }
728 })
729 .collect();
730
731 Ok(ret)
732 }
733
734 pub async fn list_temp_accounts(&self, access_key: &str) -> Result<Vec<UserIdentity>> {
735 let cache = self.cache.snapshot();
736 let users = Arc::clone(&cache.users);
737 let mut user_exists = false;
738 let mut ret = Vec::new();
739
740 for v in users.values() {
741 let is_derived = v.credentials.is_service_account() || v.credentials.is_temp();
742
743 if !is_derived && v.credentials.access_key.as_str() == access_key {
744 user_exists = true;
745 } else if is_derived && v.credentials.parent_user == access_key {
746 user_exists = true;
747 if v.credentials.is_temp() {
748 let mut u = v.clone();
749 u.credentials.secret_key = String::new();
750 u.credentials.session_token = String::new();
751
752 ret.push(u);
753 }
754 }
755 }
756
757 let sts_accounts = Arc::clone(&cache.sts_accounts);
758 for v in sts_accounts.values() {
759 if v.credentials.parent_user == access_key {
760 user_exists = true;
761 if v.credentials.is_temp() && !v.credentials.is_service_account() {
762 let mut u = v.clone();
763 u.credentials.secret_key = String::new();
764 u.credentials.session_token = String::new();
765
766 ret.push(u);
767 }
768 }
769 }
770
771 if !user_exists {
772 return Err(Error::NoSuchUser(access_key.to_string()));
773 }
774
775 Ok(ret)
776 }
777
778 pub async fn list_sts_accounts(&self, access_key: &str) -> Result<Vec<Credentials>> {
779 let cache = self.cache.snapshot();
780 let sts_accounts = Arc::clone(&cache.sts_accounts);
781 Ok(sts_accounts
782 .values()
783 .filter_map(|x| {
784 if !access_key.is_empty()
785 && x.credentials.parent_user.as_str() == access_key
786 && x.credentials.is_temp()
787 && !x.credentials.is_service_account()
788 {
789 let mut c = x.credentials.clone();
790 c.secret_key = String::new();
791 c.session_token = String::new();
792 return Some(c);
793 }
794
795 None
796 })
797 .collect())
798 }
799
800 pub async fn list_service_accounts(&self, access_key: &str) -> Result<Vec<Credentials>> {
801 let cache = self.cache.snapshot();
802 let users = Arc::clone(&cache.users);
803 Ok(users
804 .values()
805 .filter_map(|x| {
806 if !access_key.is_empty()
807 && x.credentials.parent_user.as_str() == access_key
808 && x.credentials.is_service_account()
809 {
810 let mut c = x.credentials.clone();
811 c.secret_key = String::new();
812 c.session_token = String::new();
813 return Some(c);
814 }
815
816 None
817 })
818 .collect())
819 }
820
821 pub async fn add_service_account(&self, cred: Credentials) -> Result<OffsetDateTime> {
823 self.add_service_account_at(cred, OffsetDateTime::now_utc()).await
824 }
825
826 pub async fn add_service_account_at(&self, cred: Credentials, updated_at: OffsetDateTime) -> Result<OffsetDateTime> {
829 if cred.access_key.is_empty() || cred.parent_user.is_empty() {
830 return Err(Error::InvalidArgument);
831 }
832
833 let _mutation_guard = self.cache.service_account_mutation_lock().lock().await;
834 let cache = self.cache.snapshot();
835 if cache.users.contains_key(&cred.access_key) || cache.sts_accounts.contains_key(&cred.access_key) {
836 return Err(Error::AccessKeyAlreadyExists);
837 }
838 drop(cache);
839
840 let mut u = UserIdentity::new(cred);
841 u.update_at = Some(updated_at);
842
843 self.api
844 .save_user_identity(&u.credentials.access_key, UserType::Svc, u.clone(), None)
845 .await?;
846
847 self.update_user_with_claims(&u.credentials.access_key, u.clone())?;
848
849 Ok(updated_at)
850 }
851
852 pub async fn update_service_account(&self, name: &str, opts: UpdateServiceAccountOpts) -> Result<OffsetDateTime> {
853 self.update_service_account_at(name, opts, OffsetDateTime::now_utc()).await
854 }
855
856 pub async fn update_service_account_at(
860 &self,
861 name: &str,
862 opts: UpdateServiceAccountOpts,
863 updated_at: OffsetDateTime,
864 ) -> Result<OffsetDateTime> {
865 let _mutation_guard = self.cache.service_account_mutation_lock().lock().await;
866 let cache = self.cache.snapshot();
867 let Some(ui) = cache.users.get(name).cloned() else {
868 return Err(Error::NoSuchServiceAccount(name.to_string()));
869 };
870
871 if !ui.credentials.is_service_account() {
872 return Err(Error::NoSuchServiceAccount(name.to_string()));
873 }
874 drop(cache);
875
876 let mut cr = ui.credentials.clone();
877 let current_secret_key = cr.secret_key.clone();
878
879 if let Some(secret) = opts.secret_key {
880 if !is_secret_key_valid(&secret) {
881 return Err(Error::InvalidSecretKeyLength);
882 }
883 cr.secret_key = secret;
884 }
885
886 if let Some(parent_user) = opts.parent_user {
887 if parent_user.is_empty() || !opts.allow_site_replicator_account || name != SITE_REPLICATOR_SERVICE_ACCOUNT {
890 return Err(Error::IAMActionNotAllowed);
891 }
892 cr.parent_user = parent_user;
893 }
894
895 if opts.name.is_some() {
896 cr.name = opts.name;
897 }
898
899 if opts.description.is_some() {
900 cr.description = opts.description;
901 }
902
903 let token_without_expiration = cr.expiration.is_none();
904
905 if opts.expiration.is_some() {
906 cr.expiration = opts.expiration;
908 }
909
910 if let Some(status) = opts.status {
911 cr.status = account_status_flag(&status).to_owned();
912 }
913
914 let mut m: HashMap<String, Value> = if token_without_expiration {
915 get_claims_from_token_with_secret_allow_missing_exp(&cr.session_token, ¤t_secret_key)?
916 } else {
917 get_claims_from_token_with_secret(&cr.session_token, ¤t_secret_key)?
918 };
919 m.remove(SESSION_POLICY_NAME_EXTRACTED);
920
921 let nosp = if let Some(policy) = &opts.session_policy {
922 policy.version.is_empty() && policy.statements.is_empty()
923 } else {
924 false
925 };
926
927 if m.contains_key(SESSION_POLICY_NAME) && nosp {
928 m.remove(SESSION_POLICY_NAME);
929 m.insert(iam_policy_claim_name_sa(), Value::String(INHERITED_POLICY_TYPE.to_owned()));
930 }
931
932 if let Some(session_policy) = &opts.session_policy {
933 session_policy.validate()?;
934 if !session_policy.version.is_empty() && !session_policy.statements.is_empty() {
935 let policy_buf = serde_json::to_vec(&session_policy)?;
936 if policy_buf.len() > MAX_SVCSESSION_POLICY_SIZE {
937 return Err(Error::PolicyTooLarge);
938 }
939
940 m.insert(
941 SESSION_POLICY_NAME.to_owned(),
942 Value::String(base64_simd::URL_SAFE_NO_PAD.encode_to_string(&policy_buf)),
943 );
944 m.insert(iam_policy_claim_name_sa(), Value::String(EMBEDDED_POLICY_TYPE.to_owned()));
945 }
946 }
947
948 if let Some(expiration) = opts.expiration {
949 m.insert("exp".to_owned(), Value::Number(serde_json::Number::from(expiration.unix_timestamp())));
950 }
951
952 m.insert("accessKey".to_owned(), Value::String(name.to_owned()));
953 if name == SITE_REPLICATOR_SERVICE_ACCOUNT && opts.allow_site_replicator_account {
954 m.insert(SITE_REPLICATOR_CLAIM.to_owned(), Value::Bool(true));
955 }
956 m.insert("parent".to_owned(), Value::String(cr.parent_user.clone()));
960
961 cr.session_token = jwt_sign(&m, &cr.secret_key)?;
962
963 let mut u = UserIdentity::new(cr);
964 u.update_at = Some(updated_at);
965 self.api
966 .save_user_identity(&u.credentials.access_key, UserType::Svc, u.clone(), None)
967 .await?;
968 self.update_user_with_claims(&u.credentials.access_key, u.clone())?;
969
970 Ok(updated_at)
971 }
972
973 pub async fn policy_db_get(&self, name: &str, groups: &Option<Vec<String>>) -> Result<Vec<String>> {
974 if name.is_empty() {
975 return Err(Error::InvalidArgument);
976 }
977
978 let (policies, _) = self.policy_db_get_internal(name, false, false).await?;
979 self.policy_db_get_with_groups(policies, groups).await
980 }
981
982 pub async fn sts_policy_db_get(&self, name: &str, groups: &Option<Vec<String>>) -> Result<Vec<String>> {
983 if name.is_empty() {
984 return Err(Error::InvalidArgument);
985 }
986
987 let cache = self.cache.snapshot();
988 let sts_policies = Arc::clone(&cache.sts_policies);
989 drop(cache);
990 let mapped_policy = match sts_policies.get(name) {
991 Some(policy) => policy.clone(),
992 None => {
993 let mut policies = HashMap::new();
994 if let Err(err) = self.api.load_mapped_policy(name, UserType::Sts, false, &mut policies).await
995 && !is_err_no_such_policy(&err)
996 {
997 return Err(err);
998 }
999 match policies.get(name) {
1000 Some(policy) => {
1001 self.cache.add_or_update_sts_policy(name, policy, OffsetDateTime::now_utc());
1002 policy.clone()
1003 }
1004 None => MappedPolicy::default(),
1005 }
1006 }
1007 };
1008
1009 self.policy_db_get_with_groups(mapped_policy.to_slice(), groups).await
1010 }
1011
1012 async fn policy_db_get_with_groups(&self, mut policies: Vec<String>, groups: &Option<Vec<String>>) -> Result<Vec<String>> {
1013 let present = !policies.is_empty();
1014
1015 if let Some(groups) = groups {
1016 for group in groups.iter() {
1017 let (gp, _) = match self.policy_db_get_internal(group, true, present).await {
1018 Ok(result) => result,
1019 Err(err) if is_err_no_such_group(&err) => continue,
1020 Err(err) => return Err(err),
1021 };
1022 gp.iter().for_each(|v| {
1023 policies.push(v.clone());
1024 });
1025 }
1026 }
1027
1028 Ok(policies)
1029 }
1030
1031 async fn policy_db_get_internal(
1032 &self,
1033 name: &str,
1034 is_group: bool,
1035 policy_present: bool,
1036 ) -> Result<(Vec<String>, OffsetDateTime)> {
1037 if is_group {
1038 let cache = self.cache.snapshot();
1039 let groups = Arc::clone(&cache.groups);
1040 drop(cache);
1041
1042 let g = match groups.get(name) {
1043 Some(p) => p.clone(),
1044 None => {
1045 let mut m = HashMap::new();
1046 self.api.load_group(name, &mut m).await?;
1047 if let Some(p) = m.get(name) {
1048 self.cache.add_or_update_group(name, p, OffsetDateTime::now_utc());
1049 }
1050
1051 m.get(name).cloned().ok_or_else(|| Error::NoSuchGroup(name.to_string()))?
1052 }
1053 };
1054
1055 if g.status == STATUS_DISABLED {
1056 return Ok((Vec::new(), OffsetDateTime::now_utc()));
1057 }
1058
1059 let cache = self.cache.snapshot();
1060 let group_policies = Arc::clone(&cache.group_policies);
1061 drop(cache);
1062 if let Some(policy) = group_policies.get(name) {
1063 return Ok((policy.to_slice(), policy.update_at));
1064 }
1065
1066 if !policy_present {
1067 let mut m = HashMap::new();
1068 if let Err(err) = self.api.load_mapped_policy(name, UserType::Reg, true, &mut m).await
1069 && !is_err_no_such_policy(&err)
1070 {
1071 return Err(err);
1072 }
1073 if let Some(p) = m.get(name) {
1074 self.cache.add_or_update_group_policy(name, p, OffsetDateTime::now_utc());
1075 return Ok((p.to_slice(), p.update_at));
1076 }
1077
1078 return Ok((Vec::new(), OffsetDateTime::now_utc()));
1079 }
1080
1081 return Ok((Vec::new(), OffsetDateTime::now_utc()));
1082 }
1083
1084 let cache = self.cache.snapshot();
1085 let users = Arc::clone(&cache.users);
1086 let user_policies = Arc::clone(&cache.user_policies);
1087 let sts_policies = Arc::clone(&cache.sts_policies);
1088 let groups_cache = Arc::clone(&cache.groups);
1089 let group_policies = Arc::clone(&cache.group_policies);
1090 let user_group_memberships = Arc::clone(&cache.user_group_memberships);
1091 drop(cache);
1092 let u = users.get(name).cloned().unwrap_or_default();
1093 if !u.credentials.is_valid() {
1094 return Ok((Vec::new(), OffsetDateTime::now_utc()));
1095 }
1096
1097 let mp = match user_policies.get(name) {
1098 Some(p) => p.clone(),
1099 None => {
1100 let mut m = HashMap::new();
1101 if let Err(err) = self.api.load_mapped_policy(name, UserType::Reg, false, &mut m).await
1102 && !is_err_no_such_policy(&err)
1103 {
1104 return Err(err);
1105 }
1106 if let Some(p) = m.get(name) {
1107 self.cache.add_or_update_user_policy(name, p, OffsetDateTime::now_utc());
1108 p.clone()
1109 } else {
1110 match sts_policies.get(name) {
1111 Some(p) => p.clone(),
1112 None => {
1113 let mut m = HashMap::new();
1114 if let Err(err) = self.api.load_mapped_policy(name, UserType::Sts, false, &mut m).await
1115 && !is_err_no_such_policy(&err)
1116 {
1117 return Err(err);
1118 }
1119 if let Some(p) = m.get(name) {
1120 self.cache.add_or_update_sts_policy(name, p, OffsetDateTime::now_utc());
1121 p.clone()
1122 } else {
1123 MappedPolicy::default()
1124 }
1125 }
1126 }
1127 }
1128 }
1129 };
1130
1131 let mut policies: HashSet<String> = mp.to_slice().into_iter().collect();
1132
1133 if let Some(groups) = u.credentials.groups.as_ref() {
1134 for group in groups.iter() {
1135 if groups_cache.get(group).filter(|v| v.status == STATUS_DISABLED).is_some() {
1136 return Ok((Vec::new(), OffsetDateTime::now_utc()));
1137 }
1138
1139 let mp = match group_policies.get(group) {
1140 Some(p) => p.clone(),
1141 None => {
1142 let mut m = HashMap::new();
1143 if let Err(err) = self.api.load_mapped_policy(group, UserType::Reg, true, &mut m).await
1144 && !is_err_no_such_policy(&err)
1145 {
1146 return Err(err);
1147 }
1148 if let Some(p) = m.get(group) {
1149 self.cache.add_or_update_group_policy(group, p, OffsetDateTime::now_utc());
1150 p.clone()
1151 } else {
1152 MappedPolicy::default()
1153 }
1154 }
1155 };
1156
1157 mp.to_slice().iter().for_each(|v| {
1158 policies.insert(v.clone());
1159 });
1160 }
1161 }
1162
1163 let update_at = mp.update_at;
1164
1165 for group in user_group_memberships.get(name).cloned().unwrap_or_default().iter() {
1166 if groups_cache.get(group).filter(|v| v.status == STATUS_DISABLED).is_some() {
1167 return Ok((Vec::new(), OffsetDateTime::now_utc()));
1168 }
1169
1170 let mp = match group_policies.get(group) {
1171 Some(p) => p.clone(),
1172 None => {
1173 let mut m = HashMap::new();
1174 if let Err(err) = self.api.load_mapped_policy(group, UserType::Reg, true, &mut m).await
1175 && !is_err_no_such_policy(&err)
1176 {
1177 return Err(err);
1178 }
1179 if let Some(p) = m.get(group) {
1180 self.cache.add_or_update_group_policy(group, p, OffsetDateTime::now_utc());
1181 p.clone()
1182 } else {
1183 MappedPolicy::default()
1184 }
1185 }
1186 };
1187
1188 mp.to_slice().iter().for_each(|v| {
1189 policies.insert(v.clone());
1190 });
1191 }
1192
1193 Ok((policies.into_iter().collect(), update_at))
1194 }
1195 pub async fn policy_db_set(&self, name: &str, user_type: UserType, is_group: bool, policy: &str) -> Result<OffsetDateTime> {
1196 self.policy_db_set_at(name, user_type, is_group, policy, OffsetDateTime::now_utc())
1197 .await
1198 }
1199
1200 pub async fn policy_db_set_at(
1203 &self,
1204 name: &str,
1205 user_type: UserType,
1206 is_group: bool,
1207 policy: &str,
1208 updated_at: OffsetDateTime,
1209 ) -> Result<OffsetDateTime> {
1210 if name.is_empty() {
1211 return Err(Error::InvalidArgument);
1212 }
1213
1214 if policy.is_empty() {
1215 if let Err(err) = self.api.delete_mapped_policy(name, user_type, is_group).await
1216 && !is_err_no_such_policy(&err)
1217 {
1218 return Err(err);
1219 }
1220
1221 if is_group {
1222 self.cache.delete_group_policy(name, OffsetDateTime::now_utc());
1223 } else if user_type == UserType::Sts {
1224 self.cache.delete_sts_policy(name, OffsetDateTime::now_utc());
1225 } else {
1226 self.cache.delete_user_policy(name, OffsetDateTime::now_utc());
1227 }
1228
1229 return Ok(updated_at);
1230 }
1231
1232 let mut mp = MappedPolicy::new(policy);
1233 mp.update_at = updated_at;
1234
1235 let cache = self.cache.snapshot();
1236 let policy_docs_cache = Arc::clone(&cache.policy_docs);
1237 drop(cache);
1238 for p in mp.to_slice() {
1239 if !policy_docs_cache.contains_key(&p) {
1240 return Err(Error::NoSuchPolicy);
1241 }
1242 }
1243
1244 self.api
1245 .save_mapped_policy(name, user_type, is_group, mp.clone(), None)
1246 .await?;
1247
1248 if is_group {
1249 self.cache.add_or_update_group_policy(name, &mp, OffsetDateTime::now_utc());
1250 } else if user_type == UserType::Sts {
1251 self.cache.add_or_update_sts_policy(name, &mp, OffsetDateTime::now_utc());
1252 } else {
1253 self.cache.add_or_update_user_policy(name, &mp, OffsetDateTime::now_utc());
1254 }
1255
1256 Ok(updated_at)
1257 }
1258
1259 pub async fn set_temp_user(&self, access_key: &str, cred: &Credentials, policy_name: Option<&str>) -> Result<OffsetDateTime> {
1260 if access_key.is_empty() || !cred.is_temp() || cred.is_expired() || cred.parent_user.is_empty() {
1261 error!(
1262 "set temp user invalid argument, access_key: {}, is_temp: {}, is_expired: {}, parent_user_empty: {}",
1263 access_key,
1264 cred.is_temp(),
1265 cred.is_expired(),
1266 cred.parent_user.is_empty()
1267 );
1268 return Err(Error::InvalidArgument);
1269 }
1270
1271 let mutation_lock = self.cache.sts_account_mutation_lock(access_key);
1272 let _mutation_guard = mutation_lock.lock().await;
1273
1274 let sts_policy_update = if let Some(policy) = policy_name {
1275 let mp = MappedPolicy::new(policy);
1276 let (_, combined_policy_stmt) = filter_policies(&self.cache, &mp.policies, "temp");
1277 if combined_policy_stmt.is_empty() {
1278 return Err(Error::other(format!("Required policy not found: {}", IamError::NoSuchPolicy)));
1279 }
1280
1281 self.api
1282 .save_mapped_policy(&cred.parent_user, UserType::Sts, false, mp.clone(), None)
1283 .await?;
1284
1285 Some(mp)
1286 } else {
1287 None
1288 };
1289
1290 let u = UserIdentity::new(cred.clone());
1291 self.api
1292 .save_user_identity(access_key, UserType::Sts, u.clone(), None)
1293 .await?;
1294 self.verify_temp_user_persistence(access_key).await?;
1295
1296 let now = self.cache.with_write_lock(|cache| {
1297 let now = OffsetDateTime::now_utc();
1298 if let Some(mp) = &sts_policy_update {
1299 cache.add_or_update_sts_policy(&cred.parent_user, mp, now);
1300 }
1301 cache.add_or_update_sts_account(access_key, &u, now);
1302 now
1303 });
1304
1305 Ok(now)
1306 }
1307
1308 pub async fn get_user_info(&self, name: &str) -> Result<rustfs_madmin::UserInfo> {
1309 let cache = self.cache.snapshot();
1310 let users = Arc::clone(&cache.users);
1311 let policies = Arc::clone(&cache.user_policies);
1312 let group_members = Arc::clone(&cache.user_group_memberships);
1313
1314 let u = match users.get(name) {
1315 Some(u) => u,
1316 None => return Err(Error::NoSuchUser(name.to_string())),
1317 };
1318
1319 if u.credentials.is_temp() || u.credentials.is_service_account() {
1320 return Err(Error::IAMActionNotAllowed);
1321 }
1322
1323 let mut uinfo = rustfs_madmin::UserInfo {
1324 status: if u.credentials.is_valid() {
1325 AccountStatus::Enabled
1326 } else {
1327 AccountStatus::Disabled
1328 },
1329 updated_at: u.update_at,
1330 ..Default::default()
1331 };
1332
1333 if let Some(p) = policies.get(name) {
1334 uinfo.policy_name = Some(p.policies.clone());
1335 uinfo.updated_at = Some(p.update_at);
1336 }
1337
1338 if let Some(members) = group_members.get(name) {
1339 uinfo.member_of = Some(members.iter().cloned().collect());
1340 }
1341
1342 Ok(uinfo)
1343 }
1344
1345 pub async fn get_users(&self) -> Result<HashMap<String, rustfs_madmin::UserInfo>> {
1347 let mut m = HashMap::new();
1348
1349 let cache = self.cache.snapshot();
1350 let users = Arc::clone(&cache.users);
1351 let policies = Arc::clone(&cache.user_policies);
1352 let group_members = Arc::clone(&cache.user_group_memberships);
1353
1354 for (k, v) in users.iter() {
1355 if v.credentials.is_temp() || v.credentials.is_service_account() {
1356 continue;
1357 }
1358
1359 let mut u = rustfs_madmin::UserInfo {
1360 status: if v.credentials.is_valid() {
1361 AccountStatus::Enabled
1362 } else {
1363 AccountStatus::Disabled
1364 },
1365 updated_at: v.update_at,
1366 ..Default::default()
1367 };
1368
1369 if let Some(p) = policies.get(k) {
1370 u.policy_name = Some(p.policies.clone());
1371 u.updated_at = Some(p.update_at);
1372 }
1373
1374 if let Some(members) = group_members.get(k) {
1375 u.member_of = Some(members.iter().cloned().collect());
1376 }
1377
1378 m.insert(k.clone(), u);
1379 }
1380
1381 Ok(m)
1382 }
1383 pub async fn get_bucket_users(&self, bucket_name: &str) -> Result<HashMap<String, rustfs_madmin::UserInfo>> {
1384 let cache = self.cache.snapshot();
1385 let users = Arc::clone(&cache.users);
1386 let policies_cache = Arc::clone(&cache.user_policies);
1387 let group_members = Arc::clone(&cache.user_group_memberships);
1388 let group_policy_cache = Arc::clone(&cache.group_policies);
1389 let policy_docs_cache = Arc::clone(&cache.policy_docs);
1390 drop(cache);
1391
1392 let mut ret = HashMap::new();
1393
1394 for (k, v) in users.iter() {
1395 if v.credentials.is_temp() || v.credentials.is_service_account() {
1396 continue;
1397 }
1398
1399 let mut policies = Vec::new();
1400 if let Some(p) = policies_cache.get(k) {
1401 policies.push(p.policies.clone());
1402
1403 if let Some(groups) = group_members.get(k) {
1404 for group in groups {
1405 if let Some(p) = group_policy_cache.get(group) {
1406 policies.push(p.policies.clone());
1407 }
1408 }
1409 }
1410 }
1411
1412 let matched_policies = filter_policies_from_docs(policy_docs_cache.as_ref(), &policies.join(","), bucket_name).0;
1413 if matched_policies.is_empty() {
1414 continue;
1415 }
1416
1417 let mut u = rustfs_madmin::UserInfo {
1418 policy_name: Some(matched_policies),
1419 status: if v.credentials.is_valid() {
1420 AccountStatus::Enabled
1421 } else {
1422 AccountStatus::Disabled
1423 },
1424 updated_at: v.update_at,
1425 ..Default::default()
1426 };
1427
1428 if let Some(members) = group_members.get(k) {
1429 u.member_of = Some(members.iter().cloned().collect());
1430 }
1431
1432 ret.insert(k.clone(), u);
1433 }
1434
1435 Ok(ret)
1436 }
1437 pub async fn get_users_with_mapped_policies(&self) -> HashMap<String, String> {
1438 let mut m = HashMap::new();
1439
1440 let cache = self.cache.snapshot();
1441 cache.user_policies.iter().for_each(|(k, v)| {
1442 m.insert(k.clone(), v.policies.clone());
1443 });
1444
1445 cache.sts_policies.iter().for_each(|(k, v)| {
1446 m.insert(k.clone(), v.policies.clone());
1447 });
1448
1449 m
1450 }
1451
1452 pub async fn add_user(&self, access_key: &str, args: &AddOrUpdateUserReq) -> Result<OffsetDateTime> {
1453 self.add_user_at(access_key, args, OffsetDateTime::now_utc()).await
1454 }
1455
1456 pub async fn add_user_at(
1459 &self,
1460 access_key: &str,
1461 args: &AddOrUpdateUserReq,
1462 updated_at: OffsetDateTime,
1463 ) -> Result<OffsetDateTime> {
1464 let cache = self.cache.snapshot();
1465 let users = Arc::clone(&cache.users);
1466 if let Some(x) = users.get(access_key) {
1467 warn!(error = ?x, "IAM user already exists");
1468 if x.credentials.is_temp() {
1469 return Err(Error::AccessKeyAlreadyExists);
1470 }
1471 }
1472 drop(cache);
1473 drop(users);
1474
1475 let status = {
1476 match &args.status {
1477 AccountStatus::Enabled => auth::ACCOUNT_ON,
1478 _ => auth::ACCOUNT_OFF,
1479 }
1480 };
1481 let mut user_entry = UserIdentity::from(Credentials {
1482 access_key: access_key.to_string(),
1483 secret_key: args.secret_key.to_string(),
1484 status: status.to_owned(),
1485 ..Default::default()
1486 });
1487 user_entry.update_at = Some(updated_at);
1488
1489 self.api
1490 .save_user_identity(access_key, UserType::Reg, user_entry.clone(), None)
1491 .await?;
1492
1493 self.update_user_with_claims(access_key, user_entry)?;
1494
1495 Ok(updated_at)
1496 }
1497
1498 pub async fn delete_user(&self, access_key: &str, utype: UserType) -> Result<()> {
1499 self.delete_user_with_revision(access_key, utype).await?;
1500 Ok(())
1501 }
1502
1503 pub async fn delete_service_account_with_revision(&self, access_key: &str) -> Result<OffsetDateTime> {
1504 self.delete_user_with_revision(access_key, UserType::Svc).await
1505 }
1506
1507 async fn delete_user_with_revision(&self, access_key: &str, utype: UserType) -> Result<OffsetDateTime> {
1508 if access_key.is_empty() {
1509 return Err(Error::InvalidArgument);
1510 }
1511
1512 let sts_mutation_lock = (utype == UserType::Sts).then(|| self.cache.sts_account_mutation_lock(access_key));
1513 let _sts_mutation_guard = match &sts_mutation_lock {
1514 Some(lock) => Some(lock.lock().await),
1515 None => None,
1516 };
1517 let _service_account_guard = if utype == UserType::Svc {
1518 Some(self.cache.service_account_mutation_lock().lock().await)
1519 } else {
1520 None
1521 };
1522
1523 if utype == UserType::Reg {
1524 let cache = self.cache.snapshot();
1525 let member_of = cache.user_group_memberships.get(access_key).cloned();
1526 drop(cache);
1527 if let Some(member_of) = member_of {
1528 for member in member_of.iter() {
1529 let _ = self
1530 .remove_members_from_group(member, vec![access_key.to_string()], false)
1531 .await?;
1532 }
1533 }
1534
1535 let mut service_accounts_to_delete = Vec::new();
1536 let mut temp_accounts_to_delete = HashSet::new();
1537 let cache = self.cache.snapshot();
1538 for v in cache.users.values() {
1539 let u = &v.credentials;
1540 if u.parent_user.as_str() == access_key {
1541 if u.is_service_account() {
1542 service_accounts_to_delete.push(u.access_key.clone());
1543 }
1544
1545 if u.is_temp() {
1546 temp_accounts_to_delete.insert(u.access_key.clone());
1547 }
1548 }
1549 }
1550 for v in cache.sts_accounts.values() {
1551 let u = &v.credentials;
1552 if u.parent_user.as_str() == access_key {
1553 temp_accounts_to_delete.insert(u.access_key.clone());
1554 }
1555 }
1556 drop(cache);
1557
1558 for access_key in service_accounts_to_delete.iter() {
1559 let _ = self.api.delete_user_identity(access_key, UserType::Svc).await;
1560 }
1561 for access_key in temp_accounts_to_delete.iter() {
1562 let _ = self.api.delete_user_identity(access_key, UserType::Sts).await;
1563 }
1564
1565 self.cache.with_write_lock(|cache| {
1566 let now = OffsetDateTime::now_utc();
1567 for access_key in service_accounts_to_delete.iter() {
1568 cache.delete_user(access_key, now);
1569 }
1570 for access_key in temp_accounts_to_delete.iter() {
1571 cache.delete_sts_account(access_key, now);
1572 cache.delete_user(access_key, now);
1573 }
1574 });
1575 }
1576
1577 if utype != UserType::Sts {
1578 let _ = self.api.delete_mapped_policy(access_key, utype, false).await;
1579 }
1580
1581 if utype != UserType::Sts {
1582 self.cache.delete_user_policy(access_key, OffsetDateTime::now_utc());
1583 }
1584
1585 if let Err(err) = self.api.delete_user_identity(access_key, utype).await
1586 && !is_err_no_such_user(&err)
1587 {
1588 return Err(err);
1589 }
1590
1591 let deleted_at = OffsetDateTime::now_utc();
1592 self.cache.with_write_lock(|cache| {
1593 if utype == UserType::Sts {
1594 cache.delete_sts_account(access_key, deleted_at);
1595 if cache
1596 .state()
1597 .users
1598 .get(access_key)
1599 .is_some_and(|identity| identity.credentials.is_temp())
1600 {
1601 cache.delete_user(access_key, deleted_at);
1602 }
1603 } else {
1604 cache.delete_user(access_key, deleted_at);
1605 }
1606 });
1607
1608 Ok(deleted_at)
1609 }
1610
1611 pub async fn update_user_secret_key(&self, access_key: &str, secret_key: &str) -> Result<(OffsetDateTime, AccountStatus)> {
1612 if access_key.is_empty() || secret_key.is_empty() {
1613 return Err(Error::InvalidArgument);
1614 }
1615
1616 let cache = self.cache.snapshot();
1617 let users = Arc::clone(&cache.users);
1618 let u = match users.get(access_key) {
1619 Some(u) => u,
1620 None => return Err(Error::NoSuchUser(access_key.to_string())),
1621 };
1622
1623 let mut cred = u.credentials.clone();
1624 cred.secret_key = secret_key.to_string();
1625
1626 let status = if cred.is_valid() {
1630 AccountStatus::Enabled
1631 } else {
1632 AccountStatus::Disabled
1633 };
1634 let u = UserIdentity::from(cred);
1635 let updated_at = u.update_at.unwrap_or_else(OffsetDateTime::now_utc);
1636 drop(cache);
1637 drop(users);
1638
1639 self.api
1640 .save_user_identity(access_key, UserType::Reg, u.clone(), None)
1641 .await?;
1642
1643 self.update_user_with_claims(access_key, u)?;
1644 Ok((updated_at, status))
1645 }
1646
1647 pub async fn add_user_ssh_public_key(&self, access_key: &str, public_key: &str) -> Result<()> {
1649 if access_key.is_empty() || public_key.is_empty() {
1650 return Err(Error::InvalidArgument);
1651 }
1652
1653 let cache = self.cache.snapshot();
1654 let users = Arc::clone(&cache.users);
1655 let u = match users.get(access_key) {
1656 Some(u) => u,
1657 None => return Err(Error::NoSuchUser(access_key.to_string())),
1658 };
1659
1660 let mut user_identity = u.clone();
1661 user_identity.add_ssh_public_key(public_key);
1662 drop(cache);
1663 drop(users);
1664
1665 self.api
1666 .save_user_identity(access_key, UserType::Reg, user_identity.clone(), None)
1667 .await?;
1668
1669 self.update_user_with_claims(access_key, user_identity)
1670 }
1671
1672 pub async fn set_user_status(&self, access_key: &str, status: AccountStatus) -> Result<OffsetDateTime> {
1673 self.set_user_status_at(access_key, status, OffsetDateTime::now_utc()).await
1674 }
1675
1676 pub async fn set_user_status_at(
1679 &self,
1680 access_key: &str,
1681 status: AccountStatus,
1682 updated_at: OffsetDateTime,
1683 ) -> Result<OffsetDateTime> {
1684 if access_key.is_empty() {
1685 return Err(Error::InvalidArgument);
1686 }
1687
1688 if !access_key.is_empty() && status != AccountStatus::Enabled && status != AccountStatus::Disabled {
1689 return Err(Error::InvalidArgument);
1690 }
1691
1692 let cache = self.cache.snapshot();
1693 let users = Arc::clone(&cache.users);
1694 let u = match users.get(access_key) {
1695 Some(u) => u,
1696 None => return Err(Error::NoSuchUser(access_key.to_string())),
1697 };
1698
1699 if u.credentials.is_temp() || u.credentials.is_service_account() {
1700 return Err(Error::IAMActionNotAllowed);
1701 }
1702
1703 let status = {
1704 match status {
1705 AccountStatus::Enabled => auth::ACCOUNT_ON,
1706 _ => auth::ACCOUNT_OFF,
1707 }
1708 };
1709
1710 let mut user_entry = UserIdentity::from(Credentials {
1711 access_key: access_key.to_string(),
1712 secret_key: u.credentials.secret_key.clone(),
1713 status: status.to_owned(),
1714 ..Default::default()
1715 });
1716 user_entry.update_at = Some(updated_at);
1717 drop(cache);
1718 drop(users);
1719
1720 self.api
1721 .save_user_identity(access_key, UserType::Reg, user_entry.clone(), None)
1722 .await?;
1723
1724 self.update_user_with_claims(access_key, user_entry)?;
1725
1726 Ok(updated_at)
1727 }
1728
1729 fn update_user_with_claims(&self, k: &str, u: UserIdentity) -> Result<()> {
1730 let mut u = u;
1731 if !u.credentials.session_token.is_empty() {
1732 u.credentials.claims = Some(if u.credentials.expiration.is_none() {
1733 extract_jwt_claims_allow_missing_exp(&u)?
1734 } else {
1735 extract_jwt_claims(&u)?
1736 });
1737 }
1738
1739 if u.credentials.is_temp() && !u.credentials.is_service_account() {
1740 self.cache.add_or_update_sts_account(k, &u, OffsetDateTime::now_utc());
1741 } else {
1742 self.cache.add_or_update_user(k, &u, OffsetDateTime::now_utc());
1743 }
1744
1745 Ok(())
1746 }
1747
1748 pub async fn is_temp_user(&self, access_key: &str) -> Result<(bool, String)> {
1749 let u = match self.get_user(access_key).await {
1750 Some(u) => u,
1751 None => return Err(Error::NoSuchUser(access_key.to_string())),
1752 };
1753
1754 if u.credentials.is_temp() {
1755 Ok((true, u.credentials.parent_user))
1756 } else {
1757 Ok((false, String::new()))
1758 }
1759 }
1760
1761 pub async fn add_users_to_group(&self, group: &str, members: Vec<String>) -> Result<OffsetDateTime> {
1762 self.add_users_to_group_at(group, members, OffsetDateTime::now_utc()).await
1763 }
1764
1765 pub async fn add_users_to_group_at(
1768 &self,
1769 group: &str,
1770 members: Vec<String>,
1771 updated_at: OffsetDateTime,
1772 ) -> Result<OffsetDateTime> {
1773 if group.is_empty() {
1774 return Err(Error::InvalidArgument);
1775 }
1776
1777 let cache = self.cache.snapshot();
1778 let users_cache = Arc::clone(&cache.users);
1779
1780 for member in members.iter() {
1781 if let Some(u) = users_cache.get(member) {
1782 if u.credentials.is_temp() || u.credentials.is_service_account() {
1783 return Err(Error::IAMActionNotAllowed);
1784 }
1785 } else {
1786 return Err(Error::NoSuchUser(member.to_string()));
1787 }
1788 }
1789
1790 let gi = match cache.groups.get(group) {
1799 Some(res) => {
1800 let mut gi = res.clone();
1801 let mut uniq_set: HashSet<String, std::collections::hash_map::RandomState> =
1802 HashSet::from_iter(gi.members.iter().cloned());
1803 uniq_set.extend(members.iter().cloned());
1804
1805 gi.members = uniq_set.into_iter().collect();
1806 gi.update_at = Some(updated_at);
1807 gi
1808 }
1809 None => {
1810 let mut gi = GroupInfo::new(members.clone());
1811 gi.update_at = Some(updated_at);
1812 gi
1813 }
1814 };
1815 drop(cache);
1816
1817 self.api.save_group_info(group, gi.clone()).await?;
1818
1819 self.cache.with_write_lock(|cache| {
1820 let now = OffsetDateTime::now_utc();
1821 cache.add_or_update_group(group, &gi, now);
1822
1823 let user_group_memberships = Arc::clone(&cache.state().user_group_memberships);
1824 members.iter().for_each(|member| {
1825 let mut m = user_group_memberships.get(member).cloned().unwrap_or_default();
1826 m.insert(group.to_string());
1827 cache.add_or_update_user_group_membership(member, &m, now);
1828 });
1829 });
1830
1831 Ok(updated_at)
1832 }
1833
1834 pub async fn set_group_status(&self, name: &str, enable: bool) -> Result<OffsetDateTime> {
1835 self.set_group_status_at(name, enable, OffsetDateTime::now_utc()).await
1836 }
1837
1838 pub async fn set_group_status_at(&self, name: &str, enable: bool, updated_at: OffsetDateTime) -> Result<OffsetDateTime> {
1841 if name.is_empty() {
1842 return Err(Error::InvalidArgument);
1843 }
1844
1845 let cache = self.cache.snapshot();
1846 let groups = Arc::clone(&cache.groups);
1847 let mut gi = match groups.get(name) {
1848 Some(gi) => gi.clone(),
1849 None => return Err(Error::NoSuchGroup(name.to_string())),
1850 };
1851 drop(cache);
1852
1853 if enable {
1854 gi.status = STATUS_ENABLED.to_owned();
1855 } else {
1856 gi.status = STATUS_DISABLED.to_owned();
1857 }
1858 gi.update_at = Some(updated_at);
1859
1860 self.api.save_group_info(name, gi.clone()).await?;
1861
1862 self.cache.add_or_update_group(name, &gi, OffsetDateTime::now_utc());
1865
1866 Ok(updated_at)
1867 }
1868
1869 pub async fn get_group_description(&self, name: &str) -> Result<GroupDesc> {
1870 let cache = self.cache.snapshot();
1871 let gi = cache
1872 .groups
1873 .get(name)
1874 .cloned()
1875 .ok_or_else(|| Error::NoSuchGroup(name.to_string()))?;
1876
1877 let cached_mapped_policy = cache.group_policies.get(name).cloned();
1878 drop(cache);
1879
1880 let mapped_policy = if let Some(policy) = cached_mapped_policy {
1881 Some(policy)
1882 } else {
1883 let mut policies = HashMap::new();
1884 if let Err(err) = self.api.load_mapped_policy(name, UserType::Reg, true, &mut policies).await
1885 && !is_err_no_such_policy(&err)
1886 {
1887 return Err(err);
1888 }
1889
1890 if let Some(policy) = policies.get(name).cloned() {
1891 self.cache
1892 .add_or_update_group_policy(name, &policy, OffsetDateTime::now_utc());
1893 Some(policy)
1894 } else {
1895 None
1896 }
1897 };
1898
1899 Ok(build_group_desc(name, gi, mapped_policy))
1900 }
1901
1902 pub async fn list_groups(&self) -> Result<Vec<String>> {
1903 Ok(self.cache.snapshot().groups.keys().cloned().collect())
1904 }
1905
1906 pub async fn update_groups(&self) -> Result<Vec<String>> {
1907 let mut groups_set = HashSet::new();
1908 let mut groups = HashMap::new();
1909 self.api.load_groups(&mut groups).await?;
1910
1911 let mut group_policies = HashMap::new();
1912
1913 self.api
1914 .load_mapped_policies(UserType::Reg, true, &mut group_policies)
1915 .await?;
1916 self.cache.with_write_lock(|cache| {
1917 let now = OffsetDateTime::now_utc();
1918 for (group, gi) in groups.iter() {
1919 cache.add_or_update_group(group, gi, now);
1920 groups_set.insert(group.to_string());
1921 }
1922 for (group, gi) in group_policies.iter() {
1923 cache.add_or_update_group_policy(group, gi, now);
1924 groups_set.insert(group.to_string());
1925 }
1926 });
1927
1928 Ok(groups_set.into_iter().collect())
1929 }
1930
1931 pub async fn remove_members_from_group(
1932 &self,
1933 name: &str,
1934 members: Vec<String>,
1935 update_cache_only: bool,
1936 ) -> Result<OffsetDateTime> {
1937 self.remove_members_from_group_at(name, members, update_cache_only, OffsetDateTime::now_utc())
1938 .await
1939 }
1940
1941 pub async fn remove_members_from_group_at(
1945 &self,
1946 name: &str,
1947 members: Vec<String>,
1948 update_cache_only: bool,
1949 updated_at: OffsetDateTime,
1950 ) -> Result<OffsetDateTime> {
1951 let cache = self.cache.snapshot();
1952 let mut gi = cache
1953 .groups
1954 .get(name)
1955 .cloned()
1956 .ok_or_else(|| Error::NoSuchGroup(name.to_string()))?;
1957 drop(cache);
1958
1959 let s: HashSet<&String> = HashSet::from_iter(gi.members.iter());
1960 let d: HashSet<&String> = HashSet::from_iter(members.iter());
1961 gi.members = s.difference(&d).map(|v| v.to_string()).collect::<Vec<String>>();
1962 gi.update_at = Some(updated_at);
1963 if !update_cache_only {
1964 self.api.save_group_info(name, gi.clone()).await?;
1965 }
1966
1967 self.cache.with_write_lock(|cache| {
1968 let now = OffsetDateTime::now_utc();
1971 cache.add_or_update_group(name, &gi, now);
1972
1973 let user_group_memberships = Arc::clone(&cache.state().user_group_memberships);
1974 members.iter().for_each(|member| {
1975 if let Some(m) = user_group_memberships.get(member) {
1976 let mut m = m.clone();
1977 m.remove(name);
1978 cache.add_or_update_user_group_membership(member, &m, now);
1979 }
1980 });
1981 });
1982
1983 Ok(updated_at)
1984 }
1985
1986 pub async fn remove_users_from_group(&self, group: &str, members: Vec<String>) -> Result<OffsetDateTime> {
1987 self.remove_users_from_group_at(group, members, OffsetDateTime::now_utc())
1988 .await
1989 }
1990
1991 pub async fn remove_users_from_group_at(
1995 &self,
1996 group: &str,
1997 members: Vec<String>,
1998 updated_at: OffsetDateTime,
1999 ) -> Result<OffsetDateTime> {
2000 if group.is_empty() {
2001 return Err(Error::InvalidArgument);
2002 }
2003
2004 let cache = self.cache.snapshot();
2005 let users_cache = Arc::clone(&cache.users);
2006 let groups_cache = Arc::clone(&cache.groups);
2007 drop(cache);
2008
2009 for member in members.iter() {
2010 if let Some(u) = users_cache.get(member) {
2011 if u.credentials.is_temp() || u.credentials.is_service_account() {
2012 return Err(Error::IAMActionNotAllowed);
2013 }
2014 } else {
2015 return Err(Error::NoSuchUser(member.to_string()));
2016 }
2017 }
2018
2019 let gi = if members.is_empty() {
2020 let mut m = HashMap::new();
2022 self.api.load_group(group, &mut m).await?;
2023 m.get(group).cloned().ok_or_else(|| Error::NoSuchGroup(group.to_string()))?
2024 } else {
2025 groups_cache
2026 .get(group)
2027 .cloned()
2028 .ok_or_else(|| Error::NoSuchGroup(group.to_string()))?
2029 };
2030
2031 if members.is_empty() && !gi.members.is_empty() {
2032 return Err(Error::GroupNotEmpty);
2033 }
2034
2035 if members.is_empty() {
2036 if let Err(err) = self.api.delete_mapped_policy(group, UserType::Reg, true).await
2037 && !is_err_no_such_policy(&err)
2038 {
2039 return Err(err);
2040 }
2041
2042 if let Err(err) = self.api.delete_group_info(group).await
2043 && !is_err_no_such_group(&err)
2044 {
2045 return Err(err);
2046 }
2047
2048 self.cache.with_write_lock(|cache| {
2049 let now = OffsetDateTime::now_utc();
2050 self.remove_group_from_memberships_map_unlocked(cache, group, now);
2051 cache.delete_group(group, now);
2052 cache.delete_group_policy(group, now);
2053 });
2054
2055 return Ok(updated_at);
2056 }
2057
2058 self.remove_members_from_group_at(group, members, false, updated_at).await
2059 }
2060
2061 fn remove_group_from_memberships_map_unlocked(&self, cache: &mut LockedCache, group: &str, now: OffsetDateTime) {
2062 let user_group_memberships = Arc::clone(&cache.state().user_group_memberships);
2063 for (k, v) in user_group_memberships.iter() {
2064 if v.contains(group) {
2065 let mut m = v.clone();
2066 m.remove(group);
2067 cache.add_or_update_user_group_membership(k, &m, now);
2068 }
2069 }
2070 }
2071
2072 fn update_group_memberships_map_unlocked(&self, cache: &mut LockedCache, group: &str, gi: &GroupInfo, now: OffsetDateTime) {
2073 let user_group_memberships = Arc::clone(&cache.state().user_group_memberships);
2074 for member in gi.members.iter() {
2075 let mut m = user_group_memberships.get(member).cloned().unwrap_or_default();
2076 m.insert(group.to_string());
2077 cache.add_or_update_user_group_membership(member, &m, now);
2078 }
2079 }
2080
2081 fn remove_user_from_cached_groups(&self, cache: &mut LockedCache, user: &str, now: OffsetDateTime) {
2082 let member_of = cache.state().user_group_memberships.get(user).cloned().unwrap_or_default();
2083 for group in member_of.iter() {
2084 if let Some(group_info) = cache.state().groups.get(group).cloned() {
2085 let mut group_info = group_info;
2086 group_info.members.retain(|member| member != user);
2087 cache.add_or_update_group(group, &group_info, now);
2088 }
2089 }
2090 cache.delete_user_group_membership(user, now);
2091 }
2092
2093 pub async fn group_notification_handler(&self, group: &str) -> Result<()> {
2094 let mut m = HashMap::new();
2095 if let Err(err) = self.api.load_group_no_lock(group, &mut m).await {
2096 if !is_err_no_such_group(&err) {
2097 return Err(err);
2098 }
2099
2100 self.cache.with_write_lock(|cache| {
2101 let now = OffsetDateTime::now_utc();
2102 self.remove_group_from_memberships_map_unlocked(cache, group, now);
2103 cache.delete_group(group, now);
2104 cache.delete_group_policy(group, now);
2105 });
2106
2107 return Ok(());
2108 }
2109
2110 let gi = m[group].clone();
2111
2112 self.cache.with_write_lock(|cache| {
2113 let now = OffsetDateTime::now_utc();
2114 cache.add_or_update_group(group, &gi, now);
2115 self.remove_group_from_memberships_map_unlocked(cache, group, now);
2116 self.update_group_memberships_map_unlocked(cache, group, &gi, now);
2117 });
2118
2119 Ok(())
2120 }
2121
2122 pub async fn policy_notification_handler(&self, policy: &str) -> Result<()> {
2123 let mut m = HashMap::new();
2124 if let Err(err) = self.api.load_policy_doc_no_lock(policy, &mut m).await {
2125 if !is_err_no_such_policy(&err) {
2126 return Err(err);
2127 }
2128
2129 self.cache.with_write_lock(|cache| {
2130 let now = OffsetDateTime::now_utc();
2131 cache.delete_policy_doc(policy, now);
2132
2133 let user_policy_cache = Arc::clone(&cache.state().user_policies);
2134 let users_cache = Arc::clone(&cache.state().users);
2135 for (k, v) in user_policy_cache.iter() {
2136 let mut set = v.policy_set();
2137 if set.contains(policy) {
2138 if !users_cache.contains_key(k) {
2139 cache.delete_user_policy(k, now);
2140 continue;
2141 }
2142
2143 set.remove(policy);
2144
2145 let mp = MappedPolicy::new(&set.iter().cloned().collect::<Vec<_>>().join(","));
2146
2147 cache.add_or_update_user_policy(k, &mp, now);
2148 }
2149 }
2150
2151 let group_policy_cache = Arc::clone(&cache.state().group_policies);
2152 for (k, v) in group_policy_cache.iter() {
2153 let mut set = v.policy_set();
2154 if set.contains(policy) {
2155 set.remove(policy);
2156
2157 let mp = MappedPolicy::new(&set.iter().cloned().collect::<Vec<_>>().join(","));
2158 cache.add_or_update_group_policy(k, &mp, now);
2159 }
2160 }
2161 });
2162
2163 return Ok(());
2164 }
2165
2166 self.cache.with_write_lock(|cache| {
2167 cache.add_or_update_policy_doc(policy, &m[policy], OffsetDateTime::now_utc());
2168 });
2169
2170 Ok(())
2171 }
2172
2173 pub async fn policy_mapping_notification_handler(&self, name: &str, user_type: UserType, is_group: bool) -> Result<()> {
2174 let mut m = HashMap::new();
2175 if let Err(err) = self.api.load_mapped_policy_no_lock(name, user_type, is_group, &mut m).await {
2176 if !is_err_no_such_policy(&err) {
2177 return Err(err);
2178 }
2179
2180 self.cache.with_write_lock(|cache| {
2181 let now = OffsetDateTime::now_utc();
2182 if is_group {
2183 cache.delete_group_policy(name, now);
2184 } else if user_type == UserType::Sts {
2185 cache.delete_sts_policy(name, now);
2186 } else {
2187 cache.delete_user_policy(name, now);
2188 }
2189 });
2190
2191 return Ok(());
2192 }
2193
2194 let mp = m[name].clone();
2195
2196 self.cache.with_write_lock(|cache| {
2197 let now = OffsetDateTime::now_utc();
2198 if is_group {
2199 cache.add_or_update_group_policy(name, &mp, now);
2200 } else if user_type == UserType::Sts {
2201 cache.add_or_update_sts_policy(name, &mp, now);
2202 } else {
2203 cache.add_or_update_user_policy(name, &mp, now);
2204 }
2205 });
2206
2207 Ok(())
2208 }
2209 pub async fn user_notification_handler(&self, name: &str, user_type: UserType) -> Result<()> {
2210 let sts_mutation_lock = (user_type == UserType::Sts).then(|| self.cache.sts_account_mutation_lock(name));
2211 let _sts_mutation_guard = match &sts_mutation_lock {
2212 Some(lock) => Some(lock.lock().await),
2213 None => None,
2214 };
2215 let _service_account_guard = if user_type == UserType::Svc {
2216 Some(self.cache.service_account_mutation_lock().lock().await)
2217 } else {
2218 None
2219 };
2220 let mut m = HashMap::new();
2221 if let Err(err) = self.api.load_user_no_lock(name, user_type, &mut m).await {
2222 if !is_err_no_such_user(&err) {
2223 return Err(err);
2224 }
2225
2226 let mut service_accounts_to_delete = Vec::new();
2227 let mut temp_accounts_to_delete = HashSet::new();
2228 if user_type == UserType::Reg {
2229 let cache = self.cache.snapshot();
2230 for v in cache.users.values() {
2231 let u = &v.credentials;
2232 if u.parent_user.as_str() == name && u.is_service_account() {
2233 service_accounts_to_delete.push(u.access_key.clone());
2234 }
2235 }
2236
2237 for u in cache.sts_accounts.values() {
2238 let u = &u.credentials;
2239 if u.parent_user.as_str() == name {
2240 temp_accounts_to_delete.insert(u.access_key.clone());
2241 }
2242 }
2243 drop(cache);
2244
2245 for access_key in service_accounts_to_delete.iter() {
2246 let _ = self.api.delete_user_identity(access_key, UserType::Svc).await;
2247 }
2248 for access_key in temp_accounts_to_delete.iter() {
2249 let _ = self.api.delete_user_identity(access_key, UserType::Sts).await;
2250 }
2251 }
2252
2253 self.cache.with_write_lock(|cache| {
2254 let now = OffsetDateTime::now_utc();
2255 match user_type {
2256 UserType::Sts => cache.delete_sts_account(name, now),
2257 UserType::Reg | UserType::Svc => cache.delete_user(name, now),
2258 UserType::None => {}
2259 }
2260 if user_type != UserType::Sts {
2261 self.remove_user_from_cached_groups(cache, name, now);
2262 }
2263 if user_type == UserType::Reg {
2264 for access_key in service_accounts_to_delete.iter() {
2265 cache.delete_user(access_key, now);
2266 }
2267 for access_key in temp_accounts_to_delete.iter() {
2268 cache.delete_sts_account(access_key, now);
2269 cache.delete_user(access_key, now);
2270 }
2271 }
2272 if user_type != UserType::Sts {
2273 cache.delete_user_policy(name, now);
2274 }
2275 });
2276
2277 return Ok(());
2278 }
2279
2280 let u = m[name].clone();
2281 let mut user_policy_update = None;
2282 let mut sts_policy_update = None;
2283
2284 match user_type {
2285 UserType::Sts => {
2286 let parent_user = u.credentials.parent_user.clone();
2287 let mut policies = HashMap::new();
2288 if let Err(err) = self
2289 .api
2290 .load_mapped_policy_no_lock(&parent_user, user_type, false, &mut policies)
2291 .await
2292 {
2293 if !is_err_no_such_policy(&err) {
2294 return Err(err);
2295 }
2296 } else if let Some(policy) = policies.get(&parent_user).cloned() {
2297 sts_policy_update = Some((parent_user, policy));
2298 }
2299 }
2300 UserType::Reg => {
2301 let mut policies = HashMap::new();
2302 if let Err(err) = self
2303 .api
2304 .load_mapped_policy_no_lock(name, user_type, false, &mut policies)
2305 .await
2306 {
2307 if !is_err_no_such_policy(&err) {
2308 return Err(err);
2309 }
2310 } else if let Some(policy) = policies.get(name).cloned() {
2311 user_policy_update = Some((name.to_string(), policy));
2312 }
2313 }
2314
2315 UserType::Svc => {
2316 let parent_user = u.credentials.parent_user.clone();
2317 let cache = self.cache.snapshot();
2318 let parent_user_type = if cache.users.contains_key(&parent_user) {
2319 UserType::Reg
2320 } else {
2321 UserType::Sts
2322 };
2323 drop(cache);
2324
2325 if parent_user_type == UserType::Reg {
2326 let mut policies = HashMap::new();
2327 if let Err(err) = self
2328 .api
2329 .load_mapped_policy_no_lock(&parent_user, UserType::Reg, false, &mut policies)
2330 .await
2331 {
2332 if !is_err_no_such_policy(&err) {
2333 return Err(err);
2334 }
2335 } else if let Some(policy) = policies.get(&parent_user).cloned() {
2336 user_policy_update = Some((parent_user, policy));
2337 }
2338 } else {
2339 let mut policies = HashMap::new();
2340 if let Err(err) = self
2341 .api
2342 .load_mapped_policy_no_lock(&parent_user, UserType::Sts, false, &mut policies)
2343 .await
2344 {
2345 if !is_err_no_such_policy(&err) {
2346 return Err(err);
2347 }
2348 } else if let Some(policy) = policies.get(&parent_user).cloned() {
2349 sts_policy_update = Some((parent_user, policy));
2350 }
2351 }
2352 }
2353 UserType::None => {}
2354 }
2355
2356 self.cache.with_write_lock(|cache| {
2357 let now = OffsetDateTime::now_utc();
2358 match user_type {
2359 UserType::Sts => {
2360 cache.add_or_update_sts_account(name, &u, now);
2361 }
2362 UserType::Reg | UserType::Svc => {
2363 cache.add_or_update_user(name, &u, now);
2364 }
2365 UserType::None => {}
2366 }
2367
2368 if let Some((name, policy)) = &user_policy_update {
2369 cache.add_or_update_user_policy(name, policy, now);
2370 }
2371 if let Some((name, policy)) = &sts_policy_update {
2372 cache.add_or_update_sts_policy(name, policy, now);
2373 }
2374 });
2375
2376 Ok(())
2377 }
2378}
2379
2380pub(crate) fn account_status_flag(status: &str) -> &'static str {
2384 match status {
2385 val if val == AccountStatus::Enabled.as_ref() => auth::ACCOUNT_ON,
2386 val if val == AccountStatus::Disabled.as_ref() => auth::ACCOUNT_OFF,
2387 auth::ACCOUNT_ON => auth::ACCOUNT_ON,
2388 auth::ACCOUNT_OFF => auth::ACCOUNT_OFF,
2389 _ => auth::ACCOUNT_OFF,
2390 }
2391}
2392
2393pub fn get_default_policies() -> HashMap<String, PolicyDoc> {
2394 let default_policies = &DEFAULT_POLICIES;
2395 default_policies
2396 .iter()
2397 .map(|(n, p)| {
2398 (
2399 n.to_string(),
2400 PolicyDoc {
2401 version: 1,
2402 policy: p.clone(),
2403 ..Default::default()
2404 },
2405 )
2406 })
2407 .collect()
2408}
2409
2410#[deprecated(
2412 since = "1.0.0",
2413 note = "use get_default_policies instead; this alias will be removed in the next breaking release"
2414)]
2415pub fn get_default_policyes() -> HashMap<String, PolicyDoc> {
2416 get_default_policies()
2417}
2418
2419fn set_default_canned_policies(policies: &mut HashMap<String, PolicyDoc>) {
2420 let default_policies = &DEFAULT_POLICIES;
2421 for (k, v) in default_policies.iter() {
2422 let name = k.to_string();
2423 policies.entry(name).or_insert_with(|| PolicyDoc::default_policy(v.clone()));
2424 }
2425}
2426
2427pub fn get_token_signing_key() -> Option<String> {
2428 crate::root_credentials::token_signing_key()
2429}
2430
2431pub fn extract_jwt_claims(u: &UserIdentity) -> Result<HashMap<String, Value>> {
2432 let Some(sys_key) = get_token_signing_key() else {
2433 return Err(Error::other("global active sk not init"));
2434 };
2435
2436 let keys = vec![&sys_key, &u.credentials.secret_key];
2437
2438 for key in keys {
2439 if let Ok(claims) = get_claims_from_token_with_secret(&u.credentials.session_token, key) {
2440 return Ok(claims);
2441 }
2442 }
2443 Err(Error::other("unable to extract claims"))
2444}
2445
2446pub fn extract_jwt_claims_allow_missing_exp(u: &UserIdentity) -> Result<HashMap<String, Value>> {
2447 let Some(sys_key) = get_token_signing_key() else {
2448 return Err(Error::other("global active sk not init"));
2449 };
2450
2451 let keys = vec![&sys_key, &u.credentials.secret_key];
2452
2453 for key in keys {
2454 if let Ok(claims) = get_claims_from_token_with_secret_allow_missing_exp(&u.credentials.session_token, key) {
2455 return Ok(claims);
2456 }
2457 }
2458 Err(Error::other("unable to extract claims"))
2459}
2460
2461fn filter_policies(cache: &Cache, policy_name: &str, bucket_name: &str) -> (String, Policy) {
2462 let cache = cache.snapshot();
2463 filter_policies_from_docs(cache.policy_docs.as_ref(), policy_name, bucket_name)
2464}
2465
2466fn filter_policies_from_docs(policy_docs: &CacheEntity<PolicyDoc>, policy_name: &str, bucket_name: &str) -> (String, Policy) {
2467 let mp = MappedPolicy::new(policy_name).to_slice();
2468
2469 let mut policies = Vec::new();
2470 let mut to_merge = Vec::new();
2471 for policy in mp {
2472 if policy.is_empty() {
2473 continue;
2474 }
2475
2476 if let Some(p) = policy_docs.get(&policy)
2477 && (bucket_name.is_empty() || pollster::block_on(p.policy.match_resource(bucket_name)))
2478 {
2479 policies.push(policy);
2480 to_merge.push(p.policy.clone());
2481 }
2482 }
2483
2484 (policies.join(","), Policy::merge_policies(to_merge))
2485}
2486
2487fn build_group_desc(name: &str, group_info: GroupInfo, mapped_policy: Option<MappedPolicy>) -> GroupDesc {
2488 let (policy, updated_at) = mapped_policy
2493 .map(|policy| (policy.policies, Some(policy.update_at)))
2494 .unwrap_or_else(|| (String::new(), group_info.update_at));
2495
2496 GroupDesc {
2497 name: name.to_string(),
2498 policy,
2499 members: group_info.members,
2500 updated_at,
2501 status: group_info.status,
2502 }
2503}
2504
2505#[cfg(test)]
2506mod tests {
2507 use super::*;
2508 use rustfs_policy::policy::{Policy, PolicyDoc};
2509 use serde_json::json;
2510 use std::{
2511 collections::HashMap,
2512 sync::{
2513 Arc, Mutex,
2514 atomic::{AtomicBool, AtomicUsize, Ordering},
2515 },
2516 };
2517 use tokio::sync::Notify;
2518
2519 #[test]
2520 fn test_build_group_desc_without_mapping_reports_the_stored_group_timestamp() {
2521 let stamp = OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("valid timestamp");
2522 let group_info = GroupInfo {
2523 version: 1,
2524 status: "enabled".to_string(),
2525 members: vec!["alice".to_string()],
2526 update_at: Some(stamp),
2527 };
2528
2529 let first = build_group_desc("team", group_info.clone(), None);
2530 let second = build_group_desc("team", group_info, None);
2531
2532 assert_eq!(first.updated_at, Some(stamp));
2533 assert_eq!(first.updated_at, second.updated_at);
2534 assert!(first.policy.is_empty());
2535 }
2536
2537 #[test]
2538 fn test_build_group_desc_with_mapping_reports_the_mapping_timestamp() {
2539 let group_stamp = OffsetDateTime::from_unix_timestamp(1_700_000_000).expect("valid timestamp");
2540 let mapping_stamp = OffsetDateTime::from_unix_timestamp(1_700_000_500).expect("valid timestamp");
2541 let group_info = GroupInfo {
2542 version: 1,
2543 status: "enabled".to_string(),
2544 members: vec![],
2545 update_at: Some(group_stamp),
2546 };
2547 let mapping = MappedPolicy {
2548 version: 1,
2549 policies: "readwrite".to_string(),
2550 update_at: mapping_stamp,
2551 };
2552
2553 let desc = build_group_desc("team", group_info, Some(mapping));
2554
2555 assert_eq!(desc.updated_at, Some(mapping_stamp));
2556 assert_eq!(desc.policy, "readwrite");
2557 }
2558
2559 #[derive(Clone)]
2560 struct FailingInitialLoadStore;
2561
2562 #[async_trait::async_trait]
2563 impl Store for FailingInitialLoadStore {
2564 fn has_watcher(&self) -> bool {
2565 false
2566 }
2567
2568 async fn save_iam_config<Item: Serialize + Send>(&self, _item: Item, _path: impl AsRef<str> + Send) -> Result<()> {
2569 Ok(())
2570 }
2571
2572 async fn load_iam_config<Item: serde::de::DeserializeOwned>(&self, _path: impl AsRef<str> + Send) -> Result<Item> {
2573 Err(Error::ConfigNotFound)
2574 }
2575
2576 async fn delete_iam_config(&self, _path: impl AsRef<str> + Send) -> Result<()> {
2577 Err(Error::InvalidArgument)
2578 }
2579
2580 async fn save_user_identity(
2581 &self,
2582 _name: &str,
2583 _user_type: UserType,
2584 _item: UserIdentity,
2585 _ttl: Option<usize>,
2586 ) -> Result<()> {
2587 Err(Error::InvalidArgument)
2588 }
2589
2590 async fn delete_user_identity(&self, _name: &str, _user_type: UserType) -> Result<()> {
2591 Err(Error::InvalidArgument)
2592 }
2593
2594 async fn load_user_identity(&self, _name: &str, _user_type: UserType) -> Result<UserIdentity> {
2595 Err(Error::InvalidArgument)
2596 }
2597
2598 async fn load_user(&self, _name: &str, _user_type: UserType, _m: &mut HashMap<String, UserIdentity>) -> Result<()> {
2599 Err(Error::InvalidArgument)
2600 }
2601
2602 async fn load_users(&self, _user_type: UserType, _m: &mut HashMap<String, UserIdentity>) -> Result<()> {
2603 Err(Error::InvalidArgument)
2604 }
2605
2606 async fn load_secret_key(&self, _name: &str, _user_type: UserType) -> Result<String> {
2607 Err(Error::InvalidArgument)
2608 }
2609
2610 async fn save_group_info(&self, _name: &str, _item: GroupInfo) -> Result<()> {
2611 Err(Error::InvalidArgument)
2612 }
2613
2614 async fn delete_group_info(&self, _name: &str) -> Result<()> {
2615 Err(Error::InvalidArgument)
2616 }
2617
2618 async fn load_group(&self, _name: &str, _m: &mut HashMap<String, GroupInfo>) -> Result<()> {
2619 Err(Error::InvalidArgument)
2620 }
2621
2622 async fn load_groups(&self, _m: &mut HashMap<String, GroupInfo>) -> Result<()> {
2623 Err(Error::InvalidArgument)
2624 }
2625
2626 async fn save_policy_doc(&self, _name: &str, _item: PolicyDoc) -> Result<()> {
2627 Err(Error::InvalidArgument)
2628 }
2629
2630 async fn delete_policy_doc(&self, _name: &str) -> Result<()> {
2631 Err(Error::InvalidArgument)
2632 }
2633
2634 async fn load_policy(&self, _name: &str) -> Result<PolicyDoc> {
2635 Err(Error::InvalidArgument)
2636 }
2637
2638 async fn load_policy_doc(&self, _name: &str, _m: &mut HashMap<String, PolicyDoc>) -> Result<()> {
2639 Err(Error::InvalidArgument)
2640 }
2641
2642 async fn load_policy_docs(&self, _m: &mut HashMap<String, PolicyDoc>) -> Result<()> {
2643 Err(Error::InvalidArgument)
2644 }
2645
2646 async fn save_mapped_policy(
2647 &self,
2648 _name: &str,
2649 _user_type: UserType,
2650 _is_group: bool,
2651 _item: MappedPolicy,
2652 _ttl: Option<usize>,
2653 ) -> Result<()> {
2654 Err(Error::InvalidArgument)
2655 }
2656
2657 async fn delete_mapped_policy(&self, _name: &str, _user_type: UserType, _is_group: bool) -> Result<()> {
2658 Err(Error::InvalidArgument)
2659 }
2660
2661 async fn load_mapped_policy(
2662 &self,
2663 _name: &str,
2664 _user_type: UserType,
2665 _is_group: bool,
2666 _m: &mut HashMap<String, MappedPolicy>,
2667 ) -> Result<()> {
2668 Err(Error::InvalidArgument)
2669 }
2670
2671 async fn load_mapped_policies(
2672 &self,
2673 _user_type: UserType,
2674 _is_group: bool,
2675 _m: &mut HashMap<String, MappedPolicy>,
2676 ) -> Result<()> {
2677 Err(Error::InvalidArgument)
2678 }
2679
2680 async fn load_all(&self, _cache: &Cache) -> Result<()> {
2681 Err(Error::Io(std::io::Error::other("initial load failed")))
2682 }
2683 }
2684
2685 #[derive(Clone)]
2686 struct DelayedTempUserVisibilityStore {
2687 saved_user: Arc<Mutex<Option<UserIdentity>>>,
2688 load_attempts: Arc<AtomicUsize>,
2689 visible_after_attempt: usize,
2690 block_account_save: Arc<AtomicBool>,
2691 account_save_started: Arc<Notify>,
2692 release_account_save: Arc<Notify>,
2693 block_account_load: Arc<AtomicBool>,
2694 account_load_started: Arc<Notify>,
2695 release_account_load: Arc<Notify>,
2696 }
2697
2698 impl DelayedTempUserVisibilityStore {
2699 fn new(visible_after_attempt: usize) -> Self {
2700 Self {
2701 saved_user: Arc::new(Mutex::new(None)),
2702 load_attempts: Arc::new(AtomicUsize::new(0)),
2703 visible_after_attempt,
2704 block_account_save: Arc::new(AtomicBool::new(false)),
2705 account_save_started: Arc::new(Notify::new()),
2706 release_account_save: Arc::new(Notify::new()),
2707 block_account_load: Arc::new(AtomicBool::new(false)),
2708 account_load_started: Arc::new(Notify::new()),
2709 release_account_load: Arc::new(Notify::new()),
2710 }
2711 }
2712 }
2713
2714 #[async_trait::async_trait]
2715 impl Store for DelayedTempUserVisibilityStore {
2716 fn has_watcher(&self) -> bool {
2717 false
2718 }
2719
2720 async fn save_iam_config<Item: Serialize + Send>(&self, _item: Item, _path: impl AsRef<str> + Send) -> Result<()> {
2721 Ok(())
2722 }
2723
2724 async fn load_iam_config<Item: serde::de::DeserializeOwned>(&self, _path: impl AsRef<str> + Send) -> Result<Item> {
2725 Err(Error::ConfigNotFound)
2726 }
2727
2728 async fn delete_iam_config(&self, _path: impl AsRef<str> + Send) -> Result<()> {
2729 Err(Error::InvalidArgument)
2730 }
2731
2732 async fn save_user_identity(
2733 &self,
2734 _name: &str,
2735 user_type: UserType,
2736 item: UserIdentity,
2737 _ttl: Option<usize>,
2738 ) -> Result<()> {
2739 if matches!(user_type, UserType::Svc | UserType::Sts) && self.block_account_save.load(Ordering::SeqCst) {
2740 self.account_save_started.notify_one();
2741 self.release_account_save.notified().await;
2742 }
2743 *self.saved_user.lock().expect("saved_user mutex poisoned") = Some(item);
2744 Ok(())
2745 }
2746
2747 async fn delete_user_identity(&self, _name: &str, _user_type: UserType) -> Result<()> {
2748 *self.saved_user.lock().expect("saved_user mutex poisoned") = None;
2749 Ok(())
2750 }
2751
2752 async fn load_user_identity(&self, name: &str, _user_type: UserType) -> Result<UserIdentity> {
2753 let attempt = self.load_attempts.fetch_add(1, Ordering::SeqCst) + 1;
2754 if attempt <= self.visible_after_attempt {
2755 return Err(Error::NoSuchUser(name.to_string()));
2756 }
2757
2758 self.saved_user
2759 .lock()
2760 .expect("saved_user mutex poisoned")
2761 .clone()
2762 .ok_or_else(|| Error::NoSuchUser(name.to_string()))
2763 }
2764
2765 async fn load_user(&self, name: &str, user_type: UserType, m: &mut HashMap<String, UserIdentity>) -> Result<()> {
2766 let loaded = self
2767 .saved_user
2768 .lock()
2769 .expect("saved_user mutex poisoned")
2770 .clone()
2771 .ok_or_else(|| Error::NoSuchUser(name.to_string()))?;
2772 let matches_user_type = match user_type {
2773 UserType::Sts => loaded.credentials.is_temp(),
2774 UserType::Svc => loaded.credentials.is_service_account(),
2775 UserType::Reg => !loaded.credentials.is_temp() && !loaded.credentials.is_service_account(),
2776 UserType::None => false,
2777 };
2778 if !matches_user_type {
2779 return Err(Error::NoSuchUser(name.to_string()));
2780 }
2781 if self.block_account_load.load(Ordering::SeqCst) {
2782 self.account_load_started.notify_one();
2783 self.release_account_load.notified().await;
2784 }
2785 m.insert(name.to_string(), loaded);
2786 Ok(())
2787 }
2788
2789 async fn load_users(&self, _user_type: UserType, _m: &mut HashMap<String, UserIdentity>) -> Result<()> {
2790 Err(Error::InvalidArgument)
2791 }
2792
2793 async fn load_secret_key(&self, _name: &str, _user_type: UserType) -> Result<String> {
2794 Err(Error::InvalidArgument)
2795 }
2796
2797 async fn save_group_info(&self, _name: &str, _item: GroupInfo) -> Result<()> {
2798 Err(Error::InvalidArgument)
2799 }
2800
2801 async fn delete_group_info(&self, _name: &str) -> Result<()> {
2802 Err(Error::InvalidArgument)
2803 }
2804
2805 async fn load_group(&self, _name: &str, _m: &mut HashMap<String, GroupInfo>) -> Result<()> {
2806 Err(Error::InvalidArgument)
2807 }
2808
2809 async fn load_groups(&self, _m: &mut HashMap<String, GroupInfo>) -> Result<()> {
2810 Err(Error::InvalidArgument)
2811 }
2812
2813 async fn save_policy_doc(&self, _name: &str, _item: PolicyDoc) -> Result<()> {
2814 Err(Error::InvalidArgument)
2815 }
2816
2817 async fn delete_policy_doc(&self, _name: &str) -> Result<()> {
2818 Err(Error::InvalidArgument)
2819 }
2820
2821 async fn load_policy(&self, _name: &str) -> Result<PolicyDoc> {
2822 Err(Error::InvalidArgument)
2823 }
2824
2825 async fn load_policy_doc(&self, _name: &str, _m: &mut HashMap<String, PolicyDoc>) -> Result<()> {
2826 Err(Error::InvalidArgument)
2827 }
2828
2829 async fn load_policy_docs(&self, _m: &mut HashMap<String, PolicyDoc>) -> Result<()> {
2830 Err(Error::InvalidArgument)
2831 }
2832
2833 async fn save_mapped_policy(
2834 &self,
2835 _name: &str,
2836 _user_type: UserType,
2837 _is_group: bool,
2838 _item: MappedPolicy,
2839 _ttl: Option<usize>,
2840 ) -> Result<()> {
2841 Ok(())
2842 }
2843
2844 async fn delete_mapped_policy(&self, _name: &str, _user_type: UserType, _is_group: bool) -> Result<()> {
2845 Err(Error::InvalidArgument)
2846 }
2847
2848 async fn load_mapped_policy(
2849 &self,
2850 _name: &str,
2851 _user_type: UserType,
2852 _is_group: bool,
2853 _m: &mut HashMap<String, MappedPolicy>,
2854 ) -> Result<()> {
2855 Err(Error::NoSuchPolicy)
2856 }
2857
2858 async fn load_mapped_policies(
2859 &self,
2860 _user_type: UserType,
2861 _is_group: bool,
2862 _m: &mut HashMap<String, MappedPolicy>,
2863 ) -> Result<()> {
2864 Err(Error::InvalidArgument)
2865 }
2866
2867 async fn load_all(&self, _cache: &Cache) -> Result<()> {
2868 Ok(())
2869 }
2870 }
2871
2872 fn build_test_temp_credentials() -> Credentials {
2873 Credentials {
2874 access_key: "STSACCESS123".to_string(),
2875 secret_key: "test-secret-key".to_string(),
2876 session_token: "test-session-token".to_string(),
2877 expiration: Some(OffsetDateTime::now_utc() + time::Duration::hours(1)),
2878 status: STATUS_ENABLED.to_string(),
2879 parent_user: "parent-user".to_string(),
2880 groups: Some(vec!["console-admins".to_string()]),
2881 claims: None,
2882 name: None,
2883 description: None,
2884 }
2885 }
2886
2887 fn build_test_iam_cache<T: Store>(api: T) -> IamCache<T> {
2888 let (sender, _receiver) = mpsc::channel::<i64>(1);
2889 IamCache {
2890 cache: Cache::default(),
2891 api,
2892 state: Arc::new(AtomicU8::new(IamState::Ready as u8)),
2893 loading: Arc::new(AtomicBool::new(false)),
2894 roles: HashMap::new(),
2895 send_chan: sender,
2896 last_timestamp: AtomicI64::new(0),
2897 sync_failures: AtomicU64::new(0),
2898 sync_successes: AtomicU64::new(0),
2899 last_sync_duration_millis: AtomicU64::new(0),
2900 }
2901 }
2902
2903 #[tokio::test]
2904 async fn sts_policy_lookup_ignores_colliding_regular_user_mapping() {
2905 let iam = build_test_iam_cache(FailingInitialLoadStore);
2906 let parent = "TwyekekG2eMes0qk9Tgh7KXEitwGi1z2W1f2KccrXGA";
2907 let user = UserIdentity::new(Credentials {
2908 access_key: parent.to_string(),
2909 secret_key: "regular-user-secret".to_string(),
2910 status: STATUS_ENABLED.to_string(),
2911 ..Default::default()
2912 });
2913 let now = OffsetDateTime::now_utc();
2914 iam.cache.add_or_update_user(parent, &user, now);
2915 iam.cache
2916 .add_or_update_user_policy(parent, &MappedPolicy::new("regular-policy"), now);
2917 iam.cache
2918 .add_or_update_sts_policy(parent, &MappedPolicy::new("oidc-policy"), now);
2919
2920 assert_eq!(
2921 iam.policy_db_get(parent, &None).await.expect("regular lookup should succeed"),
2922 vec!["regular-policy"]
2923 );
2924 assert_eq!(
2925 iam.sts_policy_db_get(parent, &None).await.expect("STS lookup should succeed"),
2926 vec!["oidc-policy"]
2927 );
2928 }
2929
2930 #[tokio::test]
2931 async fn set_temp_user_retries_until_sts_identity_becomes_visible() {
2932 let store = DelayedTempUserVisibilityStore::new(2);
2933 let cache = build_test_iam_cache(store.clone());
2934 let cred = build_test_temp_credentials();
2935
2936 let updated_at = cache
2937 .set_temp_user(&cred.access_key, &cred, None)
2938 .await
2939 .expect("temp user should succeed once persistence becomes visible");
2940
2941 assert!(updated_at <= OffsetDateTime::now_utc());
2942 assert_eq!(store.load_attempts.load(Ordering::SeqCst), 3);
2943
2944 let snapshot = cache.cache.snapshot();
2945 let sts_identity = snapshot
2946 .sts_accounts
2947 .get(&cred.access_key)
2948 .expect("verified temp user should be cached");
2949 assert_eq!(sts_identity.credentials.parent_user, cred.parent_user);
2950 }
2951
2952 #[tokio::test]
2953 async fn set_temp_user_fails_when_sts_identity_never_becomes_visible() {
2954 let store = DelayedTempUserVisibilityStore::new(TEMP_USER_PERSISTENCE_VERIFY_MAX_RETRIES + 1);
2955 let cache = build_test_iam_cache(store.clone());
2956 let cred = build_test_temp_credentials();
2957
2958 let err = cache
2959 .set_temp_user(&cred.access_key, &cred, None)
2960 .await
2961 .expect_err("temp user should fail when persistence never becomes visible");
2962
2963 assert!(matches!(err, Error::NoSuchUser(user) if user == cred.access_key));
2964 assert_eq!(store.load_attempts.load(Ordering::SeqCst), TEMP_USER_PERSISTENCE_VERIFY_MAX_RETRIES + 1);
2965
2966 let snapshot = cache.cache.snapshot();
2967 assert!(
2968 !snapshot.sts_accounts.contains_key(&cred.access_key),
2969 "cache must not publish a temp user that was not durably visible"
2970 );
2971 }
2972
2973 #[tokio::test]
2974 async fn service_account_notification_cannot_overwrite_concurrent_update() {
2975 let _ = rustfs_credentials::init_global_action_credentials(
2976 Some("TESTROOTACCESSKEY".to_string()),
2977 Some("TESTROOTSECRET123".to_string()),
2978 );
2979 let store = DelayedTempUserVisibilityStore::new(0);
2980 let cache = Arc::new(build_test_iam_cache(store.clone()));
2981 let access_key = "SERIALIZEDSERVICE01";
2982 let secret_key = "serializedServiceSecret123";
2983 let metadata = HashMap::from([
2984 ("parent".to_string(), Value::String("parent-user".to_string())),
2985 (iam_policy_claim_name_sa(), Value::String(INHERITED_POLICY_TYPE.to_string())),
2986 ]);
2987 let credentials = Credentials {
2988 access_key: access_key.to_string(),
2989 secret_key: secret_key.to_string(),
2990 session_token: jwt_sign(&metadata, secret_key).expect("sign service account token"),
2991 status: auth::ACCOUNT_ON.to_string(),
2992 parent_user: "parent-user".to_string(),
2993 claims: Some(metadata),
2994 description: Some("old".to_string()),
2995 ..Default::default()
2996 };
2997 cache.add_service_account(credentials).await.expect("seed service account");
2998
2999 store.block_account_load.store(true, Ordering::SeqCst);
3000 let notification = {
3001 let cache = Arc::clone(&cache);
3002 tokio::spawn(async move { cache.user_notification_handler(access_key, UserType::Svc).await })
3003 };
3004 store.account_load_started.notified().await;
3005
3006 let update = {
3007 let cache = Arc::clone(&cache);
3008 tokio::spawn(async move {
3009 cache
3010 .update_service_account(
3011 access_key,
3012 UpdateServiceAccountOpts {
3013 session_policy: None,
3014 secret_key: None,
3015 name: None,
3016 description: Some("new".to_string()),
3017 expiration: None,
3018 status: None,
3019 parent_user: None,
3020 allow_site_replicator_account: false,
3021 },
3022 )
3023 .await
3024 })
3025 };
3026 tokio::task::yield_now().await;
3027 assert!(!update.is_finished(), "update must wait for the in-flight cache refresh");
3028
3029 store.release_account_load.notify_one();
3030 notification.await.expect("notification task").expect("notification refresh");
3031 update.await.expect("update task").expect("service account update");
3032
3033 let snapshot = cache.cache.snapshot();
3034 assert_eq!(
3035 snapshot
3036 .users
3037 .get(access_key)
3038 .and_then(|identity| identity.credentials.description.as_deref()),
3039 Some("new")
3040 );
3041 }
3042
3043 #[tokio::test]
3044 async fn concurrent_service_account_create_cannot_overwrite_first_writer() {
3045 let store = DelayedTempUserVisibilityStore::new(0);
3046 store.block_account_save.store(true, Ordering::SeqCst);
3047 let cache = Arc::new(build_test_iam_cache(store.clone()));
3048 let access_key = "SERIALIZEDSERVICE00";
3049 let credentials = |secret_key: &str| Credentials {
3050 access_key: access_key.to_string(),
3051 secret_key: secret_key.to_string(),
3052 status: auth::ACCOUNT_ON.to_string(),
3053 parent_user: "parent-user".to_string(),
3054 ..Default::default()
3055 };
3056
3057 let first = {
3058 let cache = Arc::clone(&cache);
3059 tokio::spawn(async move { cache.add_service_account(credentials("firstServiceSecret123")).await })
3060 };
3061 store.account_save_started.notified().await;
3062
3063 let second = {
3064 let cache = Arc::clone(&cache);
3065 tokio::spawn(async move { cache.add_service_account(credentials("secondServiceSecret234")).await })
3066 };
3067 tokio::task::yield_now().await;
3068 assert!(!second.is_finished(), "second create must wait for the first writer");
3069
3070 store.block_account_save.store(false, Ordering::SeqCst);
3071 store.release_account_save.notify_waiters();
3072 first.await.expect("first create task").expect("first create");
3073 let err = second
3074 .await
3075 .expect("second create task")
3076 .expect_err("duplicate create must fail");
3077
3078 assert_eq!(err, Error::AccessKeyAlreadyExists);
3079 assert_eq!(
3080 cache
3081 .cache
3082 .snapshot()
3083 .users
3084 .get(access_key)
3085 .map(|identity| identity.credentials.secret_key.as_str()),
3086 Some("firstServiceSecret123")
3087 );
3088 }
3089
3090 #[tokio::test]
3091 async fn service_account_notification_cannot_restore_concurrent_delete() {
3092 let _ = rustfs_credentials::init_global_action_credentials(
3093 Some("TESTROOTACCESSKEY".to_string()),
3094 Some("TESTROOTSECRET123".to_string()),
3095 );
3096 let store = DelayedTempUserVisibilityStore::new(0);
3097 let cache = Arc::new(build_test_iam_cache(store.clone()));
3098 let access_key = "SERIALIZEDSERVICE02";
3099 let secret_key = "serializedServiceSecret234";
3100 let metadata = HashMap::from([
3101 ("parent".to_string(), Value::String("parent-user".to_string())),
3102 (iam_policy_claim_name_sa(), Value::String(INHERITED_POLICY_TYPE.to_string())),
3103 ]);
3104 let credentials = Credentials {
3105 access_key: access_key.to_string(),
3106 secret_key: secret_key.to_string(),
3107 session_token: jwt_sign(&metadata, secret_key).expect("sign service account token"),
3108 status: auth::ACCOUNT_ON.to_string(),
3109 parent_user: "parent-user".to_string(),
3110 claims: Some(metadata),
3111 ..Default::default()
3112 };
3113 cache.add_service_account(credentials).await.expect("seed service account");
3114
3115 store.block_account_load.store(true, Ordering::SeqCst);
3116 let notification = {
3117 let cache = Arc::clone(&cache);
3118 tokio::spawn(async move { cache.user_notification_handler(access_key, UserType::Svc).await })
3119 };
3120 store.account_load_started.notified().await;
3121
3122 let delete = {
3123 let cache = Arc::clone(&cache);
3124 tokio::spawn(async move { cache.delete_service_account_with_revision(access_key).await })
3125 };
3126 tokio::task::yield_now().await;
3127 assert!(!delete.is_finished(), "delete must wait for the in-flight cache refresh");
3128
3129 store.release_account_load.notify_one();
3130 notification.await.expect("notification task").expect("notification refresh");
3131 delete.await.expect("delete task").expect("service account delete");
3132
3133 assert!(!cache.cache.snapshot().users.contains_key(access_key));
3134 assert!(store.saved_user.lock().expect("saved_user mutex poisoned").is_none());
3135 }
3136
3137 #[tokio::test]
3138 async fn sts_notification_cannot_restore_concurrent_delete() {
3139 let store = DelayedTempUserVisibilityStore::new(0);
3140 let cache = Arc::new(build_test_iam_cache(store.clone()));
3141 let credentials = build_test_temp_credentials();
3142 let access_key = credentials.access_key.clone();
3143 cache
3144 .set_temp_user(&access_key, &credentials, None)
3145 .await
3146 .expect("seed temporary account");
3147
3148 store.block_account_load.store(true, Ordering::SeqCst);
3149 let notification = {
3150 let cache = Arc::clone(&cache);
3151 let access_key = access_key.clone();
3152 tokio::spawn(async move { cache.user_notification_handler(&access_key, UserType::Sts).await })
3153 };
3154 store.account_load_started.notified().await;
3155
3156 let delete_started = Arc::new(Notify::new());
3157 let delete = {
3158 let cache = Arc::clone(&cache);
3159 let access_key = access_key.clone();
3160 let delete_started = Arc::clone(&delete_started);
3161 tokio::spawn(async move {
3162 delete_started.notify_one();
3163 cache.delete_user(&access_key, UserType::Sts).await
3164 })
3165 };
3166 delete_started.notified().await;
3167 tokio::task::yield_now().await;
3168 let delete_waited_for_notification = !delete.is_finished();
3169
3170 store.release_account_load.notify_one();
3171 notification.await.expect("notification task").expect("notification refresh");
3172 delete.await.expect("delete task").expect("temporary account delete");
3173
3174 assert!(delete_waited_for_notification, "delete must wait for the in-flight STS cache refresh");
3175 assert!(!cache.cache.snapshot().sts_accounts.contains_key(&access_key));
3176 assert!(store.saved_user.lock().expect("saved_user mutex poisoned").is_none());
3177 }
3178
3179 #[tokio::test]
3180 async fn sts_auth_reload_cannot_restore_concurrent_delete() {
3181 let store = DelayedTempUserVisibilityStore::new(0);
3182 let cache = Arc::new(build_test_iam_cache(store.clone()));
3183 let credentials = build_test_temp_credentials();
3184 let access_key = credentials.access_key.clone();
3185 cache
3186 .set_temp_user(&access_key, &credentials, None)
3187 .await
3188 .expect("seed temporary account");
3189 cache.cache.delete_sts_account(&access_key, OffsetDateTime::now_utc());
3190
3191 store.block_account_load.store(true, Ordering::SeqCst);
3192 let reload = {
3193 let cache = Arc::clone(&cache);
3194 let access_key = access_key.clone();
3195 tokio::spawn(async move { cache.load_user(&access_key).await })
3196 };
3197 store.account_load_started.notified().await;
3198
3199 let delete_started = Arc::new(Notify::new());
3200 let delete = {
3201 let cache = Arc::clone(&cache);
3202 let access_key = access_key.clone();
3203 let delete_started = Arc::clone(&delete_started);
3204 tokio::spawn(async move {
3205 delete_started.notify_one();
3206 cache.delete_user(&access_key, UserType::Sts).await
3207 })
3208 };
3209 delete_started.notified().await;
3210 tokio::task::yield_now().await;
3211 let delete_waited_for_reload = !delete.is_finished();
3212
3213 store.release_account_load.notify_one();
3214 reload.await.expect("reload task").expect("authentication cache reload");
3215 delete.await.expect("delete task").expect("temporary account delete");
3216
3217 assert!(delete_waited_for_reload, "delete must wait for the in-flight authentication reload");
3218 assert!(!cache.cache.snapshot().sts_accounts.contains_key(&access_key));
3219 assert!(store.saved_user.lock().expect("saved_user mutex poisoned").is_none());
3220 }
3221
3222 #[tokio::test]
3223 async fn sts_create_cannot_restore_concurrent_delete() {
3224 let store = DelayedTempUserVisibilityStore::new(0);
3225 store.block_account_save.store(true, Ordering::SeqCst);
3226 let cache = Arc::new(build_test_iam_cache(store.clone()));
3227 let credentials = build_test_temp_credentials();
3228 let access_key = credentials.access_key.clone();
3229
3230 let create = {
3231 let cache = Arc::clone(&cache);
3232 let access_key = access_key.clone();
3233 tokio::spawn(async move { cache.set_temp_user(&access_key, &credentials, None).await })
3234 };
3235 store.account_save_started.notified().await;
3236
3237 let delete_started = Arc::new(Notify::new());
3238 let delete = {
3239 let cache = Arc::clone(&cache);
3240 let access_key = access_key.clone();
3241 let delete_started = Arc::clone(&delete_started);
3242 tokio::spawn(async move {
3243 delete_started.notify_one();
3244 cache.delete_user(&access_key, UserType::Sts).await
3245 })
3246 };
3247 delete_started.notified().await;
3248 tokio::task::yield_now().await;
3249 let delete_waited_for_create = !delete.is_finished();
3250
3251 store.block_account_save.store(false, Ordering::SeqCst);
3252 store.release_account_save.notify_one();
3253 create.await.expect("create task").expect("temporary account create");
3254 delete.await.expect("delete task").expect("temporary account delete");
3255
3256 assert!(delete_waited_for_create, "delete must wait for the in-flight STS create");
3257 assert!(!cache.cache.snapshot().sts_accounts.contains_key(&access_key));
3258 assert!(store.saved_user.lock().expect("saved_user mutex poisoned").is_none());
3259 }
3260
3261 #[tokio::test]
3262 async fn test_init_keeps_error_state_when_initial_load_fails() {
3263 let (sender, receiver) = mpsc::channel::<i64>(1);
3264 let sys = Arc::new(IamCache {
3265 api: FailingInitialLoadStore,
3266 cache: Cache::default(),
3267 state: Arc::new(AtomicU8::new(IamState::Uninitialized as u8)),
3268 loading: Arc::new(AtomicBool::new(false)),
3269 send_chan: sender,
3270 roles: HashMap::new(),
3271 last_timestamp: AtomicI64::new(0),
3272 sync_failures: AtomicU64::new(0),
3273 sync_successes: AtomicU64::new(0),
3274 last_sync_duration_millis: AtomicU64::new(0),
3275 });
3276
3277 let result = Arc::clone(&sys).init(receiver).await;
3278
3279 assert!(matches!(result, Err(Error::Io(_))));
3280 assert!(!sys.is_ready());
3281 assert_eq!(sys.state.load(Ordering::SeqCst), IamState::Error as u8);
3282 assert_eq!(sys.sync_failures.load(Ordering::Relaxed), 3);
3283 }
3284
3285 #[test]
3286 fn test_get_iam_format_file_path() {
3287 let path = get_iam_format_file_path();
3288 assert!(path.contains(IAM_FORMAT_FILE));
3289 assert!(path.contains(&*IAM_CONFIG_PREFIX));
3290 assert_eq!(path, format!("{}/{}", *IAM_CONFIG_PREFIX, IAM_FORMAT_FILE));
3291 }
3292
3293 #[test]
3294 fn test_get_default_policies() {
3295 let policies = get_default_policies();
3296
3297 assert!(!policies.is_empty());
3299
3300 for (name, policy_doc) in &policies {
3302 assert!(!name.is_empty());
3303 assert!(policy_doc.version >= 0);
3305 }
3306 }
3307
3308 #[test]
3309 #[allow(deprecated)]
3310 fn deprecated_get_default_policyes_matches_current_api() {
3311 assert_eq!(get_default_policyes().len(), get_default_policies().len());
3312 }
3313
3314 #[test]
3315 fn test_get_token_signing_key() {
3316 let key = get_token_signing_key();
3319 if let Some(k) = key {
3321 assert!(!k.is_empty());
3322 } }
3324
3325 #[test]
3326 fn test_extract_jwt_claims_basic() {
3327 let user_identity = UserIdentity {
3328 version: 1,
3329 credentials: Credentials {
3330 access_key: "test-access-key".to_string(),
3331 secret_key: "test-secret-key".to_string(),
3332 session_token: "invalid-token".to_string(), expiration: None,
3334 status: "enabled".to_string(),
3335 parent_user: "".to_string(),
3336 groups: None,
3337 claims: Some({
3338 let mut claims = HashMap::new();
3339 claims.insert("sub".to_string(), json!("test-user"));
3340 claims.insert("aud".to_string(), json!("test-audience"));
3341 claims
3342 }),
3343 name: None,
3344 description: None,
3345 },
3346 update_at: Some(OffsetDateTime::now_utc()),
3347 };
3348
3349 let result = extract_jwt_claims(&user_identity);
3350 assert!(result.is_err());
3352 }
3353
3354 #[test]
3355 fn test_extract_jwt_claims_no_claims() {
3356 let user_identity = UserIdentity {
3357 version: 1,
3358 credentials: Credentials {
3359 access_key: "test-access-key".to_string(),
3360 secret_key: "test-secret-key".to_string(),
3361 session_token: "".to_string(), expiration: None,
3363 status: "enabled".to_string(),
3364 parent_user: "".to_string(),
3365 groups: None,
3366 claims: None,
3367 name: None,
3368 description: None,
3369 },
3370 update_at: Some(OffsetDateTime::now_utc()),
3371 };
3372
3373 let result = extract_jwt_claims(&user_identity);
3374 assert!(result.is_err());
3376 }
3377
3378 #[test]
3379 fn test_filter_policies_empty_bucket() {
3380 let cache = Cache::default();
3381 let policy_name = "test-policy";
3382 let bucket_name = "";
3383
3384 let (name, policy) = filter_policies(&cache, policy_name, bucket_name);
3385
3386 assert_eq!(name, "");
3388 assert!(policy.statements.is_empty());
3389 }
3390
3391 #[test]
3392 fn test_filter_policies_with_bucket() {
3393 let cache = Cache::default();
3394 let policy_name = "test-policy";
3395 let bucket_name = "test-bucket";
3396
3397 let (name, policy) = filter_policies(&cache, policy_name, bucket_name);
3398
3399 assert_eq!(name, "");
3401 assert!(policy.statements.is_empty());
3402 }
3403
3404 #[test]
3405 fn test_mapped_policy_operations() {
3406 let policy_name = "test-policy";
3407 let mapped_policy = MappedPolicy::new(policy_name);
3408
3409 let policies = mapped_policy.to_slice();
3411 assert!(!policies.is_empty());
3412 assert!(policies.iter().any(|p| p.contains(policy_name)));
3413 }
3414
3415 #[test]
3416 fn test_user_identity_structure() {
3417 let credentials = Credentials {
3418 access_key: "AKIAIOSFODNN7EXAMPLE".to_string(),
3419 secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_string(),
3420 session_token: "".to_string(),
3421 expiration: None,
3422 status: "enabled".to_string(),
3423 parent_user: "parent-user".to_string(),
3424 groups: Some(vec!["group1".to_string(), "group2".to_string()]),
3425 claims: None,
3426 name: None,
3427 description: None,
3428 };
3429
3430 let user_identity = UserIdentity {
3431 version: 1,
3432 credentials,
3433 update_at: Some(OffsetDateTime::now_utc()),
3434 };
3435
3436 assert_eq!(user_identity.version, 1);
3438 assert_eq!(user_identity.credentials.access_key, "AKIAIOSFODNN7EXAMPLE");
3439 assert_eq!(user_identity.credentials.secret_key, "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY");
3440 assert_eq!(user_identity.credentials.status, "enabled");
3441 assert_eq!(user_identity.credentials.parent_user, "parent-user");
3442 assert_eq!(user_identity.credentials.groups, Some(vec!["group1".to_string(), "group2".to_string()]));
3443 }
3444
3445 #[test]
3446 fn test_policy_structure() {
3447 let policy = Policy {
3448 id: Default::default(),
3449 version: "2012-10-17".to_string(),
3450 statements: vec![],
3451 };
3452
3453 assert_eq!(policy.version, "2012-10-17");
3455 assert_eq!(policy.statements.len(), 0);
3456 assert!(policy.is_empty());
3457 }
3458
3459 #[test]
3460 fn test_policy_doc_structure() {
3461 let policy = Policy {
3462 id: Default::default(),
3463 version: "2012-10-17".to_string(),
3464 statements: vec![],
3465 };
3466
3467 let policy_doc = PolicyDoc {
3468 version: 1,
3469 policy,
3470 create_date: Some(OffsetDateTime::now_utc()),
3471 update_date: Some(OffsetDateTime::now_utc()),
3472 };
3473
3474 assert_eq!(policy_doc.version, 1);
3476 assert_eq!(policy_doc.policy.version, "2012-10-17");
3477 assert!(policy_doc.policy.statements.is_empty());
3478 }
3479
3480 #[test]
3481 fn test_group_info_basic() {
3482 let group_info = GroupInfo {
3484 version: 1,
3485 status: STATUS_ENABLED.to_string(),
3486 members: vec!["user1".to_string(), "user2".to_string()],
3487 update_at: Some(OffsetDateTime::now_utc()),
3488 };
3489
3490 assert_eq!(group_info.version, 1);
3491 assert_eq!(group_info.status, STATUS_ENABLED);
3492 assert_eq!(group_info.members.len(), 2);
3493 assert!(group_info.members.contains(&"user1".to_string()));
3494 assert!(group_info.members.contains(&"user2".to_string()));
3495 }
3496
3497 #[test]
3498 fn test_update_service_account_opts() {
3499 let policy = Policy {
3500 id: Default::default(),
3501 version: "2012-10-17".to_string(),
3502 statements: vec![],
3503 };
3504
3505 let opts = UpdateServiceAccountOpts {
3506 secret_key: Some("new-secret-key".to_string()),
3507 status: Some(STATUS_ENABLED.to_string()),
3508 name: Some("service-account-name".to_string()),
3509 description: Some("Updated service account".to_string()),
3510 expiration: None,
3511 session_policy: Some(policy),
3512 parent_user: None,
3513 allow_site_replicator_account: false,
3514 };
3515
3516 assert_eq!(opts.secret_key, Some("new-secret-key".to_string()));
3517 assert_eq!(opts.status, Some(STATUS_ENABLED.to_string()));
3518 assert_eq!(opts.name, Some("service-account-name".to_string()));
3519 assert_eq!(opts.description, Some("Updated service account".to_string()));
3520 assert!(opts.session_policy.is_some());
3521 assert!(opts.expiration.is_none());
3522 }
3523
3524 #[test]
3525 fn test_status_constants() {
3526 assert_eq!(STATUS_ENABLED, "enabled");
3528 assert_eq!(STATUS_DISABLED, "disabled");
3529 }
3530
3531 #[test]
3532 fn test_session_policy_constants() {
3533 assert_eq!(SESSION_POLICY_NAME, "sessionPolicy");
3536 assert_eq!(SESSION_POLICY_NAME_EXTRACTED, "sessionPolicy-extracted");
3537 assert_eq!(MAX_SVCSESSION_POLICY_SIZE, 4096); }
3540
3541 #[test]
3542 fn test_credentials_validation() {
3543 let credentials = Credentials {
3544 access_key: "AKIAIOSFODNN7EXAMPLE".to_string(),
3545 secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_string(),
3546 session_token: "".to_string(),
3547 expiration: None,
3548 status: "on".to_string(),
3549 parent_user: "".to_string(),
3550 groups: None,
3551 claims: None,
3552 name: None,
3553 description: None,
3554 };
3555
3556 assert!(credentials.is_valid());
3558 assert!(!credentials.is_expired());
3559 assert!(!credentials.is_temp());
3560 assert!(!credentials.is_service_account());
3561 }
3562
3563 #[test]
3564 fn test_credentials_with_session_token() {
3565 let credentials = Credentials {
3566 access_key: "AKIAIOSFODNN7EXAMPLE".to_string(),
3567 secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_string(),
3568 session_token: "session-token".to_string(),
3569 expiration: Some(OffsetDateTime::now_utc() + time::Duration::hours(1)),
3570 status: "on".to_string(),
3571 parent_user: "".to_string(),
3572 groups: None,
3573 claims: None,
3574 name: None,
3575 description: None,
3576 };
3577
3578 assert!(credentials.is_valid());
3580 assert!(!credentials.is_expired());
3581 assert!(credentials.is_temp());
3582 }
3583
3584 #[test]
3585 fn test_policy_merge() {
3586 let policy1 = Policy {
3587 id: Default::default(),
3588 version: "2012-10-17".to_string(),
3589 statements: vec![],
3590 };
3591
3592 let policy2 = Policy {
3593 id: Default::default(),
3594 version: "2012-10-17".to_string(),
3595 statements: vec![],
3596 };
3597
3598 let merged = Policy::merge_policies(vec![policy1, policy2]);
3599 assert_eq!(merged.version, "2012-10-17");
3600 assert!(merged.statements.is_empty());
3601 assert!(merged.is_empty());
3602 }
3603
3604 #[test]
3605 fn test_build_group_desc_preserves_policy_for_disabled_group() {
3606 let group_info = GroupInfo {
3607 status: STATUS_DISABLED.to_string(),
3608 members: vec!["alice".to_string()],
3609 ..Default::default()
3610 };
3611 let mapped_policy = MappedPolicy::new("readonly");
3612
3613 let desc = build_group_desc("ops", group_info, Some(mapped_policy));
3614
3615 assert_eq!(desc.name, "ops");
3616 assert_eq!(desc.status, STATUS_DISABLED);
3617 assert_eq!(desc.policy, "readonly");
3618 assert_eq!(desc.members, vec!["alice".to_string()]);
3619 assert!(desc.updated_at.is_some());
3620 }
3621
3622 #[tokio::test]
3623 async fn delete_policy_propagates_backend_error_and_keeps_cache() {
3624 let cache = build_test_iam_cache(FailingInitialLoadStore);
3628
3629 let policy = Policy {
3630 id: Default::default(),
3631 version: "2012-10-17".to_string(),
3632 statements: vec![],
3633 };
3634 let policy_doc = PolicyDoc {
3635 version: 1,
3636 policy,
3637 create_date: Some(OffsetDateTime::now_utc()),
3638 update_date: Some(OffsetDateTime::now_utc()),
3639 };
3640 cache
3641 .cache
3642 .add_or_update_policy_doc("permissive-policy", &policy_doc, OffsetDateTime::now_utc());
3643
3644 let result = cache.delete_policy("permissive-policy", true).await;
3645
3646 assert!(
3648 result.is_err(),
3649 "delete_policy must surface a real backend delete failure instead of reporting success"
3650 );
3651 assert!(
3652 cache.cache.snapshot().policy_docs.contains_key("permissive-policy"),
3653 "cache must not evict a policy whose backend delete failed"
3654 );
3655 }
3656}