fapolicy_rules/ops.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 crate::db::{RuleEntry, DB};
10
11use crate::error::Error;
12use crate::read::deserialize_rules_db;
13
14// Mutable
15#[derive(Default, Clone, Debug)]
16pub struct Changeset {
17 db: DB,
18 src: Option<String>,
19}
20
21impl Changeset {
22 pub fn get(&self) -> &DB {
23 &self.db
24 }
25
26 pub fn src(&self) -> Option<&String> {
27 self.src.as_ref()
28 }
29
30 // todo;; how to properly convey lints and errors in the parse fail?
31 // perhaps just roll it up to a _simple_ Error/Warn/Ok result enum
32 pub fn set(&mut self, text: &str) -> Result<&DB, Error> {
33 // todo;; what to do with the source text here?
34 // writing it out verbatim to the disk at deploy would be ideal
35 // but it has to be stashed somewhere until writing at deploy time
36 // Q: use compression? stash in temp file? stash in XDG dir?
37 // there is also the question of preserving the rule editing session
38 // as was done for trust
39 match deserialize_rules_db(text) {
40 Ok(r) => {
41 self.db = r;
42 self.src = Some(text.to_string());
43 Ok(&self.db)
44 }
45 Err(e) => Err(e),
46 }
47 }
48
49 pub fn rule(&self, id: usize) -> Option<&RuleEntry> {
50 self.db.rule(id)
51 }
52
53 pub fn apply(&self) -> &DB {
54 &self.db
55 }
56}
57
58#[cfg(test)]
59mod tests {
60 use crate::ops::Changeset;
61 use std::error::Error;
62
63 #[test]
64 fn deserialize() -> Result<(), Box<dyn Error>> {
65 let mut cs = Changeset::default();
66 let txt = "[foo.rules]\ndeny_audit perm=open all : all";
67 let _x1 = cs.set(txt);
68
69 let txt = "[foo.rules]\nfffdeny_audit perm=open all : all";
70 let _x2 = cs.set(txt)?;
71
72 Ok(())
73 }
74}