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
# Permission Checking Guide

Use WAMI's policy evaluation engine **without** a full store for lightweight permission checking.

## Use Cases

✅ **Perfect for:**
- Policy validation in CI/CD
- Unit testing IAM policies
- Static policy analysis
- Permission simulators
- Policy linters and validators

❌ **Not suitable for:**
- Full IAM management (use [IAM Guide]IAM_GUIDE.md)
- Persistent storage (use [Store Implementation]STORE_IMPLEMENTATION.md)
- Multi-tenant systems (use [Multi-Tenant Guide]MULTI_TENANT_GUIDE.md)

## Quick Start

### Basic Permission Check

```rust
use wami::iam::{PolicyEvaluator, PolicyDocument};
use wami::iam::policy_evaluation::Action;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Define a policy
    let policy_json = r#"
    {
        "Version": "2012-10-17",
        "Statement": [{
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:PutObject"
            ],
            "Resource": "arn:aws:s3:::my-bucket/*"
        }]
    }
    "#;
    
    let policy: PolicyDocument = serde_json::from_str(policy_json)?;
    let evaluator = PolicyEvaluator::new();
    
    // Check if action is allowed
    let result = evaluator.evaluate(
        &[policy],
        &Action::from("s3:GetObject"),
        "arn:aws:s3:::my-bucket/file.txt",
        &Default::default(),
    );
    
    match result {
        Ok(allowed) if allowed => println!("✓ Access allowed"),
        Ok(_) => println!("✗ Access denied"),
        Err(e) => println!("Error: {:?}", e),
    }
    
    Ok(())
}
```

## Core Concepts

### Policy Evaluation Flow

```
1. Parse Policy JSON → PolicyDocument
2. Create PolicyEvaluator
3. Call evaluate(policies, action, resource, context)
4. Returns: Ok(true) = Allow, Ok(false) = Deny, Err = Error
```

### Components

```rust
use wami::iam::policy_evaluation::{
    PolicyEvaluator,      // Evaluates policies
    PolicyDocument,       // AWS policy structure
    Action,               // e.g., "s3:GetObject"
    EvaluationContext,    // Additional context (IP, time, etc.)
};
```

## Examples

### Example 1: Multiple Policies

```rust
use wami::iam::{PolicyEvaluator, PolicyDocument};
use wami::iam::policy_evaluation::Action;

let admin_policy: PolicyDocument = serde_json::from_str(r#"{
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Allow",
        "Action": "*",
        "Resource": "*"
    }]
}"#)?;

let deny_delete_policy: PolicyDocument = serde_json::from_str(r#"{
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Deny",
        "Action": "s3:DeleteBucket",
        "Resource": "*"
    }]
}"#)?;

let evaluator = PolicyEvaluator::new();

// Admin can do most things
let can_read = evaluator.evaluate(
    &[admin_policy.clone(), deny_delete_policy.clone()],
    &Action::from("s3:GetObject"),
    "arn:aws:s3:::bucket/key",
    &Default::default(),
)?;
println!("Can read: {}", can_read); // true

// But explicit deny blocks deletion
let can_delete = evaluator.evaluate(
    &[admin_policy, deny_delete_policy],
    &Action::from("s3:DeleteBucket"),
    "arn:aws:s3:::bucket",
    &Default::default(),
)?;
println!("Can delete bucket: {}", can_delete); // false - explicit deny wins
```

### Example 2: Condition Evaluation

```rust
use wami::iam::policy_evaluation::EvaluationContext;
use std::collections::HashMap;

let policy: PolicyDocument = serde_json::from_str(r#"{
    "Version": "2012-10-17",
    "Statement": [{
        "Effect": "Allow",
        "Action": "s3:*",
        "Resource": "arn:aws:s3:::my-bucket/*",
        "Condition": {
            "IpAddress": {
                "aws:SourceIp": ["192.168.1.0/24"]
            }
        }
    }]
}"#)?;

let evaluator = PolicyEvaluator::new();

// Without context - denied
let result = evaluator.evaluate(
    &[policy.clone()],
    &Action::from("s3:GetObject"),
    "arn:aws:s3:::my-bucket/file.txt",
    &Default::default(),
)?;
println!("Without IP context: {}", result); // false

// With matching IP - allowed
let mut context = EvaluationContext::default();
context.insert("aws:SourceIp".to_string(), "192.168.1.100".to_string());

let result = evaluator.evaluate(
    &[policy],
    &Action::from("s3:GetObject"),
    "arn:aws:s3:::my-bucket/file.txt",
    &context,
)?;
println!("With matching IP: {}", result); // true
```

### Example 3: Policy Validation Tool

```rust
use wami::iam::PolicyDocument;

fn validate_policy(policy_json: &str) -> Result<(), String> {
    // Parse policy
    let policy: PolicyDocument = serde_json::from_str(policy_json)
        .map_err(|e| format!("Invalid JSON: {}", e))?;
    
    // Validate version
    if policy.version != "2012-10-17" {
        return Err("Policy must use Version 2012-10-17".to_string());
    }
    
    // Validate statements
    for (i, statement) in policy.statement.iter().enumerate() {
        // Check effect
        if statement.effect != "Allow" && statement.effect != "Deny" {
            return Err(format!("Statement {}: Effect must be Allow or Deny", i));
        }
        
        // Check actions
        if statement.action.is_empty() {
            return Err(format!("Statement {}: Action cannot be empty", i));
        }
        
        // Check resources
        if statement.resource.is_empty() {
            return Err(format!("Statement {}: Resource cannot be empty", i));
        }
    }
    
    Ok(())
}

// Usage
match validate_policy(policy_json) {
    Ok(_) => println!("✓ Policy is valid"),
    Err(e) => println!("✗ Invalid policy: {}", e),
}
```

### Example 4: Policy Simulator

```rust
use wami::iam::{PolicyEvaluator, PolicyDocument};
use wami::iam::policy_evaluation::Action;

struct PolicySimulator {
    evaluator: PolicyEvaluator,
    policies: Vec<PolicyDocument>,
}

impl PolicySimulator {
    fn new(policies: Vec<PolicyDocument>) -> Self {
        Self {
            evaluator: PolicyEvaluator::new(),
            policies,
        }
    }
    
    fn can(&self, action: &str, resource: &str) -> bool {
        self.evaluator
            .evaluate(
                &self.policies,
                &Action::from(action),
                resource,
                &Default::default(),
            )
            .unwrap_or(false)
    }
    
    fn simulate_scenario(&self, name: &str, actions: Vec<(&str, &str)>) {
        println!("\n📋 Scenario: {}", name);
        for (action, resource) in actions {
            let result = self.can(action, resource);
            let icon = if result { "✓" } else { "✗" };
            println!("  {} {} on {}", icon, action, resource);
        }
    }
}

// Usage
let policies = vec![/* your policies */];
let simulator = PolicySimulator::new(policies);

simulator.simulate_scenario("Developer Access", vec![
    ("s3:GetObject", "arn:aws:s3:::dev-bucket/*"),
    ("s3:PutObject", "arn:aws:s3:::dev-bucket/*"),
    ("s3:DeleteBucket", "arn:aws:s3:::dev-bucket"),
    ("dynamodb:Query", "arn:aws:dynamodb:us-east-1:123456789012:table/DevTable"),
]);
```

### Example 5: CI/CD Policy Linter

```rust
use std::fs;
use wami::iam::PolicyDocument;

fn lint_policies_in_directory(dir: &str) -> Result<(), Box<dyn std::error::Error>> {
    let mut errors = Vec::new();
    
    for entry in fs::read_dir(dir)? {
        let entry = entry?;
        let path = entry.path();
        
        if path.extension().map(|e| e == "json").unwrap_or(false) {
            let content = fs::read_to_string(&path)?;
            
            match serde_json::from_str::<PolicyDocument>(&content) {
                Ok(policy) => {
                    println!("✓ {} - Valid", path.display());
                    
                    // Additional checks
                    if policy.statement.is_empty() {
                        println!("  ⚠ Warning: No statements");
                    }
                    
                    for stmt in &policy.statement {
                        if stmt.action.contains(&"*".to_string()) {
                            println!("  ⚠ Warning: Overly permissive action: *");
                        }
                        if stmt.resource.contains(&"*".to_string()) {
                            println!("  ⚠ Warning: Overly permissive resource: *");
                        }
                    }
                }
                Err(e) => {
                    errors.push(format!("{}: {}", path.display(), e));
                    println!("✗ {} - Invalid: {}", path.display(), e);
                }
            }
        }
    }
    
    if !errors.is_empty() {
        return Err(format!("Found {} invalid policies", errors.len()).into());
    }
    
    Ok(())
}

// Run in CI/CD
fn main() {
    if let Err(e) = lint_policies_in_directory("./policies") {
        eprintln!("Policy validation failed: {}", e);
        std::process::exit(1);
    }
    println!("\n✓ All policies valid!");
}
```

## Testing Policies

### Unit Tests

```rust
#[cfg(test)]
mod tests {
    use super::*;
    use wami::iam::{PolicyEvaluator, PolicyDocument};
    use wami::iam::policy_evaluation::Action;
    
    #[test]
    fn test_s3_read_only_policy() {
        let policy: PolicyDocument = serde_json::from_str(r#"{
            "Version": "2012-10-17",
            "Statement": [{
                "Effect": "Allow",
                "Action": ["s3:GetObject", "s3:ListBucket"],
                "Resource": ["arn:aws:s3:::my-bucket", "arn:aws:s3:::my-bucket/*"]
            }]
        }"#).unwrap();
        
        let evaluator = PolicyEvaluator::new();
        
        // Should allow reads
        assert!(evaluator.evaluate(
            &[policy.clone()],
            &Action::from("s3:GetObject"),
            "arn:aws:s3:::my-bucket/file.txt",
            &Default::default(),
        ).unwrap());
        
        // Should deny writes
        assert!(!evaluator.evaluate(
            &[policy],
            &Action::from("s3:PutObject"),
            "arn:aws:s3:::my-bucket/file.txt",
            &Default::default(),
        ).unwrap());
    }
}
```

## Policy Evaluation Rules

### 1. Default Deny
If no policy explicitly allows, access is denied.

### 2. Explicit Deny Wins
A "Deny" statement always overrides "Allow".

### 3. Action Matching
- Exact match: `"s3:GetObject"` matches `"s3:GetObject"`
- Wildcard: `"s3:*"` matches all S3 actions
- Multiple: `["s3:GetObject", "s3:PutObject"]`

### 4. Resource Matching
- Exact: `"arn:aws:s3:::bucket/key"`
- Wildcard: `"arn:aws:s3:::bucket/*"`
- Multiple: `["arn:...", "arn:..."]`

### 5. Condition Evaluation
Conditions must ALL be true for statement to apply.

```json
{
    "Condition": {
        "StringEquals": {"aws:username": "alice"},
        "IpAddress": {"aws:SourceIp": "192.168.1.0/24"}
    }
}
```
Both conditions must match.

## Best Practices

### ✅ Do

- **Validate in CI/CD**: Catch policy errors before deployment
- **Test combinations**: Test Allow + Deny interactions
- **Use specific actions**: Avoid wildcard `*` where possible
- **Document policies**: Add comments explaining intent
- **Version control**: Keep policies in git

### ❌ Don't

- **Don't use for production auth**: This is for validation, not runtime auth
- **Don't skip error handling**: Policy errors can fail silently
- **Don't assume default allow**: Default is always deny
- **Don't forget conditions**: They can drastically change behavior

## Integration Examples

### With CI/CD (GitHub Actions)

```yaml
name: Validate IAM Policies
on: [pull_request]

jobs:
  validate:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions-rs/toolchain@v1
        with:
          toolchain: stable
      - run: cargo test --test policy_validation
```

### As a CLI Tool

```rust
use clap::{Parser, Subcommand};

#[derive(Parser)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    Validate { file: String },
    Simulate { policy: String, action: String, resource: String },
}

fn main() {
    let cli = Cli::parse();
    
    match cli.command {
        Commands::Validate { file } => {
            // Validate policy file
        }
        Commands::Simulate { policy, action, resource } => {
            // Simulate access
        }
    }
}
```

## Next Steps

- **[IAM Guide]IAM_GUIDE.md** - Full IAM management
- **[Store Implementation]STORE_IMPLEMENTATION.md** - Persistent storage
- **[Multi-Tenant]MULTI_TENANT_GUIDE.md** - Tenant isolation
- **[Examples]EXAMPLES.md** - More code samples

## Resources

- **Policy Evaluator**: `src/iam/policy_evaluation/`
- **Examples**: `examples/policy_validation.rs`
- **API Docs**: `cargo doc --open`

## Support

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