wami 0.17.1

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
//! Canonical Policy Evaluator
//!
//! Single source of truth for IAM policy evaluation logic. Used by both:
//! - `AuthorizationService` for real-time authorization decisions
//! - `EvaluationService` for policy simulation (simulate-custom-policy / simulate-principal-policy)
//!
//! # Evaluation Rules
//!
//! 1. **Deny overrides Allow**: an explicit Deny from ANY statement wins
//! 2. **Conditions narrow applicability**: a failed condition means NoMatch, not Deny
//! 3. **Glob matching**: `*` = single segment, `**` = multi-segment
//! 4. **Variable substitution**: `${tenant}`, `${principal}`, `${service}` from context

use wami_condition::{
    evaluate_condition_block, evaluator::parse_condition_block, ConditionContext,
};
use wami_core::arn::matching::{glob_match, matches_arn_pattern, MatchContext};
use wami_core::arn::WamiArn;
use wami_core::context::WamiContext;
use wami_core::error::{AmiError, Result};
use wami_core::types::{PolicyDocument, PolicyStatement};

use super::decision::PolicySource;

/// Policy evaluation result for a single policy document.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PolicyEffect {
    /// Policy explicitly allows the action
    Allow,
    /// Policy explicitly denies the action (overrides any allow)
    Deny,
    /// Policy doesn't match this action/resource (or condition failed)
    NoMatch,
}

/// The statement that decided a document, and what it decided.
///
/// One per document, not one per matching statement: evaluation stops at the
/// first match, denies before allows, so a document has exactly one decisive
/// statement or none at all.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatementHit {
    /// What the statement decided — never `NoMatch`.
    pub effect: PolicyEffect,
    /// The statement's `Sid`, if it has one.
    pub sid: Option<String>,
    /// Its position in the document.
    pub index: usize,
}

/// Evaluate a single policy document against an action and resource.
///
/// Returns the statement that decided, or `None` when the document does not
/// apply. Which statement decided is what lets a caller write an audit line
/// naming it — the effect alone cannot be traced back to anything.
pub fn evaluate_policy_document(
    policy: &PolicyDocument,
    action: &str,
    resource_arn: &WamiArn,
    context: &WamiContext,
) -> Option<StatementHit> {
    let resource_str = resource_arn.to_string();
    let match_ctx = MatchContext {
        tenant: Some(context.tenant_path().as_string()),
        principal: Some(context.caller_arn().resource.resource_id.clone()),
        service: Some(context.caller_arn().service.to_string()),
    };
    let cond_ctx = build_condition_context(context, resource_arn);

    let hit = |effect: PolicyEffect, index: usize, statement: &PolicyStatement| StatementHit {
        effect,
        sid: statement.sid.clone(),
        index,
    };

    let applies = |statement: &PolicyStatement| {
        matches_action(&statement.action, action)
            && matches_resource(&statement.resource, &resource_str, &match_ctx)
            && matches_condition(statement, &cond_ctx)
    };

    // Explicit denies first — a deny anywhere in the document wins over an
    // allow later in it.
    for (index, statement) in policy.statement.iter().enumerate() {
        if statement.effect.to_lowercase() == "deny" && applies(statement) {
            return Some(hit(PolicyEffect::Deny, index, statement));
        }
    }

    for (index, statement) in policy.statement.iter().enumerate() {
        if statement.effect.to_lowercase() == "allow" && applies(statement) {
            return Some(hit(PolicyEffect::Allow, index, statement));
        }
    }

    None
}

/// Check if an action matches any of the policy action patterns.
///
/// Supports wildcards via `glob_match`: `iam:*`, `*`, `iam:Get*`
pub fn matches_action(policy_actions: &[String], action: &str) -> bool {
    for policy_action in policy_actions {
        if glob_match(policy_action, action) {
            return true;
        }
    }
    false
}

/// Check if a resource matches any of the policy resource patterns.
///
/// Supports:
/// - `*` (match all)
/// - Single-star wildcards: `arn:wami:iam:*:user/*`
/// - Double-star globbing: `arn:wami:hub:*:space/le-zinc/**`
/// - Variable substitution: `${tenant}`, `${principal}`, `${service}`
pub fn matches_resource(
    policy_resources: &[String],
    resource: &str,
    match_ctx: &MatchContext,
) -> bool {
    for policy_resource in policy_resources {
        if matches_arn_pattern(policy_resource, resource, match_ctx) {
            return true;
        }
    }
    false
}

/// Build a [`ConditionContext`] from a [`WamiContext`] and the target resource ARN.
pub fn build_condition_context(context: &WamiContext, resource_arn: &WamiArn) -> ConditionContext {
    let mut builder = ConditionContext::builder()
        .principal_arn(context.caller_arn().to_string())
        .username(context.caller_arn().resource.resource_id.clone())
        .principal_type(context.caller_arn().resource.resource_type.clone())
        .resource_arn(resource_arn.to_string());

    // Tenant info
    if let Some(primary) = context.tenant_path().root_u64() {
        builder = builder.tenant_id(primary).principal_tenant_id(primary);
    }
    if let Some(resource_tenant) = resource_arn.tenant_path.root_u64() {
        builder = builder.resource_tenant_id(resource_tenant);
    }

    // Request metadata (set by HTTP/transport layer)
    if let Some(ip) = context.source_ip() {
        builder = builder.source_ip(ip);
    }
    if let Some(mfa) = context.mfa_present() {
        builder = builder.mfa_present(mfa);
    }
    if let Some(secure) = context.secure_transport() {
        builder = builder.secure_transport(secure);
    }

    builder.build()
}

/// Evaluate the condition block of a policy statement (if present).
///
/// Returns `true` if:
/// - The statement has no condition (unconditional match), OR
/// - The condition block evaluates to `true`.
///
/// Returns `false` if the condition cannot be parsed or evaluates to `false`.
pub fn matches_condition(statement: &PolicyStatement, cond_ctx: &ConditionContext) -> bool {
    let condition_value = match &statement.condition {
        Some(v) if !v.is_null() => v,
        _ => return true, // No condition → always matches
    };

    let block = match parse_condition_block(condition_value) {
        Ok(b) => b,
        Err(_) => return false,
    };

    evaluate_condition_block(&block, cond_ctx).unwrap_or_default()
}

/// Parse a policy document, refusing to guess when it cannot be read.
///
/// This used to swallow the error and hand back an empty document. For an
/// `Allow` that was merely useless; for a `Deny` it was a fail-open — the
/// statement meant to block the action stopped existing, and any `Allow` from
/// another source won. One typo was enough:
///
/// ```text
/// {"Effect":"Deny","Actions":["iam:*"],"Resource":["*"]}
///                   ^ plural — valid JSON, not a PolicyStatement
/// ```
///
/// Refusing to decide is the only safe answer: a document that cannot be read
/// might have contained a deny, and there is no way to know.
pub fn parse_policy_doc(json: &str, policy: &PolicySource) -> Result<PolicyDocument> {
    serde_json::from_str(json).map_err(|e| AmiError::UnreadablePolicy {
        policy: policy.to_string(),
        message: e.to_string(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use wami_core::arn::TenantPath;

    fn make_context() -> WamiContext {
        let arn: WamiArn = "arn:wami:iam:12345678:wami:999:user/alice".parse().unwrap();
        WamiContext::builder()
            .instance_id("999")
            .tenant_path(TenantPath::single(12345678))
            .caller_arn(arn)
            .is_root(false)
            .build()
            .unwrap()
    }

    fn make_policy(effect: &str, actions: &[&str], resources: &[&str]) -> PolicyDocument {
        PolicyDocument {
            version: "2012-10-17".to_string(),
            statement: vec![PolicyStatement {
                sid: None,
                effect: effect.to_string(),
                action: actions.iter().map(|a| a.to_string()).collect(),
                resource: resources.iter().map(|r| r.to_string()).collect(),
                condition: None,
            }],
        }
    }

    fn make_statement(
        effect: &str,
        actions: &[&str],
        resources: &[&str],
        condition: Option<serde_json::Value>,
    ) -> PolicyStatement {
        PolicyStatement {
            sid: None,
            effect: effect.to_string(),
            action: actions.iter().map(|a| a.to_string()).collect(),
            resource: resources.iter().map(|r| r.to_string()).collect(),
            condition,
        }
    }

    // ─── matches_action ───────────────────────────────────────

    #[test]
    fn matches_action_exact() {
        let actions = vec!["iam:GetUser".to_string()];
        assert!(matches_action(&actions, "iam:GetUser"));
    }

    #[test]
    fn matches_action_wildcard_star() {
        let actions = vec!["*".to_string()];
        assert!(matches_action(&actions, "iam:GetUser"));
        assert!(matches_action(&actions, "sts:AssumeRole"));
    }

    #[test]
    fn matches_action_prefix_wildcard() {
        let actions = vec!["iam:Get*".to_string()];
        assert!(matches_action(&actions, "iam:GetUser"));
        assert!(matches_action(&actions, "iam:GetRole"));
        assert!(!matches_action(&actions, "iam:PutUser"));
    }

    #[test]
    fn matches_action_no_match() {
        let actions = vec!["iam:GetUser".to_string()];
        assert!(!matches_action(&actions, "iam:DeleteUser"));
    }

    #[test]
    fn matches_action_multiple_patterns() {
        let actions = vec!["iam:GetUser".to_string(), "iam:ListUsers".to_string()];
        assert!(matches_action(&actions, "iam:GetUser"));
        assert!(matches_action(&actions, "iam:ListUsers"));
        assert!(!matches_action(&actions, "iam:DeleteUser"));
    }

    #[test]
    fn matches_action_service_wildcard() {
        let actions = vec!["iam:*".to_string()];
        assert!(matches_action(&actions, "iam:GetUser"));
        assert!(matches_action(&actions, "iam:DeleteRole"));
        assert!(!matches_action(&actions, "sts:AssumeRole"));
    }

    // ─── matches_resource ─────────────────────────────────────

    #[test]
    fn matches_resource_wildcard() {
        let resources = vec!["*".to_string()];
        let ctx = MatchContext {
            tenant: None,
            principal: None,
            service: None,
        };
        assert!(matches_resource(
            &resources,
            "arn:wami:iam:123:wami:999:user/bob",
            &ctx
        ));
    }

    #[test]
    fn matches_resource_exact() {
        let resources = vec!["arn:wami:iam:12345678:wami:999:user/bob".to_string()];
        let ctx = MatchContext {
            tenant: None,
            principal: None,
            service: None,
        };
        assert!(matches_resource(
            &resources,
            "arn:wami:iam:12345678:wami:999:user/bob",
            &ctx
        ));
        assert!(!matches_resource(
            &resources,
            "arn:wami:iam:12345678:wami:999:user/alice",
            &ctx
        ));
    }

    #[test]
    fn matches_resource_no_match() {
        let resources = vec!["arn:wami:iam:999:wami:1:role/admin".to_string()];
        let ctx = MatchContext {
            tenant: None,
            principal: None,
            service: None,
        };
        assert!(!matches_resource(
            &resources,
            "arn:wami:iam:12345678:wami:999:user/bob",
            &ctx
        ));
    }

    #[test]
    fn matches_resource_multiple() {
        let resources = vec![
            "arn:wami:iam:12345678:wami:999:user/alice".to_string(),
            "arn:wami:iam:12345678:wami:999:user/bob".to_string(),
        ];
        let ctx = MatchContext {
            tenant: None,
            principal: None,
            service: None,
        };
        assert!(matches_resource(
            &resources,
            "arn:wami:iam:12345678:wami:999:user/bob",
            &ctx
        ));
    }

    // ─── matches_condition ────────────────────────────────────

    #[test]
    fn matches_condition_no_condition() {
        let stmt = make_statement("Allow", &["iam:*"], &["*"], None);
        let cond_ctx = ConditionContext::builder().build();
        assert!(matches_condition(&stmt, &cond_ctx));
    }

    #[test]
    fn matches_condition_null_condition() {
        let stmt = make_statement("Allow", &["iam:*"], &["*"], Some(serde_json::Value::Null));
        let cond_ctx = ConditionContext::builder().build();
        assert!(matches_condition(&stmt, &cond_ctx));
    }

    #[test]
    fn matches_condition_invalid_json() {
        // A non-null, non-object value that can't be parsed as a condition block
        let stmt = make_statement(
            "Allow",
            &["iam:*"],
            &["*"],
            Some(serde_json::json!("not a condition")),
        );
        let cond_ctx = ConditionContext::builder().build();
        assert!(!matches_condition(&stmt, &cond_ctx));
    }

    // ─── parse_policy_doc ─────────────────────────────────────

    fn a_policy() -> PolicySource {
        PolicySource::UserInline {
            name: "p".to_string(),
        }
    }

    #[test]
    fn parse_policy_doc_valid() {
        let json = r#"{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["iam:GetUser"],"Resource":["*"]}]}"#;
        let doc = parse_policy_doc(json, &a_policy()).unwrap();
        assert_eq!(doc.statement.len(), 1);
        assert_eq!(doc.statement[0].effect, "Allow");
    }

    #[test]
    fn a_sid_survives_a_round_trip() {
        let json = r#"{"Version":"2012-10-17","Statement":[{"Sid":"AllowReads","Effect":"Allow","Action":["iam:GetUser"],"Resource":["*"]}]}"#;
        let doc = parse_policy_doc(json, &a_policy()).unwrap();
        assert_eq!(doc.statement[0].sid.as_deref(), Some("AllowReads"));
        // Documents without a Sid must not gain an empty one when written back.
        let plain = parse_policy_doc(
            r#"{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["a"],"Resource":["*"]}]}"#,
            &a_policy(),
        )
        .unwrap();
        assert!(!serde_json::to_string(&plain).unwrap().contains("Sid"));
    }

    #[test]
    fn an_unreadable_policy_refuses_to_parse_instead_of_returning_nothing() {
        // The whole of #120: this used to yield an empty document, so a Deny
        // written with a typo simply stopped existing and any Allow elsewhere
        // won. Now it cannot be mistaken for a policy that permits nothing.
        for bad in ["not json at all", "", r#"{"Version":"2012-10-17"}"#] {
            let err = parse_policy_doc(bad, &a_policy()).unwrap_err();
            assert!(
                matches!(err, AmiError::UnreadablePolicy { .. }),
                "{bad:?} gave {err:?}"
            );
        }
    }

    #[test]
    fn a_deny_with_a_typo_no_longer_vanishes() {
        // Valid JSON, so it passes a `serde_json::Value` check, but not a
        // PolicyStatement: "Actions" instead of "Action". One character.
        let typo = r#"{"Version":"2012-10-17","Statement":[{"Effect":"Deny","Actions":["iam:*"],"Resource":["*"]}]}"#;
        assert!(serde_json::from_str::<serde_json::Value>(typo).is_ok());

        let err = parse_policy_doc(typo, &a_policy()).unwrap_err();
        assert!(matches!(err, AmiError::UnreadablePolicy { .. }));
        // And the operator is told which policy to go fix.
        assert!(err.to_string().contains("user inline policy p"));
    }

    // ─── evaluate_policy_document ─────────────────────────────

    #[test]
    fn evaluate_allow_policy() {
        let ctx = make_context();
        let policy = make_policy("Allow", &["iam:GetUser"], &["*"]);
        let resource: WamiArn = "arn:wami:iam:12345678:wami:999:user/bob".parse().unwrap();
        assert_eq!(
            evaluate_policy_document(&policy, "iam:GetUser", &resource, &ctx).map(|hit| hit.effect),
            Some(PolicyEffect::Allow)
        );
    }

    #[test]
    fn evaluate_deny_overrides_allow() {
        let ctx = make_context();
        let policy = PolicyDocument {
            version: "2012-10-17".to_string(),
            statement: vec![
                make_statement("Allow", &["iam:*"], &["*"], None),
                make_statement("Deny", &["iam:DeleteUser"], &["*"], None),
            ],
        };
        let resource: WamiArn = "arn:wami:iam:12345678:wami:999:user/bob".parse().unwrap();
        assert_eq!(
            evaluate_policy_document(&policy, "iam:DeleteUser", &resource, &ctx)
                .map(|hit| hit.effect),
            Some(PolicyEffect::Deny)
        );
    }

    #[test]
    fn evaluate_no_match() {
        let ctx = make_context();
        let policy = make_policy("Allow", &["sts:AssumeRole"], &["*"]);
        let resource: WamiArn = "arn:wami:iam:12345678:wami:999:user/bob".parse().unwrap();
        assert!(evaluate_policy_document(&policy, "iam:GetUser", &resource, &ctx).is_none());
    }

    #[test]
    fn evaluate_deny_only() {
        let ctx = make_context();
        let policy = make_policy("Deny", &["iam:*"], &["*"]);
        let resource: WamiArn = "arn:wami:iam:12345678:wami:999:user/bob".parse().unwrap();
        assert_eq!(
            evaluate_policy_document(&policy, "iam:GetUser", &resource, &ctx).map(|hit| hit.effect),
            Some(PolicyEffect::Deny)
        );
    }

    #[test]
    fn evaluate_empty_statements() {
        let ctx = make_context();
        let policy = PolicyDocument {
            version: "2012-10-17".to_string(),
            statement: vec![],
        };
        let resource: WamiArn = "arn:wami:iam:12345678:wami:999:user/bob".parse().unwrap();
        assert!(evaluate_policy_document(&policy, "iam:GetUser", &resource, &ctx).is_none());
    }

    #[test]
    fn evaluate_wildcard_action_and_resource() {
        let ctx = make_context();
        let policy = make_policy("Allow", &["*"], &["*"]);
        let resource: WamiArn = "arn:wami:iam:12345678:wami:999:user/bob".parse().unwrap();
        assert_eq!(
            evaluate_policy_document(&policy, "anything:Here", &resource, &ctx)
                .map(|hit| hit.effect),
            Some(PolicyEffect::Allow)
        );
    }

    // ─── build_condition_context ──────────────────────────────

    #[test]
    fn build_condition_context_populates_fields() {
        let ctx = make_context();
        let resource: WamiArn = "arn:wami:iam:12345678:wami:999:user/bob".parse().unwrap();
        let cond_ctx = build_condition_context(&ctx, &resource);
        // Verify the context was built (non-panicking is the test)
        // The builder returns a ConditionContext with the fields set
        let _ = cond_ctx;
    }

    #[test]
    fn build_condition_context_with_source_ip() {
        let arn: WamiArn = "arn:wami:iam:12345678:wami:999:user/alice".parse().unwrap();
        let ctx = WamiContext::builder()
            .instance_id("999")
            .tenant_path(TenantPath::single(12345678))
            .caller_arn(arn)
            .is_root(false)
            .source_ip("10.0.0.1")
            .build()
            .unwrap();
        let resource: WamiArn = "arn:wami:iam:12345678:wami:999:user/bob".parse().unwrap();
        let cond_ctx = build_condition_context(&ctx, &resource);
        let _ = cond_ctx;
    }

    #[test]
    fn build_condition_context_with_mfa() {
        let arn: WamiArn = "arn:wami:iam:12345678:wami:999:user/alice".parse().unwrap();
        let ctx = WamiContext::builder()
            .instance_id("999")
            .tenant_path(TenantPath::single(12345678))
            .caller_arn(arn)
            .is_root(false)
            .mfa_present(true)
            .secure_transport(true)
            .build()
            .unwrap();
        let resource: WamiArn = "arn:wami:iam:12345678:wami:999:user/bob".parse().unwrap();
        let cond_ctx = build_condition_context(&ctx, &resource);
        let _ = cond_ctx;
    }
}