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
use serde::{Deserialize, Serialize};
use std::collections::{HashMap, HashSet};
use std::fmt;

use itertools::Itertools;
use std::fs::File;

mod lookups;

use crate::commands::execution::ActionExecution;
use crate::commands::{Command, FiniCommand};
use crate::context::PicoContext;
use crate::runtime::PicoRuntime;
use crate::values::PicoValue;
use lookups::Lookups;

#[derive(Serialize, Deserialize, Debug)]
pub struct IncludeFile {
    pub include: String,
    pub namespaces: Option<Vec<String>>,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum RuleFileRoot {
    Command(Command),
    IncludeFile(IncludeFile),
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(untagged)]
pub enum RuleFileFini {
    FiniCommand(FiniCommand),
}

///
/// The internal reprsentation of a Pico rule file
#[derive(Serialize, Deserialize, Debug)]
pub struct RuleFile {
    #[serde(default = "RuleFile::default_version")]
    version: String,

    #[serde(default)]
    pub lookups: Lookups,

    // optional namespaces this file creates
    pub namespaces: Option<Vec<String>>,

    pub root: Vec<RuleFileRoot>,

    pub fini: Vec<RuleFileFini>,
}

impl RuleFile {
    pub fn default_version() -> String {
        String::from("1.1")
    }
}
impl fmt::Display for RuleFile {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.namespaces {
            Some(ns) => write!(
                f,
                "version={}, rule count={} namespaces={}",
                self.version,
                self.root.len(),
                ns.join(",")
            ),
            None => write!(
                f,
                "version={}, rule count={}",
                self.version,
                self.root.len()
            ),
        }
    }
}

#[derive(Debug)]
enum FileStatus {
    Unchecked,
    Loaded,
    Missing,
}

#[derive(Debug)]
pub struct PicoRules {
    rulefile_cache: HashMap<String, PicoRules>,
    entrypoint: String,
    rulefile: Option<RuleFile>,
    status: FileStatus,

    allowed_namespaces: HashSet<String>,
}

impl fmt::Display for PicoRules {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.rulefile {
            Some(rf) => write!(
                f,
                "PicoRule: {}, includes: [{}], namespaces: [{}], rule summary: [{}]",
                self.entrypoint,
                self.rulefile_cache.keys().join(", "),
                self.allowed_namespaces.iter().join(", "),
                rf
            ),
            None => write!(
                f,
                "PicoRule: {}, includes: [{}], namespaces: [{}], rule summary: [NOT LOADED]",
                self.entrypoint,
                self.rulefile_cache.keys().join(", "),
                self.allowed_namespaces.iter().join(", "),
            ),
        }
    }
}

impl Default for PicoRules {
    fn default() -> Self {
        Self {
            rulefile_cache: HashMap::new(),
            entrypoint: String::new(),
            rulefile: None,
            status: FileStatus::Missing,
            allowed_namespaces: HashSet::new(),
        }
    }
}

impl PicoRules {
    pub fn new() -> Self {
        Default::default()
    }

    pub fn all_namespace(&self, collected: &mut Vec<String>) {
        //let collected_namespace: Vec<String> = Vec::new();

        if let Some(rf) = &self.rulefile {
            if let Some(ns_v) = &rf.namespaces {
                for ns in ns_v {
                    collected.push(ns.to_string());
                }
            }
        }
        for (_key, pico_rule) in &self.rulefile_cache {
            PicoRules::all_namespace(pico_rule, collected);
        }
    }

    pub fn set_entry(mut self, entrypoint: &str) -> Self {
        self.entrypoint = entrypoint.to_string();
        self
    }

    pub fn load_rulefile(mut self, rulefile_name: &str) -> Self {
        info!("Loading... {}", rulefile_name);
        match File::open(&rulefile_name) {
            Ok(opened_file) => {
                let rule_file: RuleFile = serde_json::from_reader(opened_file).unwrap();
                if let Some(namespaces) = &rule_file.namespaces {
                    trace!(
                        "rule file has namespaces defined: {:?}",
                        rule_file.namespaces
                    );
                    for ns in namespaces {
                        info!("[{}] Adding namespace {}", rulefile_name, ns);
                        self.allowed_namespaces.insert(ns.to_string());
                    }
                }
                self.rulefile = Some(rule_file);
                self.status = FileStatus::Loaded;
            }
            Err(x) => {
                error!("failed to open: {:?}", x);
                self.status = FileStatus::Missing;
            }
        }
        self.set_entry(rulefile_name)
    }

    // convenience, returns vec of filenames this file also includes
    fn included_filenames(&self) -> Vec<String> {
        match &self.rulefile {
            Some(rf) => rf
                .root
                .iter()
                .filter_map(|r| match r {
                    RuleFileRoot::IncludeFile(f) => Some(f.include.clone()),
                    _ => None,
                })
                .collect(),
            None => Vec::new(),
        }
    }

    fn include_sections(&self) -> Vec<&IncludeFile> {
        let include_sections: Vec<&IncludeFile> = match &self.rulefile {
            Some(rfc) => rfc
                .root
                .iter()
                .filter_map(|r| match r {
                    RuleFileRoot::IncludeFile(f) => Some(f),
                    _ => None,
                })
                .collect(),
            None => Vec::new(),
        };

        include_sections
    }

    pub fn setup_rules(mut self) -> Self {
        if let Some(rf) = &self.rulefile {
            if let Some(namespaces) = &rf.namespaces {}
        }

        self
    }

    /*
     * load all included but unloaded files into the cache
     */
    pub fn load_includes(mut self) -> Self {
        let imported_rules: Vec<PicoRules> = self
            .include_sections()
            .iter()
            .map(|i| {
                info!("includes: [{}]", i.include);

                info!("permitted namespace [{:?}]", i.namespaces);

                let mut imported_pico_rule =
                    PicoRules::new().load_rulefile(&i.include).load_includes();

                if let Some(allowed_namespaces) = &i.namespaces {
                    for ns in allowed_namespaces {
                        imported_pico_rule.allowed_namespaces.insert(ns.to_string());
                    }
                }
                imported_pico_rule
            })
            .collect();

        for pr in imported_rules {
            info!("Importing {}", pr);
            self.rulefile_cache.insert(pr.entrypoint.to_string(), pr);
        }
        self
    }

    pub fn run_with_context(&self, runtime: &mut PicoRuntime, ctx: &mut PicoContext) {
        trace!("RUNTIME: {:?}", runtime.variables);

        runtime.add();
        runtime.set("key", "value");
        match &self.rulefile {
            Some(rule_file) => {
                for command in &rule_file.root {
                    match command {
                        RuleFileRoot::IncludeFile(i) => {
                            // ensure the local scope variables are cleared
                            ctx.local_clear();
                            trace!("command include {:?}", i);
                            let pico_rule = self.rulefile_cache.get(&i.include).unwrap();

                            pico_rule.run_with_context(runtime, ctx);
                        }
                        RuleFileRoot::Command(c) => match c.run_with_context(&self, runtime, ctx) {
                            _ => {}
                        },
                    }
                }
                for fini_command in &rule_file.fini {
                    match fini_command {
                        RuleFileFini::FiniCommand(fc) => {
                            match fc.run_with_context(&self, runtime, ctx) {
                                Ok(data) => info!("returned data {:?}", data),
                                Err(e) => {}
                            }
                        }
                    }
                }

                //rule_file.run_with_context_new(state, ctx);
            }
            None => {
                trace!("Cache-miss");
            }
        };
        runtime.remove();
    }

    pub fn is_ns_allowed(&self, requested_namespace: &str) -> bool {
        debug!("checking namespace access for [{}]", requested_namespace);
        trace!("Allowed namespaces {:?}", self.allowed_namespaces);

        self.allowed_namespaces.contains(requested_namespace)
    }

    pub fn table_lookup_value(&self, table: &str, key: &str) -> Option<&PicoValue> {
        match &self.rulefile {
            None => None,
            Some(rf) => match rf.lookups.get(table) {
                None => None,
                Some(m) => Some(m.lookup(key)),
            },
        }
    }
}