alien-aws-clients 1.2.15

Alien Developer Platform
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
use crate::aws::AwsClientConfigExt;
use std::fmt::Debug;

use crate::aws::aws_request_utils::{AwsRequestBuilderExt, AwsSignConfig};
use crate::aws::AwsClientConfig;
use alien_client_core::RequestBuilderExt;
use alien_client_core::{ErrorData, Result};
use alien_error::{AlienError, ContextError};
use async_trait::async_trait;
use aws_credential_types::Credentials;
use bon::Builder;
use form_urlencoded;

#[cfg(feature = "test-utils")]
use mockall::automock;
use quick_xml;
use reqwest::{Client, StatusCode};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

#[cfg_attr(feature = "test-utils", automock)]
#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
pub trait IamApi: Send + Sync + Debug {
    // Role Operations
    async fn create_role(&self, request: CreateRoleRequest) -> Result<CreateRoleResponse>;
    async fn get_role(&self, role_name: &str) -> Result<GetRoleResponse>;
    async fn delete_role(&self, role_name: &str) -> Result<()>;
    async fn put_role_policy(
        &self,
        role_name: &str,
        policy_name: &str,
        policy_document: &str,
    ) -> Result<()>;
    async fn get_role_policy(
        &self,
        role_name: &str,
        policy_name: &str,
    ) -> Result<GetRolePolicyResponse>;
    async fn delete_role_policy(&self, role_name: &str, policy_name: &str) -> Result<()>;
    async fn update_assume_role_policy(&self, role_name: &str, policy_document: &str)
        -> Result<()>;
    async fn list_attached_role_policies(
        &self,
        role_name: &str,
    ) -> Result<ListAttachedRolePoliciesResponse>;
    async fn attach_role_policy(&self, role_name: &str, policy_arn: &str) -> Result<()>;
    async fn detach_role_policy(&self, role_name: &str, policy_arn: &str) -> Result<()>;
    async fn list_role_policies(&self, role_name: &str) -> Result<ListRolePoliciesResponse>;

    // Instance Profile Operations
    async fn create_instance_profile(
        &self,
        request: CreateInstanceProfileRequest,
    ) -> Result<CreateInstanceProfileResponse>;
    async fn get_instance_profile(
        &self,
        instance_profile_name: &str,
    ) -> Result<GetInstanceProfileResponse>;
    async fn delete_instance_profile(&self, instance_profile_name: &str) -> Result<()>;
    async fn add_role_to_instance_profile(
        &self,
        instance_profile_name: &str,
        role_name: &str,
    ) -> Result<()>;
    async fn remove_role_from_instance_profile(
        &self,
        instance_profile_name: &str,
        role_name: &str,
    ) -> Result<()>;
    async fn list_instance_profiles(
        &self,
        request: ListInstanceProfilesRequest,
    ) -> Result<ListInstanceProfilesResponse>;
}

/// AWS IAM client using the new request/​error abstractions.
#[derive(Debug, Clone)]
pub struct IamClient {
    client: Client,
    config: AwsClientConfig,
}

impl IamClient {
    pub fn new(client: Client, config: AwsClientConfig) -> Self {
        Self { client, config }
    }

    fn sign_config(&self) -> AwsSignConfig {
        AwsSignConfig {
            service_name: "iam".into(),
            // IAM is *always* signed in us-east-1 regardless of the target region.
            region: self.config.region.clone(),
            credentials: self.config.get_credentials(),
            signing_region: Some("us-east-1".into()),
        }
    }

    fn get_base_url(&self) -> String {
        if let Some(override_url) = self.config.get_service_endpoint_option("iam") {
            override_url.to_string()
        } else {
            "https://iam.amazonaws.com".to_string()
        }
    }

    fn build_form_body(action: &str, version: &str, params: Vec<(String, String)>) -> String {
        let mut all = vec![
            ("Action".to_string(), action.to_string()),
            ("Version".to_string(), version.to_string()),
        ];
        all.extend(params);

        all.into_iter()
            .map(|(k, v)| {
                format!(
                    "{}={}",
                    k,
                    form_urlencoded::byte_serialize(v.as_bytes()).collect::<String>()
                )
            })
            .collect::<Vec<String>>()
            .join("&")
    }

    // ---- Internal helpers ------------------------------------------------
    async fn post_xml<T: DeserializeOwned + Send + 'static>(
        &self,
        body: String,
        operation_name: &str,
        resource_name: &str,
    ) -> Result<T> {
        let base_url = self.get_base_url();
        let url = format!("{}/", base_url.trim_end_matches('/'));
        let builder = self
            .client
            .post(&url)
            .host("iam.amazonaws.com")
            .content_type_form()
            .body(body.clone());

        let result =
            crate::aws::aws_request_utils::sign_send_xml(builder, &self.sign_config()).await;

        match result {
            Ok(v) => Ok(v),
            Err(e) => {
                if let Some(ErrorData::HttpResponseError {
                    http_status,
                    http_response_text: Some(ref text),
                    ..
                }) = &e.error
                {
                    let status = StatusCode::from_u16(*http_status)
                        .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
                    if let Some(mapped) =
                        Self::map_iam_error(status, text, operation_name, resource_name, &body)
                    {
                        Err(e.context(mapped))
                    } else {
                        // Couldn't parse IAM error, use original error
                        Err(e)
                    }
                } else {
                    Err(e)
                }
            }
        }
    }

    async fn post_no_response(
        &self,
        body: String,
        operation_name: &str,
        resource_name: &str,
    ) -> Result<()> {
        let base_url = self.get_base_url();
        let url = format!("{}/", base_url.trim_end_matches('/'));
        let builder = self
            .client
            .post(&url)
            .host("iam.amazonaws.com")
            .content_type_form()
            .body(body.clone());

        let result =
            crate::aws::aws_request_utils::sign_send_no_response(builder, &self.sign_config())
                .await;

        match result {
            Ok(_) => Ok(()),
            Err(e) => {
                if let Some(ErrorData::HttpResponseError {
                    http_status,
                    http_response_text: Some(ref text),
                    ..
                }) = &e.error
                {
                    let status = StatusCode::from_u16(*http_status)
                        .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);
                    if let Some(mapped) =
                        Self::map_iam_error(status, text, operation_name, resource_name, &body)
                    {
                        Err(e.context(mapped))
                    } else {
                        // Couldn't parse IAM error, use original error
                        Err(e)
                    }
                } else {
                    Err(e)
                }
            }
        }
    }

    fn map_iam_error(
        status: StatusCode,
        error_body: &str,
        operation: &str,
        resource_name: &str,
        request_body: &str,
    ) -> Option<ErrorData> {
        // Attempt to parse the canonical AWS error XML.
        let parsed_error: std::result::Result<IamErrorResponse, _> =
            quick_xml::de::from_str(error_body);

        let (error_code, error_message) = match parsed_error {
            Ok(e) => (
                e.error.code.unwrap_or_else(|| "UnknownErrorCode".into()),
                e.error.message.unwrap_or_else(|| "Unknown error".into()),
            ),
            Err(_) => {
                // If we can't parse the response, return None to use original error
                return None;
            }
        };

        Some(match error_code.as_str() {
            // Access & auth
            "AccessDenied"
            | "AccessDeniedException"
            | "UnauthorizedOperation"
            | "InvalidUserID.NotFound"
            | "AuthFailure"
            | "SignatureDoesNotMatch"
            | "TokenRefreshRequired"
            | "NotAuthorized"
            | "InvalidClientTokenId"
            | "MissingAuthenticationToken"
            | "OptInRequired" => ErrorData::RemoteAccessDenied {
                resource_type: "IAM Resource".into(),
                resource_name: resource_name.into(),
            },

            // Rate limiting / throttling
            "Throttling" | "ThrottlingException" | "RequestLimitExceeded" => {
                ErrorData::RateLimitExceeded {
                    message: error_message,
                }
            }

            // Service unavailable
            "ServiceUnavailable" | "InternalFailure" | "ServiceFailure" => {
                ErrorData::RemoteServiceUnavailable {
                    message: error_message,
                }
            }

            // Not found
            "NoSuchEntity" | "NoSuchRole" | "NoSuchPolicy" => ErrorData::RemoteResourceNotFound {
                resource_type: "IAM Resource".into(),
                resource_name: resource_name.into(),
            },

            // Already exists
            "EntityAlreadyExists" | "RoleAlreadyExists" => ErrorData::RemoteResourceConflict {
                message: error_message,
                resource_type: "IAM Resource".into(),
                resource_name: resource_name.into(),
            },

            // Quota / limit exceeded
            "LimitExceeded"
            | "LimitExceededException"
            | "PolicySizeLimitExceeded"
            | "RoleSizeLimitExceeded" => ErrorData::QuotaExceeded {
                message: error_message,
            },

            // Generic fallback categories
            _ => match status {
                StatusCode::CONFLICT => ErrorData::RemoteResourceConflict {
                    message: error_message,
                    resource_type: "IAM Resource".into(),
                    resource_name: resource_name.into(),
                },
                StatusCode::NOT_FOUND => ErrorData::RemoteResourceNotFound {
                    resource_type: "IAM Resource".into(),
                    resource_name: resource_name.into(),
                },
                StatusCode::FORBIDDEN | StatusCode::UNAUTHORIZED => ErrorData::RemoteAccessDenied {
                    resource_type: "IAM Resource".into(),
                    resource_name: resource_name.into(),
                },
                StatusCode::TOO_MANY_REQUESTS => ErrorData::RateLimitExceeded {
                    message: error_message,
                },
                StatusCode::SERVICE_UNAVAILABLE
                | StatusCode::BAD_GATEWAY
                | StatusCode::GATEWAY_TIMEOUT => ErrorData::RemoteServiceUnavailable {
                    message: error_message,
                },
                _ => ErrorData::HttpResponseError {
                    message: format!("IAM operation failed: {}", error_message),
                    url: "iam.amazonaws.com".into(),
                    http_status: status.as_u16(),
                    http_response_text: Some(error_body.into()),
                    http_request_text: Some(request_body.into()),
                },
            },
        })
    }

    // ---- Public API ------------------------------------------------------
}

#[cfg_attr(target_arch = "wasm32", async_trait::async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait::async_trait)]
impl IamApi for IamClient {
    async fn create_role(&self, request: CreateRoleRequest) -> Result<CreateRoleResponse> {
        let mut params: Vec<(String, String)> = vec![
            ("RoleName".to_string(), request.role_name.clone()),
            (
                "AssumeRolePolicyDocument".to_string(),
                request.assume_role_policy_document.clone(),
            ),
        ];

        if let Some(ref path) = request.path {
            params.push(("Path".to_string(), path.clone()));
        }
        if let Some(ref description) = request.description {
            params.push(("Description".to_string(), description.clone()));
        }
        if let Some(max_session) = request.max_session_duration {
            params.push(("MaxSessionDuration".to_string(), max_session.to_string()));
        }

        // Handle tags array
        if let Some(ref tags) = request.tags {
            for (i, tag) in tags.iter().enumerate() {
                params.push((format!("Tags.member.{}.Key", i + 1), tag.key.clone()));
                params.push((format!("Tags.member.{}.Value", i + 1), tag.value.clone()));
            }
        }

        let body = Self::build_form_body("CreateRole", "2010-05-08", params);
        self.post_xml(body, "CreateRole", &request.role_name).await
    }

    async fn get_role(&self, role_name: &str) -> Result<GetRoleResponse> {
        let params = vec![("RoleName".to_string(), role_name.to_string())];
        let body = Self::build_form_body("GetRole", "2010-05-08", params);
        self.post_xml(body, "GetRole", role_name).await
    }

    async fn delete_role(&self, role_name: &str) -> Result<()> {
        let params = vec![("RoleName".to_string(), role_name.to_string())];
        let body = Self::build_form_body("DeleteRole", "2010-05-08", params);
        self.post_no_response(body, "DeleteRole", role_name).await
    }

    async fn put_role_policy(
        &self,
        role_name: &str,
        policy_name: &str,
        policy_document: &str,
    ) -> Result<()> {
        let params = vec![
            ("RoleName".to_string(), role_name.to_string()),
            ("PolicyName".to_string(), policy_name.to_string()),
            ("PolicyDocument".to_string(), policy_document.to_string()),
        ];
        let body = Self::build_form_body("PutRolePolicy", "2010-05-08", params);
        let resource = format!("{}:{}", role_name, policy_name);
        self.post_no_response(body, "PutRolePolicy", &resource)
            .await
    }

    async fn get_role_policy(
        &self,
        role_name: &str,
        policy_name: &str,
    ) -> Result<GetRolePolicyResponse> {
        let params = vec![
            ("RoleName".to_string(), role_name.to_string()),
            ("PolicyName".to_string(), policy_name.to_string()),
        ];
        let body = Self::build_form_body("GetRolePolicy", "2010-05-08", params);
        let resource = format!("{}:{}", role_name, policy_name);
        self.post_xml(body, "GetRolePolicy", &resource).await
    }

    async fn delete_role_policy(&self, role_name: &str, policy_name: &str) -> Result<()> {
        let params = vec![
            ("RoleName".to_string(), role_name.to_string()),
            ("PolicyName".to_string(), policy_name.to_string()),
        ];
        let body = Self::build_form_body("DeleteRolePolicy", "2010-05-08", params);
        let resource = format!("{}:{}", role_name, policy_name);
        self.post_no_response(body, "DeleteRolePolicy", &resource)
            .await
    }

    async fn update_assume_role_policy(
        &self,
        role_name: &str,
        policy_document: &str,
    ) -> Result<()> {
        let params = vec![
            ("RoleName".to_string(), role_name.to_string()),
            ("PolicyDocument".to_string(), policy_document.to_string()),
        ];
        let body = Self::build_form_body("UpdateAssumeRolePolicy", "2010-05-08", params);
        self.post_no_response(body, "UpdateAssumeRolePolicy", role_name)
            .await
    }

    async fn list_attached_role_policies(
        &self,
        role_name: &str,
    ) -> Result<ListAttachedRolePoliciesResponse> {
        let params = vec![("RoleName".to_string(), role_name.to_string())];
        let body = Self::build_form_body("ListAttachedRolePolicies", "2010-05-08", params);
        self.post_xml(body, "ListAttachedRolePolicies", role_name)
            .await
    }

    async fn detach_role_policy(&self, role_name: &str, policy_arn: &str) -> Result<()> {
        let params = vec![
            ("RoleName".to_string(), role_name.to_string()),
            ("PolicyArn".to_string(), policy_arn.to_string()),
        ];
        let body = Self::build_form_body("DetachRolePolicy", "2010-05-08", params);
        let resource = format!("{}:{}", role_name, policy_arn);
        self.post_no_response(body, "DetachRolePolicy", &resource)
            .await
    }

    async fn list_role_policies(&self, role_name: &str) -> Result<ListRolePoliciesResponse> {
        let params = vec![("RoleName".to_string(), role_name.to_string())];
        let body = Self::build_form_body("ListRolePolicies", "2010-05-08", params);
        self.post_xml(body, "ListRolePolicies", role_name).await
    }

    async fn attach_role_policy(&self, role_name: &str, policy_arn: &str) -> Result<()> {
        let params = vec![
            ("RoleName".to_string(), role_name.to_string()),
            ("PolicyArn".to_string(), policy_arn.to_string()),
        ];
        let body = Self::build_form_body("AttachRolePolicy", "2010-05-08", params);
        let resource = format!("{}:{}", role_name, policy_arn);
        self.post_no_response(body, "AttachRolePolicy", &resource)
            .await
    }

    // ---------------------------------------------------------------------------
    // Instance Profile Operations
    // ---------------------------------------------------------------------------

    async fn create_instance_profile(
        &self,
        request: CreateInstanceProfileRequest,
    ) -> Result<CreateInstanceProfileResponse> {
        let mut params: Vec<(String, String)> = vec![(
            "InstanceProfileName".to_string(),
            request.instance_profile_name.clone(),
        )];

        if let Some(ref path) = request.path {
            params.push(("Path".to_string(), path.clone()));
        }

        if let Some(ref tags) = request.tags {
            for (i, tag) in tags.iter().enumerate() {
                params.push((format!("Tags.member.{}.Key", i + 1), tag.key.clone()));
                params.push((format!("Tags.member.{}.Value", i + 1), tag.value.clone()));
            }
        }

        let body = Self::build_form_body("CreateInstanceProfile", "2010-05-08", params);
        self.post_xml(
            body,
            "CreateInstanceProfile",
            &request.instance_profile_name,
        )
        .await
    }

    async fn get_instance_profile(
        &self,
        instance_profile_name: &str,
    ) -> Result<GetInstanceProfileResponse> {
        let params = vec![(
            "InstanceProfileName".to_string(),
            instance_profile_name.to_string(),
        )];
        let body = Self::build_form_body("GetInstanceProfile", "2010-05-08", params);
        self.post_xml(body, "GetInstanceProfile", instance_profile_name)
            .await
    }

    async fn delete_instance_profile(&self, instance_profile_name: &str) -> Result<()> {
        let params = vec![(
            "InstanceProfileName".to_string(),
            instance_profile_name.to_string(),
        )];
        let body = Self::build_form_body("DeleteInstanceProfile", "2010-05-08", params);
        self.post_no_response(body, "DeleteInstanceProfile", instance_profile_name)
            .await
    }

    async fn add_role_to_instance_profile(
        &self,
        instance_profile_name: &str,
        role_name: &str,
    ) -> Result<()> {
        let params = vec![
            (
                "InstanceProfileName".to_string(),
                instance_profile_name.to_string(),
            ),
            ("RoleName".to_string(), role_name.to_string()),
        ];
        let body = Self::build_form_body("AddRoleToInstanceProfile", "2010-05-08", params);
        let resource = format!("{}:{}", instance_profile_name, role_name);
        self.post_no_response(body, "AddRoleToInstanceProfile", &resource)
            .await
    }

    async fn remove_role_from_instance_profile(
        &self,
        instance_profile_name: &str,
        role_name: &str,
    ) -> Result<()> {
        let params = vec![
            (
                "InstanceProfileName".to_string(),
                instance_profile_name.to_string(),
            ),
            ("RoleName".to_string(), role_name.to_string()),
        ];
        let body = Self::build_form_body("RemoveRoleFromInstanceProfile", "2010-05-08", params);
        let resource = format!("{}:{}", instance_profile_name, role_name);
        self.post_no_response(body, "RemoveRoleFromInstanceProfile", &resource)
            .await
    }

    async fn list_instance_profiles(
        &self,
        request: ListInstanceProfilesRequest,
    ) -> Result<ListInstanceProfilesResponse> {
        let mut params: Vec<(String, String)> = Vec::new();

        if let Some(ref path_prefix) = request.path_prefix {
            params.push(("PathPrefix".to_string(), path_prefix.clone()));
        }
        if let Some(ref marker) = request.marker {
            params.push(("Marker".to_string(), marker.clone()));
        }
        if let Some(max_items) = request.max_items {
            params.push(("MaxItems".to_string(), max_items.to_string()));
        }

        let body = Self::build_form_body("ListInstanceProfiles", "2010-05-08", params);
        self.post_xml(body, "ListInstanceProfiles", "instance-profiles")
            .await
    }
}

// -------------------------------------------------------------------------
// Error XML structs (PascalCase matching AWS IAM)
// -------------------------------------------------------------------------

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct IamErrorResponse {
    pub error: IamErrorDetails,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
struct IamErrorDetails {
    pub code: Option<String>,
    pub message: Option<String>,
}

// -------------------------------------------------------------------------
// Request / response payloads (intact from previous implementation)
// -------------------------------------------------------------------------

#[derive(Serialize, Debug, Clone, Builder)]
#[serde(rename_all = "PascalCase")]
pub struct CreateRoleRequest {
    pub role_name: String,
    pub assume_role_policy_document: String,
    pub path: Option<String>,
    pub description: Option<String>,
    pub max_session_duration: Option<i32>,
    #[serde(skip)]
    pub tags: Option<Vec<CreateRoleTag>>,
}

#[derive(Serialize, Debug, Clone)]
pub struct CreateRoleTag {
    pub key: String,
    pub value: String,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct CreateRoleResponse {
    pub create_role_result: CreateRoleResult,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct CreateRoleResult {
    pub role: Role,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Role {
    pub path: String,
    pub role_name: String,
    pub role_id: String,
    pub arn: String,
    pub create_date: String,
    pub assume_role_policy_document: Option<String>,
    pub description: Option<String>,
    pub max_session_duration: Option<i32>,
    pub permissions_boundary: Option<AttachedPermissionsBoundary>,
    pub tags: Option<Tags>,
    pub role_last_used: Option<RoleLastUsed>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct AttachedPermissionsBoundary {
    pub permissions_boundary_type: Option<String>,
    pub permissions_boundary_arn: Option<String>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Tags {
    #[serde(rename = "member", default)]
    pub member: Vec<Tag>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct Tag {
    pub key: String,
    pub value: String,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct RoleLastUsed {
    pub last_used_date: Option<String>,
    pub region: Option<String>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct GetRoleResponse {
    pub get_role_result: GetRoleResult,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct GetRoleResult {
    pub role: Role,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct GetRolePolicyResponse {
    pub get_role_policy_result: GetRolePolicyResult,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct GetRolePolicyResult {
    pub role_name: String,
    pub policy_name: String,
    pub policy_document: String,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct ListAttachedRolePoliciesResponse {
    pub list_attached_role_policies_result: ListAttachedRolePoliciesResult,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct ListAttachedRolePoliciesResult {
    pub attached_policies: Option<AttachedPolicies>,
    pub is_truncated: Option<bool>,
    pub marker: Option<String>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct AttachedPolicies {
    #[serde(rename = "member", default)]
    pub member: Vec<AttachedPolicy>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct AttachedPolicy {
    pub policy_name: String,
    pub policy_arn: String,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct ListRolePoliciesResponse {
    pub list_role_policies_result: ListRolePoliciesResult,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct ListRolePoliciesResult {
    pub policy_names: Option<PolicyNames>,
    pub is_truncated: Option<bool>,
    pub marker: Option<String>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct PolicyNames {
    #[serde(rename = "member", default)]
    pub member: Vec<String>,
}

// -------------------------------------------------------------------------
// Instance Profile structures
// -------------------------------------------------------------------------

/// Request to create an instance profile.
#[derive(Serialize, Debug, Clone, Builder)]
#[serde(rename_all = "PascalCase")]
pub struct CreateInstanceProfileRequest {
    /// The name of the instance profile.
    pub instance_profile_name: String,
    /// The path for the instance profile.
    pub path: Option<String>,
    /// Tags for the instance profile.
    #[serde(skip)]
    pub tags: Option<Vec<CreateRoleTag>>,
}

/// Response from creating an instance profile.
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct CreateInstanceProfileResponse {
    pub create_instance_profile_result: CreateInstanceProfileResult,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct CreateInstanceProfileResult {
    pub instance_profile: InstanceProfile,
}

/// Response from getting an instance profile.
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct GetInstanceProfileResponse {
    pub get_instance_profile_result: GetInstanceProfileResult,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct GetInstanceProfileResult {
    pub instance_profile: InstanceProfile,
}

/// Request to list instance profiles.
#[derive(Serialize, Debug, Clone, Builder, Default)]
#[serde(rename_all = "PascalCase")]
pub struct ListInstanceProfilesRequest {
    /// The path prefix for filtering.
    pub path_prefix: Option<String>,
    /// The marker for pagination.
    pub marker: Option<String>,
    /// The maximum number of items to return.
    pub max_items: Option<i32>,
}

/// Response from listing instance profiles.
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct ListInstanceProfilesResponse {
    pub list_instance_profiles_result: ListInstanceProfilesResult,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct ListInstanceProfilesResult {
    pub instance_profiles: Option<InstanceProfiles>,
    pub is_truncated: Option<bool>,
    pub marker: Option<String>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct InstanceProfiles {
    #[serde(rename = "member", default)]
    pub member: Vec<InstanceProfile>,
}

/// Represents an IAM instance profile.
#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct InstanceProfile {
    /// The path to the instance profile.
    pub path: String,
    /// The name of the instance profile.
    pub instance_profile_name: String,
    /// The ID of the instance profile.
    pub instance_profile_id: String,
    /// The ARN of the instance profile.
    pub arn: String,
    /// The date and time the instance profile was created.
    pub create_date: String,
    /// The roles associated with the instance profile.
    pub roles: Option<InstanceProfileRoles>,
    /// Tags associated with the instance profile.
    pub tags: Option<Tags>,
}

#[derive(Deserialize, Debug)]
#[serde(rename_all = "PascalCase")]
pub struct InstanceProfileRoles {
    #[serde(rename = "member", default)]
    pub member: Vec<Role>,
}

// -------------------------------------------------------------------------
// Trust policy structures for IAM role trust relationships
// -------------------------------------------------------------------------

/// Trust policy principal types
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum TrustPolicyPrincipal {
    /// AWS service principal (e.g., lambda.amazonaws.com)
    Service {
        #[serde(rename = "Service")]
        service: TrustPolicyPrincipalValue,
    },
    /// AWS IAM principal (e.g., role ARN)
    Aws {
        #[serde(rename = "AWS")]
        aws: TrustPolicyPrincipalValue,
    },
}

/// Principal value can be a single string or array of strings
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum TrustPolicyPrincipalValue {
    /// Single principal
    Single(String),
    /// Multiple principals
    Multiple(Vec<String>),
}

/// Trust policy statement
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct TrustPolicyStatement {
    /// Effect of the statement (Allow/Deny)
    pub effect: String,
    /// Principal that can assume the role
    pub principal: TrustPolicyPrincipal,
    /// Action being permitted (usually sts:AssumeRole)
    pub action: String,
}

/// Complete trust policy document
#[derive(Debug, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct TrustPolicyDocument {
    /// Policy version (typically "2012-10-17")
    pub version: String,
    /// List of policy statements
    pub statement: Vec<TrustPolicyStatement>,
}