fapolicy_rules/
rule.rs

1/*
2 * Copyright Concurrent Technologies Corporation 2021
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
7 */
8
9use std::fmt::{Display, Formatter};
10
11use crate::{Decision, Object, Permission, Subject};
12
13/// # Rule
14/// A Rule is used by fapolicyd to make decisions about access rights. The rules follow a simple format of:
15/// ### `decision perm subject : object`
16///
17/// They are evaluated from top to bottom with the first rule to match being used for the access control decision.
18/// The colon is mandatory to separate subject and object since they share keywords.
19///
20/// ### Currently only v2 rule format is supported.
21///
22#[derive(Clone, Debug, PartialEq)]
23pub struct Rule {
24    pub subj: Subject,
25    pub perm: Permission,
26    pub obj: Object,
27    pub dec: Decision,
28}
29
30impl Rule {
31    pub fn new(subj: Subject, perm: Permission, obj: Object, dec: Decision) -> Self {
32        Rule {
33            subj,
34            perm,
35            obj,
36            dec,
37        }
38    }
39
40    pub fn allow(subj: Subject, perm: Permission, obj: Object) -> Self {
41        Self::new(subj, perm, obj, Decision::Allow)
42    }
43
44    pub fn deny(subj: Subject, perm: Permission, obj: Object) -> Self {
45        Self::new(subj, perm, obj, Decision::DenyAudit)
46    }
47}
48
49impl Display for Rule {
50    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
51        f.write_fmt(format_args!(
52            "{} {} {} : {}",
53            self.dec, self.perm, self.subj, self.obj
54        ))
55    }
56}
57
58#[cfg(test)]
59mod tests {
60    use crate::object::Part as ObjPart;
61    use crate::subject::Part as SubjPart;
62
63    use super::*;
64
65    #[test]
66    fn display() {
67        let r = Rule::deny(
68            Subject::from(SubjPart::All),
69            Permission::Open,
70            Object::from(ObjPart::All),
71        );
72        let expected = "deny_audit perm=open all : all";
73
74        assert_eq!(expected, format!("{}", r));
75    }
76}