scratchstack-aspen 0.3.1

AWS IAM policy language (Aspen) parser and internal representation
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
use {
    crate::{
        display_json, from_str_json, serutil::MapList, ActionList, AspenError, Condition, Context, Decision, Effect,
        PolicyVersion, Principal, ResourceList,
    },
    derive_builder::Builder,
    serde::{
        de::{Deserializer, MapAccess, Visitor},
        Deserialize, Serialize,
    },
    std::fmt::{Formatter, Result as FmtResult},
};

/// An Aspen policy statement.
///
/// Statement structs are immutable after creation. They can be created using the [StatementBuilder].
#[derive(Builder, Clone, Debug, Eq, PartialEq, Serialize)]
#[builder(build_fn(validate = "Self::validate"))]
#[serde(deny_unknown_fields, rename_all = "PascalCase")]
pub struct Statement {
    /// The user-provided statement id.
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    sid: Option<String>,

    /// The effect of the statement (allow or deny).
    effect: Effect,

    /// The list of actions this statement applies to. Exactly one of `action` or `not_action` must be set.
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    action: Option<ActionList>,

    /// The list of actions this statement does not apply to. Exactly one of `action` or `not_action` must be set.
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    not_action: Option<ActionList>,

    /// The list of resources this statement applies to. This cannot be combined with `not_resource`.
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    resource: Option<ResourceList>,

    /// The list of resources this statement does not apply to. This cannot be combined with `resource`.
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    not_resource: Option<ResourceList>,

    /// The list of principals this statement applies to. This cannot be combined with `not_principal`.
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    principal: Option<Principal>,

    /// The list of principals this statement does not apply to. This cannot be combined with `principal`.
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    not_principal: Option<Principal>,

    /// Conditions that must be met for this statement to apply.
    #[builder(setter(into, strip_option), default)]
    #[serde(skip_serializing_if = "Option::is_none")]
    condition: Option<Condition>,
}

impl Statement {
    /// Create a new [StatementBuilder] for building a [Statement].
    pub fn builder() -> StatementBuilder {
        StatementBuilder::default()
    }

    /// Returns the user-provided statement id if provided, else `None`.
    #[inline]
    pub fn sid(&self) -> Option<&str> {
        self.sid.as_deref()
    }

    /// Returns the effect of the statement (allow or deny).
    #[inline]
    pub fn effect(&self) -> &Effect {
        &self.effect
    }

    /// Returns the list of actions this statement applies to if provided, else `None`.
    #[inline]
    pub fn action(&self) -> Option<&ActionList> {
        self.action.as_ref()
    }

    /// Returns the list of actions this statement does not apply to if provided, else `None`.
    #[inline]
    pub fn not_action(&self) -> Option<&ActionList> {
        self.not_action.as_ref()
    }

    /// Returns the list of resources this statement applies to if provided, else `None`.
    #[inline]
    pub fn resource(&self) -> Option<&ResourceList> {
        self.resource.as_ref()
    }

    /// Returns the list of resources this statement does not apply to if provided, else `None`.
    #[inline]
    pub fn not_resource(&self) -> Option<&ResourceList> {
        self.not_resource.as_ref()
    }

    /// Returns the list of principals this statement applies to if provided, else `None`.
    #[inline]
    pub fn principal(&self) -> Option<&Principal> {
        self.principal.as_ref()
    }

    /// Returns the list of principals this statement does not apply to if provided, else `None`.
    #[inline]
    pub fn not_principal(&self) -> Option<&Principal> {
        self.not_principal.as_ref()
    }

    /// Returns the conditions that must be met for this statement to apply if provided, else `None`.
    #[inline]
    pub fn condition(&self) -> Option<&Condition> {
        self.condition.as_ref()
    }

    /// Evaluate this statement against the specified request [Context], using the [PolicyVersion] to perform
    /// variable substitution.
    ///
    /// # Example
    ///
    /// ```
    /// # use scratchstack_aspen::{Action, Context, Decision, Effect, PolicyVersion, Resource, Statement};
    /// # use scratchstack_arn::Arn;
    /// # use scratchstack_aws_principal::{Principal, User, SessionData, SessionValue};
    /// # use std::str::FromStr;
    /// let actor = Principal::from(vec![User::from_str("arn:aws:iam::123456789012:user/exampleuser").unwrap().into()]);
    /// let s3_object_arn = Arn::from_str("arn:aws:s3:::examplebucket/exampleuser/my-object").unwrap();
    /// let resources = vec![s3_object_arn.clone()];
    /// let session_data = SessionData::from([("aws:username", SessionValue::from("exampleuser"))]);
    /// let context = Context::builder()
    ///     .service("s3").api("GetObject").actor(actor.clone()).resources(resources.clone())
    ///     .session_data(session_data.clone()).build().unwrap();
    /// let statement = Statement::builder().effect(Effect::Allow).action(vec![Action::new("s3", "Get*").unwrap()])
    ///     .resource(Resource::Any).build().unwrap();
    /// assert_eq!(statement.evaluate(&context, PolicyVersion::V2012_10_17).unwrap(), Decision::Allow);
    ///
    /// let context = Context::builder()
    ///     .service("s3").api("PutObject").actor(actor).resources(resources)
    ///     .session_data(session_data).build().unwrap();
    /// assert_eq!(statement.evaluate(&context, PolicyVersion::V2012_10_17).unwrap(), Decision::DefaultDeny);
    /// ```
    pub fn evaluate(&self, context: &Context, pv: PolicyVersion) -> Result<Decision, AspenError> {
        // Does the action match the context?
        if let Some(actions) = self.action() {
            let mut matched = false;
            for action in actions.iter() {
                if action.matches(context.service(), context.api()) {
                    matched = true;
                    break;
                }
            }

            if !matched {
                return Ok(Decision::DefaultDeny);
            }
        } else if let Some(actions) = self.not_action() {
            let mut matched = false;
            for action in actions.iter() {
                if action.matches(context.service(), context.api()) {
                    matched = true;
                    break;
                }
            }

            if matched {
                return Ok(Decision::DefaultDeny);
            }
        } else {
            unreachable!("Statement must have either an Action or NotAction");
        }

        // Does the resource match the context?
        if let Some(resources) = self.resource() {
            let candidates = context.resources();
            if candidates.is_empty() {
                // We need a resource statement that is a wildcard.
                if !resources.iter().any(|r| r.is_any()) {
                    return Ok(Decision::DefaultDeny);
                }
            } else {
                for candidate in candidates {
                    let mut candidate_matched = false;

                    for resource in resources.iter() {
                        if resource.matches(context, pv, candidate)? {
                            candidate_matched = true;
                            break;
                        }
                    }

                    if !candidate_matched {
                        return Ok(Decision::DefaultDeny);
                    }
                }
            }
        } else if let Some(resources) = self.not_resource() {
            let candidates = context.resources();
            log::trace!("NotResource: candidates = {:?}", candidates);
            if candidates.is_empty() {
                // We cannot have a resource statement that is a wildcard.
                if resources.iter().any(|r| r.is_any()) {
                    return Ok(Decision::DefaultDeny);
                }
            } else {
                for candidate in candidates {
                    log::trace!("NotResource: candidate = {:?}", candidate);
                    for resource in resources.iter() {
                        if resource.matches(context, pv, candidate)? {
                            log::trace!("NotResource: candidate {:?} matched resource {:?}", candidate, resource);
                            return Ok(Decision::DefaultDeny);
                        }
                    }
                }

                log::trace!("NotResource: no matches");
            }
        }
        // We're allowed to not have a resource if this is a resource-based policy.

        // Does the principal match the context?
        if let Some(principal) = self.principal() {
            if !principal.matches(context.actor()) {
                return Ok(Decision::DefaultDeny);
            }
        } else if let Some(principal) = self.not_principal() {
            if principal.matches(context.actor()) {
                return Ok(Decision::DefaultDeny);
            }
        }
        // We're allowed to not have a principal if this is a principal-based policy.

        // Do the conditions match?
        if let Some(conditions) = self.condition() {
            for (key, values) in conditions.iter() {
                if !key.matches(values, context, pv)? {
                    return Ok(Decision::DefaultDeny);
                }
            }
        }

        // Everything matches here. Return the effect.
        match self.effect() {
            Effect::Allow => Ok(Decision::Allow),
            Effect::Deny => Ok(Decision::Deny),
        }
    }
}

display_json!(Statement);
from_str_json!(Statement);

impl<'de> Deserialize<'de> for Statement {
    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        deserializer.deserialize_map(StatementVisitor {})
    }
}

struct StatementVisitor;
impl<'de> Visitor<'de> for StatementVisitor {
    type Value = Statement;

    fn expecting(&self, formatter: &mut Formatter) -> FmtResult {
        formatter.write_str("a map of statement properties")
    }

    fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Statement, A::Error> {
        let mut builder = Statement::builder();
        let mut sid_seen = false;
        let mut effect_seen = false;
        let mut action_seen = false;
        let mut not_action_seen = false;
        let mut resource_seen = false;
        let mut not_resource_seen = false;
        let mut principal_seen = false;
        let mut not_principal_seen = false;
        let mut condition_seen = false;

        while let Some(key) = access.next_key::<&str>()? {
            match key {
                "Sid" => {
                    if sid_seen {
                        return Err(serde::de::Error::duplicate_field("Sid"));
                    }

                    sid_seen = true;
                    builder.sid(access.next_value::<&str>()?);
                }
                "Effect" => {
                    if effect_seen {
                        return Err(serde::de::Error::duplicate_field("Effect"));
                    }

                    effect_seen = true;
                    builder.effect(access.next_value::<Effect>()?);
                }
                "Action" => {
                    if action_seen {
                        return Err(serde::de::Error::duplicate_field("Action"));
                    }

                    action_seen = true;
                    builder.action(access.next_value::<ActionList>()?);
                }
                "NotAction" => {
                    if not_action_seen {
                        return Err(serde::de::Error::duplicate_field("NotAction"));
                    }

                    not_action_seen = true;
                    builder.not_action(access.next_value::<ActionList>()?);
                }
                "Resource" => {
                    if resource_seen {
                        return Err(serde::de::Error::duplicate_field("Resource"));
                    }

                    resource_seen = true;
                    builder.resource(access.next_value::<ResourceList>()?);
                }
                "NotResource" => {
                    if not_resource_seen {
                        return Err(serde::de::Error::duplicate_field("NotResource"));
                    }

                    not_resource_seen = true;
                    builder.not_resource(access.next_value::<ResourceList>()?);
                }
                "Principal" => {
                    if principal_seen {
                        return Err(serde::de::Error::duplicate_field("Principal"));
                    }

                    principal_seen = true;
                    builder.principal(access.next_value::<Principal>()?);
                }
                "NotPrincipal" => {
                    if not_principal_seen {
                        return Err(serde::de::Error::duplicate_field("NotPrincipal"));
                    }

                    not_principal_seen = true;
                    builder.not_principal(access.next_value::<Principal>()?);
                }
                "Condition" => {
                    if condition_seen {
                        return Err(serde::de::Error::duplicate_field("Condition"));
                    }

                    condition_seen = true;
                    builder.condition(access.next_value::<Condition>()?);
                }
                _ => {
                    return Err(serde::de::Error::unknown_field(
                        key,
                        &[
                            "Sid",
                            "Effect",
                            "Action",
                            "NotAction",
                            "Resource",
                            "NotResource",
                            "Principal",
                            "NotPrincipal",
                            "Condition",
                        ],
                    ));
                }
            }
        }

        builder.build().map_err(|e| match e {
            StatementBuilderError::ValidationError(s) => {
                let msg2 = s.replace('.', ";").trim_end_matches(|c| c == ';').to_string();
                serde::de::Error::custom(StatementBuilderError::ValidationError(msg2))
            }
            _ => serde::de::Error::custom(e),
        })
    }
}

impl StatementBuilder {
    fn validate(&self) -> Result<(), StatementBuilderError> {
        let mut errors = Vec::with_capacity(5);
        if self.effect.is_none() {
            errors.push("Effect must be set.");
        }

        match (&self.action, &self.not_action) {
            (Some(_), Some(_)) => errors.push("Action and NotAction cannot both be set."),
            (None, None) => errors.push("Either Action or NotAction must be set."),
            _ => (),
        }

        match (&self.resource, &self.not_resource) {
            (Some(_), Some(_)) => errors.push("Resource and NotResource cannot both be set."),
            (None, None) => errors.push("Either Resource or NotResource must be set."),
            _ => (),
        }

        if let (Some(_), Some(_)) = (&self.principal, &self.not_principal) {
            errors.push("Principal and NotPrincipal cannot both be set.");
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(StatementBuilderError::ValidationError(errors.join(" ")))
        }
    }
}

/// A list of statements. In JSON, this may be an object or an array of objects.
pub type StatementList = MapList<Statement>;

#[cfg(test)]
mod tests {
    use {
        crate::{
            Action, AwsPrincipal, Context, Decision, Effect, Policy, PolicyVersion, Principal, Resource,
            SpecifiedPrincipal, Statement,
        },
        indoc::indoc,
        pretty_assertions::assert_eq,
        scratchstack_aws_principal::{Principal as PrincipalActor, PrincipalIdentity, SessionData, User},
        std::str::FromStr,
    };

    #[test_log::test]
    fn test_blank_policy_import() {
        let policy = Policy::from_str(indoc! { r#"
            {
                "Version": "2012-10-17",
                "Statement": []
            }"# })
        .unwrap();
        assert_eq!(policy.version(), PolicyVersion::V2012_10_17);
        assert!(policy.id().is_none());

        let policy_str = policy.to_string();
        assert_eq!(
            policy_str,
            indoc! { r#"
            {
                "Version": "2012-10-17",
                "Statement": []
            }"#}
        );
    }

    #[test_log::test]
    fn test_builder() {
        let err = Statement::builder().build().unwrap_err();
        assert_eq!(
            err.to_string(),
            "Effect must be set. Either Action or NotAction must be set. Either Resource or NotResource must be set."
        );

        let err = Statement::builder().effect(Effect::Allow).build().unwrap_err();
        assert_eq!(
            err.to_string(),
            "Either Action or NotAction must be set. Either Resource or NotResource must be set."
        );

        let err = Statement::builder()
            .effect(Effect::Allow)
            .action(Action::from_str("ec2:RunInstances").unwrap())
            .build()
            .unwrap_err();
        assert_eq!(err.to_string(), "Either Resource or NotResource must be set.");

        let err = Statement::builder()
            .effect(Effect::Allow)
            .action(Action::from_str("ec2:RunInstances").unwrap())
            .resource(Resource::from_str("arn:aws:ec2:us-east-1:123456789012:instance/i-01234567890abcdef").unwrap())
            .principal(
                SpecifiedPrincipal::builder().aws(AwsPrincipal::from_str("123456789012").unwrap()).build().unwrap(),
            )
            .not_principal(
                SpecifiedPrincipal::builder().aws(AwsPrincipal::from_str("123456789012").unwrap()).build().unwrap(),
            )
            .build()
            .unwrap_err();
        assert_eq!(err.to_string(), "Principal and NotPrincipal cannot both be set.");

        let s = Statement::builder()
            .sid("sid1")
            .effect(Effect::Allow)
            .action(Action::from_str("ec2:RunInstances").unwrap())
            .resource(Resource::from_str("arn:aws:ec2:us-east-1:123456789012:instance/i-01234567890abcdef").unwrap())
            .principal(
                SpecifiedPrincipal::builder().aws(AwsPrincipal::from_str("123456789012").unwrap()).build().unwrap(),
            )
            .build()
            .unwrap();

        assert_eq!(s.sid(), Some("sid1"));
        assert_eq!(s.effect(), &Effect::Allow);
        assert_eq!(s.action().unwrap().len(), 1);
        assert_eq!(s.action().unwrap()[0].to_string(), "ec2:RunInstances");

        let s2 = s.clone();
        assert_eq!(s, s2);

        let s = Statement::builder()
            .sid("sid1")
            .effect(Effect::Allow)
            .action(Action::from_str("ec2:RunInstances").unwrap())
            .not_resource(vec![
                Resource::from_str("arn:aws:ec2:us-east-1:123456789012:instance/i-01234567890abcdef").unwrap(),
                Resource::from_str("arn:aws:ec2:us-west-1:123456789012:instance/i-01234567890abcdef").unwrap(),
            ])
            .not_principal(
                SpecifiedPrincipal::builder().aws(AwsPrincipal::from_str("123456789012").unwrap()).build().unwrap(),
            )
            .build()
            .unwrap();

        assert_eq!(s.not_resource().unwrap().len(), 2);
        assert_eq!(
            s.not_resource().unwrap()[0].to_string(),
            "arn:aws:ec2:us-east-1:123456789012:instance/i-01234567890abcdef"
        );
        let principal = s.not_principal().unwrap();
        if let Principal::Specified(specified) = principal {
            assert_eq!(specified.aws().unwrap().len(), 1);
            assert_eq!(specified.aws().unwrap()[0].to_string(), "123456789012");
        } else {
            panic!("not_principal is not SpecifiedPrincipal");
        }
    }

    #[test_log::test]
    fn test_context_without_resources() {
        let mut sb = Statement::builder();
        sb.effect(Effect::Allow).action(Action::Any).resource(Resource::Any);

        let s = sb.build().unwrap();
        let actor = PrincipalActor::from(vec![PrincipalIdentity::from(
            User::new("aws", "123456789012", "/", "MyUser").unwrap(),
        )]);
        let sd = SessionData::new();
        let context =
            Context::builder().api("DescribeInstances").actor(actor).service("ec2").session_data(sd).build().unwrap();

        assert_eq!(s.evaluate(&context, PolicyVersion::None).unwrap(), Decision::Allow);

        sb.resource(Resource::from_str("arn:aws:ec2:us-east-1:123456789012:instance/i-01234567890abcdef").unwrap());
        let s = sb.build().unwrap();
        assert_eq!(s.evaluate(&context, PolicyVersion::None).unwrap(), Decision::DefaultDeny);

        let mut sb = Statement::builder();
        sb.effect(Effect::Allow).action(Action::Any).not_resource(Resource::Any);
        let s = sb.build().unwrap();
        assert_eq!(s.evaluate(&context, PolicyVersion::None).unwrap(), Decision::DefaultDeny);
    }

    #[test_log::test]
    fn test_bad_actions() {
        let policy_str = indoc! { r#"
            {
                "Version": "2012-10-17",
                "Statement": {
                    "Effect": "Allow",
                    "Action": ["ec2:"],
                    "Resource": "*",
                    "Principal": {
                        "AWS": ["arn:aws:"]
                    }
                }
            }"# };
        let e = Policy::from_str(policy_str).unwrap_err();
        assert_eq!(e.to_string(), r#"Invalid action: ec2: at line 5 column 26"#);
    }

    #[test_log::test]
    fn test_bad_principals() {
        let policy_str = indoc! { r#"
            {
                "Version": "2012-10-17",
                "Statement": {
                    "Effect": "Allow",
                    "Action": "*",
                    "Resource": "*",
                    "Principal": {
                        "AWS": ["arn:aws:"]
                    }
                }
            }"# };
        let e = Policy::from_str(policy_str).unwrap_err();
        assert_eq!(e.to_string(), r#"Invalid principal: arn:aws: at line 8 column 31"#);
    }

    #[test_log::test]
    fn test_bad_resources() {
        let policy_str = indoc! { r#"
            {
                "Version": "2012-10-17",
                "Statement": {
                    "Effect": "Allow",
                    "Action": "*",
                    "Resource": [2],
                    "Principal": "*"
                }
            }"# };
        let e = Policy::from_str(policy_str).unwrap_err();
        assert_eq!(
            e.to_string(),
            r#"invalid value: sequence, expected Resource or list of Resource at line 6 column 23"#
        );

        let policy_str = indoc! { r#"
            {
                "Version": "2012-10-17",
                "Statement": {
                    "Effect": "Allow",
                    "Action": "*",
                    "Resource": ["foo-bar-baz"],
                    "Principal": "*"
                }
            }"# };
        let e = Policy::from_str(policy_str).unwrap_err();
        assert_eq!(e.to_string(), r#"Invalid resource: foo-bar-baz at line 6 column 35"#);
    }
}