Skip to main content

fakecloud_iam/
state.rs

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>,                      // user names
73    pub inline_policies: BTreeMap<String, String>, // policy_name -> document
74    pub attached_policies: Vec<String>,            // policy ARNs
75}
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>, // role names
85    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    /// Console password. Stored in plaintext for emulator parity —
100    /// fakecloud is not a security boundary, and round-tripping it
101    /// is what `ChangePassword` / `UpdateLoginProfile` need to
102    /// validate against. Empty for legacy snapshots that pre-date
103    /// password storage.
104    #[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/// Identity associated with a set of credentials, for GetCallerIdentity resolution.
196#[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/// A temporary credential issued by STS (`AssumeRole`, `AssumeRoleWithWebIdentity`,
204/// `AssumeRoleWithSAML`, `GetSessionToken`, `GetFederationToken`).
205///
206/// Unlike [`CredentialIdentity`], which only remembers the principal ARN for
207/// `GetCallerIdentity`, this struct also retains the secret access key and
208/// session token so that SigV4 verification and IAM enforcement (added in
209/// later batches) can look them up when a client signs a request with
210/// temporary credentials. `expiration` is the absolute wall-clock time at
211/// which the credential becomes invalid.
212#[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    /// Session policies passed to the STS call that minted this credential.
222    /// Raw JSON policy documents. The `Policy` parameter contributes one
223    /// entry; `PolicyArns` contribute additional entries (resolved to
224    /// documents at mint time). Empty when the STS call carried no
225    /// session policies.
226    #[serde(default)]
227    pub session_policies: Vec<String>,
228    /// True iff the AssumeRole / GetSessionToken call that minted this
229    /// credential supplied MFA (`SerialNumber` + `TokenCode`). Surfaces
230    /// to downstream IAM evaluation as `aws:MultiFactorAuthPresent`.
231    #[serde(default)]
232    pub mfa_present: bool,
233    /// Wall-clock time at which the credential was issued. Surfaces to
234    /// downstream IAM evaluation as `aws:TokenIssueTime` and feeds
235    /// `aws:MultiFactorAuthAge` (computed at evaluation time as
236    /// `now - issued_at` in seconds when MFA was asserted).
237    #[serde(default = "default_issued_at")]
238    pub issued_at: DateTime<Utc>,
239    /// `aws:FederatedProvider` — for AssumeRoleWithSAML this is the
240    /// SAML provider ARN; for AssumeRoleWithWebIdentity it is the OIDC
241    /// provider ARN (or a friendly host name like
242    /// `cognito-identity.amazonaws.com`); `None` for plain AssumeRole /
243    /// GetSessionToken / GetFederationToken.
244    #[serde(default)]
245    pub federated_provider: Option<String>,
246}
247
248/// Default for [`StsTempCredential::issued_at`] when deserializing
249/// snapshots written before the field existed.
250fn default_issued_at() -> DateTime<Utc> {
251    Utc::now()
252}
253
254/// Result of looking up a set of credentials by access key ID.
255///
256/// Carries the secret + resolved principal + owning account id. The account
257/// id is intentionally read from the credential itself rather than from
258/// global config, so that once #381 (multi-account isolation) lands, the same
259/// lookup already returns the correct account for the credential.
260#[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    /// Session policies from the STS call that minted this credential.
268    /// Empty for IAM user access keys.
269    pub session_policies: Vec<String>,
270    /// Tags on the principal (IAM user or assumed role) for
271    /// `aws:PrincipalTag/<key>` condition evaluation.
272    pub principal_tags: Option<BTreeMap<String, String>>,
273    /// True when the underlying STS credential was minted with MFA;
274    /// surfaces as `aws:MultiFactorAuthPresent` to downstream IAM
275    /// evaluation. Always false for raw IAM user access keys.
276    pub mfa_present: bool,
277    /// Wall-clock time at which the underlying STS credential was
278    /// issued. Surfaces as `aws:TokenIssueTime` and drives
279    /// `aws:MultiFactorAuthAge`. `None` for raw IAM user access keys
280    /// (AWS does not expose `aws:TokenIssueTime` for long-lived
281    /// credentials).
282    pub token_issued_at: Option<DateTime<Utc>>,
283    /// `aws:FederatedProvider` for the underlying credential, when
284    /// applicable. Set by AssumeRoleWithSAML / AssumeRoleWithWebIdentity;
285    /// always `None` for IAM user keys, plain AssumeRole, GetSessionToken,
286    /// and GetFederationToken.
287    pub federated_provider: Option<String>,
288}
289
290/// Convert a `Vec<Tag>` to a `BTreeMap<String, String>`.
291/// Returns `None` when the input is empty (no tags to evaluate).
292pub 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/// Tracks when an access key was last used.
314#[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>>, // username -> keys
326    pub roles: BTreeMap<String, IamRole>,
327    pub policies: BTreeMap<String, IamPolicy>, // arn -> policy
328    pub role_policies: BTreeMap<String, Vec<String>>, // role_name -> managed policy arns
329    pub role_inline_policies: BTreeMap<String, BTreeMap<String, String>>, // role_name -> {policy_name -> doc}
330    pub user_policies: BTreeMap<String, Vec<String>>, // user_name -> managed policy arns
331    pub user_inline_policies: BTreeMap<String, BTreeMap<String, String>>, // user_name -> {policy_name -> doc}
332    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>, // arn -> provider
336    pub oidc_providers: BTreeMap<String, OidcProvider>, // arn -> provider
337    pub server_certificates: BTreeMap<String, ServerCertificate>, // name -> cert
338    pub signing_certificates: BTreeMap<String, Vec<SigningCertificate>>, // user_name -> certs
339    pub account_aliases: Vec<String>,
340    pub account_password_policy: Option<AccountPasswordPolicy>,
341    pub virtual_mfa_devices: BTreeMap<String, VirtualMfaDevice>, // serial_number -> device
342    pub service_linked_role_deletions: BTreeMap<String, ServiceLinkedRoleDeletion>,
343    /// Maps access key ID to the identity that should be returned by GetCallerIdentity.
344    pub credential_identities: BTreeMap<String, CredentialIdentity>,
345    /// Temporary credentials issued by STS, keyed by access key ID. Includes
346    /// the secret access key and session token — required for SigV4
347    /// verification and IAM enforcement. Expired entries are purged lazily on
348    /// lookup.
349    pub sts_temp_credentials: BTreeMap<String, StsTempCredential>,
350    pub credential_report_generated: bool,
351    pub ssh_public_keys: BTreeMap<String, Vec<SshPublicKey>>, // user_name -> keys
352    pub access_key_last_used: BTreeMap<String, AccessKeyLastUsed>,
353    /// Per-user service-specific credentials (Codecommit/Keyspaces).
354    #[serde(default)]
355    pub service_specific_credentials: BTreeMap<String, Vec<ServiceSpecificCredential>>, // user -> creds
356    /// Per-resource-arn tag map for SAML/Server cert/MFA device tags.
357    #[serde(default)]
358    pub extra_tags: BTreeMap<String, Vec<(String, String)>>,
359    /// Organizations integration toggles.
360    #[serde(default)]
361    pub organizations_root_credentials_management: bool,
362    #[serde(default)]
363    pub organizations_root_sessions: bool,
364    /// Generated ServiceLastAccessed jobs keyed by job id.
365    #[serde(default)]
366    pub service_last_accessed_jobs: BTreeMap<String, ServiceLastAccessedJob>,
367    /// Organizations access reports keyed by job id.
368    #[serde(default)]
369    pub organizations_access_reports: BTreeMap<String, OrganizationsAccessReport>,
370    /// `SetSecurityTokenServicePreferences` value (e.g. `v1Token`,
371    /// `v2Token`). `None` means caller hasn't configured a preference.
372    #[serde(default)]
373    pub global_endpoint_token_version: Option<String>,
374    /// Delegation requests keyed by id. Records every state transition
375    /// (`PENDING` -> `ACCEPTED`/`REJECTED`/`SENT`) and the parameters
376    /// supplied at create-time so `GetDelegationRequest` can roundtrip
377    /// them.
378    #[serde(default)]
379    pub delegation_requests: BTreeMap<String, DelegationRequest>,
380    /// Whether outbound web identity federation is enabled for this
381    /// account. Toggled by `EnableOutboundWebIdentityFederation` /
382    /// `DisableOutboundWebIdentityFederation`.
383    #[serde(default)]
384    pub outbound_web_identity_federation_enabled: bool,
385}
386
387#[derive(Debug, Clone, Serialize, Deserialize)]
388pub struct DelegationRequest {
389    pub id: String,
390    pub owner_account_id: Option<String>,
391    pub description: String,
392    pub request_message: Option<String>,
393    pub requestor_workflow_id: String,
394    pub redirect_url: Option<String>,
395    pub notification_channel: String,
396    pub session_duration: i64,
397    pub only_send_by_owner: bool,
398    pub status: String,
399    pub notes: Option<String>,
400    pub created_at: DateTime<Utc>,
401    pub policy_template_arn: Option<String>,
402}
403
404#[derive(Debug, Clone, Serialize, Deserialize)]
405pub struct ServiceSpecificCredential {
406    pub credential_id: String,
407    pub user_name: String,
408    pub service_name: String,
409    pub service_user_name: String,
410    pub service_password: String,
411    pub status: String,
412    pub create_date: DateTime<Utc>,
413}
414
415#[derive(Debug, Clone, Serialize, Deserialize)]
416pub struct ServiceLastAccessedJob {
417    pub job_id: String,
418    pub status: String,
419    pub job_creation_date: DateTime<Utc>,
420    pub arn: String,
421}
422
423#[derive(Debug, Clone, Serialize, Deserialize)]
424pub struct OrganizationsAccessReport {
425    pub job_id: String,
426    pub status: String,
427    pub created_at: DateTime<Utc>,
428    pub entity_path: String,
429}
430
431impl IamState {
432    pub fn new(account_id: &str) -> Self {
433        Self {
434            account_id: account_id.to_string(),
435            users: BTreeMap::new(),
436            access_keys: BTreeMap::new(),
437            roles: BTreeMap::new(),
438            policies: BTreeMap::new(),
439            role_policies: BTreeMap::new(),
440            role_inline_policies: BTreeMap::new(),
441            user_policies: BTreeMap::new(),
442            user_inline_policies: BTreeMap::new(),
443            groups: BTreeMap::new(),
444            instance_profiles: BTreeMap::new(),
445            login_profiles: BTreeMap::new(),
446            saml_providers: BTreeMap::new(),
447            oidc_providers: BTreeMap::new(),
448            server_certificates: BTreeMap::new(),
449            signing_certificates: BTreeMap::new(),
450            account_aliases: Vec::new(),
451            account_password_policy: None,
452            virtual_mfa_devices: BTreeMap::new(),
453            service_linked_role_deletions: BTreeMap::new(),
454            credential_identities: BTreeMap::new(),
455            sts_temp_credentials: BTreeMap::new(),
456            credential_report_generated: false,
457            ssh_public_keys: BTreeMap::new(),
458            access_key_last_used: BTreeMap::new(),
459            service_specific_credentials: BTreeMap::new(),
460            extra_tags: BTreeMap::new(),
461            organizations_root_credentials_management: false,
462            organizations_root_sessions: false,
463            service_last_accessed_jobs: BTreeMap::new(),
464            organizations_access_reports: BTreeMap::new(),
465            global_endpoint_token_version: None,
466            delegation_requests: BTreeMap::new(),
467            outbound_web_identity_federation_enabled: false,
468        }
469    }
470
471    pub fn reset(&mut self) {
472        let account_id = self.account_id.clone();
473        *self = Self::new(&account_id);
474    }
475
476    /// Look up the secret access key, session token, and resolved principal
477    /// for a given access key ID.
478    ///
479    /// Searches IAM user access keys first, then STS temporary credentials.
480    /// Expired STS temporary credentials are purged in-place and skipped.
481    ///
482    /// Returns `None` if the AKID is unknown or its STS credential has
483    /// expired.
484    ///
485    /// Required for SigV4 signature verification (batch 3) and principal
486    /// resolution (batch 4). Callers must hold a write lock on
487    /// [`IamState`] to allow the lazy purge; read-only callers should use
488    /// [`IamState::credential_secret_readonly`].
489    pub fn credential_secret(&mut self, access_key_id: &str) -> Option<SecretLookup> {
490        // IAM user access keys: look up by scanning (same pattern the
491        // existing GetCallerIdentity path uses).
492        for keys in self.access_keys.values() {
493            for key in keys {
494                // Deactivated (Inactive) keys must not authenticate; AWS
495                // returns InvalidClientTokenId. Skipping makes the lookup miss
496                // (bug-audit 2026-05-28, 5.1).
497                if key.access_key_id == access_key_id && key.status == "Active" {
498                    if let Some(user) = self.users.get(&key.user_name) {
499                        return Some(SecretLookup {
500                            secret_access_key: key.secret_access_key.clone(),
501                            session_token: None,
502                            principal_arn: user.arn.clone(),
503                            user_id: user.user_id.clone(),
504                            account_id: self.account_id.clone(),
505                            session_policies: Vec::new(),
506                            principal_tags: tags_to_hashmap(&user.tags),
507                            mfa_present: false,
508                            token_issued_at: None,
509                            federated_provider: None,
510                        });
511                    }
512                }
513            }
514        }
515
516        // STS temporary credentials: direct hash lookup, with lazy expiry
517        // purging so expired entries don't accumulate.
518        let now = Utc::now();
519        if let Some(temp) = self.sts_temp_credentials.get(access_key_id) {
520            if temp.expiration > now {
521                let principal_tags = self.resolve_role_tags(&temp.principal_arn);
522                return Some(SecretLookup {
523                    secret_access_key: temp.secret_access_key.clone(),
524                    session_token: Some(temp.session_token.clone()),
525                    principal_arn: temp.principal_arn.clone(),
526                    user_id: temp.user_id.clone(),
527                    account_id: temp.account_id.clone(),
528                    session_policies: temp.session_policies.clone(),
529                    principal_tags,
530                    mfa_present: temp.mfa_present,
531                    token_issued_at: Some(temp.issued_at),
532                    federated_provider: temp.federated_provider.clone(),
533                });
534            }
535            self.sts_temp_credentials.remove(access_key_id);
536        }
537        None
538    }
539
540    /// Read-only variant of [`IamState::credential_secret`] that does not
541    /// purge expired entries. Prefer the mutable variant wherever possible
542    /// to keep the temp-credential table small.
543    pub fn credential_secret_readonly(&self, access_key_id: &str) -> Option<SecretLookup> {
544        for keys in self.access_keys.values() {
545            for key in keys {
546                // Deactivated (Inactive) keys must not authenticate; AWS
547                // returns InvalidClientTokenId. Skipping makes the lookup miss
548                // (bug-audit 2026-05-28, 5.1).
549                if key.access_key_id == access_key_id && key.status == "Active" {
550                    if let Some(user) = self.users.get(&key.user_name) {
551                        return Some(SecretLookup {
552                            secret_access_key: key.secret_access_key.clone(),
553                            session_token: None,
554                            principal_arn: user.arn.clone(),
555                            user_id: user.user_id.clone(),
556                            account_id: self.account_id.clone(),
557                            session_policies: Vec::new(),
558                            principal_tags: tags_to_hashmap(&user.tags),
559                            mfa_present: false,
560                            token_issued_at: None,
561                            federated_provider: None,
562                        });
563                    }
564                }
565            }
566        }
567
568        let now = Utc::now();
569        let temp = self.sts_temp_credentials.get(access_key_id)?;
570        if temp.expiration <= now {
571            return None;
572        }
573        let principal_tags = self.resolve_role_tags(&temp.principal_arn);
574        Some(SecretLookup {
575            secret_access_key: temp.secret_access_key.clone(),
576            session_token: Some(temp.session_token.clone()),
577            principal_arn: temp.principal_arn.clone(),
578            user_id: temp.user_id.clone(),
579            account_id: temp.account_id.clone(),
580            session_policies: temp.session_policies.clone(),
581            principal_tags,
582            mfa_present: temp.mfa_present,
583            token_issued_at: Some(temp.issued_at),
584            federated_provider: temp.federated_provider.clone(),
585        })
586    }
587
588    /// Resolve role tags from an assumed-role principal ARN.
589    /// ARN format: `arn:aws:sts::<account>:assumed-role/<role-name>/<session>`
590    /// Looks up the role by name and returns its tags.
591    fn resolve_role_tags(&self, principal_arn: &str) -> Option<BTreeMap<String, String>> {
592        // assumed-role ARNs: arn:aws:sts::<account>:assumed-role/<role>/<session>
593        let parts: Vec<&str> = principal_arn.split(':').collect();
594        if parts.len() < 6 {
595            return None;
596        }
597        let resource = parts[5];
598        if let Some(rest) = resource.strip_prefix("assumed-role/") {
599            let role_name = rest.split('/').next()?;
600            let role = self.roles.get(role_name)?;
601            return tags_to_hashmap(&role.tags);
602        }
603        None
604    }
605}
606
607impl AccountState for IamState {
608    fn new_for_account(account_id: &str, _region: &str, _endpoint: &str) -> Self {
609        Self::new(account_id)
610    }
611}
612
613pub type SharedIamState = std::sync::Arc<RwLock<MultiAccountState<IamState>>>;
614
615/// On-disk snapshot envelope for IAM state. Versioned so future schema
616/// changes fail loudly instead of silently corrupting state.
617///
618/// Schema v2 stores multi-account state. v1 snapshots are migrated on
619/// load by wrapping the single `IamState` as the default account.
620#[derive(Debug, Clone, Serialize, Deserialize)]
621pub struct IamSnapshot {
622    pub schema_version: u32,
623    /// v2+: multi-account state. Present when `schema_version >= 2`.
624    #[serde(default)]
625    pub accounts: Option<MultiAccountState<IamState>>,
626    /// v1 compat: single-account state. Present when `schema_version == 1`.
627    #[serde(default)]
628    pub state: Option<IamState>,
629}
630
631pub const IAM_SNAPSHOT_SCHEMA_VERSION: u32 = 2;
632
633#[cfg(test)]
634mod tests {
635    use super::*;
636    use fakecloud_aws::arn::Arn;
637
638    fn iam_user(name: &str, account_id: &str) -> IamUser {
639        IamUser {
640            user_name: name.to_string(),
641            user_id: format!("AIDA{}", name.to_uppercase()),
642            arn: Arn::global("iam", account_id, &format!("user/{name}")).to_string(),
643            path: "/".to_string(),
644            created_at: Utc::now(),
645            tags: Vec::new(),
646            permissions_boundary: None,
647        }
648    }
649
650    fn iam_key(user: &str, akid: &str, secret: &str) -> IamAccessKey {
651        IamAccessKey {
652            access_key_id: akid.to_string(),
653            secret_access_key: secret.to_string(),
654            user_name: user.to_string(),
655            status: "Active".to_string(),
656            created_at: Utc::now(),
657        }
658    }
659
660    #[test]
661    fn credential_secret_returns_iam_user_key() {
662        let mut state = IamState::new("123456789012");
663        state
664            .users
665            .insert("alice".to_string(), iam_user("alice", "123456789012"));
666        state.access_keys.insert(
667            "alice".to_string(),
668            vec![iam_key("alice", "FKIAALICE", "secret-alice")],
669        );
670        let lookup = state.credential_secret("FKIAALICE").unwrap();
671        assert_eq!(lookup.secret_access_key, "secret-alice");
672        assert_eq!(lookup.principal_arn, "arn:aws:iam::123456789012:user/alice");
673        assert_eq!(lookup.account_id, "123456789012");
674        assert_eq!(lookup.session_token, None);
675    }
676
677    #[test]
678    fn credential_secret_returns_sts_temp_credential_when_unexpired() {
679        let mut state = IamState::new("123456789012");
680        state.sts_temp_credentials.insert(
681            "FSIATEMPKEY".to_string(),
682            StsTempCredential {
683                access_key_id: "FSIATEMPKEY".to_string(),
684                secret_access_key: "temp-secret".to_string(),
685                session_token: "temp-token".to_string(),
686                principal_arn: "arn:aws:sts::123456789012:assumed-role/R/s".to_string(),
687                user_id: "AROA:session".to_string(),
688                account_id: "123456789012".to_string(),
689                expiration: Utc::now() + chrono::Duration::minutes(30),
690                session_policies: Vec::new(),
691                mfa_present: false,
692                issued_at: Utc::now(),
693                federated_provider: None,
694            },
695        );
696        let lookup = state.credential_secret("FSIATEMPKEY").unwrap();
697        assert_eq!(lookup.secret_access_key, "temp-secret");
698        assert_eq!(lookup.session_token.as_deref(), Some("temp-token"));
699        assert_eq!(
700            lookup.principal_arn,
701            "arn:aws:sts::123456789012:assumed-role/R/s"
702        );
703    }
704
705    #[test]
706    fn credential_secret_purges_expired_sts_credentials() {
707        let mut state = IamState::new("123456789012");
708        state.sts_temp_credentials.insert(
709            "FSIAOLD".to_string(),
710            StsTempCredential {
711                access_key_id: "FSIAOLD".to_string(),
712                secret_access_key: "s".to_string(),
713                session_token: "t".to_string(),
714                principal_arn: "arn".to_string(),
715                user_id: "id".to_string(),
716                account_id: "123456789012".to_string(),
717                expiration: Utc::now() - chrono::Duration::seconds(1),
718                session_policies: Vec::new(),
719                mfa_present: false,
720                issued_at: Utc::now(),
721                federated_provider: None,
722            },
723        );
724        assert!(state.credential_secret("FSIAOLD").is_none());
725        assert!(!state.sts_temp_credentials.contains_key("FSIAOLD"));
726    }
727
728    #[test]
729    fn credential_secret_readonly_does_not_purge() {
730        let mut state = IamState::new("123456789012");
731        state.sts_temp_credentials.insert(
732            "FSIAOLD".to_string(),
733            StsTempCredential {
734                access_key_id: "FSIAOLD".to_string(),
735                secret_access_key: "s".to_string(),
736                session_token: "t".to_string(),
737                principal_arn: "arn".to_string(),
738                user_id: "id".to_string(),
739                account_id: "123456789012".to_string(),
740                expiration: Utc::now() - chrono::Duration::seconds(1),
741                session_policies: Vec::new(),
742                mfa_present: false,
743                issued_at: Utc::now(),
744                federated_provider: None,
745            },
746        );
747        assert!(state.credential_secret_readonly("FSIAOLD").is_none());
748        assert!(state.sts_temp_credentials.contains_key("FSIAOLD"));
749    }
750
751    #[test]
752    fn credential_secret_returns_none_for_unknown_akid() {
753        let mut state = IamState::new("123456789012");
754        assert!(state.credential_secret("FKIAUNKNOWN").is_none());
755    }
756
757    // bug-audit 2026-05-28, 5.1: a deactivated (Inactive) access key must not
758    // authenticate, so the credential lookup must miss.
759    #[test]
760    fn credential_secret_skips_inactive_key() {
761        let mut state = IamState::new("123456789012");
762        let mut key = iam_key("alice", "FKIAALICE", "secret123");
763        key.status = "Inactive".to_string();
764        state.access_keys.insert("alice".to_string(), vec![key]);
765        assert!(state.credential_secret("FKIAALICE").is_none());
766    }
767}