Skip to main content

rustfs_iam/
error.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::IamStorageError;
16use rustfs_policy::policy::Error as PolicyError;
17use std::sync::Arc;
18
19pub type Result<T> = core::result::Result<T, Error>;
20
21#[derive(thiserror::Error, Debug)]
22pub enum Error {
23    // Arc payloads keep Clone variant-preserving for the non-cloneable inner
24    // errors (backlog#1831 PR2). Display is unchanged; the source() chain is
25    // not forwarded (Arc<E> does not implement std::error::Error).
26    #[error("{0}")]
27    PolicyError(Arc<PolicyError>),
28
29    #[error("{0}")]
30    StringError(String),
31
32    #[error("crypto: {0}")]
33    CryptoError(Arc<rustfs_crypto::Error>),
34
35    #[error("user '{0}' does not exist")]
36    NoSuchUser(String),
37
38    #[error("account '{0}' does not exist")]
39    NoSuchAccount(String),
40
41    #[error("service account '{0}' does not exist")]
42    NoSuchServiceAccount(String),
43
44    #[error("temp account '{0}' does not exist")]
45    NoSuchTempAccount(String),
46
47    #[error("group '{0}' does not exist")]
48    NoSuchGroup(String),
49
50    #[error("policy does not exist")]
51    NoSuchPolicy,
52
53    #[error("policy in use")]
54    PolicyInUse,
55
56    #[error("group not empty")]
57    GroupNotEmpty,
58
59    #[error("invalid arguments specified")]
60    InvalidArgument,
61
62    #[error("not initialized")]
63    IamSysNotInitialized,
64
65    #[error("invalid access key length")]
66    InvalidAccessKeyLength,
67
68    #[error("invalid secret key length")]
69    InvalidSecretKeyLength,
70
71    #[error("access key contains reserved characters =,")]
72    ContainsReservedChars,
73
74    #[error("group name contains reserved characters =,")]
75    GroupNameContainsReservedChars,
76
77    #[error("access key is already in use")]
78    AccessKeyAlreadyExists,
79
80    #[error("action not allowed")]
81    IAMActionNotAllowed,
82
83    #[error("no secret key with access key")]
84    NoSecretKeyWithAccessKey,
85
86    #[error("no access key with secret key")]
87    NoAccessKeyWithSecretKey,
88
89    #[error("policy too large")]
90    PolicyTooLarge,
91
92    #[error("config not found")]
93    ConfigNotFound,
94
95    #[error("io error: {0}")]
96    Io(std::io::Error),
97
98    #[error("system already initialized")]
99    IamSysAlreadyInitialized,
100}
101
102impl PartialEq for Error {
103    fn eq(&self, other: &Self) -> bool {
104        match (self, other) {
105            (Error::StringError(a), Error::StringError(b)) => a == b,
106            (Error::NoSuchUser(a), Error::NoSuchUser(b)) => a == b,
107            (Error::NoSuchAccount(a), Error::NoSuchAccount(b)) => a == b,
108            (Error::NoSuchServiceAccount(a), Error::NoSuchServiceAccount(b)) => a == b,
109            (Error::NoSuchTempAccount(a), Error::NoSuchTempAccount(b)) => a == b,
110            (Error::NoSuchGroup(a), Error::NoSuchGroup(b)) => a == b,
111            (Error::Io(a), Error::Io(b)) => a.kind() == b.kind() && a.to_string() == b.to_string(),
112            // For complex types like PolicyError and CryptoError, compare string representations
113            (a, b) => std::mem::discriminant(a) == std::mem::discriminant(b) && a.to_string() == b.to_string(),
114        }
115    }
116}
117
118impl Clone for Error {
119    fn clone(&self) -> Self {
120        match self {
121            Error::PolicyError(e) => Error::PolicyError(Arc::clone(e)),
122            Error::StringError(s) => Error::StringError(s.clone()),
123            Error::CryptoError(e) => Error::CryptoError(Arc::clone(e)),
124            Error::NoSuchUser(s) => Error::NoSuchUser(s.clone()),
125            Error::NoSuchAccount(s) => Error::NoSuchAccount(s.clone()),
126            Error::NoSuchServiceAccount(s) => Error::NoSuchServiceAccount(s.clone()),
127            Error::NoSuchTempAccount(s) => Error::NoSuchTempAccount(s.clone()),
128            Error::NoSuchGroup(s) => Error::NoSuchGroup(s.clone()),
129            Error::NoSuchPolicy => Error::NoSuchPolicy,
130            Error::PolicyInUse => Error::PolicyInUse,
131            Error::GroupNotEmpty => Error::GroupNotEmpty,
132            Error::InvalidArgument => Error::InvalidArgument,
133            Error::IamSysNotInitialized => Error::IamSysNotInitialized,
134            Error::InvalidAccessKeyLength => Error::InvalidAccessKeyLength,
135            Error::InvalidSecretKeyLength => Error::InvalidSecretKeyLength,
136            Error::ContainsReservedChars => Error::ContainsReservedChars,
137            Error::GroupNameContainsReservedChars => Error::GroupNameContainsReservedChars,
138            Error::AccessKeyAlreadyExists => Error::AccessKeyAlreadyExists,
139            Error::IAMActionNotAllowed => Error::IAMActionNotAllowed,
140            Error::NoSecretKeyWithAccessKey => Error::NoSecretKeyWithAccessKey,
141            Error::NoAccessKeyWithSecretKey => Error::NoAccessKeyWithSecretKey,
142            Error::PolicyTooLarge => Error::PolicyTooLarge,
143            Error::ConfigNotFound => Error::ConfigNotFound,
144            Error::Io(e) => Error::Io(std::io::Error::new(e.kind(), e.to_string())),
145            Error::IamSysAlreadyInitialized => Error::IamSysAlreadyInitialized,
146        }
147    }
148}
149
150impl From<PolicyError> for Error {
151    fn from(e: PolicyError) -> Self {
152        Error::PolicyError(Arc::new(e))
153    }
154}
155
156impl From<rustfs_crypto::Error> for Error {
157    fn from(e: rustfs_crypto::Error) -> Self {
158        Error::CryptoError(Arc::new(e))
159    }
160}
161
162impl Error {
163    pub fn other<E>(error: E) -> Self
164    where
165        E: Into<Box<dyn std::error::Error + Send + Sync>>,
166    {
167        Error::Io(std::io::Error::other(error))
168    }
169}
170
171impl From<IamStorageError> for Error {
172    fn from(e: IamStorageError) -> Self {
173        match e {
174            IamStorageError::ConfigNotFound => Error::ConfigNotFound,
175            _ => Error::other(e),
176        }
177    }
178}
179
180impl From<Error> for IamStorageError {
181    fn from(e: Error) -> Self {
182        match e {
183            Error::ConfigNotFound => IamStorageError::ConfigNotFound,
184            _ => IamStorageError::other(e),
185        }
186    }
187}
188
189/// Deliberately a flat, exhaustive mapping rather than a wrapper variant
190/// (backlog#1845 step 8 verdict): folding iam::Error into a
191/// `Policy(Arc<policy::Error>)` wrapper would leave ~140 production
192/// construction/match sites across iam and the admin handlers to migrate in
193/// auth-critical code, and a type alias is blocked by the orphan rule (iam's
194/// `From<IamStorageError>` / io conversions cannot be implemented for a
195/// foreign type). The drift risk the fold aimed at is already covered by the
196/// compiler: this match has no catch-all, so any new policy variant fails the
197/// build here until mapped, and `policy_to_iam_mapping_preserves_messages`
198/// pins that every arm keeps the rendered message intact.
199impl From<rustfs_policy::error::Error> for Error {
200    fn from(e: rustfs_policy::error::Error) -> Self {
201        match e {
202            rustfs_policy::error::Error::PolicyTooLarge => Error::PolicyTooLarge,
203            rustfs_policy::error::Error::InvalidArgument => Error::InvalidArgument,
204            rustfs_policy::error::Error::IAMActionNotAllowed => Error::IAMActionNotAllowed,
205            rustfs_policy::error::Error::NoSecretKeyWithAccessKey => Error::NoSecretKeyWithAccessKey,
206            rustfs_policy::error::Error::NoAccessKeyWithSecretKey => Error::NoAccessKeyWithSecretKey,
207            rustfs_policy::error::Error::Io(e) => Error::Io(e),
208            rustfs_policy::error::Error::NoSuchUser(s) => Error::NoSuchUser(s),
209            rustfs_policy::error::Error::NoSuchAccount(s) => Error::NoSuchAccount(s),
210            rustfs_policy::error::Error::NoSuchServiceAccount(s) => Error::NoSuchServiceAccount(s),
211            rustfs_policy::error::Error::NoSuchTempAccount(s) => Error::NoSuchTempAccount(s),
212            rustfs_policy::error::Error::NoSuchGroup(s) => Error::NoSuchGroup(s),
213            rustfs_policy::error::Error::NoSuchPolicy => Error::NoSuchPolicy,
214            rustfs_policy::error::Error::PolicyInUse => Error::PolicyInUse,
215            rustfs_policy::error::Error::GroupNotEmpty => Error::GroupNotEmpty,
216            rustfs_policy::error::Error::InvalidAccessKeyLength => Error::InvalidAccessKeyLength,
217            rustfs_policy::error::Error::InvalidSecretKeyLength => Error::InvalidSecretKeyLength,
218            rustfs_policy::error::Error::ContainsReservedChars => Error::ContainsReservedChars,
219            rustfs_policy::error::Error::GroupNameContainsReservedChars => Error::GroupNameContainsReservedChars,
220            rustfs_policy::error::Error::IamSysNotInitialized => Error::IamSysNotInitialized,
221            rustfs_policy::error::Error::PolicyError(e) => Error::PolicyError(Arc::new(e)),
222            rustfs_policy::error::Error::StringError(s) => Error::StringError(s),
223            rustfs_policy::error::Error::CryptoError(e) => Error::CryptoError(Arc::new(e)),
224            rustfs_policy::error::Error::IamSysAlreadyInitialized => Error::IamSysAlreadyInitialized,
225            // These policy variants had dead same-name twins on iam::Error (zero
226            // construction and zero match sites, removed in backlog#1831); the
227            // message is preserved through StringError instead. Their six dead
228            // siblings on policy::Error were deleted outright (backlog#1845).
229            err @ (rustfs_policy::error::Error::InvalidServiceType(_) | rustfs_policy::error::Error::JWTError(_)) => {
230                Error::StringError(err.to_string())
231            }
232        }
233    }
234}
235
236impl From<Error> for std::io::Error {
237    fn from(e: Error) -> Self {
238        std::io::Error::other(e)
239    }
240}
241
242impl From<serde_json::Error> for Error {
243    fn from(e: serde_json::Error) -> Self {
244        Error::other(e)
245    }
246}
247
248impl From<base64_simd::Error> for Error {
249    fn from(e: base64_simd::Error) -> Self {
250        Error::other(e)
251    }
252}
253
254pub fn is_err_config_not_found(err: &Error) -> bool {
255    matches!(err, Error::ConfigNotFound)
256}
257
258// pub fn is_err_no_such_user(e: &Error) -> bool {
259//     matches!(e, Error::NoSuchUser(_))
260// }
261
262pub fn is_err_no_such_policy(err: &Error) -> bool {
263    matches!(err, Error::NoSuchPolicy)
264}
265
266pub fn is_err_no_such_user(err: &Error) -> bool {
267    matches!(err, Error::NoSuchUser(_))
268}
269
270pub fn is_err_no_such_account(err: &Error) -> bool {
271    matches!(err, Error::NoSuchAccount(_))
272}
273
274pub fn is_err_no_such_temp_account(err: &Error) -> bool {
275    matches!(err, Error::NoSuchTempAccount(_))
276}
277
278pub fn is_err_no_such_group(err: &Error) -> bool {
279    matches!(err, Error::NoSuchGroup(_))
280}
281
282pub fn is_err_no_such_service_account(err: &Error) -> bool {
283    matches!(err, Error::NoSuchServiceAccount(_))
284}
285
286#[cfg(test)]
287mod tests {
288    use super::*;
289    use std::io::{Error as IoError, ErrorKind};
290
291    #[test]
292    fn test_iam_error_to_io_error_conversion() {
293        let iam_errors = vec![
294            Error::NoSuchUser("testuser".to_string()),
295            Error::NoSuchAccount("testaccount".to_string()),
296            Error::InvalidArgument,
297            Error::AccessKeyAlreadyExists,
298            Error::IAMActionNotAllowed,
299            Error::PolicyTooLarge,
300            Error::ConfigNotFound,
301        ];
302
303        for iam_error in iam_errors {
304            let io_error: std::io::Error = iam_error.clone().into();
305
306            // Check that conversion creates an io::Error
307            assert_eq!(io_error.kind(), ErrorKind::Other);
308
309            // Check that the error message is preserved
310            assert!(io_error.to_string().contains(&iam_error.to_string()));
311        }
312    }
313
314    #[test]
315    fn test_iam_error_from_storage_error() {
316        // Test conversion from StorageError
317        let storage_error = IamStorageError::ConfigNotFound;
318        let iam_error: Error = storage_error.into();
319        assert_eq!(iam_error, Error::ConfigNotFound);
320
321        // Test reverse conversion
322        let back_to_storage: IamStorageError = iam_error.into();
323        assert_eq!(back_to_storage, IamStorageError::ConfigNotFound);
324    }
325
326    #[test]
327    fn test_iam_error_from_policy_error() {
328        use rustfs_policy::error::Error as PolicyError;
329
330        let policy_errors = vec![
331            (PolicyError::NoSuchUser("user1".to_string()), Error::NoSuchUser("user1".to_string())),
332            (PolicyError::NoSuchPolicy, Error::NoSuchPolicy),
333            (PolicyError::InvalidArgument, Error::InvalidArgument),
334            (PolicyError::PolicyTooLarge, Error::PolicyTooLarge),
335        ];
336
337        for (policy_error, expected_iam_error) in policy_errors {
338            let converted_iam_error: Error = policy_error.into();
339            assert_eq!(converted_iam_error, expected_iam_error);
340        }
341    }
342
343    #[test]
344    fn test_iam_error_other_function() {
345        let custom_error = "Custom IAM error";
346        let iam_error = Error::other(custom_error);
347
348        match iam_error {
349            Error::Io(io_error) => {
350                assert!(io_error.to_string().contains(custom_error));
351                assert_eq!(io_error.kind(), ErrorKind::Other);
352            }
353            _ => panic!("Expected Io variant"),
354        }
355    }
356
357    #[test]
358    fn test_iam_error_from_serde_json() {
359        // Test conversion from serde_json::Error
360        let invalid_json = r#"{"invalid": json}"#;
361        let json_error = serde_json::from_str::<serde_json::Value>(invalid_json).unwrap_err();
362        let iam_error: Error = json_error.into();
363
364        match iam_error {
365            Error::Io(io_error) => {
366                assert_eq!(io_error.kind(), ErrorKind::Other);
367            }
368            _ => panic!("Expected Io variant"),
369        }
370    }
371
372    #[test]
373    fn test_helper_functions() {
374        // Test helper functions for error type checking
375        assert!(is_err_config_not_found(&Error::ConfigNotFound));
376        assert!(!is_err_config_not_found(&Error::NoSuchPolicy));
377
378        assert!(is_err_no_such_policy(&Error::NoSuchPolicy));
379        assert!(!is_err_no_such_policy(&Error::ConfigNotFound));
380
381        assert!(is_err_no_such_user(&Error::NoSuchUser("test".to_string())));
382        assert!(!is_err_no_such_user(&Error::NoSuchAccount("test".to_string())));
383
384        assert!(is_err_no_such_account(&Error::NoSuchAccount("test".to_string())));
385        assert!(!is_err_no_such_account(&Error::NoSuchUser("test".to_string())));
386
387        assert!(is_err_no_such_temp_account(&Error::NoSuchTempAccount("test".to_string())));
388        assert!(!is_err_no_such_temp_account(&Error::NoSuchAccount("test".to_string())));
389
390        assert!(is_err_no_such_group(&Error::NoSuchGroup("test".to_string())));
391        assert!(!is_err_no_such_group(&Error::NoSuchUser("test".to_string())));
392
393        assert!(is_err_no_such_service_account(&Error::NoSuchServiceAccount("test".to_string())));
394        assert!(!is_err_no_such_service_account(&Error::NoSuchAccount("test".to_string())));
395    }
396
397    #[test]
398    fn test_iam_error_io_preservation() {
399        // Test that Io variant preserves original io::Error
400        let original_io = IoError::new(ErrorKind::PermissionDenied, "access denied");
401        let iam_error = Error::Io(original_io);
402
403        let converted_io: std::io::Error = iam_error.into();
404        // Note: Our clone implementation creates a new io::Error with the same kind and message
405        // but it becomes ErrorKind::Other when cloned
406        assert_eq!(converted_io.kind(), ErrorKind::Other);
407        assert!(converted_io.to_string().contains("access denied"));
408    }
409
410    #[test]
411    fn clone_preserves_variant_identity_and_message() {
412        // backlog#1831 PR2: cloning must never demote a variant to a different
413        // one (the old Clone stringified PolicyError/CryptoError into
414        // StringError). Pin discriminant and rendered message across clone.
415        let errors = vec![
416            Error::PolicyError(Arc::new(PolicyError::NonAction)),
417            Error::CryptoError(Arc::new(rustfs_crypto::Error::ErrInvalidKeyLength)),
418            Error::Io(std::io::Error::other("io payload")),
419            Error::StringError("plain".to_string()),
420            Error::NoSuchUser("u".to_string()),
421            Error::ConfigNotFound,
422        ];
423
424        for error in errors {
425            let cloned = error.clone();
426            assert_eq!(
427                std::mem::discriminant(&error),
428                std::mem::discriminant(&cloned),
429                "clone must keep the variant of {error:?}"
430            );
431            assert_eq!(error.to_string(), cloned.to_string(), "clone must keep the rendered message");
432        }
433    }
434
435    #[test]
436    fn test_error_display_format() {
437        let test_cases = vec![
438            (Error::NoSuchUser("testuser".to_string()), "user 'testuser' does not exist"),
439            (Error::NoSuchAccount("testaccount".to_string()), "account 'testaccount' does not exist"),
440            (Error::InvalidArgument, "invalid arguments specified"),
441            (Error::AccessKeyAlreadyExists, "access key is already in use"),
442            (Error::IAMActionNotAllowed, "action not allowed"),
443            (Error::ConfigNotFound, "config not found"),
444        ];
445
446        for (error, expected_message) in test_cases {
447            assert_eq!(error.to_string(), expected_message);
448        }
449    }
450
451    #[test]
452    fn policy_to_iam_mapping_preserves_messages() {
453        use rustfs_policy::error::Error as PErr;
454        // One representative per policy::error::Error variant. When a new
455        // variant is added, the exhaustive From match breaks the build first;
456        // extend this list in the same change so the message stays pinned.
457        let representatives: Vec<PErr> = vec![
458            PErr::PolicyError(rustfs_policy::policy::Error::NonResource),
459            PErr::StringError("free-form".to_string()),
460            PErr::NoSuchUser("u".to_string()),
461            PErr::NoSuchAccount("a".to_string()),
462            PErr::NoSuchServiceAccount("sa".to_string()),
463            PErr::NoSuchTempAccount("ta".to_string()),
464            PErr::NoSuchGroup("g".to_string()),
465            PErr::NoSuchPolicy,
466            PErr::PolicyInUse,
467            PErr::GroupNotEmpty,
468            PErr::InvalidArgument,
469            PErr::IamSysNotInitialized,
470            PErr::InvalidServiceType("svc".to_string()),
471            PErr::InvalidAccessKeyLength,
472            PErr::InvalidSecretKeyLength,
473            PErr::ContainsReservedChars,
474            PErr::GroupNameContainsReservedChars,
475            PErr::IAMActionNotAllowed,
476            PErr::NoSecretKeyWithAccessKey,
477            PErr::NoAccessKeyWithSecretKey,
478            PErr::PolicyTooLarge,
479            PErr::Io(std::io::Error::other("io detail")),
480            PErr::IamSysAlreadyInitialized,
481        ];
482
483        for policy_err in representatives {
484            let rendered = policy_err.to_string();
485            let iam_err: Error = policy_err.into();
486            assert_eq!(iam_err.to_string(), rendered, "policy->iam conversion must preserve the rendered message");
487        }
488
489        // The one #[from] payload variant: rendering is preserved end to end.
490        let jwt_err =
491            rustfs_policy::error::Error::from(jsonwebtoken::errors::Error::from(jsonwebtoken::errors::ErrorKind::InvalidToken));
492        let rendered = jwt_err.to_string();
493        let iam_err: Error = jwt_err.into();
494        assert_eq!(iam_err.to_string(), rendered);
495    }
496}