Skip to main content

rustfs_iam/
cache.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 std::{
16    collections::{HashMap, HashSet},
17    ops::{Deref, DerefMut},
18    ptr,
19    sync::{Arc, Mutex, Weak},
20};
21
22use arc_swap::{ArcSwap, Guard};
23use rustfs_policy::{
24    auth::UserIdentity,
25    policy::{Args, PolicyDoc},
26};
27use time::OffsetDateTime;
28use tokio::sync::Mutex as AsyncMutex;
29use tracing::warn;
30
31use crate::store::{GroupInfo, MappedPolicy};
32
33/// Immutable IAM cache snapshot published atomically by [`Cache`].
34///
35/// Readers should load one `CacheState` and read all related maps from it. Writers
36/// must go through `Cache`/`LockedCache` so multi-map updates publish as one state.
37#[derive(Clone)]
38pub(crate) struct CacheState {
39    pub(crate) policy_docs: Arc<CacheEntity<PolicyDoc>>,
40    pub(crate) users: Arc<CacheEntity<UserIdentity>>,
41    pub(crate) user_policies: Arc<CacheEntity<MappedPolicy>>,
42    pub(crate) sts_accounts: Arc<CacheEntity<UserIdentity>>,
43    pub(crate) sts_policies: Arc<CacheEntity<MappedPolicy>>,
44    pub(crate) groups: Arc<CacheEntity<GroupInfo>>,
45    pub(crate) user_group_memberships: Arc<CacheEntity<HashSet<String>>>,
46    pub(crate) group_policies: Arc<CacheEntity<MappedPolicy>>,
47}
48
49impl Default for CacheState {
50    fn default() -> Self {
51        Self {
52            policy_docs: Arc::new(CacheEntity::default()),
53            users: Arc::new(CacheEntity::default()),
54            user_policies: Arc::new(CacheEntity::default()),
55            sts_accounts: Arc::new(CacheEntity::default()),
56            sts_policies: Arc::new(CacheEntity::default()),
57            groups: Arc::new(CacheEntity::default()),
58            user_group_memberships: Arc::new(CacheEntity::default()),
59            group_policies: Arc::new(CacheEntity::default()),
60        }
61    }
62}
63
64pub struct Cache {
65    state: ArcSwap<CacheState>,
66    write_lock: Mutex<()>,
67    service_account_mutation_lock: AsyncMutex<()>,
68    sts_account_mutation_locks: Arc<StsMutationLockRegistry>,
69}
70
71struct StsMutationLockRegistry {
72    locks: Mutex<HashMap<String, Weak<AsyncMutex<StsMutationLockState>>>>,
73}
74
75pub(crate) struct StsMutationLockState {
76    access_key: String,
77    registry: Weak<StsMutationLockRegistry>,
78    lock: Weak<AsyncMutex<StsMutationLockState>>,
79}
80
81impl Drop for StsMutationLockState {
82    fn drop(&mut self) {
83        let Some(registry) = self.registry.upgrade() else {
84            return;
85        };
86        let mut locks = registry.locks.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
87        if locks.get(&self.access_key).is_some_and(|current| current.ptr_eq(&self.lock)) {
88            locks.remove(&self.access_key);
89        }
90    }
91}
92
93impl Default for Cache {
94    fn default() -> Self {
95        Self {
96            state: ArcSwap::new(Arc::new(CacheState::default())),
97            write_lock: Mutex::new(()),
98            service_account_mutation_lock: AsyncMutex::new(()),
99            sts_account_mutation_locks: Arc::new(StsMutationLockRegistry {
100                locks: Mutex::new(HashMap::new()),
101            }),
102        }
103    }
104}
105
106pub(crate) type CacheSnapshot = Guard<Arc<CacheState>>;
107
108impl Cache {
109    pub(crate) fn service_account_mutation_lock(&self) -> &AsyncMutex<()> {
110        &self.service_account_mutation_lock
111    }
112
113    pub(crate) fn sts_account_mutation_lock(&self, access_key: &str) -> Arc<AsyncMutex<StsMutationLockState>> {
114        let mut locks = self
115            .sts_account_mutation_locks
116            .locks
117            .lock()
118            .unwrap_or_else(|poisoned| poisoned.into_inner());
119        if let Some(lock) = locks.get(access_key).and_then(Weak::upgrade) {
120            return lock;
121        }
122
123        let registry = Arc::downgrade(&self.sts_account_mutation_locks);
124        let access_key_owned = access_key.to_string();
125        let lock = Arc::new_cyclic(|lock| {
126            AsyncMutex::new(StsMutationLockState {
127                access_key: access_key_owned,
128                registry,
129                lock: lock.clone(),
130            })
131        });
132        locks.insert(access_key.to_string(), Arc::downgrade(&lock));
133        lock
134    }
135
136    pub(crate) fn snapshot(&self) -> CacheSnapshot {
137        self.state.load()
138    }
139
140    pub(crate) fn with_write_lock<R>(&self, f: impl FnOnce(&mut LockedCache) -> R) -> R {
141        let _guard = self.write_lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
142        let current = self.state.load_full();
143        let mut locked = LockedCache {
144            state: CacheState::clone(&current),
145            current_ptr: Arc::as_ptr(&current),
146            dirty: false,
147        };
148        let ret = f(&mut locked);
149        if locked.dirty {
150            self.state.store(Arc::new(locked.state));
151        }
152        ret
153    }
154
155    pub fn add_or_update_policy_doc(&self, key: &str, value: &PolicyDoc, t: OffsetDateTime) {
156        self.with_write_lock(|cache| cache.add_or_update_policy_doc(key, value, t));
157    }
158
159    pub fn add_or_update_user(&self, key: &str, value: &UserIdentity, t: OffsetDateTime) {
160        self.with_write_lock(|cache| cache.add_or_update_user(key, value, t));
161    }
162
163    pub fn add_or_update_user_policy(&self, key: &str, value: &MappedPolicy, t: OffsetDateTime) {
164        self.with_write_lock(|cache| cache.add_or_update_user_policy(key, value, t));
165    }
166
167    pub fn add_or_update_sts_account(&self, key: &str, value: &UserIdentity, t: OffsetDateTime) {
168        self.with_write_lock(|cache| cache.add_or_update_sts_account(key, value, t));
169    }
170
171    pub fn add_or_update_sts_policy(&self, key: &str, value: &MappedPolicy, t: OffsetDateTime) {
172        self.with_write_lock(|cache| cache.add_or_update_sts_policy(key, value, t));
173    }
174
175    pub fn add_or_update_group(&self, key: &str, value: &GroupInfo, t: OffsetDateTime) {
176        self.with_write_lock(|cache| cache.add_or_update_group(key, value, t));
177    }
178
179    pub fn add_or_update_user_group_membership(&self, key: &str, value: &HashSet<String>, t: OffsetDateTime) {
180        self.with_write_lock(|cache| cache.add_or_update_user_group_membership(key, value, t));
181    }
182
183    pub fn add_or_update_group_policy(&self, key: &str, value: &MappedPolicy, t: OffsetDateTime) {
184        self.with_write_lock(|cache| cache.add_or_update_group_policy(key, value, t));
185    }
186
187    pub fn delete_policy_doc(&self, key: &str, t: OffsetDateTime) {
188        self.with_write_lock(|cache| cache.delete_policy_doc(key, t));
189    }
190
191    pub fn delete_user(&self, key: &str, t: OffsetDateTime) {
192        self.with_write_lock(|cache| cache.delete_user(key, t));
193    }
194
195    pub fn delete_user_policy(&self, key: &str, t: OffsetDateTime) {
196        self.with_write_lock(|cache| cache.delete_user_policy(key, t));
197    }
198
199    pub fn delete_sts_account(&self, key: &str, t: OffsetDateTime) {
200        self.with_write_lock(|cache| cache.delete_sts_account(key, t));
201    }
202
203    pub fn delete_sts_policy(&self, key: &str, t: OffsetDateTime) {
204        self.with_write_lock(|cache| cache.delete_sts_policy(key, t));
205    }
206
207    pub fn delete_group(&self, key: &str, t: OffsetDateTime) {
208        self.with_write_lock(|cache| cache.delete_group(key, t));
209    }
210
211    pub fn delete_group_policy(&self, key: &str, t: OffsetDateTime) {
212        self.with_write_lock(|cache| cache.delete_group_policy(key, t));
213    }
214}
215
216pub(crate) struct LockedCache {
217    state: CacheState,
218    current_ptr: *const CacheState,
219    dirty: bool,
220}
221
222impl LockedCache {
223    pub(crate) fn state(&self) -> &CacheState {
224        &self.state
225    }
226
227    pub(crate) fn matches_snapshot(&self, snapshot: &CacheSnapshot) -> bool {
228        ptr::eq(self.current_ptr, Arc::as_ptr(snapshot))
229    }
230
231    fn exec<T: Clone>(target: &mut Arc<CacheEntity<T>>, t: OffsetDateTime, mut op: impl FnMut(&mut CacheEntity<T>)) -> bool {
232        if target.load_time >= t {
233            return false;
234        }
235
236        let mut new = CacheEntity::clone(target);
237        op(&mut new);
238        *target = Arc::new(new);
239        true
240    }
241
242    fn replaced<T>(value: CacheEntity<T>) -> Arc<CacheEntity<T>> {
243        Arc::new(value.update_load_time())
244    }
245
246    pub(crate) fn replace_policy_docs(&mut self, value: CacheEntity<PolicyDoc>) {
247        self.state.policy_docs = Self::replaced(value);
248        self.dirty = true;
249    }
250
251    pub(crate) fn replace_users(&mut self, value: CacheEntity<UserIdentity>) {
252        self.state.users = Self::replaced(value);
253        self.dirty = true;
254    }
255
256    pub(crate) fn replace_user_policies(&mut self, value: CacheEntity<MappedPolicy>) {
257        self.state.user_policies = Self::replaced(value);
258        self.dirty = true;
259    }
260
261    pub(crate) fn replace_sts_accounts(&mut self, value: CacheEntity<UserIdentity>) {
262        self.state.sts_accounts = Self::replaced(value);
263        self.dirty = true;
264    }
265
266    pub(crate) fn replace_sts_policies(&mut self, value: CacheEntity<MappedPolicy>) {
267        self.state.sts_policies = Self::replaced(value);
268        self.dirty = true;
269    }
270
271    pub(crate) fn replace_groups(&mut self, value: CacheEntity<GroupInfo>) {
272        self.state.groups = Self::replaced(value);
273        self.dirty = true;
274    }
275
276    pub(crate) fn replace_group_policies(&mut self, value: CacheEntity<MappedPolicy>) {
277        self.state.group_policies = Self::replaced(value);
278        self.dirty = true;
279    }
280
281    pub(crate) fn replace_user_group_memberships(&mut self, value: CacheEntity<HashSet<String>>) {
282        self.state.user_group_memberships = Self::replaced(value);
283        self.dirty = true;
284    }
285
286    pub(crate) fn add_or_update_policy_doc(&mut self, key: &str, value: &PolicyDoc, t: OffsetDateTime) {
287        self.dirty |= Self::exec(&mut self.state.policy_docs, t, |map| {
288            map.insert(key.to_string(), value.clone());
289        });
290    }
291
292    pub(crate) fn add_or_update_user(&mut self, key: &str, value: &UserIdentity, t: OffsetDateTime) {
293        self.dirty |= Self::exec(&mut self.state.users, t, |map| {
294            map.insert(key.to_string(), value.clone());
295        });
296    }
297
298    pub(crate) fn add_or_update_user_policy(&mut self, key: &str, value: &MappedPolicy, t: OffsetDateTime) {
299        self.dirty |= Self::exec(&mut self.state.user_policies, t, |map| {
300            map.insert(key.to_string(), value.clone());
301        });
302    }
303
304    pub(crate) fn add_or_update_sts_account(&mut self, key: &str, value: &UserIdentity, t: OffsetDateTime) {
305        self.dirty |= Self::exec(&mut self.state.sts_accounts, t, |map| {
306            map.insert(key.to_string(), value.clone());
307        });
308    }
309
310    pub(crate) fn add_or_update_sts_policy(&mut self, key: &str, value: &MappedPolicy, t: OffsetDateTime) {
311        self.dirty |= Self::exec(&mut self.state.sts_policies, t, |map| {
312            map.insert(key.to_string(), value.clone());
313        });
314    }
315
316    pub(crate) fn add_or_update_group(&mut self, key: &str, value: &GroupInfo, t: OffsetDateTime) {
317        self.dirty |= Self::exec(&mut self.state.groups, t, |map| {
318            map.insert(key.to_string(), value.clone());
319        });
320    }
321
322    pub(crate) fn add_or_update_user_group_membership(&mut self, key: &str, value: &HashSet<String>, t: OffsetDateTime) {
323        self.dirty |= Self::exec(&mut self.state.user_group_memberships, t, |map| {
324            map.insert(key.to_string(), value.clone());
325        });
326    }
327
328    pub(crate) fn add_or_update_group_policy(&mut self, key: &str, value: &MappedPolicy, t: OffsetDateTime) {
329        self.dirty |= Self::exec(&mut self.state.group_policies, t, |map| {
330            map.insert(key.to_string(), value.clone());
331        });
332    }
333
334    pub(crate) fn delete_policy_doc(&mut self, key: &str, t: OffsetDateTime) {
335        self.dirty |= Self::exec(&mut self.state.policy_docs, t, |map| {
336            map.remove(key);
337        });
338    }
339
340    pub(crate) fn delete_user(&mut self, key: &str, t: OffsetDateTime) {
341        self.dirty |= Self::exec(&mut self.state.users, t, |map| {
342            map.remove(key);
343        });
344    }
345
346    pub(crate) fn delete_user_policy(&mut self, key: &str, t: OffsetDateTime) {
347        self.dirty |= Self::exec(&mut self.state.user_policies, t, |map| {
348            map.remove(key);
349        });
350    }
351
352    pub(crate) fn delete_user_group_membership(&mut self, key: &str, t: OffsetDateTime) {
353        self.dirty |= Self::exec(&mut self.state.user_group_memberships, t, |map| {
354            map.remove(key);
355        });
356    }
357
358    pub(crate) fn delete_sts_account(&mut self, key: &str, t: OffsetDateTime) {
359        self.dirty |= Self::exec(&mut self.state.sts_accounts, t, |map| {
360            map.remove(key);
361        });
362    }
363
364    pub(crate) fn delete_sts_policy(&mut self, key: &str, t: OffsetDateTime) {
365        self.dirty |= Self::exec(&mut self.state.sts_policies, t, |map| {
366            map.remove(key);
367        });
368    }
369
370    pub(crate) fn delete_group(&mut self, key: &str, t: OffsetDateTime) {
371        self.dirty |= Self::exec(&mut self.state.groups, t, |map| {
372            map.remove(key);
373        });
374    }
375
376    pub(crate) fn delete_group_policy(&mut self, key: &str, t: OffsetDateTime) {
377        self.dirty |= Self::exec(&mut self.state.group_policies, t, |map| {
378            map.remove(key);
379        });
380    }
381
382    pub(crate) fn build_user_group_memberships(&mut self) {
383        let groups = Arc::clone(&self.state.groups);
384        let mut user_group_memberships = HashMap::new();
385        for (group_name, group) in groups.iter() {
386            for user_name in &group.members {
387                user_group_memberships
388                    .entry(user_name.clone())
389                    .or_insert_with(HashSet::new)
390                    .insert(group_name.clone());
391            }
392        }
393        self.replace_user_group_memberships(CacheEntity::new(user_group_memberships));
394    }
395}
396
397impl CacheInner {
398    #[inline]
399    pub fn get_user(&self, user_name: &str) -> Option<&UserIdentity> {
400        self.snapshot
401            .users
402            .get(user_name)
403            .or_else(|| self.snapshot.sts_accounts.get(user_name))
404    }
405
406    // todo
407    pub fn is_allowed_sts(&self, _args: &Args, _parent: &str) -> bool {
408        warn!("policy cache STS check path is not implemented");
409        false
410    }
411
412    // todo
413    pub fn is_allowed_service_account(&self, _args: &Args, _parent: &str) -> bool {
414        warn!("policy cache service account check path is not implemented");
415        false
416    }
417
418    pub fn is_allowed(&self, _args: Args) -> bool {
419        warn!("policy cache is_allowed check path is currently denied by default");
420        false
421    }
422
423    pub fn policy_db_get(&self, _name: &str, _groups: &[String]) -> Vec<String> {
424        warn!("policy cache policy_db_get is not implemented, returning empty policy set");
425        vec![]
426    }
427}
428
429#[derive(Clone)]
430pub struct CacheEntity<T> {
431    map: HashMap<String, T>,
432    /// The time of the reload
433    load_time: OffsetDateTime,
434}
435
436impl<T> Deref for CacheEntity<T> {
437    type Target = HashMap<String, T>;
438    fn deref(&self) -> &Self::Target {
439        &self.map
440    }
441}
442
443impl<T> DerefMut for CacheEntity<T> {
444    fn deref_mut(&mut self) -> &mut Self::Target {
445        &mut self.map
446    }
447}
448
449impl<T> CacheEntity<T> {
450    pub fn new(map: HashMap<String, T>) -> Self {
451        Self {
452            map,
453            load_time: OffsetDateTime::UNIX_EPOCH,
454        }
455    }
456}
457
458impl<T> Default for CacheEntity<T> {
459    fn default() -> Self {
460        Self {
461            map: HashMap::new(),
462            load_time: OffsetDateTime::UNIX_EPOCH,
463        }
464    }
465}
466
467impl<T> CacheEntity<T> {
468    pub fn update_load_time(mut self) -> Self {
469        self.load_time = OffsetDateTime::now_utc();
470        self
471    }
472}
473
474pub struct CacheInner {
475    snapshot: CacheSnapshot,
476}
477
478impl From<&Cache> for CacheInner {
479    fn from(value: &Cache) -> Self {
480        Self {
481            snapshot: value.snapshot(),
482        }
483    }
484}
485
486#[cfg(test)]
487mod tests {
488    use std::sync::Arc;
489
490    use futures::future::join_all;
491    use rustfs_policy::auth::UserIdentity;
492    use time::OffsetDateTime;
493
494    use crate::cache::Cache;
495    use crate::store::MappedPolicy;
496
497    #[test]
498    fn sts_mutation_locks_are_keyed_and_prune_unused_entries() {
499        let cache = Cache::default();
500        let first = cache.sts_account_mutation_lock("first");
501        let same = cache.sts_account_mutation_lock("first");
502        let different = cache.sts_account_mutation_lock("different");
503
504        assert!(Arc::ptr_eq(&first, &same));
505        assert!(!Arc::ptr_eq(&first, &different));
506        drop(first);
507        drop(same);
508        drop(different);
509
510        let _next = cache.sts_account_mutation_lock("next");
511        let locks = cache
512            .sts_account_mutation_locks
513            .locks
514            .lock()
515            .expect("STS mutation lock registry mutex poisoned");
516        assert!(!locks.contains_key("first"));
517        assert!(!locks.contains_key("different"));
518        assert!(locks.contains_key("next"));
519    }
520
521    #[tokio::test]
522    async fn test_cache_entity_add() {
523        let owner = Arc::new(Cache::default());
524
525        let mut f = vec![];
526
527        for (index, key) in (0..100).map(|x| x.to_string()).enumerate() {
528            let owner = Arc::clone(&owner);
529            f.push(async move {
530                let user = UserIdentity {
531                    version: index as i64,
532                    ..Default::default()
533                };
534                owner.add_or_update_user(&key, &user, OffsetDateTime::now_utc());
535            });
536        }
537        join_all(f).await;
538
539        let cache = owner.snapshot();
540        for (index, key) in (0..100).map(|x| x.to_string()).enumerate() {
541            assert_eq!(cache.users.get(&key).map(|user| user.version), Some(index as i64));
542        }
543    }
544
545    #[tokio::test]
546    async fn test_cache_entity_update() {
547        let owner = Arc::new(Cache::default());
548
549        let mut f = vec![];
550
551        for (index, key) in (0..100).map(|x| x.to_string()).enumerate() {
552            let owner = Arc::clone(&owner);
553            f.push(async move {
554                let user = UserIdentity {
555                    version: index as i64,
556                    ..Default::default()
557                };
558                owner.add_or_update_user(&key, &user, OffsetDateTime::now_utc());
559            });
560        }
561        join_all(f).await;
562
563        let cache_load = owner.snapshot();
564        for (index, key) in (0..100).map(|x| x.to_string()).enumerate() {
565            assert_eq!(cache_load.users.get(&key).map(|user| user.version), Some(index as i64));
566        }
567
568        let mut f = vec![];
569
570        for (index, key) in (0..100).map(|x| x.to_string()).enumerate() {
571            let owner = Arc::clone(&owner);
572            f.push(async move {
573                let user = UserIdentity {
574                    version: (index * 1000) as i64,
575                    ..Default::default()
576                };
577                owner.add_or_update_user(&key, &user, OffsetDateTime::now_utc());
578            });
579        }
580        join_all(f).await;
581
582        let cache_load = owner.snapshot();
583        for (index, key) in (0..100).map(|x| x.to_string()).enumerate() {
584            assert_eq!(cache_load.users.get(&key).map(|user| user.version), Some((index * 1000) as i64));
585        }
586    }
587
588    #[tokio::test]
589    async fn test_cache_entity_delete() {
590        let owner = Arc::new(Cache::default());
591
592        let mut f = vec![];
593
594        for (index, key) in (0..100).map(|x| x.to_string()).enumerate() {
595            let owner = Arc::clone(&owner);
596            f.push(async move {
597                let user = UserIdentity {
598                    version: index as i64,
599                    ..Default::default()
600                };
601                owner.add_or_update_user(&key, &user, OffsetDateTime::now_utc());
602            });
603        }
604        join_all(f).await;
605
606        let cache_load = owner.snapshot();
607        for (index, key) in (0..100).map(|x| x.to_string()).enumerate() {
608            assert_eq!(cache_load.users.get(&key).map(|user| user.version), Some(index as i64));
609        }
610        drop(cache_load);
611
612        let mut f = vec![];
613
614        for key in (0..100).map(|x| x.to_string()) {
615            let owner = Arc::clone(&owner);
616            f.push(async move {
617                owner.delete_user(&key, OffsetDateTime::now_utc());
618            });
619        }
620        join_all(f).await;
621
622        let cache_load = owner.snapshot();
623        assert!(cache_load.users.is_empty());
624    }
625
626    #[tokio::test]
627    async fn test_cache_snapshot_reads_one_published_state() {
628        let cache = Cache::default();
629        let before = cache.snapshot();
630        let user = UserIdentity {
631            version: 7,
632            ..Default::default()
633        };
634        let policy = MappedPolicy::new("readwrite");
635
636        cache.with_write_lock(|cache| {
637            let now = OffsetDateTime::now_utc();
638            cache.add_or_update_user("snapshot-user", &user, now);
639            cache.add_or_update_user_policy("snapshot-user", &policy, now);
640        });
641
642        assert!(!before.users.contains_key("snapshot-user"));
643        assert!(!before.user_policies.contains_key("snapshot-user"));
644
645        let after = cache.snapshot();
646        assert!(after.users.contains_key("snapshot-user"));
647        assert!(after.user_policies.contains_key("snapshot-user"));
648    }
649}