Skip to content

Commit

Permalink
Implement glob builtins
Browse files Browse the repository at this point in the history
  • Loading branch information
ereslibre committed Sep 10, 2021
1 parent dbdcb52 commit f7c9a1a
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 2 deletions.
46 changes: 46 additions & 0 deletions crates/burrego/src/opa/builtins/glob.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
use anyhow::{anyhow, Result};

pub fn quote_meta(args: &[serde_json::Value]) -> Result<serde_json::Value> {
if args.len() != 1 {
return Err(anyhow!("glob.quote_meta: wrong number of arguments"));
}

let input = args[0]
.as_str()
.ok_or_else(|| anyhow!("glob.quote_meta: 1st parameter is not a string"))?;

serde_json::to_value(escape(input))
.map_err(|e| anyhow!("glob.quote_meta: cannot convert value into JSON: {:?}", e))
}

fn escape(s: &str) -> String {
let mut escaped = String::new();
for c in s.chars() {
match c {
'*' | '?' | '\\' | '[' | ']' | '{' | '}' => {
escaped.push('\\');
escaped.push(c);
}
c => {
escaped.push(c);
}
}
}
escaped
}

#[cfg(test)]
mod test {
#[test]
fn escape() {
assert_eq!(super::escape("*.domain.com"), r"\*.domain.com",);

assert_eq!(super::escape("*.domain-*.com"), r"\*.domain-\*.com",);

assert_eq!(super::escape("domain.com"), r"domain.com",);

assert_eq!(super::escape("domain-[ab].com"), r"domain-\[ab\].com",);

assert_eq!(super::escape("nie?ce"), r"nie\?ce",);
}
}
8 changes: 7 additions & 1 deletion crates/burrego/src/opa/builtins/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ use anyhow::Result;
use std::collections::HashMap;

pub mod encoding;
pub mod glob;
pub mod strings;

pub type BuiltinFunctionsMap =
HashMap<&'static str, fn(&[serde_json::Value]) -> Result<serde_json::Value>>;

pub fn get_builtins() -> BuiltinFunctionsMap {
let mut functions: BuiltinFunctionsMap = HashMap::new();
functions.insert("sprintf", strings::sprintf);

// encoding
functions.insert(
Expand All @@ -26,5 +26,11 @@ pub fn get_builtins() -> BuiltinFunctionsMap {
functions.insert("hex.encode", encoding::hex::encode);
functions.insert("hex.decode", encoding::hex::decode);

// glob
functions.insert("glob.quote_meta", glob::quote_meta);

// strings
functions.insert("sprintf", strings::sprintf);

functions
}
3 changes: 2 additions & 1 deletion src/policy_evaluator.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use anyhow::{anyhow, Result};
use serde::Serialize;
use serde_json::{json, value};
use serde_json::value;
use std::{
convert::{TryFrom, TryInto},
fmt, fs,
Expand Down Expand Up @@ -235,6 +235,7 @@ impl PolicyEvaluator {
mod tests {
use super::*;

use serde_json::json;
use std::collections::HashMap;

#[test]
Expand Down

0 comments on commit f7c9a1a

Please sign in to comment.