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
use std::error::Error as StdError;

use lazy_static::lazy_static;
use regex::Regex;
use serde::Deserialize;

use crate::{
    core::{Identities, Operations, Resources},
    matcher, Decision, DefaultSubstituter, DefaultValidator, Error, Policy, PolicyValidator,
    ResourceMatcher, Result, Substituter,
};

/// A policy builder, responsible for parsing policy definition
/// and constructing [`Policy`] struct.
///
/// It handles policy definition versioning and allows fine-grained
/// configuration of [`Policy`] components.
pub struct PolicyBuilder<V, M, S> {
    validator: V,
    matcher: M,
    substituter: S,
    source: Source,
    default_decision: Decision,
}

impl PolicyBuilder<DefaultValidator, matcher::Default, DefaultSubstituter> {
    /// Constructs a [`PolicyBuilder`] from provided json policy definition, with
    /// default configuration.
    ///
    /// Call to this method does not parse or validate the json, all heavy work
    /// is done in `build` method.
    pub fn from_json(
        json: impl Into<String>,
    ) -> PolicyBuilder<DefaultValidator, matcher::Default, DefaultSubstituter> {
        PolicyBuilder {
            source: Source::Json(json.into()),
            validator: DefaultValidator,
            matcher: matcher::Default,
            substituter: DefaultSubstituter,
            default_decision: Decision::Denied,
        }
    }

    /// Constructs a [`PolicyBuilder`] from provided policy definition struct, with
    /// default configuration.
    ///
    /// Call to this method does not validate the definition, all heavy work
    /// is done in `build` method.
    pub fn from_definition(
        definition: PolicyDefinition,
    ) -> PolicyBuilder<DefaultValidator, matcher::Default, DefaultSubstituter> {
        PolicyBuilder {
            source: Source::Definition(definition),
            validator: DefaultValidator,
            matcher: matcher::Default,
            substituter: DefaultSubstituter,
            default_decision: Decision::Denied,
        }
    }
}

impl<V, M, S, E> PolicyBuilder<V, M, S>
where
    V: PolicyValidator<Error = E>,
    M: ResourceMatcher,
    S: Substituter,
    E: StdError + Sync + Into<Box<dyn StdError>> + 'static,
{
    /// Specifies the [`PolicyValidator`] to validate the policy definition.
    pub fn with_validator<V1>(self, validator: V1) -> PolicyBuilder<V1, M, S> {
        PolicyBuilder {
            source: self.source,
            validator,
            matcher: self.matcher,
            substituter: self.substituter,
            default_decision: self.default_decision,
        }
    }

    /// Specifies the [`ResourceMatcher`] to use with Policy.
    pub fn with_matcher<M1>(self, matcher: M1) -> PolicyBuilder<V, M1, S> {
        PolicyBuilder {
            source: self.source,
            validator: self.validator,
            matcher,
            substituter: self.substituter,
            default_decision: self.default_decision,
        }
    }

    /// Specifies the [`Substituter`] to use with Policy.
    pub fn with_substituter<S1>(self, substituter: S1) -> PolicyBuilder<V, M, S1> {
        PolicyBuilder {
            source: self.source,
            validator: self.validator,
            matcher: self.matcher,
            substituter,
            default_decision: self.default_decision,
        }
    }

    /// Specifies the default decision that [`Policy`] will return if
    /// no rules match the request.
    pub fn with_default_decision(mut self, decision: Decision) -> Self {
        self.default_decision = decision;
        self
    }

    /// Builds a [`Policy`] consuming the builder.
    ///
    /// This method does all the heavy lifting of deserializing json, validating and
    /// constructing the policy rules tree.
    ///
    /// # Errors
    /// Returns  [`PolicyValidator::Error`] if any.
    pub fn build(self) -> Result<Policy<M, S>> {
        let PolicyBuilder {
            validator,
            matcher,
            substituter,
            source,
            default_decision,
        } = self;

        let mut definition: PolicyDefinition = match source {
            Source::Json(json) => PolicyDefinition::from_json(&json)?,
            Source::Definition(definition) => definition,
        };

        for (order, mut statement) in definition.statements.iter_mut().enumerate() {
            statement.order = order;
        }

        validator
            .validate(&definition)
            .map_err(|e| Error::Validation(e.into()))?;

        let mut static_rules = Identities::new();
        let mut variable_rules = Identities::new();

        for statement in definition.statements {
            process_statement(&statement, &mut static_rules, &mut variable_rules);
        }

        Ok(Policy {
            default_decision,
            resource_matcher: matcher,
            substituter,
            static_rules: static_rules.0,
            variable_rules: variable_rules.0,
        })
    }
}

fn process_statement(
    statement: &Statement,
    static_rules: &mut Identities,
    variable_rules: &mut Identities,
) {
    let (static_ids, variable_ids) = process_identities(statement);

    static_rules.merge(static_ids);
    variable_rules.merge(variable_ids);
}

fn process_identities(statement: &Statement) -> (Identities, Identities) {
    let mut static_ids = Identities::new();
    let mut variable_ids = Identities::new();
    for identity in &statement.identities {
        let (static_ops, variable_ops) = process_operations(&statement);

        if is_variable_rule(identity) {
            // if current identity has substitutions,
            // then the whole operation subtree need
            // to be cloned into substitutions tree.
            let mut all = static_ops.clone();
            all.merge(variable_ops);
            variable_ids.insert(identity, all);
        } else {
            // else, divide operations and operation substitutions
            // between identities and identity substitutions.
            static_ids.insert(identity, static_ops);
            variable_ids.insert(identity, variable_ops);
        }
    }

    (static_ids, variable_ids)
}

fn process_operations(statement: &Statement) -> (Operations, Operations) {
    let mut static_ops = Operations::new();
    let mut variable_ops = Operations::new();
    for operation in &statement.operations {
        let (static_res, variable_res) = process_resources(&statement);

        if is_variable_rule(operation) {
            // if current operation has variables,
            // then the whole resource subtree need
            // to be cloned into variables tree.
            let mut all = static_res.clone();
            all.merge(variable_res);
            variable_ops.insert(operation, all);
        } else {
            // else, divide static resources and variable resources
            // between static operations and variable operation.
            static_ops.insert(operation, static_res);
            variable_ops.insert(operation, variable_res);
        }
    }

    (static_ops, variable_ops)
}

fn process_resources(statement: &Statement) -> (Resources, Resources) {
    let mut static_res = Resources::new();
    let mut variable_res = Resources::new();
    if statement.resources.is_empty() {
        static_res.insert("", statement.into());
    }

    for resource in &statement.resources {
        // split resources into two buckets - static or variable rules:
        let map = if is_variable_rule(resource) {
            &mut variable_res
        } else {
            &mut static_res
        };

        map.insert(resource, statement.into());
    }

    (static_res, variable_res)
}

fn is_variable_rule(value: &str) -> bool {
    lazy_static! {
        static ref VAR_PATTERN: Regex =
            Regex::new(r#"\{\{[^\{\}]+\}\}"#).expect("failed to create a Regex from pattern");
    }
    VAR_PATTERN.is_match(value)
}

enum Source {
    Json(String),
    Definition(PolicyDefinition),
}

/// Represents a deserialized policy definition.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PolicyDefinition {
    pub(super) statements: Vec<Statement>,
}

impl PolicyDefinition {
    pub fn from_json(json: &str) -> Result<Self> {
        let definition: PolicyDefinition =
            serde_json::from_str(json).map_err(Error::Deserializing)?;

        Ok(definition)
    }

    pub fn statements(&self) -> &Vec<Statement> {
        &self.statements
    }
}

/// Represents a statement in a policy definition.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Statement {
    #[serde(default)]
    pub(super) order: usize,
    #[serde(default)]
    pub(super) description: String,
    pub(super) effect: Effect,
    pub(super) identities: Vec<String>,
    pub(super) operations: Vec<String>,
    #[serde(default)]
    pub(super) resources: Vec<String>,
}

impl Statement {
    pub(crate) fn order(&self) -> usize {
        self.order
    }

    pub fn description(&self) -> &str {
        &self.description
    }

    pub fn effect(&self) -> Effect {
        self.effect
    }

    pub fn identities(&self) -> &Vec<String> {
        &self.identities
    }

    pub fn operations(&self) -> &Vec<String> {
        &self.operations
    }

    pub fn resources(&self) -> &Vec<String> {
        &self.resources
    }
}

/// Represents an effect on a statement.
#[derive(Debug, Deserialize, Copy, Clone, PartialOrd, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum Effect {
    Allow,
    Deny,
}

#[cfg(test)]
mod tests {
    use std::result::Result as StdResult;

    use assert_matches::assert_matches;

    use crate::{
        core::{tests::build_policy, Effect, EffectOrd},
        validator::ValidatorError,
    };

    use super::*;

    #[test]
    fn test_basic_definition() {
        let json = r#"{
            "statements": [
                {
                    "effect": "allow",
                    "identities": [
                        "actor_a"
                    ],
                    "operations": [
                        "read"
                    ],
                    "resources": [
                        "resource_group"
                    ]
                },
                {
                    "effect": "allow",
                    "identities": [
                        "actor_b"
                    ],
                    "operations": [
                        "write"
                    ],
                    "resources": [
                        "resource_1"
                    ]
                },
                {
                    "description": "Deny all other identities to read",
                    "effect": "deny",
                    "identities": [
                        "{{var_actor}}"
                    ],
                    "operations": [
                        "read"
                    ],
                    "resources": [
                        "resource_group"
                    ]
                }
            ]
        }"#;

        let policy = build_policy(json);

        assert_eq!(1, policy.variable_rules.len());
        assert_eq!(2, policy.static_rules.len());
    }

    #[test]
    fn identity_merge_rules() {
        let json = r#"{
            "statements": [
                {
                    "effect": "allow",
                    "identities": [
                        "actor_a"
                    ],
                    "operations": [
                        "write"
                    ],
                    "resources": [
                        "events/telemetry"
                    ]
                },
                {
                    "effect": "allow",
                    "identities": [
                        "actor_a"
                    ],
                    "operations": [
                        "read"
                    ],
                    "resources": [
                        "resource_1"
                    ]
                },
                {
                    "effect": "allow",
                    "identities": [
                        "actor_a"
                    ],
                    "operations": [
                        "read"
                    ],
                    "resources": [
                        "{{variable}}/#"
                    ]
                },
                {
                    "effect": "allow",
                    "identities": [
                        "actor_a"
                    ],
                    "operations": [
                        "write"
                    ],
                    "resources": [
                        "{{variable}}/#"
                    ]
                }
            ]
        }"#;

        let policy = build_policy(json);

        // assert static rules have 1 identity and 2 operations
        assert_eq!(1, policy.static_rules.len());
        assert_eq!(2, policy.static_rules["actor_a"].0.len());

        // assert variable rules have 1 identity and 2 operations
        assert_eq!(1, policy.variable_rules.len());
        assert_eq!(2, policy.variable_rules["actor_a"].0.len());
    }

    #[test]
    fn operation_merge_rules() {
        let json = r#"{
            "statements": [
                {
                    "effect": "allow",
                    "identities": [
                        "actor_a"
                    ],
                    "operations": [
                        "write"
                    ],
                    "resources": [
                        "events/telemetry"
                    ]
                },
                {
                    "effect": "allow",
                    "identities": [
                        "actor_a"
                    ],
                    "operations": [
                        "write"
                    ],
                    "resources": [
                        "resource_1"
                    ]
                },
                {
                    "effect": "allow",
                    "identities": [
                        "actor_a"
                    ],
                    "operations": [
                        "read"
                    ],
                    "resources": [
                        "{{variable}}/#"
                    ]
                },
                {
                    "effect": "allow",
                    "identities": [
                        "actor_a"
                    ],
                    "operations": [
                        "read"
                    ],
                    "resources": [
                        "devices/{{variable}}/#"
                    ]
                }
            ]
        }"#;

        let policy = build_policy(json);

        // assert static rules have 1 identity, 1 operations and 2 resources
        assert_eq!(1, policy.static_rules["actor_a"].0.len());
        assert_eq!(2, policy.static_rules["actor_a"].0["write"].0.len());

        // assert variable rules have 1 identity, 1 operations and 2 resources
        assert_eq!(1, policy.variable_rules["actor_a"].0.len());
        assert_eq!(2, policy.variable_rules["actor_a"].0["read"].0.len());
    }

    #[test]
    fn resource_merge_rules_higher_priority_statement_wins() {
        let json = r#"{
            "statements": [
                {
                    "effect": "allow",
                    "identities": [
                        "actor_a"
                    ],
                    "operations": [
                        "write"
                    ],
                    "resources": [
                        "events/telemetry"
                    ]
                },
                {
                    "effect": "deny",
                    "identities": [
                        "actor_a"
                    ],
                    "operations": [
                        "write"
                    ],
                    "resources": [
                        "events/telemetry"
                    ]
                },
                {
                    "effect": "allow",
                    "identities": [
                        "actor_a"
                    ],
                    "operations": [
                        "read"
                    ],
                    "resources": [
                        "{{variable}}/#"
                    ]
                },
                {
                    "effect": "deny",
                    "identities": [
                        "actor_a"
                    ],
                    "operations": [
                        "read"
                    ],
                    "resources": [
                        "{{variable}}/#"
                    ]
                }
            ]
        }"#;

        let policy = build_policy(json);

        // assert higher priority rule wins.
        assert_eq!(
            EffectOrd {
                order: 0,
                effect: Effect::Allow
            },
            policy.static_rules["actor_a"].0["write"].0["events/telemetry"]
        );

        // assert higher priority rule wins for variable rules.
        assert_eq!(
            EffectOrd {
                order: 2,
                effect: Effect::Allow
            },
            policy.variable_rules["actor_a"].0["read"].0["{{variable}}/#"]
        );
    }

    #[test]
    #[allow(clippy::too_many_lines)]
    fn grouping_rules_with_variables_test() {
        let json = r#"{
            "statements": [
                {
                    "effect": "allow",
                    "identities": [
                        "actor_a",
                        "actor_b",
                        "{{var_actor}}"
                    ],
                    "operations": [
                        "write",
                        "read"
                    ],
                    "resources": [
                        "events/telemetry",
                        "devices/{{variable}}/#"
                    ]
                }
            ]
        }"#;

        let policy = build_policy(json);

        // assert static rules.
        assert_eq!(2, policy.static_rules.len());
        assert_eq!(
            policy.static_rules["actor_a"].0["write"].0["events/telemetry"],
            EffectOrd {
                effect: Effect::Allow,
                order: 0
            }
        );
        assert_eq!(
            policy.static_rules["actor_a"].0["read"].0["events/telemetry"],
            EffectOrd {
                effect: Effect::Allow,
                order: 0
            }
        );
        assert_eq!(
            policy.static_rules["actor_b"].0["write"].0["events/telemetry"],
            EffectOrd {
                effect: Effect::Allow,
                order: 0
            }
        );
        assert_eq!(
            policy.static_rules["actor_b"].0["read"].0["events/telemetry"],
            EffectOrd {
                effect: Effect::Allow,
                order: 0
            }
        );

        // assert variable rules.
        assert_eq!(3, policy.variable_rules.len());
        assert_eq!(
            policy.variable_rules["actor_a"].0["write"].0["devices/{{variable}}/#"],
            EffectOrd {
                effect: Effect::Allow,
                order: 0
            }
        );
        assert_eq!(
            policy.variable_rules["actor_a"].0["read"].0["devices/{{variable}}/#"],
            EffectOrd {
                effect: Effect::Allow,
                order: 0
            }
        );
        assert_eq!(
            policy.variable_rules["actor_b"].0["write"].0["devices/{{variable}}/#"],
            EffectOrd {
                effect: Effect::Allow,
                order: 0
            }
        );
        assert_eq!(
            policy.variable_rules["actor_b"].0["read"].0["devices/{{variable}}/#"],
            EffectOrd {
                effect: Effect::Allow,
                order: 0
            }
        );
        assert_eq!(
            policy.variable_rules["{{var_actor}}"].0["write"].0["devices/{{variable}}/#"],
            EffectOrd {
                effect: Effect::Allow,
                order: 0
            }
        );
        assert_eq!(
            policy.variable_rules["{{var_actor}}"].0["read"].0["devices/{{variable}}/#"],
            EffectOrd {
                effect: Effect::Allow,
                order: 0
            }
        );
    }

    #[test]
    fn policy_validation_test() {
        let json = r#"{
            "statements": [
                {
                    "effect": "allow",
                    "identities": [
                        "actor_a"
                    ],
                    "operations": [
                        "write"
                    ],
                    "resources": [
                        "events/telemetry"
                    ]
                },
                {
                    "effect": "allow",
                    "identities": [
                        "monitor"
                    ],
                    "operations": [
                        "read"
                    ],
                    "resources": [
                        "events/telemetry"
                    ]
                }
            ]
        }"#;

        let result = PolicyBuilder::from_json(json)
            .with_validator(FailAllValidator)
            .with_default_decision(Decision::Denied)
            .build();

        assert_matches!(result, Err(Error::Validation(_)));
    }

    #[derive(Debug)]
    struct FailAllValidator;

    impl PolicyValidator for FailAllValidator {
        type Error = ValidatorError;

        fn validate(&self, _definition: &PolicyDefinition) -> StdResult<(), Self::Error> {
            Err(ValidatorError::ValidationSummary(vec!["error".to_string()]))
        }
    }
}