Skip to main content

rustfs_iam/
store.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
15pub mod object;
16
17use crate::cache::Cache;
18use crate::error::Result;
19use rustfs_policy::{auth::UserIdentity, policy::PolicyDoc};
20use serde::{Deserialize, Serialize, de::DeserializeOwned};
21use std::collections::{HashMap, HashSet};
22use time::OffsetDateTime;
23
24#[async_trait::async_trait]
25pub trait Store: Clone + Send + Sync + 'static {
26    fn has_watcher(&self) -> bool;
27    async fn save_iam_config<Item: Serialize + Send>(&self, item: Item, path: impl AsRef<str> + Send) -> Result<()>;
28    async fn load_iam_config<Item: DeserializeOwned>(&self, path: impl AsRef<str> + Send) -> Result<Item>;
29    async fn delete_iam_config(&self, path: impl AsRef<str> + Send) -> Result<()>;
30
31    async fn save_user_identity(&self, name: &str, user_type: UserType, item: UserIdentity, ttl: Option<usize>) -> Result<()>;
32    async fn delete_user_identity(&self, name: &str, user_type: UserType) -> Result<()>;
33    async fn load_user_identity(&self, name: &str, user_type: UserType) -> Result<UserIdentity>;
34
35    async fn load_user(&self, name: &str, user_type: UserType, m: &mut HashMap<String, UserIdentity>) -> Result<()>;
36    async fn load_users(&self, user_type: UserType, m: &mut HashMap<String, UserIdentity>) -> Result<()>;
37    async fn load_secret_key(&self, name: &str, user_type: UserType) -> Result<String>;
38
39    async fn save_group_info(&self, name: &str, item: GroupInfo) -> Result<()>;
40    async fn delete_group_info(&self, name: &str) -> Result<()>;
41    async fn load_group(&self, name: &str, m: &mut HashMap<String, GroupInfo>) -> Result<()>;
42    async fn load_groups(&self, m: &mut HashMap<String, GroupInfo>) -> Result<()>;
43
44    async fn save_policy_doc(&self, name: &str, item: PolicyDoc) -> Result<()>;
45    async fn delete_policy_doc(&self, name: &str) -> Result<()>;
46    async fn load_policy(&self, name: &str) -> Result<PolicyDoc>;
47    async fn load_policy_doc(&self, name: &str, m: &mut HashMap<String, PolicyDoc>) -> Result<()>;
48    async fn load_policy_docs(&self, m: &mut HashMap<String, PolicyDoc>) -> Result<()>;
49
50    async fn save_mapped_policy(
51        &self,
52        name: &str,
53        user_type: UserType,
54        is_group: bool,
55        item: MappedPolicy,
56        ttl: Option<usize>,
57    ) -> Result<()>;
58    async fn delete_mapped_policy(&self, name: &str, user_type: UserType, is_group: bool) -> Result<()>;
59    async fn load_mapped_policy(
60        &self,
61        name: &str,
62        user_type: UserType,
63        is_group: bool,
64        m: &mut HashMap<String, MappedPolicy>,
65    ) -> Result<()>;
66    async fn load_mapped_policies(
67        &self,
68        user_type: UserType,
69        is_group: bool,
70        m: &mut HashMap<String, MappedPolicy>,
71    ) -> Result<()>;
72
73    async fn load_all(&self, cache: &Cache) -> Result<()>;
74
75    // Lock-free variants used by the cross-node notification handlers.
76    //
77    // Notification-path cache refreshes are asynchronous, best-effort, and
78    // already tolerate stale values (the periodic reload converges them), so
79    // they must not depend on the node-counted namespace-lock quorum — the
80    // same rationale as the lock-free bootstrap `load_all` (rustfs#4304;
81    // MinIO's readConfig takes no distributed lock either). The defaults
82    // forward to the locked variants so existing `Store` implementations
83    // (including test mocks) keep their behavior; `ObjectStore` overrides
84    // them with lock-free reads.
85    async fn load_user_no_lock(&self, name: &str, user_type: UserType, m: &mut HashMap<String, UserIdentity>) -> Result<()> {
86        self.load_user(name, user_type, m).await
87    }
88    async fn load_group_no_lock(&self, name: &str, m: &mut HashMap<String, GroupInfo>) -> Result<()> {
89        self.load_group(name, m).await
90    }
91    async fn load_policy_doc_no_lock(&self, name: &str, m: &mut HashMap<String, PolicyDoc>) -> Result<()> {
92        self.load_policy_doc(name, m).await
93    }
94    async fn load_mapped_policy_no_lock(
95        &self,
96        name: &str,
97        user_type: UserType,
98        is_group: bool,
99        m: &mut HashMap<String, MappedPolicy>,
100    ) -> Result<()> {
101        self.load_mapped_policy(name, user_type, is_group, m).await
102    }
103}
104
105#[derive(Debug, PartialEq, Eq, Clone, Copy)]
106pub enum UserType {
107    Svc,
108    Sts,
109    Reg,
110    None,
111}
112
113impl UserType {
114    pub fn prefix(&self) -> &'static str {
115        match self {
116            UserType::Svc => "service-accounts/",
117            UserType::Sts => "sts/",
118            UserType::Reg => "users/",
119            UserType::None => "",
120        }
121    }
122    pub fn to_u64(&self) -> u64 {
123        match self {
124            UserType::Svc => 1,
125            UserType::Sts => 2,
126            UserType::Reg => 3,
127            UserType::None => 0,
128        }
129    }
130
131    pub fn from_u64(u64: u64) -> Option<Self> {
132        match u64 {
133            1 => Some(UserType::Svc),
134            2 => Some(UserType::Sts),
135            3 => Some(UserType::Reg),
136            0 => Some(UserType::None),
137            _ => None,
138        }
139    }
140}
141
142/// Encode a [`UserType`] as the site-replication wire value for
143/// `SRPolicyMapping.userType` / `SRCredInfo.iamUserType`.
144///
145/// The wire uses MinIO's `IAMUserType` table (cmd/iam.go):
146///
147/// | wire | MinIO meaning |
148/// |------|---------------|
149/// | -1   | unknown       |
150/// | 0    | regUser       |
151/// | 1    | stsUser       |
152/// | 2    | svcUser       |
153///
154/// This is deliberately distinct from the internal encoding
155/// [`UserType::to_u64`]/[`UserType::from_u64`] (None=0, Svc=1, Sts=2, Reg=3),
156/// which is used by intra-cluster node RPC and must never change (a rolling
157/// restart mixes old and new nodes on that RPC). Do not "unify" the two
158/// tables: internal values on the SR wire mislabel users on MinIO peers.
159///
160/// Group mappings always encode as 0: MinIO routes group mappings by the
161/// `isGroup` flag (userType is effectively ignored), and pre-fix RustFS peers
162/// sent 0 for groups, so 0 is the one value every peer generation accepts.
163pub fn sr_wire_user_type(user_type: UserType, is_group: bool) -> i64 {
164    if is_group {
165        return 0;
166    }
167    match user_type {
168        UserType::Reg | UserType::None => 0,
169        UserType::Sts => 1,
170        UserType::Svc => 2,
171    }
172}
173
174/// Decode a site-replication wire `userType` value (see [`sr_wire_user_type`]
175/// for the table) into a [`UserType`].
176///
177/// - `-1` (MinIO unknown, sent for group mappings) maps to [`UserType::None`];
178///   `policy_db_set` routes group items by `is_group`, and for non-group items
179///   `None` shares the users prefix with `Reg`.
180/// - `3` is a permanent alias for [`UserType::Reg`]: pre-fix RustFS peers sent
181///   the internal encoding (`Reg.to_u64() == 3`) on the wire. Keep it forever
182///   for mixed-version site replication; do not remove.
183/// - Anything else is unknown and rejected (`None`), so callers fail closed.
184pub fn user_type_from_sr_wire(v: i64) -> Option<UserType> {
185    match v {
186        -1 => Some(UserType::None),
187        0 => Some(UserType::Reg),
188        1 => Some(UserType::Sts),
189        2 => Some(UserType::Svc),
190        3 => Some(UserType::Reg),
191        _ => None,
192    }
193}
194
195#[derive(Serialize, Deserialize, Clone)]
196pub struct MappedPolicy {
197    pub version: i64,
198    /// policy, legacy: policies. Serialize as policy.
199    #[serde(rename = "policy", alias = "policies")]
200    pub policies: String,
201    /// updatedAt (RFC3339), legacy: update_at. Serialize as updatedAt.
202    #[serde(rename = "updatedAt", alias = "update_at", with = "rustfs_policy::serde_datetime")]
203    pub update_at: OffsetDateTime,
204}
205
206impl Default for MappedPolicy {
207    fn default() -> Self {
208        Self {
209            version: 0,
210            policies: "".to_owned(),
211            update_at: OffsetDateTime::now_utc(),
212        }
213    }
214}
215
216impl MappedPolicy {
217    pub fn new(policy: &str) -> Self {
218        Self {
219            version: 1,
220            policies: policy.to_owned(),
221            update_at: OffsetDateTime::now_utc(),
222        }
223    }
224
225    pub fn to_slice(&self) -> Vec<String> {
226        self.policies
227            .split(",")
228            .filter(|v| !v.trim().is_empty())
229            .map(|v| v.to_string())
230            .collect()
231    }
232
233    pub fn policy_set(&self) -> HashSet<String> {
234        self.policies
235            .split(",")
236            .filter(|v| !v.trim().is_empty())
237            .map(|v| v.to_string())
238            .collect()
239    }
240}
241
242#[derive(Serialize, Deserialize, Clone, Debug, Default)]
243pub struct GroupInfo {
244    pub version: i64,
245    pub status: String,
246    pub members: Vec<String>,
247    /// updatedAt (RFC3339), legacy: update_at. Serialize as updatedAt.
248    #[serde(
249        rename = "updatedAt",
250        alias = "update_at",
251        default,
252        with = "rustfs_policy::serde_datetime::option"
253    )]
254    pub update_at: Option<OffsetDateTime>,
255}
256
257impl GroupInfo {
258    pub fn new(members: Vec<String>) -> Self {
259        Self {
260            version: 1,
261            status: "enabled".to_owned(),
262            members,
263            update_at: Some(OffsetDateTime::now_utc()),
264        }
265    }
266}
267
268#[cfg(test)]
269mod tests {
270    use super::{GroupInfo, MappedPolicy, UserType, sr_wire_user_type, user_type_from_sr_wire};
271
272    /// Site-replication inbound decode of `SRPolicyMapping.userType` must
273    /// follow MinIO IAMUserType wire semantics (cmd/iam.go): stsUser = 1.
274    /// The internal `UserType::from_u64` table maps 1 to Svc — reusing it at
275    /// the SR boundary lands federated STS mappings under the wrong prefix
276    /// and silently drops their effect.
277    #[test]
278    fn sr_inbound_decodes_minio_sts_wire_value_as_sts() {
279        assert_eq!(user_type_from_sr_wire(1), Some(UserType::Sts));
280    }
281
282    /// Wire-constant contract: literal MinIO IAMUserType values (cmd/iam.go).
283    /// WARNING: these literals are the cross-vendor wire format. Never "tidy"
284    /// them to match `UserType::to_u64`/`from_u64` — that internal table
285    /// (None=0, Svc=1, Sts=2, Reg=3) belongs to intra-cluster node RPC only.
286    #[test]
287    fn sr_wire_decode_matches_minio_iam_user_type_table() {
288        assert_eq!(user_type_from_sr_wire(-1), Some(UserType::None)); // MinIO unknown (group mappings)
289        assert_eq!(user_type_from_sr_wire(0), Some(UserType::Reg)); // MinIO regUser
290        assert_eq!(user_type_from_sr_wire(1), Some(UserType::Sts)); // MinIO stsUser
291        assert_eq!(user_type_from_sr_wire(2), Some(UserType::Svc)); // MinIO svcUser
292        // Permanent alias: pre-fix RustFS peers sent internal Reg=3 on the wire.
293        assert_eq!(user_type_from_sr_wire(3), Some(UserType::Reg));
294        // Unknown values fail closed.
295        assert_eq!(user_type_from_sr_wire(4), None);
296        assert_eq!(user_type_from_sr_wire(-2), None);
297    }
298
299    /// Wire-constant contract for the outbound direction.
300    #[test]
301    fn sr_wire_encode_matches_minio_iam_user_type_table() {
302        assert_eq!(sr_wire_user_type(UserType::Reg, false), 0); // MinIO regUser
303        assert_eq!(sr_wire_user_type(UserType::Sts, false), 1); // MinIO stsUser
304        assert_eq!(sr_wire_user_type(UserType::Svc, false), 2); // MinIO svcUser
305        assert_eq!(sr_wire_user_type(UserType::None, false), 0);
306        // Group mappings always go out as 0 — the value both MinIO (routes by
307        // isGroup) and pre-fix RustFS peers accept.
308        for ut in [UserType::Reg, UserType::Sts, UserType::Svc, UserType::None] {
309            assert_eq!(sr_wire_user_type(ut, true), 0);
310        }
311    }
312
313    /// Mixed-version matrix: every value a peer generation can emit decodes to
314    /// a `UserType` the receiver stores correctly.
315    #[test]
316    fn sr_wire_round_trip_covers_old_rustfs_and_minio_peers() {
317        // Old RustFS outbound: user mappings as internal Reg=3, groups as 0.
318        assert_eq!(user_type_from_sr_wire(3), Some(UserType::Reg));
319        assert_eq!(user_type_from_sr_wire(0), Some(UserType::Reg));
320        // New RustFS outbound decodes on its own kind (self round-trip).
321        for (ut, is_group) in [
322            (UserType::Reg, false),
323            (UserType::Sts, false),
324            (UserType::Svc, false),
325            (UserType::None, true),
326        ] {
327            assert!(user_type_from_sr_wire(sr_wire_user_type(ut, is_group)).is_some());
328        }
329        // Internal RPC encoding is untouched (rolling-restart contract).
330        assert_eq!(UserType::None.to_u64(), 0);
331        assert_eq!(UserType::Svc.to_u64(), 1);
332        assert_eq!(UserType::Sts.to_u64(), 2);
333        assert_eq!(UserType::Reg.to_u64(), 3);
334        assert_eq!(UserType::from_u64(1), Some(UserType::Svc));
335    }
336
337    /// uses RFC3339 for updatedAt. MappedPolicy must serialize as RFC3339.
338    #[test]
339    fn test_mapped_policy_timestamps_serialize_as_rfc3339() {
340        let mp = MappedPolicy::new("readwrite");
341        let json = serde_json::to_string(&mp).expect("serialize");
342        assert!(json.contains('T'), "MappedPolicy updatedAt should be RFC3339; got: {}", json);
343        assert!(
344            json.contains('Z') || json.contains("+00:00"),
345            "MappedPolicy updatedAt should be RFC3339; got: {}",
346            json
347        );
348    }
349
350    /// Deserialize MappedPolicy from JSON (RFC3339 updatedAt).
351    #[test]
352    fn test_mapped_policy_deserialize_minio_style_rfc3339() {
353        let minio_style = r#"{"version":1,"policy":"readwrite","updatedAt":"2025-03-07T12:00:00Z"}"#;
354        let mp: MappedPolicy = serde_json::from_str(minio_style).expect("deserialize");
355        assert_eq!(mp.policies, "readwrite");
356    }
357
358    /// GroupInfo updatedAt: uses RFC3339.
359    #[test]
360    fn test_group_info_timestamps_serialize_as_rfc3339() {
361        let g = GroupInfo::new(vec!["u1".to_string()]);
362        let json = serde_json::to_string(&g).expect("serialize");
363        assert!(json.contains('T'), "GroupInfo updatedAt should be RFC3339; got: {}", json);
364    }
365
366    /// Deserialize GroupInfo from JSON (RFC3339 updatedAt).
367    #[test]
368    fn test_group_info_deserialize_minio_style_rfc3339() {
369        let minio_style = r#"{"version":1,"status":"enabled","members":["u1"],"updatedAt":"2025-03-07T12:00:00Z"}"#;
370        let g: GroupInfo = serde_json::from_str(minio_style).expect("deserialize");
371        assert_eq!(g.members, ["u1"]);
372        assert!(g.update_at.is_some());
373    }
374}