Skip to main content

rustfs_iam/
lib.rs

1// Copyright 2024 RustFS Team
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::error::{Error, Result};
16use manager::IamCache;
17use oidc::{OidcExtraRootCaProvider, OidcSys};
18use std::sync::{Arc, OnceLock};
19use store::object::ObjectStore;
20use sys::IamSys;
21use tracing::{debug, error, info, instrument, warn};
22
23const LOG_COMPONENT_IAM: &str = "iam";
24const LOG_SUBSYSTEM_RUNTIME: &str = "runtime";
25const LOG_SUBSYSTEM_OIDC: &str = "oidc";
26const EVENT_IAM_STATE: &str = "iam_state";
27const EVENT_OIDC_STATE: &str = "oidc_state";
28
29pub mod cache;
30pub mod error;
31pub mod federation;
32pub mod keyring;
33pub mod manager;
34pub mod mfa;
35pub mod oidc;
36pub mod oidc_state;
37mod root_credentials;
38mod runtime_sources;
39mod server_config;
40mod storage_api;
41pub mod store;
42pub mod sys;
43pub mod utils;
44pub(crate) use storage_api::crate_boundary::{
45    IAM_CONFIG_ROOT_PREFIX, IamEcstoreError, IamStorageError, IamStore, classify_iam_system_path_failure_reason,
46    delete_iam_config, is_iam_first_cluster_node_local, read_iam_config_no_lock, read_iam_config_with_metadata, save_iam_config,
47    save_iam_config_with_opts,
48};
49
50pub fn is_root_access_key(access_key: &str) -> bool {
51    root_credentials::is_root_access_key(access_key)
52}
53
54/// Decrypts an at-rest IAM config blob using the same key sources as the IAM load
55/// path (RustFS master keys and MinIO-compatible legacy keys derived from the root
56/// credentials). Used by the MinIO -> RustFS migration path. See
57/// [`store::object::try_decrypt_iam_blob`].
58pub use store::object::try_decrypt_iam_blob;
59
60pub(crate) struct IamNotificationPeerErr {
61    pub(crate) err: Option<IamEcstoreError>,
62}
63
64impl From<storage_api::crate_boundary::IamEcstoreNotificationPeerErr> for IamNotificationPeerErr {
65    fn from(value: storage_api::crate_boundary::IamEcstoreNotificationPeerErr) -> Self {
66        Self { err: value.err }
67    }
68}
69
70pub(crate) async fn notify_iam_delete_policy(policy_name: &str) -> Vec<IamNotificationPeerErr> {
71    match runtime_sources::notification_sys() {
72        Some(notification_sys) => notification_sys
73            .delete_policy(policy_name)
74            .await
75            .into_iter()
76            .map(Into::into)
77            .collect(),
78        None => Vec::new(),
79    }
80}
81
82pub(crate) async fn notify_iam_load_policy(policy_name: &str) -> Vec<IamNotificationPeerErr> {
83    match runtime_sources::notification_sys() {
84        Some(notification_sys) => notification_sys
85            .load_policy(policy_name)
86            .await
87            .into_iter()
88            .map(Into::into)
89            .collect(),
90        None => Vec::new(),
91    }
92}
93
94pub(crate) async fn notify_iam_delete_user(access_key: &str) -> Vec<IamNotificationPeerErr> {
95    match runtime_sources::notification_sys() {
96        Some(notification_sys) => notification_sys
97            .delete_user(access_key)
98            .await
99            .into_iter()
100            .map(Into::into)
101            .collect(),
102        None => Vec::new(),
103    }
104}
105
106#[cfg(test)]
107pub(crate) struct LoadUserNotificationProbe {
108    pub(crate) observed: std::sync::Mutex<Option<(String, bool)>>,
109    pub(crate) remaining_failures: std::sync::atomic::AtomicUsize,
110    pub(crate) attempts: std::sync::atomic::AtomicUsize,
111    pub(crate) panic: bool,
112    pub(crate) started: tokio::sync::Notify,
113    pub(crate) release: Option<tokio::sync::Notify>,
114    pub(crate) completed: tokio::sync::Notify,
115}
116
117#[cfg(test)]
118tokio::task_local! {
119    pub(crate) static LOAD_USER_NOTIFICATION_PROBE: std::sync::Arc<LoadUserNotificationProbe>;
120}
121
122pub(crate) async fn notify_iam_load_user(access_key: &str, temp: bool) -> Vec<IamNotificationPeerErr> {
123    #[cfg(test)]
124    if let Ok(probe) = LOAD_USER_NOTIFICATION_PROBE.try_with(std::sync::Arc::clone) {
125        probe.attempts.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
126        *probe.observed.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = Some((access_key.to_string(), temp));
127        probe.started.notify_one();
128        if let Some(release) = &probe.release {
129            release.notified().await;
130        }
131        assert!(!probe.panic, "notification probe panic");
132        let should_fail = probe
133            .remaining_failures
134            .try_update(std::sync::atomic::Ordering::SeqCst, std::sync::atomic::Ordering::SeqCst, |remaining| {
135                remaining.checked_sub(1)
136            })
137            .is_ok();
138        let result = if should_fail {
139            vec![IamNotificationPeerErr {
140                err: Some(IamEcstoreError::other("peer notification failed")),
141            }]
142        } else {
143            Vec::new()
144        };
145        probe.completed.notify_one();
146        return result;
147    }
148
149    match runtime_sources::notification_sys() {
150        Some(notification_sys) => notification_sys
151            .load_user(access_key, temp)
152            .await
153            .into_iter()
154            .map(Into::into)
155            .collect(),
156        None => Vec::new(),
157    }
158}
159
160pub(crate) async fn notify_iam_load_service_account(access_key: &str) -> Vec<IamNotificationPeerErr> {
161    match runtime_sources::notification_sys() {
162        Some(notification_sys) => notification_sys
163            .load_service_account(access_key)
164            .await
165            .into_iter()
166            .map(Into::into)
167            .collect(),
168        None => Vec::new(),
169    }
170}
171
172pub(crate) async fn notify_iam_load_group(group: &str) -> Vec<IamNotificationPeerErr> {
173    match runtime_sources::notification_sys() {
174        Some(notification_sys) => notification_sys.load_group(group).await.into_iter().map(Into::into).collect(),
175        None => Vec::new(),
176    }
177}
178
179pub(crate) async fn notify_iam_load_policy_mapping(
180    user_or_group: &str,
181    user_type: u64,
182    is_group: bool,
183) -> Vec<IamNotificationPeerErr> {
184    match runtime_sources::notification_sys() {
185        Some(notification_sys) => notification_sys
186            .load_policy_mapping(user_or_group, user_type, is_group)
187            .await
188            .into_iter()
189            .map(Into::into)
190            .collect(),
191        None => Vec::new(),
192    }
193}
194
195static IAM_SYS: OnceLock<Arc<IamSys<ObjectStore>>> = OnceLock::new();
196static OIDC_SYS: OnceLock<Arc<OidcSys>> = OnceLock::new();
197
198/// Build an IAM system bound to the given store without touching the process
199/// singleton (backlog#1052 S3): a per-server context can own the returned
200/// handle while the singleton keeps serving ambient readers.
201#[instrument(skip(ecstore))]
202pub async fn build_iam_sys(ecstore: Arc<IamStore>) -> Result<Arc<IamSys<ObjectStore>>> {
203    // 1. Create the persistent storage adapter
204    let storage_adapter = ObjectStore::new(ecstore);
205
206    // 2. Create the cache manager.
207    // The `new` method now performs a blocking initial load from disk.
208    let cache_manager = IamCache::new(storage_adapter).await?;
209
210    // 3. Construct the system interface
211    Ok(Arc::new(IamSys::new(cache_manager)))
212}
213
214/// Build an IAM system for an application context and publish the first one
215/// as the ambient compatibility default.
216#[instrument(skip(ecstore))]
217pub async fn init_iam_sys_for_context(ecstore: Arc<IamStore>) -> Result<Arc<IamSys<ObjectStore>>> {
218    let iam_instance = build_iam_sys(ecstore).await?;
219    let _ = IAM_SYS.set(iam_instance.clone());
220    Ok(iam_instance)
221}
222
223#[instrument(skip(ecstore))]
224pub async fn init_iam_sys(ecstore: Arc<IamStore>) -> Result<Arc<IamSys<ObjectStore>>> {
225    if let Some(existing) = IAM_SYS.get() {
226        info!(
227            event = EVENT_IAM_STATE,
228            component = LOG_COMPONENT_IAM,
229            subsystem = LOG_SUBSYSTEM_RUNTIME,
230            state = "already_initialized",
231            "IAM runtime already initialized"
232        );
233        return Ok(existing.clone());
234    }
235
236    info!(
237        event = EVENT_IAM_STATE,
238        component = LOG_COMPONENT_IAM,
239        subsystem = LOG_SUBSYSTEM_RUNTIME,
240        state = "starting",
241        "IAM runtime starting"
242    );
243
244    let iam_instance = build_iam_sys(ecstore).await?;
245
246    // Securely set the global singleton
247    if IAM_SYS.set(iam_instance.clone()).is_err() {
248        error!(
249            event = EVENT_IAM_STATE,
250            component = LOG_COMPONENT_IAM,
251            subsystem = LOG_SUBSYSTEM_RUNTIME,
252            state = "singleton_set_failed",
253            "IAM runtime singleton set failed"
254        );
255        return Err(Error::IamSysAlreadyInitialized);
256    }
257
258    info!(
259        event = EVENT_IAM_STATE,
260        component = LOG_COMPONENT_IAM,
261        subsystem = LOG_SUBSYSTEM_RUNTIME,
262        state = "ready",
263        "IAM runtime ready"
264    );
265    Ok(iam_instance)
266}
267
268#[inline]
269pub fn get() -> Result<Arc<IamSys<ObjectStore>>> {
270    let sys = IAM_SYS.get().map(Arc::clone).ok_or(Error::IamSysNotInitialized)?;
271
272    // Double-check the internal readiness state. The OnceLock is only set
273    // after initialization and data loading complete, so this is a defensive
274    // guard to ensure callers never operate on a partially initialized system.
275    if !sys.is_ready() {
276        return Err(Error::IamSysNotInitialized);
277    }
278
279    Ok(sys)
280}
281
282pub fn get_global_iam_sys() -> Option<Arc<IamSys<ObjectStore>>> {
283    IAM_SYS.get().cloned()
284}
285
286/// Initialize the global OIDC system. Non-fatal if no OIDC providers are configured.
287pub async fn init_oidc_sys() -> Result<()> {
288    init_oidc_sys_with_extra_root_ca(None).await
289}
290
291/// Initialize the global OIDC system with an additional outbound root CA bundle.
292pub async fn init_oidc_sys_with_extra_root_ca(root_ca_pem: Option<&[u8]>) -> Result<()> {
293    init_oidc_sys_with_extra_root_ca_provider_inner(None, root_ca_pem).await
294}
295
296/// Initialize the global OIDC system with a reload-aware outbound root CA provider.
297pub async fn init_oidc_sys_with_extra_root_ca_provider(extra_root_ca_provider: OidcExtraRootCaProvider) -> Result<()> {
298    init_oidc_sys_with_extra_root_ca_provider_inner(Some(extra_root_ca_provider), None).await
299}
300
301async fn init_oidc_sys_with_extra_root_ca_provider_inner(
302    extra_root_ca_provider: Option<OidcExtraRootCaProvider>,
303    root_ca_pem: Option<&[u8]>,
304) -> Result<()> {
305    if OIDC_SYS.get().is_some() {
306        debug!(
307            event = EVENT_OIDC_STATE,
308            component = LOG_COMPONENT_IAM,
309            subsystem = LOG_SUBSYSTEM_OIDC,
310            state = "already_initialized",
311            "OIDC runtime already initialized"
312        );
313        return Ok(());
314    }
315
316    debug!(
317        event = EVENT_OIDC_STATE,
318        component = LOG_COMPONENT_IAM,
319        subsystem = LOG_SUBSYSTEM_OIDC,
320        state = "starting",
321        "OIDC runtime starting"
322    );
323
324    let oidc_sys_result = match extra_root_ca_provider {
325        Some(provider) => OidcSys::new_with_extra_root_ca_provider(provider).await,
326        None => OidcSys::new_with_extra_root_ca(root_ca_pem).await,
327    };
328    let oidc_sys = match oidc_sys_result {
329        Ok(sys) => {
330            if sys.has_providers() {
331                debug!(
332                    event = EVENT_OIDC_STATE,
333                    component = LOG_COMPONENT_IAM,
334                    subsystem = LOG_SUBSYSTEM_OIDC,
335                    provider_count = sys.list_providers().len(),
336                    state = "ready",
337                    "OIDC runtime ready"
338                );
339            } else {
340                debug!(
341                    event = EVENT_OIDC_STATE,
342                    component = LOG_COMPONENT_IAM,
343                    subsystem = LOG_SUBSYSTEM_OIDC,
344                    state = "empty",
345                    "OIDC runtime has no providers"
346                );
347            }
348            sys
349        }
350        Err(e) => {
351            warn!(
352                event = EVENT_OIDC_STATE,
353                component = LOG_COMPONENT_IAM,
354                subsystem = LOG_SUBSYSTEM_OIDC,
355                state = "init_failed_non_fatal",
356                error = %e,
357                "OIDC runtime initialization failed"
358            );
359            OidcSys::empty().map_err(Error::StringError)?
360        }
361    };
362
363    if OIDC_SYS.set(Arc::new(oidc_sys)).is_err() {
364        warn!(
365            event = EVENT_OIDC_STATE,
366            component = LOG_COMPONENT_IAM,
367            subsystem = LOG_SUBSYSTEM_OIDC,
368            state = "singleton_set_race",
369            "OIDC runtime singleton set raced"
370        );
371    }
372
373    Ok(())
374}
375
376/// Get the global OIDC system.
377pub fn get_oidc() -> Option<Arc<OidcSys>> {
378    OIDC_SYS.get().cloned()
379}