rustfs-madmin 0.0.3

Management and administration tools for RustFS, providing a web interface and API for system management.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
// Copyright 2024 RustFS Team
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::value::RawValue;
use std::collections::HashMap;
use time::OffsetDateTime;

use crate::BackendInfo;

#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Eq)]
pub enum AccountStatus {
    #[serde(rename = "enabled")]
    Enabled,
    #[serde(rename = "disabled")]
    #[default]
    Disabled,
}

impl AsRef<str> for AccountStatus {
    fn as_ref(&self) -> &str {
        match self {
            AccountStatus::Enabled => "enabled",
            AccountStatus::Disabled => "disabled",
        }
    }
}

impl TryFrom<&str> for AccountStatus {
    type Error = String;

    fn try_from(s: &str) -> Result<Self, Self::Error> {
        match s {
            "enabled" => Ok(AccountStatus::Enabled),
            "disabled" => Ok(AccountStatus::Disabled),
            _ => Err(format!("invalid account status: {s}")),
        }
    }
}

#[derive(Debug, Serialize, Deserialize)]
pub enum UserAuthType {
    #[serde(rename = "builtin")]
    Builtin,
    #[serde(rename = "ldap")]
    Ldap,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UserAuthInfo {
    #[serde(rename = "type")]
    pub auth_type: UserAuthType,

    #[serde(rename = "authServer", skip_serializing_if = "Option::is_none")]
    pub auth_server: Option<String>,

    #[serde(rename = "authServerUserID", skip_serializing_if = "Option::is_none")]
    pub auth_server_user_id: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct UserInfo {
    #[serde(rename = "userAuthInfo", skip_serializing_if = "Option::is_none")]
    pub auth_info: Option<UserAuthInfo>,

    #[serde(rename = "secretKey", skip_serializing_if = "Option::is_none")]
    pub secret_key: Option<String>,

    #[serde(rename = "policyName", skip_serializing_if = "Option::is_none")]
    pub policy_name: Option<String>,

    #[serde(rename = "status")]
    pub status: AccountStatus,

    #[serde(rename = "memberOf", skip_serializing_if = "Option::is_none")]
    pub member_of: Option<Vec<String>>,

    #[serde(rename = "updatedAt")]
    pub updated_at: Option<OffsetDateTime>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AddOrUpdateUserReq {
    #[serde(rename = "secretKey")]
    pub secret_key: String,

    #[serde(rename = "policy", skip_serializing_if = "Option::is_none")]
    pub policy: Option<String>,

    #[serde(rename = "status")]
    pub status: AccountStatus,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ServiceAccountInfo {
    #[serde(rename = "parentUser")]
    pub parent_user: String,

    #[serde(rename = "accountStatus")]
    pub account_status: String,

    #[serde(rename = "impliedPolicy")]
    pub implied_policy: bool,

    #[serde(rename = "accessKey")]
    pub access_key: String,

    #[serde(rename = "name", skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,

    #[serde(rename = "description", skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    #[serde(rename = "expiration", with = "time::serde::rfc3339::option")]
    pub expiration: Option<OffsetDateTime>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct ListServiceAccountsResp {
    #[serde(rename = "accounts")]
    pub accounts: Vec<ServiceAccountInfo>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct AddServiceAccountReq {
    #[serde(rename = "policy", skip_serializing_if = "Option::is_none")]
    pub policy: Option<String>,

    #[serde(rename = "targetUser", skip_serializing_if = "Option::is_none")]
    pub target_user: Option<String>,

    #[serde(rename = "accessKey")]
    pub access_key: String,

    #[serde(rename = "secretKey")]
    pub secret_key: String,

    #[serde(rename = "name")]
    pub name: Option<String>,

    #[serde(rename = "description", skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    #[serde(rename = "expiration", with = "time::serde::rfc3339::option")]
    pub expiration: Option<OffsetDateTime>,
}

impl AddServiceAccountReq {
    pub fn validate(&self) -> Result<(), String> {
        if self.access_key.is_empty() {
            return Err("accessKey is empty".to_string());
        }

        if self.secret_key.is_empty() {
            return Err("secretKey is empty".to_string());
        }

        if self.name.is_none() {
            return Err("name is empty".to_string());
        }

        // TODO: validate

        Ok(())
    }
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Credentials<'a> {
    pub access_key: &'a str,
    pub secret_key: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub session_token: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(with = "time::serde::rfc3339::option")]
    pub expiration: Option<OffsetDateTime>,
}

#[derive(Serialize)]
pub struct AddServiceAccountResp<'a> {
    pub credentials: Credentials<'a>,
}

#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InfoServiceAccountResp {
    pub parent_user: String,
    pub account_status: String,
    pub implied_policy: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub policy: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,

    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(with = "time::serde::rfc3339::option")]
    pub expiration: Option<OffsetDateTime>,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct UpdateServiceAccountReq {
    #[serde(rename = "newPolicy", skip_serializing_if = "Option::is_none")]
    pub new_policy: Option<String>,

    #[serde(rename = "newSecretKey", skip_serializing_if = "Option::is_none")]
    pub new_secret_key: Option<String>,

    #[serde(rename = "newStatus", skip_serializing_if = "Option::is_none")]
    pub new_status: Option<String>,

    #[serde(rename = "newName", skip_serializing_if = "Option::is_none")]
    pub new_name: Option<String>,

    #[serde(rename = "newDescription", skip_serializing_if = "Option::is_none")]
    pub new_description: Option<String>,

    #[serde(rename = "newExpiration", skip_serializing_if = "Option::is_none")]
    #[serde(with = "time::serde::rfc3339::option")]
    pub new_expiration: Option<OffsetDateTime>,
}

impl UpdateServiceAccountReq {
    pub fn validate(&self) -> Result<(), String> {
        // TODO: validate
        Ok(())
    }
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct AccountInfo {
    pub account_name: String,
    pub server: BackendInfo,
    pub policy: serde_json::Value, // Use iam/policy::parse to parse the result, to be done by the caller.
    pub buckets: Vec<BucketAccessInfo>,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct BucketAccessInfo {
    pub name: String,
    pub size: u64,
    pub objects: u64,
    pub object_sizes_histogram: HashMap<String, u64>,
    pub object_versions_histogram: HashMap<String, u64>,
    pub details: Option<BucketDetails>,
    pub prefix_usage: HashMap<String, u64>,
    #[serde(rename = "expiration", with = "time::serde::rfc3339::option")]
    pub created: Option<OffsetDateTime>,
    pub access: AccountAccess,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct BucketDetails {
    pub versioning: bool,
    pub versioning_suspended: bool,
    pub locking: bool,
    pub replication: bool,
    // pub tagging: Option<Tagging>,
}

#[derive(Debug, Serialize, Deserialize, Default)]
pub struct AccountAccess {
    pub read: bool,
    pub write: bool,
}

/// SRSessionPolicy - represents a session policy to be replicated.
#[derive(Debug, Clone)]
pub struct SRSessionPolicy(Option<Box<RawValue>>);

impl SRSessionPolicy {
    pub fn new() -> Self {
        SRSessionPolicy(None)
    }

    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        if json == "null" {
            Ok(SRSessionPolicy(None))
        } else {
            let raw_value = serde_json::from_str(json)?;
            Ok(SRSessionPolicy(Some(raw_value)))
        }
    }

    pub fn is_null(&self) -> bool {
        self.0.is_none()
    }

    pub fn as_str(&self) -> Option<&str> {
        self.0.as_ref().map(|v| v.get())
    }
}

impl Default for SRSessionPolicy {
    fn default() -> Self {
        Self::new()
    }
}

impl PartialEq for SRSessionPolicy {
    fn eq(&self, other: &Self) -> bool {
        self.0.as_ref().map(|v| v.get()) == other.0.as_ref().map(|v| v.get())
    }
}

impl Serialize for SRSessionPolicy {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match &self.0 {
            Some(raw_value) => raw_value.serialize(serializer),
            None => serializer.serialize_none(),
        }
    }
}

impl<'de> Deserialize<'de> for SRSessionPolicy {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let raw_value: Option<Box<RawValue>> = Option::deserialize(deserializer)?;
        Ok(SRSessionPolicy(raw_value))
    }
}

/// SRSvcAccCreate - create operation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SRSvcAccCreate {
    pub parent: String,

    #[serde(rename = "accessKey")]
    pub access_key: String,

    #[serde(rename = "secretKey")]
    pub secret_key: String,

    pub groups: Vec<String>,

    pub claims: HashMap<String, serde_json::Value>,

    #[serde(rename = "sessionPolicy")]
    pub session_policy: SRSessionPolicy,

    pub status: String,

    pub name: String,

    pub description: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    pub expiration: Option<OffsetDateTime>,

    #[serde(rename = "apiVersion", skip_serializing_if = "Option::is_none")]
    pub api_version: Option<String>,
}

/// ImportIAMResult - represents the structure iam import response
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ImportIAMResult {
    /// Skipped entries while import
    /// This could be due to groups, policies etc missing for
    /// imported entries. We dont fail hard in this case and
    pub skipped: IAMEntities,

    /// Removed entries - this mostly happens for policies
    /// where empty might be getting imported and that's invalid
    pub removed: IAMEntities,

    /// Newly added entries
    pub added: IAMEntities,

    /// Failed entries while import. This would have details of
    /// failed entities with respective errors
    pub failed: IAMErrEntities,
}

/// IAMEntities - represents different IAM entities
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct IAMEntities {
    /// List of policy names
    pub policies: Vec<String>,

    /// List of user names
    pub users: Vec<String>,

    /// List of group names
    pub groups: Vec<String>,

    /// List of Service Account names
    #[serde(rename = "serviceAccounts")]
    pub service_accounts: Vec<String>,

    /// List of user policies, each entry in map represents list of policies
    /// applicable to the user
    #[serde(rename = "userPolicies")]
    pub user_policies: Vec<HashMap<String, Vec<String>>>,

    /// List of group policies, each entry in map represents list of policies
    /// applicable to the group
    #[serde(rename = "groupPolicies")]
    pub group_policies: Vec<HashMap<String, Vec<String>>>,

    /// List of STS policies, each entry in map represents list of policies
    /// applicable to the STS
    #[serde(rename = "stsPolicies")]
    pub sts_policies: Vec<HashMap<String, Vec<String>>>,
}

/// IAMErrEntities - represents errored out IAM entries while import with error
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct IAMErrEntities {
    /// List of errored out policies with errors
    pub policies: Vec<IAMErrEntity>,

    /// List of errored out users with errors
    pub users: Vec<IAMErrEntity>,

    /// List of errored out groups with errors
    pub groups: Vec<IAMErrEntity>,

    /// List of errored out service accounts with errors
    #[serde(rename = "serviceAccounts")]
    pub service_accounts: Vec<IAMErrEntity>,

    /// List of errored out user policies with errors
    #[serde(rename = "userPolicies")]
    pub user_policies: Vec<IAMErrPolicyEntity>,

    /// List of errored out group policies with errors
    #[serde(rename = "groupPolicies")]
    pub group_policies: Vec<IAMErrPolicyEntity>,

    /// List of errored out STS policies with errors
    #[serde(rename = "stsPolicies")]
    pub sts_policies: Vec<IAMErrPolicyEntity>,
}

/// IAMErrEntity - represents an errored IAM entity with error details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IAMErrEntity {
    pub name: String,
    pub error: String,
}

/// IAMErrPolicyEntity - represents an errored policy entity with error details
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct IAMErrPolicyEntity {
    pub name: String,
    pub policies: Vec<String>,
    pub error: String,
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json;
    use time::OffsetDateTime;

    #[test]
    fn test_account_status_default() {
        let status = AccountStatus::default();
        assert_eq!(status, AccountStatus::Disabled);
    }

    #[test]
    fn test_account_status_as_ref() {
        assert_eq!(AccountStatus::Enabled.as_ref(), "enabled");
        assert_eq!(AccountStatus::Disabled.as_ref(), "disabled");
    }

    #[test]
    fn test_account_status_try_from_valid() {
        assert_eq!(AccountStatus::try_from("enabled").unwrap(), AccountStatus::Enabled);
        assert_eq!(AccountStatus::try_from("disabled").unwrap(), AccountStatus::Disabled);
    }

    #[test]
    fn test_account_status_try_from_invalid() {
        let result = AccountStatus::try_from("invalid");
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("invalid account status"));
    }

    #[test]
    fn test_account_status_serialization() {
        let enabled = AccountStatus::Enabled;
        let disabled = AccountStatus::Disabled;

        let enabled_json = serde_json::to_string(&enabled).unwrap();
        let disabled_json = serde_json::to_string(&disabled).unwrap();

        assert_eq!(enabled_json, "\"enabled\"");
        assert_eq!(disabled_json, "\"disabled\"");
    }

    #[test]
    fn test_account_status_deserialization() {
        let enabled: AccountStatus = serde_json::from_str("\"enabled\"").unwrap();
        let disabled: AccountStatus = serde_json::from_str("\"disabled\"").unwrap();

        assert_eq!(enabled, AccountStatus::Enabled);
        assert_eq!(disabled, AccountStatus::Disabled);
    }

    #[test]
    fn test_user_auth_type_serialization() {
        let builtin = UserAuthType::Builtin;
        let ldap = UserAuthType::Ldap;

        let builtin_json = serde_json::to_string(&builtin).unwrap();
        let ldap_json = serde_json::to_string(&ldap).unwrap();

        assert_eq!(builtin_json, "\"builtin\"");
        assert_eq!(ldap_json, "\"ldap\"");
    }

    #[test]
    fn test_user_auth_info_creation() {
        let auth_info = UserAuthInfo {
            auth_type: UserAuthType::Ldap,
            auth_server: Some("ldap.example.com".to_string()),
            auth_server_user_id: Some("user123".to_string()),
        };

        assert!(matches!(auth_info.auth_type, UserAuthType::Ldap));
        assert_eq!(auth_info.auth_server.unwrap(), "ldap.example.com");
        assert_eq!(auth_info.auth_server_user_id.unwrap(), "user123");
    }

    #[test]
    fn test_user_auth_info_serialization() {
        let auth_info = UserAuthInfo {
            auth_type: UserAuthType::Builtin,
            auth_server: None,
            auth_server_user_id: None,
        };

        let json = serde_json::to_string(&auth_info).unwrap();
        assert!(json.contains("builtin"));
        assert!(!json.contains("authServer"), "None fields should be skipped");
    }

    #[test]
    fn test_user_info_default() {
        let user_info = UserInfo::default();
        assert!(user_info.auth_info.is_none());
        assert!(user_info.secret_key.is_none());
        assert!(user_info.policy_name.is_none());
        assert_eq!(user_info.status, AccountStatus::Disabled);
        assert!(user_info.member_of.is_none());
        assert!(user_info.updated_at.is_none());
    }

    #[test]
    fn test_user_info_with_values() {
        let now = OffsetDateTime::now_utc();
        let user_info = UserInfo {
            auth_info: Some(UserAuthInfo {
                auth_type: UserAuthType::Builtin,
                auth_server: None,
                auth_server_user_id: None,
            }),
            secret_key: Some("secret123".to_string()),
            policy_name: Some("ReadOnlyAccess".to_string()),
            status: AccountStatus::Enabled,
            member_of: Some(vec!["group1".to_string(), "group2".to_string()]),
            updated_at: Some(now),
        };

        assert!(user_info.auth_info.is_some());
        assert_eq!(user_info.secret_key.unwrap(), "secret123");
        assert_eq!(user_info.policy_name.unwrap(), "ReadOnlyAccess");
        assert_eq!(user_info.status, AccountStatus::Enabled);
        assert_eq!(user_info.member_of.unwrap().len(), 2);
        assert!(user_info.updated_at.is_some());
    }

    #[test]
    fn test_add_or_update_user_req_creation() {
        let req = AddOrUpdateUserReq {
            secret_key: "newsecret".to_string(),
            policy: Some("FullAccess".to_string()),
            status: AccountStatus::Enabled,
        };

        assert_eq!(req.secret_key, "newsecret");
        assert_eq!(req.policy.unwrap(), "FullAccess");
        assert_eq!(req.status, AccountStatus::Enabled);
    }

    #[test]
    fn test_service_account_info_creation() {
        let now = OffsetDateTime::now_utc();
        let service_account = ServiceAccountInfo {
            parent_user: "admin".to_string(),
            account_status: "enabled".to_string(),
            implied_policy: true,
            access_key: "AKIAIOSFODNN7EXAMPLE".to_string(),
            name: Some("test-service".to_string()),
            description: Some("Test service account".to_string()),
            expiration: Some(now),
        };

        assert_eq!(service_account.parent_user, "admin");
        assert_eq!(service_account.account_status, "enabled");
        assert!(service_account.implied_policy);
        assert_eq!(service_account.access_key, "AKIAIOSFODNN7EXAMPLE");
        assert_eq!(service_account.name.unwrap(), "test-service");
        assert!(service_account.expiration.is_some());
    }

    #[test]
    fn test_list_service_accounts_resp_creation() {
        let resp = ListServiceAccountsResp {
            accounts: vec![
                ServiceAccountInfo {
                    parent_user: "user1".to_string(),
                    account_status: "enabled".to_string(),
                    implied_policy: false,
                    access_key: "KEY1".to_string(),
                    name: Some("service1".to_string()),
                    description: None,
                    expiration: None,
                },
                ServiceAccountInfo {
                    parent_user: "user2".to_string(),
                    account_status: "disabled".to_string(),
                    implied_policy: true,
                    access_key: "KEY2".to_string(),
                    name: Some("service2".to_string()),
                    description: Some("Second service".to_string()),
                    expiration: None,
                },
            ],
        };

        assert_eq!(resp.accounts.len(), 2);
        assert_eq!(resp.accounts[0].parent_user, "user1");
        assert_eq!(resp.accounts[1].account_status, "disabled");
    }

    #[test]
    fn test_add_service_account_req_validate_success() {
        let req = AddServiceAccountReq {
            policy: Some("ReadOnlyAccess".to_string()),
            target_user: Some("testuser".to_string()),
            access_key: "AKIAIOSFODNN7EXAMPLE".to_string(),
            secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY".to_string(),
            name: Some("test-service".to_string()),
            description: Some("Test service account".to_string()),
            expiration: None,
        };

        let result = req.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_add_service_account_req_validate_empty_access_key() {
        let req = AddServiceAccountReq {
            policy: None,
            target_user: None,
            access_key: "".to_string(),
            secret_key: "secret".to_string(),
            name: Some("test".to_string()),
            description: None,
            expiration: None,
        };

        let result = req.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("accessKey is empty"));
    }

    #[test]
    fn test_add_service_account_req_validate_empty_secret_key() {
        let req = AddServiceAccountReq {
            policy: None,
            target_user: None,
            access_key: "AKIAIOSFODNN7EXAMPLE".to_string(),
            secret_key: "".to_string(),
            name: Some("test".to_string()),
            description: None,
            expiration: None,
        };

        let result = req.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("secretKey is empty"));
    }

    #[test]
    fn test_add_service_account_req_validate_empty_name() {
        let req = AddServiceAccountReq {
            policy: None,
            target_user: None,
            access_key: "AKIAIOSFODNN7EXAMPLE".to_string(),
            secret_key: "secret".to_string(),
            name: None,
            description: None,
            expiration: None,
        };

        let result = req.validate();
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("name is empty"));
    }

    #[test]
    fn test_credentials_serialization() {
        let now = OffsetDateTime::now_utc();
        let credentials = Credentials {
            access_key: "AKIAIOSFODNN7EXAMPLE",
            secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
            session_token: Some("session123"),
            expiration: Some(now),
        };

        let json = serde_json::to_string(&credentials).unwrap();
        assert!(json.contains("AKIAIOSFODNN7EXAMPLE"));
        assert!(json.contains("wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"));
        assert!(json.contains("session123"));
    }

    #[test]
    fn test_credentials_without_optional_fields() {
        let credentials = Credentials {
            access_key: "AKIAIOSFODNN7EXAMPLE",
            secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
            session_token: None,
            expiration: None,
        };

        let json = serde_json::to_string(&credentials).unwrap();
        assert!(json.contains("AKIAIOSFODNN7EXAMPLE"));
        assert!(!json.contains("sessionToken"), "None fields should be skipped");
        assert!(!json.contains("expiration"), "None fields should be skipped");
    }

    #[test]
    fn test_add_service_account_resp_creation() {
        let credentials = Credentials {
            access_key: "AKIAIOSFODNN7EXAMPLE",
            secret_key: "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY",
            session_token: None,
            expiration: None,
        };

        let resp = AddServiceAccountResp { credentials };

        assert_eq!(resp.credentials.access_key, "AKIAIOSFODNN7EXAMPLE");
        assert_eq!(resp.credentials.secret_key, "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY");
    }

    #[test]
    fn test_info_service_account_resp_creation() {
        let now = OffsetDateTime::now_utc();
        let resp = InfoServiceAccountResp {
            parent_user: "admin".to_string(),
            account_status: "enabled".to_string(),
            implied_policy: true,
            policy: Some("ReadOnlyAccess".to_string()),
            name: Some("test-service".to_string()),
            description: Some("Test service account".to_string()),
            expiration: Some(now),
        };

        assert_eq!(resp.parent_user, "admin");
        assert_eq!(resp.account_status, "enabled");
        assert!(resp.implied_policy);
        assert_eq!(resp.policy.unwrap(), "ReadOnlyAccess");
        assert_eq!(resp.name.unwrap(), "test-service");
        assert!(resp.expiration.is_some());
    }

    #[test]
    fn test_update_service_account_req_validate() {
        let req = UpdateServiceAccountReq {
            new_policy: Some("FullAccess".to_string()),
            new_secret_key: Some("newsecret".to_string()),
            new_status: Some("enabled".to_string()),
            new_name: Some("updated-service".to_string()),
            new_description: Some("Updated description".to_string()),
            new_expiration: None,
        };

        let result = req.validate();
        assert!(result.is_ok());
    }

    #[test]
    fn test_account_info_creation() {
        use crate::BackendInfo;

        let account_info = AccountInfo {
            account_name: "testuser".to_string(),
            server: BackendInfo::default(),
            policy: serde_json::json!({"Version": "2012-10-17"}),
            buckets: vec![],
        };

        assert_eq!(account_info.account_name, "testuser");
        assert!(account_info.buckets.is_empty());
        assert!(account_info.policy.is_object());
    }

    #[test]
    fn test_bucket_access_info_creation() {
        let now = OffsetDateTime::now_utc();
        let mut sizes_histogram = HashMap::new();
        sizes_histogram.insert("small".to_string(), 100);
        sizes_histogram.insert("large".to_string(), 50);

        let mut versions_histogram = HashMap::new();
        versions_histogram.insert("v1".to_string(), 80);
        versions_histogram.insert("v2".to_string(), 70);

        let mut prefix_usage = HashMap::new();
        prefix_usage.insert("logs/".to_string(), 1000000);
        prefix_usage.insert("data/".to_string(), 5000000);

        let bucket_info = BucketAccessInfo {
            name: "test-bucket".to_string(),
            size: 6000000,
            objects: 150,
            object_sizes_histogram: sizes_histogram,
            object_versions_histogram: versions_histogram,
            details: Some(BucketDetails {
                versioning: true,
                versioning_suspended: false,
                locking: true,
                replication: false,
            }),
            prefix_usage,
            created: Some(now),
            access: AccountAccess {
                read: true,
                write: false,
            },
        };

        assert_eq!(bucket_info.name, "test-bucket");
        assert_eq!(bucket_info.size, 6000000);
        assert_eq!(bucket_info.objects, 150);
        assert_eq!(bucket_info.object_sizes_histogram.len(), 2);
        assert_eq!(bucket_info.object_versions_histogram.len(), 2);
        assert!(bucket_info.details.is_some());
        assert_eq!(bucket_info.prefix_usage.len(), 2);
        assert!(bucket_info.created.is_some());
        assert!(bucket_info.access.read);
        assert!(!bucket_info.access.write);
    }

    #[test]
    fn test_bucket_details_creation() {
        let details = BucketDetails {
            versioning: true,
            versioning_suspended: false,
            locking: true,
            replication: true,
        };

        assert!(details.versioning);
        assert!(!details.versioning_suspended);
        assert!(details.locking);
        assert!(details.replication);
    }

    #[test]
    fn test_account_access_creation() {
        let read_only = AccountAccess {
            read: true,
            write: false,
        };

        let full_access = AccountAccess { read: true, write: true };

        let no_access = AccountAccess {
            read: false,
            write: false,
        };

        assert!(read_only.read && !read_only.write);
        assert!(full_access.read && full_access.write);
        assert!(!no_access.read && !no_access.write);
    }

    #[test]
    fn test_serialization_deserialization_roundtrip() {
        let user_info = UserInfo {
            auth_info: Some(UserAuthInfo {
                auth_type: UserAuthType::Ldap,
                auth_server: Some("ldap.example.com".to_string()),
                auth_server_user_id: Some("user123".to_string()),
            }),
            secret_key: Some("secret123".to_string()),
            policy_name: Some("ReadOnlyAccess".to_string()),
            status: AccountStatus::Enabled,
            member_of: Some(vec!["group1".to_string()]),
            updated_at: None,
        };

        let json = serde_json::to_string(&user_info).unwrap();
        let deserialized: UserInfo = serde_json::from_str(&json).unwrap();

        assert_eq!(deserialized.secret_key.unwrap(), "secret123");
        assert_eq!(deserialized.policy_name.unwrap(), "ReadOnlyAccess");
        assert_eq!(deserialized.status, AccountStatus::Enabled);
        assert_eq!(deserialized.member_of.unwrap().len(), 1);
    }

    #[test]
    fn test_debug_format_all_structures() {
        let account_status = AccountStatus::Enabled;
        let user_auth_type = UserAuthType::Builtin;
        let user_info = UserInfo::default();
        let service_account = ServiceAccountInfo {
            parent_user: "test".to_string(),
            account_status: "enabled".to_string(),
            implied_policy: false,
            access_key: "key".to_string(),
            name: None,
            description: None,
            expiration: None,
        };

        // Test that all structures can be formatted with Debug
        assert!(!format!("{account_status:?}").is_empty());
        assert!(!format!("{user_auth_type:?}").is_empty());
        assert!(!format!("{user_info:?}").is_empty());
        assert!(!format!("{service_account:?}").is_empty());
    }

    #[test]
    fn test_memory_efficiency() {
        // Test that structures don't use excessive memory
        assert!(std::mem::size_of::<AccountStatus>() < 100);
        assert!(std::mem::size_of::<UserAuthType>() < 100);
        assert!(std::mem::size_of::<UserInfo>() < 2000);
        assert!(std::mem::size_of::<ServiceAccountInfo>() < 2000);
        assert!(std::mem::size_of::<AccountAccess>() < 100);
    }

    #[test]
    fn test_edge_cases() {
        // Test empty strings and edge cases
        let req = AddServiceAccountReq {
            policy: Some("".to_string()),
            target_user: Some("".to_string()),
            access_key: "valid_key".to_string(),
            secret_key: "valid_secret".to_string(),
            name: Some("valid_name".to_string()),
            description: Some("".to_string()),
            expiration: None,
        };

        // Should still validate successfully with empty optional strings
        assert!(req.validate().is_ok());

        // Test very long strings
        let long_string = "a".repeat(1000);
        let long_req = AddServiceAccountReq {
            policy: Some(long_string.clone()),
            target_user: Some(long_string.clone()),
            access_key: long_string.clone(),
            secret_key: long_string.clone(),
            name: Some(long_string.clone()),
            description: Some(long_string),
            expiration: None,
        };

        assert!(long_req.validate().is_ok());
    }
}