wami 0.10.0

Who Am I - Multicloud Identity, IAM, STS, and SSO operations library for Rust
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
# IAM Operations Guide

Complete guide to Identity and Access Management with WAMI.

## Overview

WAMI provides AWS-compatible IAM operations for managing:
- **Users** - Individual identities
- **Roles** - Assumable identities for services and applications
- **Policies** - Permission documents
- **Groups** - Collections of users
- **Access Keys** - Programmatic access credentials
- **MFA Devices** - Multi-factor authentication
- **And more...**

## Quick Reference

| Operation | Description | Example |
|-----------|-------------|---------|
| `create_user` | Create a new user | `iam.create_user(req).await?` |
| `get_user` | Fetch user details | `iam.get_user("alice").await?` |
| `list_users` | List all users | `iam.list_users(None, None).await?` |
| `delete_user` | Remove a user | `iam.delete_user("alice").await?` |
| `create_role` | Create a role | `iam.create_role(req).await?` |
| `create_policy` | Create a managed policy | `iam.create_policy(req).await?` |
| `attach_user_policy` | Attach policy to user | `iam.attach_user_policy("alice", "arn").await?` |
| `create_access_key` | Generate access keys | `iam.create_access_key(req).await?` |

## Users

### Create User

```rust
use wami::{MemoryIamClient, CreateUserRequest, Tag};

let mut iam = MemoryIamClient::new(store);

let user = iam.create_user(CreateUserRequest {
    user_name: "alice".to_string(),
    path: Some("/engineering/".to_string()),
    permissions_boundary: None,
    tags: Some(vec![
        Tag {
            key: "Department".to_string(),
            value: "Engineering".to_string(),
        },
    ]),
}).await?;

println!("Created: {}", user.data.unwrap().arn);
// Output: arn:aws:iam::123456789012:user/engineering/alice
```

### Get User

```rust
let user = iam.get_user("alice").await?;
if let Some(u) = user.data {
    println!("User: {} (created: {})", u.user_name, u.create_date);
}
```

### List Users

```rust
let response = iam.list_users(
    Some("/engineering/"), // Path prefix
    None,                  // No pagination marker
).await?;

for user in response.data.unwrap().users {
    println!("- {} ({})", user.user_name, user.arn);
}
```

### Update User

```rust
use wami::UpdateUserRequest;

iam.update_user(UpdateUserRequest {
    user_name: "alice".to_string(),
    new_path: Some("/admin/".to_string()),
    new_user_name: None,
}).await?;
```

### Delete User

```rust
iam.delete_user("alice").await?;
```

## Roles

### Create Role

```rust
use wami::CreateRoleRequest;

let role = iam.create_role(CreateRoleRequest {
    role_name: "DataScientist".to_string(),
    assume_role_policy_document: r#"{
        "Version": "2012-10-17",
        "Statement": [{
            "Effect": "Allow",
            "Principal": {
                "Service": "ec2.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }]
    }"#.to_string(),
    path: Some("/roles/".to_string()),
    description: Some("Role for data science workloads".to_string()),
    max_session_duration: Some(3600),
    permissions_boundary: None,
    tags: None,
}).await?;

println!("Role ARN: {}", role.data.unwrap().arn);
```

### Get Role

```rust
let role = iam.get_role("DataScientist").await?;
```

### List Roles

```rust
let roles = iam.list_roles(Some("/roles/"), None).await?;
```

### Attach Role Policy

```rust
iam.attach_role_policy("DataScientist", "arn:aws:iam::aws:policy/ReadOnlyAccess").await?;
```

### Delete Role

```rust
// Must detach all policies first
iam.detach_role_policy("DataScientist", "arn:aws:iam::aws:policy/ReadOnlyAccess").await?;
iam.delete_role("DataScientist").await?;
```

## Policies

### Create Managed Policy

```rust
use wami::CreatePolicyRequest;

let policy = iam.create_policy(CreatePolicyRequest {
    policy_name: "S3ReadOnly".to_string(),
    policy_document: r#"{
        "Version": "2012-10-17",
        "Statement": [{
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::my-bucket",
                "arn:aws:s3:::my-bucket/*"
            ]
        }]
    }"#.to_string(),
    path: Some("/policies/".to_string()),
    description: Some("Read-only access to S3".to_string()),
    tags: None,
}).await?;

let policy_arn = policy.data.unwrap().arn;
```

### Get Policy

```rust
let policy = iam.get_policy(&policy_arn).await?;
```

### List Policies

```rust
let policies = iam.list_policies(
    None,  // Scope: All, AWS, Local
    false, // Only attached
    Some("/policies/"),
    None,  // No pagination
).await?;
```

### Delete Policy

```rust
iam.delete_policy(&policy_arn).await?;
```

## Groups

### Create Group

```rust
use wami::CreateGroupRequest;

let group = iam.create_group(CreateGroupRequest {
    group_name: "Developers".to_string(),
    path: Some("/teams/".to_string()),
}).await?;
```

### Add User to Group

```rust
iam.add_user_to_group("alice", "Developers").await?;
```

### List Groups for User

```rust
let groups = iam.list_groups_for_user("alice", None, None).await?;
```

### Attach Group Policy

```rust
iam.attach_group_policy("Developers", policy_arn).await?;
```

### Remove User from Group

```rust
iam.remove_user_from_group("alice", "Developers").await?;
```

## Access Keys

### Create Access Key

```rust
use wami::CreateAccessKeyRequest;

let key_response = iam.create_access_key(CreateAccessKeyRequest {
    user_name: "alice".to_string(),
}).await?;

let key = key_response.data.unwrap();
println!("Access Key ID: {}", key.access_key_id);
println!("Secret Key: {}", key.secret_access_key.unwrap());
// ⚠️ Secret is only returned once! Store it securely.
```

### List Access Keys

```rust
let keys = iam.list_access_keys("alice", None, None).await?;
```

### Update Access Key Status

```rust
use wami::UpdateAccessKeyRequest;

iam.update_access_key(UpdateAccessKeyRequest {
    user_name: "alice".to_string(),
    access_key_id: "AKIAIOSFODNN7EXAMPLE".to_string(),
    status: "Inactive".to_string(), // or "Active"
}).await?;
```

### Delete Access Key

```rust
iam.delete_access_key("alice", "AKIAIOSFODNN7EXAMPLE").await?;
```

## Login Profiles (Passwords)

### Create Login Profile

```rust
use wami::CreateLoginProfileRequest;

iam.create_login_profile(CreateLoginProfileRequest {
    user_name: "alice".to_string(),
    password: "SecurePassword123!".to_string(),
    password_reset_required: Some(true),
}).await?;
```

### Update Password

```rust
use wami::UpdateLoginProfileRequest;

iam.update_login_profile(UpdateLoginProfileRequest {
    user_name: "alice".to_string(),
    password: Some("NewSecurePassword456!".to_string()),
    password_reset_required: Some(false),
}).await?;
```

### Delete Login Profile

```rust
iam.delete_login_profile("alice").await?;
```

## MFA Devices

### Enable Virtual MFA

```rust
use wami::{EnableMfaDeviceRequest, CreateVirtualMfaDeviceRequest};

// 1. Create virtual MFA device
let device = iam.create_virtual_mfa_device(CreateVirtualMfaDeviceRequest {
    virtual_mfa_device_name: "alice-mfa".to_string(),
    path: None,
    tags: None,
}).await?;

// 2. Enable it for user
iam.enable_mfa_device(EnableMfaDeviceRequest {
    user_name: "alice".to_string(),
    serial_number: device.data.unwrap().serial_number,
    authentication_code_1: "123456".to_string(),
    authentication_code_2: "234567".to_string(),
}).await?;
```

### List MFA Devices

```rust
let devices = iam.list_mfa_devices("alice", None, None).await?;
```

### Deactivate MFA

```rust
iam.deactivate_mfa_device("alice", "arn:aws:iam::123456789012:mfa/alice-mfa").await?;
```

## Advanced Operations

### Attach Inline Policy

```rust
use wami::PutUserPolicyRequest;

iam.put_user_policy(PutUserPolicyRequest {
    user_name: "alice".to_string(),
    policy_name: "inline-s3-access".to_string(),
    policy_document: r#"{
        "Version": "2012-10-17",
        "Statement": [{
            "Effect": "Allow",
            "Action": "s3:*",
            "Resource": "arn:aws:s3:::alice-bucket/*"
        }]
    }"#.to_string(),
}).await?;
```

### Permissions Boundaries

Permissions boundaries set the maximum permissions that identity-based policies can grant. The effective permissions are the intersection of identity-based policies and the boundary.

**Create a Boundary Policy:**

```rust
use wami::service::PolicyService;
use wami::wami::policies::policy::requests::CreatePolicyRequest;

let policy_service = PolicyService::new(store.clone(), account_id.to_string());

let boundary_policy = policy_service.create_policy(CreatePolicyRequest {
    policy_name: "DeveloperBoundary".to_string(),
    policy_document: r#"{
        "Version": "2012-10-17",
        "Statement": [{
            "Effect": "Allow",
            "Action": [
                "s3:*",
                "dynamodb:*",
                "lambda:*"
            ],
            "Resource": "*"
        }]
    }"#.to_string(),
    path: Some("/boundaries/".to_string()),
    description: Some("Limits developers to S3, DynamoDB, and Lambda".to_string()),
    tags: None,
}).await?;
```

**Attach Boundary to User:**

```rust
use wami::service::PermissionsBoundaryService;
use wami::wami::policies::permissions_boundary::{
    PutPermissionsBoundaryRequest, PrincipalType
};

let boundary_service = PermissionsBoundaryService::new(store.clone(), account_id.to_string());

boundary_service.put_permissions_boundary(PutPermissionsBoundaryRequest {
    principal_type: PrincipalType::User,
    principal_name: "alice".to_string(),
    permissions_boundary: boundary_policy.arn.clone(),
}).await?;
```

**Remove Boundary:**

```rust
use wami::wami::policies::permissions_boundary::DeletePermissionsBoundaryRequest;

boundary_service.delete_permissions_boundary(DeletePermissionsBoundaryRequest {
    principal_type: PrincipalType::User,
    principal_name: "alice".to_string(),
}).await?;
```

**Use Cases:**
- **Developer Sandboxes**: Prevent devs from accessing production or IAM resources
- **Contractor Access**: Limit external users to specific services
- **Delegated Administration**: Allow users to create other users within safe limits
- **Multi-tenant Isolation**: Restrict each tenant to their own resources

### Tag Resources

```rust
use wami::TagUserRequest;

iam.tag_user(TagUserRequest {
    user_name: "alice".to_string(),
    tags: vec![
        Tag {
            key: "CostCenter".to_string(),
            value: "Engineering".to_string(),
        },
    ],
}).await?;
```

## Best Practices

### 1. Use Paths for Organization

```rust
// Organize by team/department
"/teams/engineering/"
"/teams/marketing/"

// Organize by environment
"/production/"
"/staging/"
"/development/"
```

### 2. Always Tag Resources

```rust
tags: Some(vec![
    Tag { key: "Environment".into(), value: "Production".into() },
    Tag { key: "Owner".into(), value: "alice@example.com".into() },
    Tag { key: "CostCenter".into(), value: "Engineering".into() },
])
```

### 3. Use Permissions Boundaries

```rust
// Prevent privilege escalation
permissions_boundary: Some("arn:aws:iam::123456789012:policy/MaxPermissions".into())
```

### 4. Rotate Access Keys

```rust
// Create new key
let new_key = iam.create_access_key(CreateAccessKeyRequest {
    user_name: "alice".to_string(),
}).await?;

// Update application with new key

// Deactivate old key
iam.update_access_key(UpdateAccessKeyRequest {
    user_name: "alice".to_string(),
    access_key_id: old_key_id.to_string(),
    status: "Inactive".to_string(),
}).await?;

// After verification, delete old key
iam.delete_access_key("alice", &old_key_id).await?;
```

### 5. Enable MFA for Sensitive Operations

```rust
// Require MFA for production access
let policy_with_mfa = r#"{
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Allow",
        "Action": "*",
        "Resource": "*",
        "Condition": {
            "Bool": {
                "aws:MultiFactorAuthPresent": "true"
            }
        }
    }]
}"#;
```

## Error Handling

```rust
use wami::AmiError;

match iam.create_user(request).await {
    Ok(response) => println!("Created: {:?}", response.data),
    Err(AmiError::ResourceExists { resource }) => {
        println!("User already exists: {}", resource);
    }
    Err(AmiError::LimitExceeded { message }) => {
        println!("Quota exceeded: {}", message);
    }
    Err(AmiError::InvalidParameter { message }) => {
        println!("Invalid input: {}", message);
    }
    Err(e) => println!("Error: {:?}", e),
}
```

## Complete Example

```rust
use wami::{
    MemoryIamClient, CreateUserRequest, CreateRoleRequest,
    CreatePolicyRequest, CreateAccessKeyRequest, Tag,
};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    let store = wami::create_memory_store();
    let mut iam = MemoryIamClient::new(store);
    
    // 1. Create user
    let user = iam.create_user(CreateUserRequest {
        user_name: "data-scientist".to_string(),
        path: Some("/teams/ml/".to_string()),
        permissions_boundary: None,
        tags: Some(vec![
            Tag { key: "Team".into(), value: "ML".into() },
        ]),
    }).await?;
    println!("✓ User: {}", user.data.as_ref().unwrap().arn);
    
    // 2. Create policy
    let policy = iam.create_policy(CreatePolicyRequest {
        policy_name: "MLAccess".to_string(),
        policy_document: r#"{
            "Version": "2012-10-17",
            "Statement": [{
                "Effect": "Allow",
                "Action": ["s3:*", "sagemaker:*"],
                "Resource": "*"
            }]
        }"#.to_string(),
        path: Some("/policies/ml/".to_string()),
        description: Some("ML team access".to_string()),
        tags: None,
    }).await?;
    let policy_arn = policy.data.as_ref().unwrap().arn.clone();
    println!("✓ Policy: {}", policy_arn);
    
    // 3. Attach policy to user
    iam.attach_user_policy("data-scientist", &policy_arn).await?;
    println!("✓ Attached policy to user");
    
    // 4. Create access keys
    let keys = iam.create_access_key(CreateAccessKeyRequest {
        user_name: "data-scientist".to_string(),
    }).await?;
    let key = keys.data.unwrap();
    println!("✓ Access Key: {}", key.access_key_id);
    
    // 5. Create role
    let role = iam.create_role(CreateRoleRequest {
        role_name: "MLServiceRole".to_string(),
        assume_role_policy_document: r#"{
            "Version": "2012-10-17",
            "Statement": [{
                "Effect": "Allow",
                "Principal": {"Service": "sagemaker.amazonaws.com"},
                "Action": "sts:AssumeRole"
            }]
        }"#.to_string(),
        path: Some("/roles/ml/".to_string()),
        description: Some("SageMaker service role".to_string()),
        max_session_duration: Some(3600),
        permissions_boundary: None,
        tags: None,
    }).await?;
    println!("✓ Role: {}", role.data.unwrap().arn);
    
    Ok(())
}
```

## Next Steps

- **[STS Guide]STS_GUIDE.md** - Temporary credentials
- **[SSO Admin]SSO_ADMIN_GUIDE.md** - SSO configuration
- **[Multi-Tenant]MULTI_TENANT_GUIDE.md** - Tenant isolation
- **[Examples]EXAMPLES.md** - More code samples

## API Reference

Full API documentation: `cargo doc --open`

## Support

Questions? Open an issue on [GitHub](https://github.com/lsh0x/wami/issues).