1use super::{GroupInfo, MappedPolicy, Store, UserType};
16use crate::error::{Error, Result, is_err_config_not_found, is_err_no_such_group};
17use crate::{
18 IAM_CONFIG_ROOT_PREFIX, IamStorageError, IamStore, classify_iam_system_path_failure_reason, delete_iam_config,
19 read_iam_config_no_lock, read_iam_config_with_metadata, save_iam_config, save_iam_config_with_opts,
20};
21use crate::{
22 cache::{Cache, CacheEntity},
23 error::{is_err_no_such_policy, is_err_no_such_user},
24 keyring,
25 manager::{extract_jwt_claims, extract_jwt_claims_allow_missing_exp, get_default_policies},
26 root_credentials,
27};
28use futures::future::join_all;
29use rustfs_io_metrics::record_system_path_failure;
30use rustfs_policy::{auth::UserIdentity, policy::PolicyDoc};
31use rustfs_utils::{
32 MaskedAccessKey,
33 path::{SLASH_SEPARATOR, path_join_buf},
34};
35use serde::{Serialize, de::DeserializeOwned};
36use std::sync::{LazyLock, Mutex};
37use std::time::{Duration, Instant};
38use std::{collections::HashMap, sync::Arc};
39use tokio::sync::mpsc::{self, Sender};
40use tokio_util::sync::CancellationToken;
41use tracing::{debug, error, warn};
42
43use crate::storage_api::object_store::{
44 HTTPPreconditions, ListOperations, ObjectInfoOrErr as StorageObjectInfoOrErr, ObjectOperations,
45};
46
47pub static IAM_CONFIG_PREFIX: LazyLock<String> = LazyLock::new(|| format!("{IAM_CONFIG_ROOT_PREFIX}/iam"));
48pub static IAM_CONFIG_USERS_PREFIX: LazyLock<String> = LazyLock::new(|| format!("{IAM_CONFIG_ROOT_PREFIX}/iam/users/"));
49pub static IAM_CONFIG_SERVICE_ACCOUNTS_PREFIX: LazyLock<String> =
50 LazyLock::new(|| format!("{IAM_CONFIG_ROOT_PREFIX}/iam/service-accounts/"));
51pub static IAM_CONFIG_GROUPS_PREFIX: LazyLock<String> = LazyLock::new(|| format!("{IAM_CONFIG_ROOT_PREFIX}/iam/groups/"));
52pub static IAM_CONFIG_POLICIES_PREFIX: LazyLock<String> = LazyLock::new(|| format!("{IAM_CONFIG_ROOT_PREFIX}/iam/policies/"));
53pub static IAM_CONFIG_STS_PREFIX: LazyLock<String> = LazyLock::new(|| format!("{IAM_CONFIG_ROOT_PREFIX}/iam/sts/"));
54pub static IAM_CONFIG_POLICY_DB_PREFIX: LazyLock<String> = LazyLock::new(|| format!("{IAM_CONFIG_ROOT_PREFIX}/iam/policydb/"));
55pub static IAM_CONFIG_POLICY_DB_USERS_PREFIX: LazyLock<String> =
56 LazyLock::new(|| format!("{IAM_CONFIG_ROOT_PREFIX}/iam/policydb/users/"));
57pub static IAM_CONFIG_POLICY_DB_STS_USERS_PREFIX: LazyLock<String> =
58 LazyLock::new(|| format!("{IAM_CONFIG_ROOT_PREFIX}/iam/policydb/sts-users/"));
59pub static IAM_CONFIG_POLICY_DB_SERVICE_ACCOUNTS_PREFIX: LazyLock<String> =
60 LazyLock::new(|| format!("{IAM_CONFIG_ROOT_PREFIX}/iam/policydb/service-accounts/"));
61pub static IAM_CONFIG_POLICY_DB_GROUPS_PREFIX: LazyLock<String> =
62 LazyLock::new(|| format!("{IAM_CONFIG_ROOT_PREFIX}/iam/policydb/groups/"));
63
64type ObjectInfoOrErr = StorageObjectInfoOrErr<IamObjectInfo, IamStorageError>;
65type IamObjectInfo = <IamStore as ObjectOperations>::ObjectInfo;
66type IamObjectOptions = <IamStore as ObjectOperations>::ObjectOptions;
67
68const IAM_IDENTITY_FILE: &str = "identity.json";
69const IAM_POLICY_FILE: &str = "policy.json";
70const IAM_GROUP_MEMBERS_FILE: &str = "members.json";
71const BACKGROUND_WALKDIR_TIMEOUT: Duration = Duration::from_secs(60);
72
73fn get_user_identity_path(user: &str, user_type: UserType) -> String {
74 let base_path: &str = match user_type {
75 UserType::Svc => &IAM_CONFIG_SERVICE_ACCOUNTS_PREFIX,
76 UserType::Sts => &IAM_CONFIG_STS_PREFIX,
77 _ => &IAM_CONFIG_USERS_PREFIX,
78 };
79
80 path_join_buf(&[base_path, user, IAM_IDENTITY_FILE])
81}
82
83fn get_group_info_path(group: &str) -> String {
84 path_join_buf(&[&IAM_CONFIG_GROUPS_PREFIX, group, IAM_GROUP_MEMBERS_FILE])
85}
86
87fn get_policy_doc_path(name: &str) -> String {
88 path_join_buf(&[&IAM_CONFIG_POLICIES_PREFIX, name, IAM_POLICY_FILE])
89}
90
91fn get_mapped_policy_path(name: &str, user_type: UserType, is_group: bool) -> String {
92 if is_group {
93 return path_join_buf(&[&IAM_CONFIG_POLICY_DB_GROUPS_PREFIX, format!("{name}.json").as_str()]);
94 }
95 match user_type {
96 UserType::Svc => path_join_buf(&[&IAM_CONFIG_POLICY_DB_SERVICE_ACCOUNTS_PREFIX, format!("{name}.json").as_str()]),
97 UserType::Sts => path_join_buf(&[&IAM_CONFIG_POLICY_DB_STS_USERS_PREFIX, format!("{name}.json").as_str()]),
98 _ => path_join_buf(&[&IAM_CONFIG_POLICY_DB_USERS_PREFIX, format!("{name}.json").as_str()]),
99 }
100}
101
102#[derive(Clone, Copy, Debug, PartialEq, Eq)]
113enum LoadMode {
114 Locked,
116 BootstrapNoLock,
119}
120
121impl LoadMode {
122 fn no_lock(self) -> bool {
123 matches!(self, LoadMode::BootstrapNoLock)
124 }
125
126 fn read_opts(self) -> IamObjectOptions {
127 IamObjectOptions {
128 no_lock: self.no_lock(),
129 ..Default::default()
130 }
131 }
132}
133
134#[derive(Debug)]
135pub struct StringOrErr {
136 pub item: Option<String>,
137 pub err: Option<Error>,
138}
139
140const USERS_LIST_KEY: &str = "users/";
141const SVC_ACC_LIST_KEY: &str = "service-accounts/";
142const GROUPS_LIST_KEY: &str = "groups/";
143const POLICIES_LIST_KEY: &str = "policies/";
144const STS_LIST_KEY: &str = "sts/";
145const POLICY_DB_PREFIX: &str = "policydb/";
146const POLICY_DB_USERS_LIST_KEY: &str = "policydb/users/";
147const POLICY_DB_STS_USERS_LIST_KEY: &str = "policydb/sts-users/";
148const POLICY_DB_GROUPS_LIST_KEY: &str = "policydb/groups/";
149const IAM_LAZY_REWRITE_COOLDOWN: Duration = Duration::from_secs(60);
150
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152enum DecryptSource {
153 Plaintext,
154 CurrentMasterKey,
155 OldMasterKey,
156 LegacySecretKey,
157 LegacyAccessSecretKey,
158}
159
160#[derive(Debug)]
161struct DecryptOutcome {
162 plain: Vec<u8>,
163 source: DecryptSource,
164}
165
166#[derive(Default, Clone, Copy, Debug)]
167struct LazyRewriteEntry {
168 in_flight: bool,
169 cooldown_until: Option<Instant>,
170}
171
172static IAM_LAZY_REWRITE_TRACKER: LazyLock<Mutex<HashMap<String, LazyRewriteEntry>>> =
173 LazyLock::new(|| Mutex::new(HashMap::new()));
174
175fn split_path(s: &str, last_index: bool) -> (&str, &str) {
178 let i = if last_index { s.rfind('/') } else { s.find('/') };
179
180 match i {
181 Some(index) => (&s[..index + 1], &s[index + 1..]),
182 None => (s, ""),
183 }
184}
185
186pub fn try_decrypt_iam_blob(data: &[u8]) -> Option<Vec<u8>> {
199 ObjectStore::decrypt_data_with_source(data).ok().map(|outcome| outcome.plain)
200}
201
202pub(crate) fn encrypt_iam_blob(plain: &[u8]) -> Result<Vec<u8>> {
208 ObjectStore::encrypt_data_with_master_key(plain)
209}
210
211pub(crate) fn decrypt_iam_blob(data: &[u8]) -> Result<Vec<u8>> {
214 ObjectStore::decrypt_data_with_source(data).map(|outcome| outcome.plain)
215}
216
217#[derive(Clone)]
218pub struct ObjectStore {
219 object_api: Arc<IamStore>,
220}
221
222impl ObjectStore {
223 const BUCKET_NAME: &'static str = ".rustfs.sys";
224
225 pub fn new(object_api: Arc<IamStore>) -> Self {
226 Self { object_api }
227 }
228
229 fn decrypt_data_with_source(data: &[u8]) -> Result<DecryptOutcome> {
230 if Self::is_plaintext_json(data) {
231 return Ok(DecryptOutcome {
232 plain: data.to_vec(),
233 source: DecryptSource::Plaintext,
234 });
235 }
236
237 const STREAM_IO_HEADER_LEN: usize = 41;
238 let cred = root_credentials::credentials_or_default();
239 let mut last_err = None;
240
241 let mut try_decrypt_with_key = |key: &[u8], source: DecryptSource| -> Option<DecryptOutcome> {
242 if data.len() >= STREAM_IO_HEADER_LEN
243 && let Ok(plain) = rustfs_crypto::decrypt_stream_io(key, data)
244 {
245 return Some(DecryptOutcome { plain, source });
246 }
247
248 match rustfs_crypto::decrypt_data(key, data) {
249 Ok(plain) => Some(DecryptOutcome { plain, source }),
250 Err(err) => {
251 last_err = Some(err);
252 None
253 }
254 }
255 };
256
257 let (current_key, old_keys) = keyring::current_key_and_old_keys();
258 if let Some(key) = current_key
259 && let Some(outcome) = try_decrypt_with_key(&key, DecryptSource::CurrentMasterKey)
260 {
261 return Ok(outcome);
262 }
263
264 for key in old_keys {
265 if let Some(outcome) = try_decrypt_with_key(&key, DecryptSource::OldMasterKey) {
266 return Ok(outcome);
267 }
268 }
269
270 let secret_key = cred.secret_key;
271 let mut legacy_keys = Vec::new();
272 if !secret_key.is_empty() {
273 legacy_keys.push((secret_key.clone().into_bytes(), DecryptSource::LegacySecretKey));
274 }
275 if !cred.access_key.is_empty() && !secret_key.is_empty() {
276 legacy_keys.push((
277 format!("{}:{secret_key}", cred.access_key).into_bytes(),
278 DecryptSource::LegacyAccessSecretKey,
279 ));
280 }
281
282 for (key, source) in legacy_keys {
283 if let Some(outcome) = try_decrypt_with_key(&key, source) {
284 return Ok(outcome);
285 }
286 }
287
288 Err(last_err.unwrap_or(rustfs_crypto::Error::ErrUnexpectedHeader).into())
289 }
290
291 fn encrypt_data_with_master_key(data: &[u8]) -> Result<Vec<u8>> {
292 let Some(master_key) = keyring::encrypt_key() else {
293 return Err(Error::other("iam master key is not configured"));
294 };
295
296 let encrypted = rustfs_crypto::encrypt_stream_io(&master_key, data)?;
297 Ok(encrypted)
298 }
299
300 fn prepare_data_for_storage(data: &[u8]) -> Result<Vec<u8>> {
301 if keyring::encrypt_key().is_some() {
302 let encrypted = Self::encrypt_data_with_master_key(data)?;
303 return Ok(encrypted);
304 }
305
306 Ok(data.to_vec())
307 }
308
309 fn should_lazy_rewrite(source: DecryptSource) -> bool {
310 matches!(
311 source,
312 DecryptSource::Plaintext
313 | DecryptSource::OldMasterKey
314 | DecryptSource::LegacySecretKey
315 | DecryptSource::LegacyAccessSecretKey
316 )
317 }
318
319 fn begin_lazy_rewrite(path: &str) -> bool {
320 let Ok(mut tracker) = IAM_LAZY_REWRITE_TRACKER.lock() else {
321 return false;
322 };
323
324 let entry = tracker.entry(path.to_owned()).or_default();
325 if entry.in_flight {
326 return false;
327 }
328 if entry.cooldown_until.is_some_and(|deadline| deadline > Instant::now()) {
329 return false;
330 }
331
332 entry.in_flight = true;
333 entry.cooldown_until = None;
334 true
335 }
336
337 fn complete_lazy_rewrite(path: &str, success: bool) {
338 let Ok(mut tracker) = IAM_LAZY_REWRITE_TRACKER.lock() else {
339 return;
340 };
341
342 if success {
343 tracker.remove(path);
344 return;
345 }
346
347 let entry = tracker.entry(path.to_owned()).or_default();
348 entry.in_flight = false;
349 entry.cooldown_until = Some(Instant::now() + IAM_LAZY_REWRITE_COOLDOWN);
350 }
351
352 fn maybe_schedule_lazy_rewrite(&self, path: &str, outcome: &DecryptOutcome, object_info: &IamObjectInfo) {
353 if !Self::should_lazy_rewrite(outcome.source) {
354 return;
355 }
356 if keyring::encrypt_key().is_none() {
357 return;
358 }
359
360 let Some(etag) = object_info.etag.clone() else {
361 return;
362 };
363
364 if !Self::begin_lazy_rewrite(path) {
365 return;
366 }
367
368 let path = path.to_owned();
369 let plain = outcome.plain.clone();
370 let store = self.clone();
371 tokio::spawn(async move {
372 let result = store.lazy_rewrite_iam_config(path.as_str(), &plain, etag.as_str()).await;
373 match result {
374 Ok(_) => {
375 Self::complete_lazy_rewrite(path.as_str(), true);
376 }
377 Err(IamStorageError::PreconditionFailed) => {
378 Self::complete_lazy_rewrite(path.as_str(), false);
379 debug!(path = %path, state = "stale_etag", "IAM lazy rewrite skipped");
380 }
381 Err(err) => {
382 Self::complete_lazy_rewrite(path.as_str(), false);
383 warn!(path = %path, error = %err, state = "rewrite_failed", "IAM lazy rewrite failed");
384 }
385 }
386 });
387 }
388
389 async fn lazy_rewrite_iam_config(&self, path: &str, plain: &[u8], etag: &str) -> std::result::Result<(), IamStorageError> {
390 let encrypted = Self::encrypt_data_with_master_key(plain).map_err(IamStorageError::other)?;
391
392 let mut opts = IamObjectOptions {
393 max_parity: true,
394 ..Default::default()
395 };
396 opts.http_preconditions = Some(HTTPPreconditions {
397 if_match: Some(etag.to_owned()),
398 ..Default::default()
399 });
400
401 save_iam_config_with_opts(self.object_api.clone(), path, encrypted, &opts).await
402 }
403
404 fn is_plaintext_json(data: &[u8]) -> bool {
405 std::str::from_utf8(data).is_ok() && serde_json::from_slice::<serde_json::Value>(data).is_ok()
406 }
407
408 #[cfg(test)]
409 fn prepare_data_for_storage_for_test(data: &[u8]) -> Result<Vec<u8>> {
410 Self::prepare_data_for_storage(data)
411 }
412
413 async fn load_iamconfig_bytes_with_metadata(
414 &self,
415 path: impl AsRef<str> + Send,
416 mode: LoadMode,
417 ) -> Result<(Vec<u8>, IamObjectInfo)> {
418 let path_ref = path.as_ref();
419 let (data, obj) = read_iam_config_with_metadata(self.object_api.clone(), path_ref, &mode.read_opts()).await?;
420 let outcome = Self::decrypt_data_with_source(&data)?;
421 self.maybe_schedule_lazy_rewrite(path_ref, &outcome, &obj);
422
423 Ok((outcome.plain, obj))
424 }
425
426 async fn list_iam_config_items(&self, prefix: &str, ctx: CancellationToken, sender: Sender<StringOrErr>) {
427 let store = self.object_api.clone();
430
431 let (tx, mut rx) = mpsc::channel::<ObjectInfoOrErr>(100);
432
433 let path = prefix.to_owned();
434 let sender_on_error = sender.clone();
435 tokio::spawn(async move {
436 let walk_opts =
437 <IamStore as ListOperations>::WalkOptions::default().with_walkdir_timeouts(BACKGROUND_WALKDIR_TIMEOUT);
438 if let Err(err) = store.walk(ctx.clone(), Self::BUCKET_NAME, &path, tx, walk_opts).await {
439 let reason = classify_iam_system_path_failure_reason(&err);
440 record_system_path_failure("iam_config", "walk", reason);
441 error!(
442 path_kind = "iam_config",
443 operation = "walk",
444 reason,
445 bucket = Self::BUCKET_NAME,
446 prefix = %path,
447 error = %err,
448 "IAM config walk failed"
449 );
450 let _ = sender_on_error
451 .send(StringOrErr {
452 item: None,
453 err: Some(err.into()),
454 })
455 .await;
456 }
457 });
458
459 let prefix = prefix.to_owned();
460 tokio::spawn(async move {
461 while let Some(v) = rx.recv().await {
462 if let Some(err) = v.err {
463 let _ = sender
464 .send(StringOrErr {
465 item: None,
466 err: Some(err.into()),
467 })
468 .await;
469 return;
470 }
471
472 if let Some(info) = v.item {
473 let object_name = if cfg!(target_os = "windows") {
474 info.name.replace('\\', "/")
475 } else {
476 info.name
477 };
478 let name = object_name.trim_start_matches(&prefix).trim_end_matches(SLASH_SEPARATOR);
479 let _ = sender
480 .send(StringOrErr {
481 item: Some(name.to_owned()),
482 err: None,
483 })
484 .await;
485 }
486 }
487 });
488 }
489
490 #[hotpath::measure]
491 async fn list_all_iamconfig_items(&self) -> Result<HashMap<String, Vec<String>>> {
492 let (tx, mut rx) = mpsc::channel::<StringOrErr>(100);
493
494 let ctx = CancellationToken::new();
495
496 self.list_iam_config_items(format!("{}/", *IAM_CONFIG_PREFIX).as_str(), ctx.clone(), tx)
497 .await;
498
499 let mut res = HashMap::new();
500
501 while let Some(v) = rx.recv().await {
502 if let Some(err) = v.err {
503 warn!(
504 path_kind = "iam_config",
505 operation = "list_items",
506 reason = "walk_result",
507 error = %err,
508 "system path list failed"
509 );
510 record_system_path_failure("iam_config", "list_items", "walk_result");
511 ctx.cancel();
512
513 return Err(err);
514 }
515
516 if let Some(item) = v.item {
517 let last_index = item.starts_with(POLICY_DB_PREFIX);
518 let (list_key, trimmed_item) = split_path(&item, last_index);
519 res.entry(list_key.to_owned())
520 .or_insert_with(Vec::new)
521 .push(trimmed_item.to_owned());
522 }
523 }
524
525 ctx.cancel();
526
527 Ok(res)
528 }
529
530 #[hotpath::measure]
531 async fn load_policy_doc_concurrent(&self, names: &[String], mode: LoadMode) -> Result<Vec<PolicyDoc>> {
532 let mut futures = Vec::with_capacity(names.len());
533
534 for name in names {
535 let policy_name = rustfs_utils::path::dir(name);
536 futures.push(async move {
537 match self.load_policy_with(&policy_name, mode).await {
538 Ok(p) => Ok(p),
539 Err(err) => {
540 if !is_err_no_such_policy(&err) {
541 Err(Error::other(format!("load policy doc failed: {err}")))
542 } else {
543 Ok(PolicyDoc::default())
544 }
545 }
546 }
547 });
548 }
549
550 let results = join_all(futures).await;
551
552 let mut policies = Vec::with_capacity(results.len());
553 for r in results {
554 match r {
555 Ok(p) => policies.push(p),
556 Err(e) => return Err(e),
557 }
558 }
559
560 Ok(policies)
561 }
562
563 async fn load_user_concurrent(&self, names: &[String], user_type: UserType, mode: LoadMode) -> Result<Vec<UserIdentity>> {
564 let mut futures = Vec::with_capacity(names.len());
565
566 for name in names {
567 let user_name = rustfs_utils::path::dir(name);
568 futures.push(async move {
569 match self.load_user_identity_with(&user_name, user_type, mode).await {
570 Ok(res) => Ok(res),
571 Err(err) => {
572 if !is_err_no_such_user(&err) {
573 Err(Error::other(format!("load user failed: {err}")))
574 } else {
575 Ok(UserIdentity::default())
576 }
577 }
578 }
579 });
580 }
581
582 let results = join_all(futures).await;
583
584 let mut users = Vec::with_capacity(results.len());
585 for r in results {
586 match r {
587 Ok(u) => users.push(u),
588 Err(e) => return Err(e),
589 }
590 }
591 Ok(users)
592 }
593
594 async fn load_iam_config_with<Item: DeserializeOwned>(&self, path: impl AsRef<str> + Send, mode: LoadMode) -> Result<Item> {
597 let path_ref = path.as_ref();
598 let (data, obj) = read_iam_config_with_metadata(self.object_api.clone(), path_ref, &mode.read_opts()).await?;
599
600 let outcome = match Self::decrypt_data_with_source(&data) {
601 Ok(v) => v,
602 Err(err) => {
603 warn!(path = %path_ref, error = %err, "IAM config decrypt failed; keeping file");
604 return Err(Error::ConfigNotFound);
606 }
607 };
608
609 self.maybe_schedule_lazy_rewrite(path_ref, &outcome, &obj);
610
611 Ok(serde_json::from_slice(&outcome.plain)?)
612 }
613
614 async fn load_user_identity_with(&self, name: &str, user_type: UserType, mode: LoadMode) -> Result<UserIdentity> {
616 let mut u: UserIdentity = self
617 .load_iam_config_with(get_user_identity_path(name, user_type), mode)
618 .await
619 .map_err(|err| {
620 if is_err_config_not_found(&err) {
621 debug!(name = %MaskedAccessKey(name), user_type = ?user_type, "IAM user identity missing");
622 Error::NoSuchUser(name.to_owned())
623 } else {
624 warn!(name = %MaskedAccessKey(name), user_type = ?user_type, error = ?err, "IAM user identity load failed");
625 err
626 }
627 })?;
628
629 if u.credentials.is_expired() {
630 let _ = self.delete_iam_config(get_user_identity_path(name, user_type)).await;
631 let _ = self.delete_iam_config(get_mapped_policy_path(name, user_type, false)).await;
632 warn!(name = %MaskedAccessKey(name), user_type = ?user_type, "IAM user identity expired and was removed");
633 return Err(Error::NoSuchUser(name.to_owned()));
634 }
635
636 if u.credentials.access_key.is_empty() {
637 u.credentials.access_key = name.to_owned();
638 }
639
640 if !u.credentials.session_token.is_empty() {
641 let claims_result = if user_type == UserType::Svc && u.credentials.expiration.is_none() {
642 extract_jwt_claims_allow_missing_exp(&u)
643 } else {
644 extract_jwt_claims(&u)
645 };
646
647 match claims_result {
648 Ok(claims) => {
649 u.credentials.claims = Some(claims);
650 }
651 Err(err) => {
652 if u.credentials.is_temp() {
653 let _ = self.delete_iam_config(get_user_identity_path(name, user_type)).await;
654 let _ = self.delete_iam_config(get_mapped_policy_path(name, user_type, false)).await;
655 }
656 warn!(name = %MaskedAccessKey(name), user_type = ?user_type, error = ?err, "IAM JWT claim extraction failed");
657 return Err(Error::NoSuchUser(name.to_owned()));
658 }
659 }
660 }
661
662 Ok(u)
663 }
664
665 async fn load_user_with(
667 &self,
668 name: &str,
669 user_type: UserType,
670 m: &mut HashMap<String, UserIdentity>,
671 mode: LoadMode,
672 ) -> Result<()> {
673 self.load_user_identity_with(name, user_type, mode).await.map(|u| {
674 m.insert(name.to_owned(), u);
675 })
676 }
677
678 async fn load_group_with(&self, name: &str, m: &mut HashMap<String, GroupInfo>, mode: LoadMode) -> Result<()> {
680 let u: GroupInfo = self
681 .load_iam_config_with(get_group_info_path(name), mode)
682 .await
683 .map_err(|err| {
684 if is_err_config_not_found(&err) {
685 Error::NoSuchGroup(name.to_string())
686 } else {
687 err
688 }
689 })?;
690
691 m.insert(name.to_owned(), u);
692 Ok(())
693 }
694
695 async fn load_policy_with(&self, name: &str, mode: LoadMode) -> Result<PolicyDoc> {
697 let (data, obj) = self
698 .load_iamconfig_bytes_with_metadata(get_policy_doc_path(name), mode)
699 .await
700 .map_err(|err| {
701 if is_err_config_not_found(&err) {
702 Error::NoSuchPolicy
703 } else {
704 err
705 }
706 })?;
707
708 let mut info = PolicyDoc::try_from(data)?;
709
710 if info.version == 0 {
711 info.create_date = obj.mod_time;
712 info.update_date = obj.mod_time;
713 }
714
715 Ok(info)
716 }
717
718 async fn load_mapped_policy_with(
720 &self,
721 name: &str,
722 user_type: UserType,
723 is_group: bool,
724 m: &mut HashMap<String, MappedPolicy>,
725 mode: LoadMode,
726 ) -> Result<()> {
727 let info = self.load_mapped_policy_internal(name, user_type, is_group, mode).await?;
728
729 m.insert(name.to_owned(), info);
730
731 Ok(())
732 }
733
734 async fn load_mapped_policy_internal(
735 &self,
736 name: &str,
737 user_type: UserType,
738 is_group: bool,
739 mode: LoadMode,
740 ) -> Result<MappedPolicy> {
741 let info: MappedPolicy = self
742 .load_iam_config_with(get_mapped_policy_path(name, user_type, is_group), mode)
743 .await
744 .map_err(|err| {
745 if is_err_config_not_found(&err) {
746 Error::NoSuchPolicy
747 } else {
748 err
749 }
750 })?;
751
752 Ok(info)
753 }
754
755 async fn load_mapped_policy_concurrent(
756 &self,
757 names: &[String],
758 user_type: UserType,
759 is_group: bool,
760 mode: LoadMode,
761 ) -> Result<Vec<MappedPolicy>> {
762 let mut futures = Vec::with_capacity(names.len());
763
764 for name in names {
765 let policy_name = name.trim_end_matches(".json");
766 futures.push(async move {
767 match self.load_mapped_policy_internal(policy_name, user_type, is_group, mode).await {
768 Ok(p) => Ok(p),
769 Err(err) => {
770 if !is_err_no_such_policy(&err) {
771 Err(Error::other(format!("load mapped policy failed: {err}")))
772 } else {
773 Ok(MappedPolicy::default())
774 }
775 }
776 }
777 });
778 }
779
780 let results = join_all(futures).await;
781
782 let mut policies = Vec::with_capacity(results.len());
783 for r in results {
784 match r {
785 Ok(p) => policies.push(p),
786 Err(e) => return Err(e),
787 }
788 }
789
790 Ok(policies)
791 }
792
793 async fn check_storage_readiness(&self) -> Result<()> {
800 let probe_path = format!("{}/format.json", *IAM_CONFIG_PREFIX);
803
804 match read_iam_config_no_lock(self.object_api.clone(), &probe_path).await {
805 Ok(_) => Ok(()),
806 Err(IamStorageError::ConfigNotFound) => Err(Error::other(format!(
807 "Storage metadata not ready: probe object '{}' not found (expected IAM config to be initialized)",
808 probe_path
809 ))),
810 Err(e) => Err(e.into()),
811 }
812 }
813}
814
815#[async_trait::async_trait]
816impl Store for ObjectStore {
817 fn has_watcher(&self) -> bool {
818 false
819 }
820 async fn load_iam_config<Item: DeserializeOwned>(&self, path: impl AsRef<str> + Send) -> Result<Item> {
821 self.load_iam_config_with(path, LoadMode::Locked).await
822 }
823 #[tracing::instrument(skip(self, item, path))]
837 async fn save_iam_config<Item: Serialize + Send>(&self, item: Item, path: impl AsRef<str> + Send) -> Result<()> {
838 let mut data = serde_json::to_vec(&item)?;
839 data = Self::prepare_data_for_storage(&data)?;
840
841 let mut attempts = 0;
842 let max_attempts = 5;
843 let path_ref = path.as_ref();
844
845 loop {
846 match save_iam_config(self.object_api.clone(), path_ref, data.clone()).await {
847 Ok(_) => {
848 debug!("Successfully saved IAM config to {}", path_ref);
849 return Ok(());
850 }
851 Err(e) if attempts < max_attempts => {
852 attempts += 1;
853 let wait_ms = 200 * (1 << attempts);
855 warn!(
856 "Storage layer not ready for IAM write (attempt {}/{}). Retrying in {}ms. Path: {}, Error: {:?}",
857 attempts, max_attempts, wait_ms, path_ref, e
858 );
859 tokio::time::sleep(std::time::Duration::from_millis(wait_ms)).await;
860 }
861 Err(e) => {
862 error!(path = %path_ref, error = ?e, "IAM config save failed");
863 return Err(e.into());
864 }
865 }
866 }
867 }
868 async fn delete_iam_config(&self, path: impl AsRef<str> + Send) -> Result<()> {
869 delete_iam_config(self.object_api.clone(), path.as_ref()).await?;
870 Ok(())
871 }
872
873 async fn save_user_identity(
874 &self,
875 name: &str,
876 user_type: UserType,
877 user_identity: UserIdentity,
878 _ttl: Option<usize>,
879 ) -> Result<()> {
880 self.check_storage_readiness().await?;
882
883 let path = get_user_identity_path(name, user_type);
884 debug!("Saving IAM identity to path: {}", path);
885
886 self.save_iam_config(user_identity, path).await.map_err(|e| {
887 error!(name, error = ?e, "IAM identity save failed");
888 e
889 })
890 }
891 async fn delete_user_identity(&self, name: &str, user_type: UserType) -> Result<()> {
892 self.delete_iam_config(get_user_identity_path(name, user_type))
893 .await
894 .map_err(|err| map_delete_user_identity_error(name, err))?;
895 Ok(())
896 }
897 async fn load_user_identity(&self, name: &str, user_type: UserType) -> Result<UserIdentity> {
898 self.load_user_identity_with(name, user_type, LoadMode::Locked).await
899 }
900 async fn load_user(&self, name: &str, user_type: UserType, m: &mut HashMap<String, UserIdentity>) -> Result<()> {
901 self.load_user_with(name, user_type, m, LoadMode::Locked).await
902 }
903 async fn load_users(&self, user_type: UserType, m: &mut HashMap<String, UserIdentity>) -> Result<()> {
904 let base_prefix = match user_type {
905 UserType::Reg => IAM_CONFIG_USERS_PREFIX.as_str(),
906 UserType::Svc => IAM_CONFIG_SERVICE_ACCOUNTS_PREFIX.as_str(),
907 UserType::Sts => IAM_CONFIG_STS_PREFIX.as_str(),
908 UserType::None => "",
909 };
910
911 let ctx = CancellationToken::new();
912 let (tx, mut rx) = mpsc::channel::<StringOrErr>(100);
913
914 self.list_iam_config_items(base_prefix, ctx.clone(), tx).await;
915
916 while let Some(v) = rx.recv().await {
917 if let Some(err) = v.err {
918 warn!(error = ?err, "IAM config item listing failed");
919 let _ = ctx.cancel();
920
921 return Err(err);
922 }
923
924 if let Some(item) = v.item {
925 let name = rustfs_utils::path::dir(&item);
926 self.load_user(&name, user_type, m).await?;
927 }
928 }
929 let _ = ctx.cancel();
930 Ok(())
931 }
932 async fn load_secret_key(&self, name: &str, user_type: UserType) -> Result<String> {
933 let u: UserIdentity = self
934 .load_iam_config(get_user_identity_path(name, user_type))
935 .await
936 .map_err(|err| {
937 if is_err_config_not_found(&err) {
938 Error::NoSuchUser(name.to_owned())
939 } else {
940 err
941 }
942 })?;
943
944 Ok(u.credentials.secret_key)
945 }
946
947 async fn save_group_info(&self, name: &str, item: GroupInfo) -> Result<()> {
948 self.save_iam_config(item, get_group_info_path(name)).await
949 }
950 async fn delete_group_info(&self, name: &str) -> Result<()> {
951 self.delete_iam_config(get_group_info_path(name)).await.map_err(|err| {
952 if is_err_config_not_found(&err) {
953 Error::NoSuchGroup(name.to_string())
954 } else {
955 err
956 }
957 })?;
958 Ok(())
959 }
960 async fn load_group(&self, name: &str, m: &mut HashMap<String, GroupInfo>) -> Result<()> {
961 self.load_group_with(name, m, LoadMode::Locked).await
962 }
963 async fn load_groups(&self, m: &mut HashMap<String, GroupInfo>) -> Result<()> {
964 let ctx = CancellationToken::new();
965 let (tx, mut rx) = mpsc::channel::<StringOrErr>(100);
966
967 self.list_iam_config_items(&IAM_CONFIG_GROUPS_PREFIX, ctx.clone(), tx).await;
968
969 while let Some(v) = rx.recv().await {
970 if let Some(err) = v.err {
971 warn!(error = ?err, "IAM config item listing failed");
972 let _ = ctx.cancel();
973
974 return Err(err);
975 }
976
977 if let Some(item) = v.item {
978 let name = rustfs_utils::path::dir(&item);
979 if let Err(err) = self.load_group(&name, m).await
980 && !is_err_no_such_group(&err)
981 {
982 return Err(err);
983 }
984 }
985 }
986 let _ = ctx.cancel();
987 Ok(())
988 }
989
990 async fn save_policy_doc(&self, name: &str, policy_doc: PolicyDoc) -> Result<()> {
991 self.save_iam_config(policy_doc, get_policy_doc_path(name)).await
992 }
993 async fn delete_policy_doc(&self, name: &str) -> Result<()> {
994 self.delete_iam_config(get_policy_doc_path(name)).await.map_err(|err| {
995 if is_err_config_not_found(&err) {
996 Error::NoSuchPolicy
997 } else {
998 err
999 }
1000 })?;
1001 Ok(())
1002 }
1003 async fn load_policy(&self, name: &str) -> Result<PolicyDoc> {
1004 self.load_policy_with(name, LoadMode::Locked).await
1005 }
1006
1007 async fn load_policy_doc(&self, name: &str, m: &mut HashMap<String, PolicyDoc>) -> Result<()> {
1008 let info = self.load_policy(name).await?;
1009 m.insert(name.to_owned(), info);
1010
1011 Ok(())
1012 }
1013 async fn load_policy_docs(&self, m: &mut HashMap<String, PolicyDoc>) -> Result<()> {
1014 let ctx = CancellationToken::new();
1015 let (tx, mut rx) = mpsc::channel::<StringOrErr>(100);
1016
1017 self.list_iam_config_items(&IAM_CONFIG_POLICIES_PREFIX, ctx.clone(), tx).await;
1018
1019 while let Some(v) = rx.recv().await {
1020 if let Some(err) = v.err {
1021 warn!(error = ?err, "IAM config item listing failed");
1022 let _ = ctx.cancel();
1023
1024 return Err(err);
1025 }
1026
1027 if let Some(item) = v.item {
1028 let name = rustfs_utils::path::dir(&item);
1029 self.load_policy_doc(&name, m).await?;
1030 }
1031 }
1032 let _ = ctx.cancel();
1033 Ok(())
1034 }
1035
1036 async fn save_mapped_policy(
1037 &self,
1038 name: &str,
1039 user_type: UserType,
1040 is_group: bool,
1041 mapped_policy: MappedPolicy,
1042 _ttl: Option<usize>,
1043 ) -> Result<()> {
1044 self.save_iam_config(mapped_policy, get_mapped_policy_path(name, user_type, is_group))
1045 .await
1046 }
1047 async fn delete_mapped_policy(&self, name: &str, user_type: UserType, is_group: bool) -> Result<()> {
1048 self.delete_iam_config(get_mapped_policy_path(name, user_type, is_group))
1049 .await
1050 .map_err(|err| {
1051 if is_err_config_not_found(&err) {
1052 Error::NoSuchPolicy
1053 } else {
1054 err
1055 }
1056 })?;
1057 Ok(())
1058 }
1059 async fn load_mapped_policy(
1060 &self,
1061 name: &str,
1062 user_type: UserType,
1063 is_group: bool,
1064 m: &mut HashMap<String, MappedPolicy>,
1065 ) -> Result<()> {
1066 self.load_mapped_policy_with(name, user_type, is_group, m, LoadMode::Locked)
1067 .await
1068 }
1069 async fn load_mapped_policies(
1070 &self,
1071 user_type: UserType,
1072 is_group: bool,
1073 m: &mut HashMap<String, MappedPolicy>,
1074 ) -> Result<()> {
1075 let base_path = {
1076 if is_group {
1077 IAM_CONFIG_POLICY_DB_GROUPS_PREFIX.as_str()
1078 } else {
1079 match user_type {
1080 UserType::Svc => IAM_CONFIG_POLICY_DB_SERVICE_ACCOUNTS_PREFIX.as_str(),
1081 UserType::Sts => IAM_CONFIG_POLICY_DB_STS_USERS_PREFIX.as_str(),
1082 _ => IAM_CONFIG_POLICY_DB_USERS_PREFIX.as_str(),
1083 }
1084 }
1085 };
1086 let ctx = CancellationToken::new();
1087 let (tx, mut rx) = mpsc::channel::<StringOrErr>(100);
1088
1089 self.list_iam_config_items(base_path, ctx.clone(), tx).await;
1090
1091 while let Some(v) = rx.recv().await {
1092 if let Some(err) = v.err {
1093 warn!(error = ?err, "IAM config item listing failed");
1094 let _ = ctx.cancel();
1095
1096 return Err(err);
1097 }
1098
1099 if let Some(item) = v.item {
1100 let name = item.trim_end_matches(".json");
1101 self.load_mapped_policy(name, user_type, is_group, m).await?;
1102 }
1103 }
1104 let _ = ctx.cancel(); Ok(())
1106 }
1107
1108 async fn load_user_no_lock(&self, name: &str, user_type: UserType, m: &mut HashMap<String, UserIdentity>) -> Result<()> {
1113 self.load_user_with(name, user_type, m, LoadMode::BootstrapNoLock).await
1114 }
1115 async fn load_group_no_lock(&self, name: &str, m: &mut HashMap<String, GroupInfo>) -> Result<()> {
1116 self.load_group_with(name, m, LoadMode::BootstrapNoLock).await
1117 }
1118 async fn load_policy_doc_no_lock(&self, name: &str, m: &mut HashMap<String, PolicyDoc>) -> Result<()> {
1119 let info = self.load_policy_with(name, LoadMode::BootstrapNoLock).await?;
1120 m.insert(name.to_owned(), info);
1121
1122 Ok(())
1123 }
1124 async fn load_mapped_policy_no_lock(
1125 &self,
1126 name: &str,
1127 user_type: UserType,
1128 is_group: bool,
1129 m: &mut HashMap<String, MappedPolicy>,
1130 ) -> Result<()> {
1131 self.load_mapped_policy_with(name, user_type, is_group, m, LoadMode::BootstrapNoLock)
1132 .await
1133 }
1134
1135 async fn load_all(&self, cache: &Cache) -> Result<()> {
1136 const LOAD_ALL_MODE: LoadMode = LoadMode::BootstrapNoLock;
1140
1141 let cache_snapshot = cache.snapshot();
1142 let listed_config_items = self.list_all_iamconfig_items().await?;
1143
1144 let mut policy_docs_cache = CacheEntity::new(get_default_policies());
1145
1146 if let Some(policies_list) = listed_config_items.get(POLICIES_LIST_KEY) {
1147 for chunk in policies_list.chunks(32) {
1152 let policy_docs = self.load_policy_doc_concurrent(chunk, LOAD_ALL_MODE).await?;
1153
1154 for (idx, p) in policy_docs.into_iter().enumerate() {
1155 if p.policy.version.is_empty() {
1156 continue;
1157 }
1158
1159 let policy_name = rustfs_utils::path::dir(&chunk[idx]);
1160 debug!(policy = %policy_name, "IAM policy loaded");
1161 policy_docs_cache.insert(policy_name, p);
1162 }
1163 }
1164 }
1165
1166 let mut user_items_cache = CacheEntity::default();
1167
1168 if let Some(item_name_list) = listed_config_items.get(USERS_LIST_KEY) {
1170 for chunk in item_name_list.chunks(32) {
1173 let items = self.load_user_concurrent(chunk, UserType::Reg, LOAD_ALL_MODE).await?;
1174
1175 for (idx, p) in items.into_iter().enumerate() {
1176 if p.credentials.access_key.is_empty() {
1177 continue;
1178 }
1179
1180 let name = rustfs_utils::path::dir(&chunk[idx]);
1181 debug!(user = %name, "IAM regular user loaded");
1182 user_items_cache.insert(name, p);
1183 }
1184 }
1185 }
1186
1187 let mut groups_cache = None;
1189 if let Some(item_name_list) = listed_config_items.get(GROUPS_LIST_KEY) {
1190 let mut items_cache = CacheEntity::default();
1191
1192 for item in item_name_list.iter() {
1193 let name = rustfs_utils::path::dir(item);
1194 debug!(group = %name, "IAM group loaded");
1195 if let Err(err) = self.load_group_with(&name, &mut items_cache, LOAD_ALL_MODE).await {
1196 return Err(Error::other(format!("load group failed: {err}")));
1197 };
1198 }
1199
1200 groups_cache = Some(items_cache);
1201 }
1202
1203 let mut user_policies_cache = None;
1205 if let Some(item_name_list) = listed_config_items.get(POLICY_DB_USERS_LIST_KEY) {
1206 let mut items_cache = CacheEntity::default();
1207
1208 for chunk in item_name_list.chunks(32) {
1211 let items = self
1212 .load_mapped_policy_concurrent(chunk, UserType::Reg, false, LOAD_ALL_MODE)
1213 .await?;
1214
1215 for (idx, p) in items.into_iter().enumerate() {
1216 if p.policies.is_empty() {
1217 continue;
1218 }
1219
1220 let name = chunk[idx].trim_end_matches(".json").to_owned();
1221 debug!(user = %name, "IAM user policy loaded");
1222 items_cache.insert(name, p);
1223 }
1224 }
1225
1226 user_policies_cache = Some(items_cache);
1227 }
1228
1229 let mut group_policies_cache = None;
1231 if let Some(item_name_list) = listed_config_items.get(POLICY_DB_GROUPS_LIST_KEY) {
1232 let mut items_cache = CacheEntity::default();
1233
1234 for item in item_name_list.iter() {
1235 let name = item.trim_end_matches(".json");
1236
1237 debug!(group = %name, "IAM group policy loaded");
1238 if let Err(err) = self
1239 .load_mapped_policy_with(name, UserType::Reg, true, &mut items_cache, LOAD_ALL_MODE)
1240 .await
1241 && !is_err_no_such_policy(&err)
1242 {
1243 return Err(Error::other(format!("load group policy failed: {err}")));
1244 };
1245 }
1246
1247 group_policies_cache = Some(items_cache);
1248 }
1249
1250 let mut sts_policies_cache = CacheEntity::default();
1251
1252 if let Some(item_name_list) = listed_config_items.get(SVC_ACC_LIST_KEY) {
1254 let mut items_cache = HashMap::default();
1255
1256 for item in item_name_list.iter() {
1257 let name = rustfs_utils::path::dir(item);
1258 debug!(user = %name, "IAM service user loaded");
1259 if let Err(err) = self
1260 .load_user_with(&name, UserType::Svc, &mut items_cache, LOAD_ALL_MODE)
1261 .await
1262 && !is_err_no_such_user(&err)
1263 {
1264 return Err(Error::other(format!("load svc user failed: {err}")));
1265 };
1266 }
1267
1268 for v in items_cache.values() {
1269 let parent = v.credentials.parent_user.clone();
1270 if !user_items_cache.contains_key(&parent) {
1271 debug!(user = %parent, "IAM STS parent policy loaded");
1272 if let Err(err) = self
1273 .load_mapped_policy_with(&parent, UserType::Sts, false, &mut sts_policies_cache, LOAD_ALL_MODE)
1274 .await
1275 && !is_err_no_such_policy(&err)
1276 {
1277 return Err(Error::other(format!("load_mapped_policy failed: {err}")));
1278 }
1279 }
1280 }
1281
1282 user_items_cache.extend(items_cache);
1284 }
1285
1286 let mut sts_items_cache = CacheEntity::default();
1287 if let Some(item_name_list) = listed_config_items.get(STS_LIST_KEY) {
1289 for item in item_name_list.iter() {
1290 debug!(path = %item, "IAM STS user path discovered");
1291
1292 let name = rustfs_utils::path::dir(item);
1293 debug!(user = %name, "IAM STS user loaded");
1294 if let Err(err) = self
1295 .load_user_with(&name, UserType::Sts, &mut sts_items_cache, LOAD_ALL_MODE)
1296 .await
1297 {
1298 debug!(user = %name, error = %err, "IAM STS user load failed");
1299 };
1300 }
1301 }
1302
1303 if let Some(item_name_list) = listed_config_items.get(POLICY_DB_STS_USERS_LIST_KEY) {
1305 for item in item_name_list.iter() {
1306 let name = item.trim_end_matches(".json");
1307 debug!(user = %name, "IAM STS user policy loaded");
1308 if let Err(err) = self
1309 .load_mapped_policy_with(name, UserType::Sts, false, &mut sts_policies_cache, LOAD_ALL_MODE)
1310 .await
1311 {
1312 debug!(user = %name, error = %err, "IAM STS user policy load failed");
1313 };
1314 }
1315 }
1316
1317 cache.with_write_lock(|cache| {
1318 if cache.matches_snapshot(&cache_snapshot) {
1319 cache.replace_policy_docs(policy_docs_cache);
1320 if let Some(groups_cache) = groups_cache {
1321 cache.replace_groups(groups_cache);
1322 }
1323 if let Some(user_policies_cache) = user_policies_cache {
1324 cache.replace_user_policies(user_policies_cache);
1325 }
1326 if let Some(group_policies_cache) = group_policies_cache {
1327 cache.replace_group_policies(group_policies_cache);
1328 }
1329 cache.replace_users(user_items_cache);
1330 cache.replace_sts_accounts(sts_items_cache);
1331 cache.replace_sts_policies(sts_policies_cache);
1332 cache.build_user_group_memberships();
1333 } else {
1334 warn!("IAM full reload cache commit skipped due to concurrent cache changes");
1335 }
1336 });
1337
1338 Ok(())
1339 }
1340}
1341
1342fn map_delete_user_identity_error(name: &str, err: Error) -> Error {
1343 if is_err_config_not_found(&err) {
1344 Error::NoSuchUser(name.to_owned())
1345 } else {
1346 err
1347 }
1348}
1349
1350#[cfg(test)]
1351mod tests {
1352 use super::{DecryptSource, LoadMode, ObjectStore, map_delete_user_identity_error};
1353 use crate::error::Error;
1354 use crate::keyring;
1355 use rustfs_credentials::{Credentials, init_global_action_credentials};
1356 use serial_test::serial;
1357 use temp_env::with_vars;
1358
1359 #[test]
1364 fn test_bootstrap_load_mode_bypasses_namespace_locks() {
1365 assert!(LoadMode::BootstrapNoLock.no_lock());
1366 assert!(LoadMode::BootstrapNoLock.read_opts().no_lock);
1367 }
1368
1369 #[test]
1371 fn test_locked_load_mode_keeps_namespace_locks() {
1372 assert!(!LoadMode::Locked.no_lock());
1373 assert!(!LoadMode::Locked.read_opts().no_lock);
1374 }
1375
1376 #[test]
1377 fn missing_user_identity_delete_maps_to_no_such_user() {
1378 let err = map_delete_user_identity_error("missing-sts", Error::ConfigNotFound);
1379 assert!(matches!(err, Error::NoSuchUser(name) if name == "missing-sts"));
1380 }
1381
1382 fn test_cred() -> Credentials {
1383 if let Some(cred) = crate::root_credentials::credentials() {
1384 return cred;
1385 }
1386 let _ = init_global_action_credentials(Some("COMPATTESTAK".to_string()), Some("COMPATTESTSK1234567890".to_string()));
1387 crate::root_credentials::credentials_or_default()
1388 }
1389
1390 #[test]
1391 fn test_decrypt_data_accepts_plaintext_json() {
1392 let raw = br#"{"Version":1,"policy":"readonly"}"#;
1393 let out = ObjectStore::decrypt_data_with_source(raw).expect("plaintext json should pass through");
1394 assert_eq!(out.plain, raw);
1395 assert_eq!(out.source, DecryptSource::Plaintext);
1396 }
1397
1398 #[test]
1399 fn test_decrypt_data_accepts_rustfs_legacy_secret_encryption() {
1400 let cred = test_cred();
1401 let plain = br#"{"accessKey":"ak","secretKey":"sk"}"#;
1402 let encrypted = rustfs_crypto::encrypt_data(cred.secret_key.as_bytes(), plain).expect("encrypt with rustfs secret");
1403 let out = ObjectStore::decrypt_data_with_source(&encrypted).expect("decrypt rustfs legacy encryption");
1404 assert_eq!(out.plain, plain);
1405 }
1406
1407 #[test]
1408 fn test_decrypt_data_accepts_access_secret_encryption() {
1409 let cred = test_cred();
1410 let plain = br#"{"Version":1,"updatedAt":"2025-03-07T12:00:00Z"}"#;
1411 let root_cred = format!("{}:{}", cred.access_key, cred.secret_key);
1412 let encrypted = rustfs_crypto::encrypt_stream_io(root_cred.as_bytes(), plain).expect("encrypt with stream_io");
1413 let out = ObjectStore::decrypt_data_with_source(&encrypted).expect("decrypt stream_io");
1414 assert_eq!(out.plain, plain);
1415 }
1416
1417 #[test]
1420 fn test_try_decrypt_iam_blob_passes_plaintext_through() {
1421 let raw = br#"{"Version":1,"policy":"readonly"}"#;
1422 let out = super::try_decrypt_iam_blob(raw).expect("plaintext json should pass through");
1423 assert_eq!(out, raw);
1424 }
1425
1426 #[test]
1427 fn test_try_decrypt_iam_blob_decrypts_legacy_secret_encryption() {
1428 let cred = test_cred();
1430 let plain = br#"{"accessKey":"ak","secretKey":"sk"}"#;
1431 let encrypted = rustfs_crypto::encrypt_data(cred.secret_key.as_bytes(), plain).expect("encrypt with rustfs secret");
1432 let out = super::try_decrypt_iam_blob(&encrypted).expect("legacy-encrypted blob should decrypt");
1433 assert_eq!(out, plain);
1434 }
1435
1436 #[test]
1437 fn test_try_decrypt_iam_blob_returns_none_on_undecryptable() {
1438 let garbage = [0x00u8, 0x01, 0x02, 0x03, 0x04, 0x05];
1441 assert!(super::try_decrypt_iam_blob(&garbage).is_none());
1442 }
1443
1444 #[test]
1445 fn test_decrypt_data_corrupt_stream_io_fails() {
1446 let cred = test_cred();
1447 let plain = br#"{"Version":1}"#;
1448 let root_cred = format!("{}:{}", cred.access_key, cred.secret_key);
1449 let mut encrypted = rustfs_crypto::encrypt_stream_io(root_cred.as_bytes(), plain).expect("encrypt with stream_io");
1450 if encrypted.len() > 50 {
1451 encrypted[50] ^= 0xFF; }
1453 let result = ObjectStore::decrypt_data_with_source(&encrypted);
1454 assert!(result.is_err(), "corrupt stream_io data should fail decrypt");
1455 }
1456
1457 #[test]
1458 fn test_decrypt_data_short_data_fails() {
1459 let short = &[0x00u8; 40]; let result = ObjectStore::decrypt_data_with_source(short);
1461 assert!(result.is_err(), "short non-JSON data should fail decrypt");
1462 }
1463
1464 #[test]
1465 #[serial]
1466 fn test_prepare_data_defaults_to_plaintext_without_iam_master_key() {
1467 let plain = br#"{"Version":1,"policy":"readonly"}"#;
1468
1469 with_vars(
1470 [
1471 (keyring::ENV_IAM_MASTER_KEY, None::<&str>),
1472 (keyring::ENV_IAM_MASTER_KEY_OLD_KEYS, None::<&str>),
1473 ],
1474 || {
1475 let stored = ObjectStore::prepare_data_for_storage_for_test(plain).expect("store bytes should build");
1476 assert_eq!(stored, plain);
1477
1478 let decrypted = ObjectStore::decrypt_data_with_source(&stored).expect("plaintext should load");
1479 assert_eq!(plain, decrypted.plain.as_slice());
1480 assert_eq!(decrypted.source, DecryptSource::Plaintext);
1481 },
1482 );
1483 }
1484
1485 #[test]
1486 #[serial]
1487 fn test_prepare_data_uses_iam_master_key_roundtrip() {
1488 let _ = test_cred();
1489 let plain = br#"{"Version":1,"policy":"master-key"}"#;
1490 let master_key = "iam-master-key-roundtrip";
1491
1492 with_vars(
1493 [
1494 (keyring::ENV_IAM_MASTER_KEY, Some(master_key)),
1495 (keyring::ENV_IAM_MASTER_KEY_OLD_KEYS, None),
1496 ],
1497 || {
1498 let encrypted = ObjectStore::prepare_data_for_storage_for_test(plain).expect("encrypt with iam master key");
1499
1500 let by_master =
1501 rustfs_crypto::decrypt_stream_io(master_key.as_bytes(), &encrypted).expect("decrypt via master key");
1502 assert_eq!(by_master, plain);
1503
1504 let by_object_store = ObjectStore::decrypt_data_with_source(&encrypted).expect("decrypt via object store");
1505 assert_eq!(by_object_store.plain, plain);
1506 assert_eq!(by_object_store.source, DecryptSource::CurrentMasterKey);
1507 },
1508 );
1509 }
1510
1511 #[test]
1512 #[serial]
1513 fn test_decrypt_data_uses_iam_old_keys_fallback_during_rotation() {
1514 let _ = test_cred();
1515 let plain = br#"{"Version":1,"policy":"rotation-fallback"}"#;
1516 let current_key = "iam-master-key-new";
1517 let old_key_used_for_data = "iam-master-key-old-2";
1518 let old_keys = format!("iam-master-key-old-1,{old_key_used_for_data}");
1519
1520 let encrypted = rustfs_crypto::encrypt_stream_io(old_key_used_for_data.as_bytes(), plain)
1521 .expect("encrypt with old iam key for rotation simulation");
1522
1523 assert!(
1524 rustfs_crypto::decrypt_stream_io(current_key.as_bytes(), &encrypted).is_err(),
1525 "current master key should not decrypt old-key encrypted data in this test"
1526 );
1527
1528 with_vars(
1529 [
1530 (keyring::ENV_IAM_MASTER_KEY, Some(current_key)),
1531 (keyring::ENV_IAM_MASTER_KEY_OLD_KEYS, Some(old_keys.as_str())),
1532 ],
1533 || {
1534 let decrypted = ObjectStore::decrypt_data_with_source(&encrypted).expect("decrypt via old-key fallback");
1535 assert_eq!(decrypted.plain, plain);
1536 assert_eq!(decrypted.source, DecryptSource::OldMasterKey);
1537 },
1538 );
1539 }
1540}