1use chrono::{DateTime, Utc};
2use parking_lot::RwLock;
3use serde::{Deserialize, Serialize};
4use std::collections::BTreeMap;
5
6use fakecloud_core::multi_account::{AccountState, MultiAccountState};
7
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct IamUser {
10 pub user_name: String,
11 pub user_id: String,
12 pub arn: String,
13 pub path: String,
14 pub created_at: DateTime<Utc>,
15 pub tags: Vec<Tag>,
16 pub permissions_boundary: Option<String>,
17}
18
19#[derive(Debug, Clone, Serialize, Deserialize)]
20pub struct IamAccessKey {
21 pub access_key_id: String,
22 pub secret_access_key: String,
23 pub user_name: String,
24 pub status: String,
25 pub created_at: DateTime<Utc>,
26}
27
28#[derive(Debug, Clone, Serialize, Deserialize)]
29pub struct IamRole {
30 pub role_name: String,
31 pub role_id: String,
32 pub arn: String,
33 pub path: String,
34 pub assume_role_policy_document: String,
35 pub created_at: DateTime<Utc>,
36 pub description: Option<String>,
37 pub max_session_duration: i32,
38 pub tags: Vec<Tag>,
39 pub permissions_boundary: Option<String>,
40}
41
42#[derive(Debug, Clone, Serialize, Deserialize)]
43pub struct IamPolicy {
44 pub policy_name: String,
45 pub policy_id: String,
46 pub arn: String,
47 pub path: String,
48 pub description: String,
49 pub created_at: DateTime<Utc>,
50 pub tags: Vec<Tag>,
51 pub default_version_id: String,
52 pub versions: Vec<PolicyVersion>,
53 pub next_version_num: u32,
54 pub attachment_count: u32,
55}
56
57#[derive(Debug, Clone, Serialize, Deserialize)]
58pub struct PolicyVersion {
59 pub version_id: String,
60 pub document: String,
61 pub is_default: bool,
62 pub created_at: DateTime<Utc>,
63}
64
65#[derive(Debug, Clone, Serialize, Deserialize)]
66pub struct IamGroup {
67 pub group_name: String,
68 pub group_id: String,
69 pub arn: String,
70 pub path: String,
71 pub created_at: DateTime<Utc>,
72 pub members: Vec<String>, pub inline_policies: BTreeMap<String, String>, pub attached_policies: Vec<String>, }
76
77#[derive(Debug, Clone, Serialize, Deserialize)]
78pub struct IamInstanceProfile {
79 pub instance_profile_name: String,
80 pub instance_profile_id: String,
81 pub arn: String,
82 pub path: String,
83 pub created_at: DateTime<Utc>,
84 pub roles: Vec<String>, pub tags: Vec<Tag>,
86}
87
88#[derive(Debug, Clone, Serialize, Deserialize)]
89pub struct Tag {
90 pub key: String,
91 pub value: String,
92}
93
94#[derive(Debug, Clone, Serialize, Deserialize)]
95pub struct LoginProfile {
96 pub user_name: String,
97 pub created_at: DateTime<Utc>,
98 pub password_reset_required: bool,
99 #[serde(default)]
105 pub password: String,
106}
107
108#[derive(Debug, Clone, Serialize, Deserialize)]
109pub struct SamlProvider {
110 pub arn: String,
111 pub name: String,
112 pub saml_metadata_document: String,
113 pub created_at: DateTime<Utc>,
114 pub valid_until: DateTime<Utc>,
115 pub tags: Vec<Tag>,
116}
117
118#[derive(Debug, Clone, Serialize, Deserialize)]
119pub struct OidcProvider {
120 pub arn: String,
121 pub url: String,
122 pub client_id_list: Vec<String>,
123 pub thumbprint_list: Vec<String>,
124 pub created_at: DateTime<Utc>,
125 pub tags: Vec<Tag>,
126}
127
128#[derive(Debug, Clone, Serialize, Deserialize)]
129pub struct ServerCertificate {
130 pub server_certificate_name: String,
131 pub server_certificate_id: String,
132 pub arn: String,
133 pub path: String,
134 pub certificate_body: String,
135 pub certificate_chain: Option<String>,
136 pub upload_date: DateTime<Utc>,
137 pub expiration: DateTime<Utc>,
138 pub tags: Vec<Tag>,
139}
140
141#[derive(Debug, Clone, Serialize, Deserialize)]
142pub struct SigningCertificate {
143 pub certificate_id: String,
144 pub user_name: String,
145 pub certificate_body: String,
146 pub status: String,
147 pub upload_date: DateTime<Utc>,
148}
149
150#[derive(Debug, Clone, Serialize, Deserialize)]
151pub struct AccountPasswordPolicy {
152 pub minimum_password_length: u32,
153 pub require_symbols: bool,
154 pub require_numbers: bool,
155 pub require_uppercase_characters: bool,
156 pub require_lowercase_characters: bool,
157 pub allow_users_to_change_password: bool,
158 pub max_password_age: u32,
159 pub password_reuse_prevention: u32,
160 pub hard_expiry: bool,
161}
162
163impl Default for AccountPasswordPolicy {
164 fn default() -> Self {
165 Self {
166 minimum_password_length: 6,
167 require_symbols: false,
168 require_numbers: false,
169 require_uppercase_characters: false,
170 require_lowercase_characters: false,
171 allow_users_to_change_password: false,
172 max_password_age: 0,
173 password_reuse_prevention: 0,
174 hard_expiry: false,
175 }
176 }
177}
178
179#[derive(Debug, Clone, Serialize, Deserialize)]
180pub struct VirtualMfaDevice {
181 pub serial_number: String,
182 pub base32_string_seed: String,
183 pub qr_code_png: String,
184 pub enable_date: Option<DateTime<Utc>>,
185 pub user: Option<String>,
186 pub tags: Vec<Tag>,
187}
188
189#[derive(Debug, Clone, Serialize, Deserialize)]
190pub struct ServiceLinkedRoleDeletion {
191 pub deletion_task_id: String,
192 pub status: String,
193}
194
195#[derive(Debug, Clone, Serialize, Deserialize)]
197pub struct CredentialIdentity {
198 pub arn: String,
199 pub user_id: String,
200 pub account_id: String,
201}
202
203#[derive(Debug, Clone, Serialize, Deserialize)]
213pub struct StsTempCredential {
214 pub access_key_id: String,
215 pub secret_access_key: String,
216 pub session_token: String,
217 pub principal_arn: String,
218 pub user_id: String,
219 pub account_id: String,
220 pub expiration: DateTime<Utc>,
221 #[serde(default)]
227 pub session_policies: Vec<String>,
228 #[serde(default)]
232 pub mfa_present: bool,
233 #[serde(default = "default_issued_at")]
238 pub issued_at: DateTime<Utc>,
239 #[serde(default)]
245 pub federated_provider: Option<String>,
246}
247
248fn default_issued_at() -> DateTime<Utc> {
251 Utc::now()
252}
253
254#[derive(Debug, Clone, PartialEq, Eq)]
261pub struct SecretLookup {
262 pub secret_access_key: String,
263 pub session_token: Option<String>,
264 pub principal_arn: String,
265 pub user_id: String,
266 pub account_id: String,
267 pub session_policies: Vec<String>,
270 pub principal_tags: Option<BTreeMap<String, String>>,
273 pub mfa_present: bool,
277 pub token_issued_at: Option<DateTime<Utc>>,
283 pub federated_provider: Option<String>,
288}
289
290pub fn tags_to_hashmap(tags: &[Tag]) -> Option<BTreeMap<String, String>> {
293 if tags.is_empty() {
294 return None;
295 }
296 Some(
297 tags.iter()
298 .map(|t| (t.key.clone(), t.value.clone()))
299 .collect(),
300 )
301}
302
303#[derive(Debug, Clone, Serialize, Deserialize)]
304pub struct SshPublicKey {
305 pub ssh_public_key_id: String,
306 pub user_name: String,
307 pub ssh_public_key_body: String,
308 pub status: String,
309 pub upload_date: DateTime<Utc>,
310 pub fingerprint: String,
311}
312
313#[derive(Debug, Clone, Serialize, Deserialize)]
315pub struct AccessKeyLastUsed {
316 pub last_used_date: DateTime<Utc>,
317 pub service_name: String,
318 pub region: String,
319}
320
321#[derive(Debug, Clone, Serialize, Deserialize)]
322pub struct IamState {
323 pub account_id: String,
324 pub users: BTreeMap<String, IamUser>,
325 pub access_keys: BTreeMap<String, Vec<IamAccessKey>>, pub roles: BTreeMap<String, IamRole>,
327 pub policies: BTreeMap<String, IamPolicy>, pub role_policies: BTreeMap<String, Vec<String>>, pub role_inline_policies: BTreeMap<String, BTreeMap<String, String>>, pub user_policies: BTreeMap<String, Vec<String>>, pub user_inline_policies: BTreeMap<String, BTreeMap<String, String>>, pub groups: BTreeMap<String, IamGroup>,
333 pub instance_profiles: BTreeMap<String, IamInstanceProfile>,
334 pub login_profiles: BTreeMap<String, LoginProfile>,
335 pub saml_providers: BTreeMap<String, SamlProvider>, pub oidc_providers: BTreeMap<String, OidcProvider>, pub server_certificates: BTreeMap<String, ServerCertificate>, pub signing_certificates: BTreeMap<String, Vec<SigningCertificate>>, pub account_aliases: Vec<String>,
340 pub account_password_policy: Option<AccountPasswordPolicy>,
341 pub virtual_mfa_devices: BTreeMap<String, VirtualMfaDevice>, pub service_linked_role_deletions: BTreeMap<String, ServiceLinkedRoleDeletion>,
343 pub credential_identities: BTreeMap<String, CredentialIdentity>,
345 pub sts_temp_credentials: BTreeMap<String, StsTempCredential>,
350 pub credential_report_generated: bool,
351 pub ssh_public_keys: BTreeMap<String, Vec<SshPublicKey>>, pub access_key_last_used: BTreeMap<String, AccessKeyLastUsed>,
353 #[serde(default)]
355 pub service_specific_credentials: BTreeMap<String, Vec<ServiceSpecificCredential>>, #[serde(default)]
358 pub extra_tags: BTreeMap<String, Vec<(String, String)>>,
359 #[serde(default)]
361 pub organizations_root_credentials_management: bool,
362 #[serde(default)]
363 pub organizations_root_sessions: bool,
364 #[serde(default)]
366 pub service_last_accessed_jobs: BTreeMap<String, ServiceLastAccessedJob>,
367 #[serde(default)]
369 pub organizations_access_reports: BTreeMap<String, OrganizationsAccessReport>,
370 #[serde(default)]
373 pub global_endpoint_token_version: Option<String>,
374}
375
376#[derive(Debug, Clone, Serialize, Deserialize)]
377pub struct ServiceSpecificCredential {
378 pub credential_id: String,
379 pub user_name: String,
380 pub service_name: String,
381 pub service_user_name: String,
382 pub service_password: String,
383 pub status: String,
384 pub create_date: DateTime<Utc>,
385}
386
387#[derive(Debug, Clone, Serialize, Deserialize)]
388pub struct ServiceLastAccessedJob {
389 pub job_id: String,
390 pub status: String,
391 pub job_creation_date: DateTime<Utc>,
392 pub arn: String,
393}
394
395#[derive(Debug, Clone, Serialize, Deserialize)]
396pub struct OrganizationsAccessReport {
397 pub job_id: String,
398 pub status: String,
399 pub created_at: DateTime<Utc>,
400 pub entity_path: String,
401}
402
403impl IamState {
404 pub fn new(account_id: &str) -> Self {
405 Self {
406 account_id: account_id.to_string(),
407 users: BTreeMap::new(),
408 access_keys: BTreeMap::new(),
409 roles: BTreeMap::new(),
410 policies: BTreeMap::new(),
411 role_policies: BTreeMap::new(),
412 role_inline_policies: BTreeMap::new(),
413 user_policies: BTreeMap::new(),
414 user_inline_policies: BTreeMap::new(),
415 groups: BTreeMap::new(),
416 instance_profiles: BTreeMap::new(),
417 login_profiles: BTreeMap::new(),
418 saml_providers: BTreeMap::new(),
419 oidc_providers: BTreeMap::new(),
420 server_certificates: BTreeMap::new(),
421 signing_certificates: BTreeMap::new(),
422 account_aliases: Vec::new(),
423 account_password_policy: None,
424 virtual_mfa_devices: BTreeMap::new(),
425 service_linked_role_deletions: BTreeMap::new(),
426 credential_identities: BTreeMap::new(),
427 sts_temp_credentials: BTreeMap::new(),
428 credential_report_generated: false,
429 ssh_public_keys: BTreeMap::new(),
430 access_key_last_used: BTreeMap::new(),
431 service_specific_credentials: BTreeMap::new(),
432 extra_tags: BTreeMap::new(),
433 organizations_root_credentials_management: false,
434 organizations_root_sessions: false,
435 service_last_accessed_jobs: BTreeMap::new(),
436 organizations_access_reports: BTreeMap::new(),
437 global_endpoint_token_version: None,
438 }
439 }
440
441 pub fn reset(&mut self) {
442 let account_id = self.account_id.clone();
443 *self = Self::new(&account_id);
444 }
445
446 pub fn credential_secret(&mut self, access_key_id: &str) -> Option<SecretLookup> {
460 for keys in self.access_keys.values() {
463 for key in keys {
464 if key.access_key_id == access_key_id {
465 if let Some(user) = self.users.get(&key.user_name) {
466 return Some(SecretLookup {
467 secret_access_key: key.secret_access_key.clone(),
468 session_token: None,
469 principal_arn: user.arn.clone(),
470 user_id: user.user_id.clone(),
471 account_id: self.account_id.clone(),
472 session_policies: Vec::new(),
473 principal_tags: tags_to_hashmap(&user.tags),
474 mfa_present: false,
475 token_issued_at: None,
476 federated_provider: None,
477 });
478 }
479 }
480 }
481 }
482
483 let now = Utc::now();
486 if let Some(temp) = self.sts_temp_credentials.get(access_key_id) {
487 if temp.expiration > now {
488 let principal_tags = self.resolve_role_tags(&temp.principal_arn);
489 return Some(SecretLookup {
490 secret_access_key: temp.secret_access_key.clone(),
491 session_token: Some(temp.session_token.clone()),
492 principal_arn: temp.principal_arn.clone(),
493 user_id: temp.user_id.clone(),
494 account_id: temp.account_id.clone(),
495 session_policies: temp.session_policies.clone(),
496 principal_tags,
497 mfa_present: temp.mfa_present,
498 token_issued_at: Some(temp.issued_at),
499 federated_provider: temp.federated_provider.clone(),
500 });
501 }
502 self.sts_temp_credentials.remove(access_key_id);
503 }
504 None
505 }
506
507 pub fn credential_secret_readonly(&self, access_key_id: &str) -> Option<SecretLookup> {
511 for keys in self.access_keys.values() {
512 for key in keys {
513 if key.access_key_id == access_key_id {
514 if let Some(user) = self.users.get(&key.user_name) {
515 return Some(SecretLookup {
516 secret_access_key: key.secret_access_key.clone(),
517 session_token: None,
518 principal_arn: user.arn.clone(),
519 user_id: user.user_id.clone(),
520 account_id: self.account_id.clone(),
521 session_policies: Vec::new(),
522 principal_tags: tags_to_hashmap(&user.tags),
523 mfa_present: false,
524 token_issued_at: None,
525 federated_provider: None,
526 });
527 }
528 }
529 }
530 }
531
532 let now = Utc::now();
533 let temp = self.sts_temp_credentials.get(access_key_id)?;
534 if temp.expiration <= now {
535 return None;
536 }
537 let principal_tags = self.resolve_role_tags(&temp.principal_arn);
538 Some(SecretLookup {
539 secret_access_key: temp.secret_access_key.clone(),
540 session_token: Some(temp.session_token.clone()),
541 principal_arn: temp.principal_arn.clone(),
542 user_id: temp.user_id.clone(),
543 account_id: temp.account_id.clone(),
544 session_policies: temp.session_policies.clone(),
545 principal_tags,
546 mfa_present: temp.mfa_present,
547 token_issued_at: Some(temp.issued_at),
548 federated_provider: temp.federated_provider.clone(),
549 })
550 }
551
552 fn resolve_role_tags(&self, principal_arn: &str) -> Option<BTreeMap<String, String>> {
556 let parts: Vec<&str> = principal_arn.split(':').collect();
558 if parts.len() < 6 {
559 return None;
560 }
561 let resource = parts[5];
562 if let Some(rest) = resource.strip_prefix("assumed-role/") {
563 let role_name = rest.split('/').next()?;
564 let role = self.roles.get(role_name)?;
565 return tags_to_hashmap(&role.tags);
566 }
567 None
568 }
569}
570
571impl AccountState for IamState {
572 fn new_for_account(account_id: &str, _region: &str, _endpoint: &str) -> Self {
573 Self::new(account_id)
574 }
575}
576
577pub type SharedIamState = std::sync::Arc<RwLock<MultiAccountState<IamState>>>;
578
579#[derive(Debug, Clone, Serialize, Deserialize)]
585pub struct IamSnapshot {
586 pub schema_version: u32,
587 #[serde(default)]
589 pub accounts: Option<MultiAccountState<IamState>>,
590 #[serde(default)]
592 pub state: Option<IamState>,
593}
594
595pub const IAM_SNAPSHOT_SCHEMA_VERSION: u32 = 2;
596
597#[cfg(test)]
598mod tests {
599 use super::*;
600 use fakecloud_aws::arn::Arn;
601
602 fn iam_user(name: &str, account_id: &str) -> IamUser {
603 IamUser {
604 user_name: name.to_string(),
605 user_id: format!("AIDA{}", name.to_uppercase()),
606 arn: Arn::global("iam", account_id, &format!("user/{name}")).to_string(),
607 path: "/".to_string(),
608 created_at: Utc::now(),
609 tags: Vec::new(),
610 permissions_boundary: None,
611 }
612 }
613
614 fn iam_key(user: &str, akid: &str, secret: &str) -> IamAccessKey {
615 IamAccessKey {
616 access_key_id: akid.to_string(),
617 secret_access_key: secret.to_string(),
618 user_name: user.to_string(),
619 status: "Active".to_string(),
620 created_at: Utc::now(),
621 }
622 }
623
624 #[test]
625 fn credential_secret_returns_iam_user_key() {
626 let mut state = IamState::new("123456789012");
627 state
628 .users
629 .insert("alice".to_string(), iam_user("alice", "123456789012"));
630 state.access_keys.insert(
631 "alice".to_string(),
632 vec![iam_key("alice", "FKIAALICE", "secret-alice")],
633 );
634 let lookup = state.credential_secret("FKIAALICE").unwrap();
635 assert_eq!(lookup.secret_access_key, "secret-alice");
636 assert_eq!(lookup.principal_arn, "arn:aws:iam::123456789012:user/alice");
637 assert_eq!(lookup.account_id, "123456789012");
638 assert_eq!(lookup.session_token, None);
639 }
640
641 #[test]
642 fn credential_secret_returns_sts_temp_credential_when_unexpired() {
643 let mut state = IamState::new("123456789012");
644 state.sts_temp_credentials.insert(
645 "FSIATEMPKEY".to_string(),
646 StsTempCredential {
647 access_key_id: "FSIATEMPKEY".to_string(),
648 secret_access_key: "temp-secret".to_string(),
649 session_token: "temp-token".to_string(),
650 principal_arn: "arn:aws:sts::123456789012:assumed-role/R/s".to_string(),
651 user_id: "AROA:session".to_string(),
652 account_id: "123456789012".to_string(),
653 expiration: Utc::now() + chrono::Duration::minutes(30),
654 session_policies: Vec::new(),
655 mfa_present: false,
656 issued_at: Utc::now(),
657 federated_provider: None,
658 },
659 );
660 let lookup = state.credential_secret("FSIATEMPKEY").unwrap();
661 assert_eq!(lookup.secret_access_key, "temp-secret");
662 assert_eq!(lookup.session_token.as_deref(), Some("temp-token"));
663 assert_eq!(
664 lookup.principal_arn,
665 "arn:aws:sts::123456789012:assumed-role/R/s"
666 );
667 }
668
669 #[test]
670 fn credential_secret_purges_expired_sts_credentials() {
671 let mut state = IamState::new("123456789012");
672 state.sts_temp_credentials.insert(
673 "FSIAOLD".to_string(),
674 StsTempCredential {
675 access_key_id: "FSIAOLD".to_string(),
676 secret_access_key: "s".to_string(),
677 session_token: "t".to_string(),
678 principal_arn: "arn".to_string(),
679 user_id: "id".to_string(),
680 account_id: "123456789012".to_string(),
681 expiration: Utc::now() - chrono::Duration::seconds(1),
682 session_policies: Vec::new(),
683 mfa_present: false,
684 issued_at: Utc::now(),
685 federated_provider: None,
686 },
687 );
688 assert!(state.credential_secret("FSIAOLD").is_none());
689 assert!(!state.sts_temp_credentials.contains_key("FSIAOLD"));
690 }
691
692 #[test]
693 fn credential_secret_readonly_does_not_purge() {
694 let mut state = IamState::new("123456789012");
695 state.sts_temp_credentials.insert(
696 "FSIAOLD".to_string(),
697 StsTempCredential {
698 access_key_id: "FSIAOLD".to_string(),
699 secret_access_key: "s".to_string(),
700 session_token: "t".to_string(),
701 principal_arn: "arn".to_string(),
702 user_id: "id".to_string(),
703 account_id: "123456789012".to_string(),
704 expiration: Utc::now() - chrono::Duration::seconds(1),
705 session_policies: Vec::new(),
706 mfa_present: false,
707 issued_at: Utc::now(),
708 federated_provider: None,
709 },
710 );
711 assert!(state.credential_secret_readonly("FSIAOLD").is_none());
712 assert!(state.sts_temp_credentials.contains_key("FSIAOLD"));
713 }
714
715 #[test]
716 fn credential_secret_returns_none_for_unknown_akid() {
717 let mut state = IamState::new("123456789012");
718 assert!(state.credential_secret("FKIAUNKNOWN").is_none());
719 }
720}