Skip to content

Commit

Permalink
simple abac implementation parse a json string into object
Browse files Browse the repository at this point in the history
in abac r_sub, r_obj, r_act can be object
use push_constant to avoid security problem if input is not properly sanitized
  • Loading branch information
xcaptain committed Apr 11, 2020
1 parent 6087cc9 commit 40b5c0f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 6 deletions.
16 changes: 10 additions & 6 deletions src/enforcer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -196,8 +196,14 @@ impl CoreApi for Enforcer {
let e_ast = get_or_err!(self, "e", ModelError::E, "effector");

for (i, token) in r_ast.tokens.iter().enumerate() {
let scope_exp = format!("let {} = \"{}\";", token, rvals[i].as_ref());
engine.eval_with_scope::<()>(&mut scope, &scope_exp)?;
if &rvals[i].as_ref()[0..=0] == "{" {
// if r_sub, r_obj or r_act is a json string, then we need to parse it into an object
// https://casbin.org/docs/en/abac#how-to-use-abac
let scope_exp = format!("const {} = #{};", token, rvals[i].as_ref());
engine.eval_with_scope::<()>(&mut scope, &scope_exp)?;
} else {
scope.push_constant(token, rvals[i].as_ref().to_owned());
}
}

for (key, func) in self.fm.fm.iter() {
Expand Down Expand Up @@ -233,8 +239,7 @@ impl CoreApi for Enforcer {
.into());
}
for (pi, ptoken) in p_ast.tokens.iter().enumerate() {
let scope_exp = format!("let {} = \"{}\";", ptoken, pvals[pi]);
engine.eval_with_scope::<()>(&mut scope, &scope_exp)?;
scope.push_constant(ptoken, pvals[pi].to_owned());
}

let eval_result = engine.eval_with_scope::<bool>(&mut scope, expstring)?;
Expand All @@ -260,8 +265,7 @@ impl CoreApi for Enforcer {
}
} else {
for token in p_ast.tokens.iter() {
let scope_exp = format!("let {} = \"{}\";", token, "");
engine.eval_with_scope::<()>(&mut scope, &scope_exp)?;
scope.push_constant(token, String::new());
}
let eval_result = engine.eval_with_scope::<bool>(&mut scope, expstring)?;
if eval_result {
Expand Down
24 changes: 24 additions & 0 deletions src/model/default_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1094,4 +1094,28 @@ mod tests {
e.enforce(&vec!["bob", "data3", "read"]).await.unwrap()
);
}

#[cfg_attr(feature = "runtime-async-std", async_std::test)]
#[cfg_attr(feature = "runtime-tokio", tokio::test)]
async fn test_abac() {
let m = DefaultModel::from_file("examples/abac_model.conf")
.await
.unwrap();

let adapter = MemoryAdapter::default();
let mut e = Enforcer::new(m, adapter).await.unwrap();

assert_eq!(
false,
e.enforce(&vec!["alice", r#"{"Owner":"bob"}"#, "read"])
.await
.unwrap()
);
assert_eq!(
true,
e.enforce(&vec!["alice", r#"{"Owner":"alice"}"#, "read"])
.await
.unwrap()
);
}
}

0 comments on commit 40b5c0f

Please sign in to comment.