Skip to content

Commit 681ef2c

Browse files
authored
Cleanup (#173)
* add register_g_function macro * improve loggter by adding log category * format code * fix cached benchmark * add circular link Todo comment * don't acquire lock more than once * fix lock name * upgrade rhai * fix tests * add domain_matching_fn * stop using :: seperator in rbac_role_manager * format code format code format code * fix cached_enforcer * add push_index macro & rename expl -> explain * remove matching fn entry * bump version * upgrade rhai * Fix: CI * FIX: clippy::redundant-closure
1 parent b3bd688 commit 681ef2c

18 files changed

+431
-552
lines changed

.gitignore

+3
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,6 @@ Cargo.lock
1818
output.txt
1919
before
2020
after
21+
22+
# design
23+
design.txt

Cargo.toml

+9-9
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "casbin"
3-
version = "0.9.2"
3+
version = "1.0.0"
44
authors = ["Joey <[email protected]>", "Cheng JIANG <[email protected]>"]
55
edition = "2018"
66
license = "Apache-2.0"
@@ -13,18 +13,18 @@ keywords = ["auth", "authorization", "rbac", "acl", "abac"]
1313
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
1414

1515
[dependencies]
16-
regex = "1.3.7"
17-
rhai = { version = "0.14.1", features = ["sync", "only_i32", "no_function", "no_float", "no_optimize"] }
16+
regex = "1.3.9"
17+
rhai = { version = "0.15.1", features = ["sync", "only_i32", "no_function", "no_float", "no_optimize", "no_module"] }
1818
ip_network = { version = "0.3.4", optional = true }
1919
ttl_cache = { version = "0.5.1", optional = true }
2020
lazy_static = "1.4.0"
21-
indexmap = "1.3.2"
22-
async-std = { version = "1.6.0", optional = true }
23-
async-trait = "0.1.31"
21+
indexmap = "1.4.0"
22+
async-std = { version = "1.6.1", optional = true }
23+
async-trait = "0.1.35"
2424
log = { version = "0.4.8", optional = true }
2525
tokio = { version = "0.2.21", optional = true, default-features = false }
2626
globset = { version = "0.4.5", optional = true }
27-
thiserror = "1.0.19"
27+
thiserror = "1.0.20"
2828

2929
[features]
3030
default = ["runtime-async-std", "incremental"]
@@ -43,8 +43,8 @@ explain = []
4343
opt-level = 0
4444

4545
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
46-
async-std = { version = "1.6.0", features = [ "attributes" ] }
46+
async-std = { version = "1.6.1", features = [ "attributes" ] }
4747

4848
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
4949
tokio = { version = "0.2.21", features = [ "full" ] }
50-
async-std = { version = "1.6.0", features = [ "attributes" ] }
50+
async-std = { version = "1.6.1", features = [ "attributes" ] }

README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ Add this package to `Cargo.toml` of your project. (Check https://crates.io/crate
2828

2929
```toml
3030
[dependencies]
31-
casbin = { version = "0.9.3", default-features = false, features = ["runtime-async-std", "logging"] }
31+
casbin = { version = "1.0.0", default-features = false, features = ["runtime-async-std", "logging"] }
3232
async-std = { version = "1.5.0", features = ["attributes"] }
3333
env_logger = "0.7.1"
3434
```

benches/benchmark.rs

+11-11
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ fn b_benmark_cached_basic_model(b: &mut Bencher) {
7373
.unwrap();
7474

7575
b.iter(|| {
76-
e.enforce(_mut(&["alice", "data1", "read"])).unwrap();
76+
e.enforce_mut(&["alice", "data1", "read"]).unwrap();
7777
});
7878
}
7979

@@ -100,7 +100,7 @@ fn b_benchmark_cached_rbac_model(b: &mut Bencher) {
100100
.unwrap();
101101

102102
b.iter(|| {
103-
e.enforce(_mut(&["alice", "data2", "read"])).unwrap();
103+
e.enforce_mut(&["alice", "data2", "read"]).unwrap();
104104
});
105105
}
106106

@@ -221,7 +221,7 @@ fn b_benchmark_cached_rbac_model_small(b: &mut Bencher) {
221221

222222
e.build_role_links().unwrap();
223223

224-
b.iter(|| e.enforce(_mut(&["user501", "data9", "read"])).unwrap());
224+
b.iter(|| e.enforce_mut(&["user501", "data9", "read"]).unwrap());
225225
}
226226

227227
#[bench]
@@ -341,7 +341,7 @@ fn b_benchmark_cached_rbac_model_medium(b: &mut Bencher) {
341341

342342
e.build_role_links().unwrap();
343343

344-
b.iter(|| e.enforce(_mut(&["user5001", "data15", "read"])).unwrap());
344+
b.iter(|| e.enforce_mut(&["user5001", "data15", "read"]).unwrap());
345345
}
346346

347347
#[bench]
@@ -461,7 +461,7 @@ fn b_benchmark_cached_rbac_model_large(b: &mut Bencher) {
461461

462462
e.build_role_links().unwrap();
463463

464-
b.iter(|| e.enforce(_mut(&["user50001", "data1500", "read"])).unwrap());
464+
b.iter(|| e.enforce_mut(&["user50001", "data1500", "read"]).unwrap());
465465
}
466466

467467
#[bench]
@@ -484,7 +484,7 @@ fn b_benchmark_cached_rbac_with_resource_roles(b: &mut Bencher) {
484484
))
485485
.unwrap();
486486

487-
b.iter(|| e.enforce(_mut(&["alice", "data1", "read"])).unwrap());
487+
b.iter(|| e.enforce_mut(&["alice", "data1", "read"]).unwrap());
488488
}
489489

490490
#[bench]
@@ -508,7 +508,7 @@ fn b_benchmark_cached_rbac_model_with_domains(b: &mut Bencher) {
508508
.unwrap();
509509

510510
b.iter(|| {
511-
e.enforce(_mut(&["alice", "domain1", "data1", "read"]))
511+
e.enforce_mut(&["alice", "domain1", "data1", "read"])
512512
.unwrap()
513513
});
514514
}
@@ -529,7 +529,7 @@ fn b_benchmark_cached_abac_model(b: &mut Bencher) {
529529
let mut e = await_future(CachedEnforcer::new("examples/abac_model.conf", ())).unwrap();
530530

531531
b.iter(|| {
532-
e.enforce(_mut(&["alice", r#"{"Owner": "alice"}"#, "read"]))
532+
e.enforce_mut(&["alice", r#"{"Owner": "alice"}"#, "read"])
533533
.unwrap()
534534
});
535535
}
@@ -558,7 +558,7 @@ fn b_benchmark_cached_key_match(b: &mut Bencher) {
558558
.unwrap();
559559

560560
b.iter(|| {
561-
e.enforce(_mut(&["alice", "/alice_data/resource1", "GET"]))
561+
e.enforce_mut(&["alice", "/alice_data/resource1", "GET"])
562562
.unwrap()
563563
});
564564
}
@@ -583,7 +583,7 @@ fn b_benchmark_cached_rbac_with_deny(b: &mut Bencher) {
583583
))
584584
.unwrap();
585585

586-
b.iter(|| e.enforce(_mut(&["alice", "data1", "read"])).unwrap());
586+
b.iter(|| e.enforce_mut(&["alice", "data1", "read"]).unwrap());
587587
}
588588

589589
#[bench]
@@ -606,5 +606,5 @@ fn b_benchmark_cached_priority_model(b: &mut Bencher) {
606606
))
607607
.unwrap();
608608

609-
b.iter(|| e.enforce(_mut(&["alice", "data1", "read"])).unwrap());
609+
b.iter(|| e.enforce_mut(&["alice", "data1", "read"]).unwrap());
610610
}

examples/rbac_with_pattern_domain_model.conf

+1-2
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,9 @@ p = sub, dom, obj, act
66

77
[role_definition]
88
g = _, _, _
9-
g2 = _, _, _
109

1110
[policy_effect]
1211
e = some(where (p.eft == allow))
1312

1413
[matchers]
15-
m = g(r.sub, p.sub, r.dom) && r.dom == p.dom && g2(r.obj, p.obj, r.dom) && regexMatch(r.act, p.act)
14+
m = g(r.sub, p.sub, r.dom) && r.dom == p.dom && regexMatch(r.act, p.act)
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
1-
p, alice, domain2, /pen/1, GET
2-
p, alice, domain1, /book/1, GET
3-
4-
p, book_admin, domain1, book_group, GET
5-
p, pen_admin, domain2, pen_group, GET
1+
p, book_admin, domain1, /pen/1 , GET
2+
p, pen_admin, domain2, /book/1 , GET
63

4+
g, eve, book_admin, *
5+
g, eve, pen_admin, *
76
g, alice, book_admin, domain1
87
g, bob, pen_admin, domain2
9-
g2, /book/:id, book_group, domain1
10-
g2, /pen/:id, pen_group, domain2

src/cached_enforcer.rs

+18-24
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ use crate::logger::Logger;
2525
use crate::{error::ModelError, get_or_err};
2626

2727
use async_trait::async_trait;
28+
use rhai::ImmutableString;
2829

2930
use std::{
3031
collections::HashMap,
@@ -64,12 +65,12 @@ impl CachedEnforcer {
6465
rvals: &[S],
6566
) -> Result<(bool, bool, Option<Vec<usize>>)> {
6667
let cache_key: Vec<String> = rvals.iter().map(|x| String::from(x.as_ref())).collect();
67-
Ok(if let Some(result) = self.cache.get(&cache_key) {
68-
(*result, true, None)
68+
Ok(if let Some(authorized) = self.cache.get(&cache_key) {
69+
(*authorized, true, None)
6970
} else {
70-
let (result, idxs) = self.enforcer.private_enforce(rvals)?;
71-
self.cache.set(cache_key.clone(), result);
72-
(result, false, idxs)
71+
let (authorized, indexes) = self.enforcer.private_enforce(rvals)?;
72+
self.cache.set(cache_key.clone(), authorized);
73+
(authorized, false, indexes)
7374
})
7475
}
7576
}
@@ -87,16 +88,15 @@ impl CoreApi for CachedEnforcer {
8788
};
8889

8990
cached_enforcer.on(Event::ClearCache, clear_cache);
91+
9092
#[cfg(any(feature = "logging", feature = "watcher"))]
91-
{
92-
cached_enforcer.on(Event::PolicyChange, notify_logger_and_watcher);
93-
}
93+
cached_enforcer.on(Event::PolicyChange, notify_logger_and_watcher);
9494

9595
Ok(cached_enforcer)
9696
}
9797

9898
#[inline]
99-
fn add_function(&mut self, fname: &str, f: fn(String, String) -> bool) {
99+
fn add_function(&mut self, fname: &str, f: fn(ImmutableString, ImmutableString) -> bool) {
100100
self.enforcer.fm.add_function(fname, f);
101101
}
102102

@@ -147,11 +147,6 @@ impl CoreApi for CachedEnforcer {
147147
self.enforcer.set_role_manager(rm)
148148
}
149149

150-
#[inline]
151-
fn add_matching_fn(&mut self, f: fn(&str, &str) -> bool) -> Result<()> {
152-
self.enforcer.add_matching_fn(f)
153-
}
154-
155150
#[inline]
156151
async fn set_model<M: TryIntoModel>(&mut self, m: M) -> Result<()> {
157152
self.enforcer.set_model(m).await
@@ -181,7 +176,8 @@ impl CoreApi for CachedEnforcer {
181176

182177
fn enforce_mut<S: AsRef<str> + Send + Sync>(&mut self, rvals: &[S]) -> Result<bool> {
183178
#[allow(unused_variables)]
184-
let (authorized, cached, idxs) = self.private_enforce(rvals)?;
179+
let (authorized, cached, indexs) = self.private_enforce(rvals)?;
180+
185181
#[cfg(feature = "logging")]
186182
{
187183
self.enforcer.get_logger().print_enforce_log(
@@ -191,15 +187,13 @@ impl CoreApi for CachedEnforcer {
191187
);
192188

193189
#[cfg(feature = "explain")]
194-
{
195-
if let Some(idxs) = idxs {
196-
let all_rules = get_or_err!(self, "p", ModelError::P, "policy").get_policy();
197-
let rules: Vec<&Vec<String>> = idxs
198-
.into_iter()
199-
.filter_map(|y| all_rules.get_index(y))
200-
.collect();
201-
self.enforcer.get_logger().print_expl_log(rules);
202-
}
190+
if let Some(indexs) = indexs {
191+
let all_rules = get_or_err!(self, "p", ModelError::P, "policy").get_policy();
192+
let rules: Vec<String> = indexs
193+
.into_iter()
194+
.filter_map(|y| all_rules.get_index(y).map(|x| x.join(", ")))
195+
.collect();
196+
self.enforcer.get_logger().print_explain_log(rules);
203197
}
204198
}
205199

src/core_api.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ use crate::Logger;
1010
use crate::emitter::EventData;
1111

1212
use async_trait::async_trait;
13+
use rhai::ImmutableString;
1314

1415
use std::sync::{Arc, RwLock};
1516

@@ -18,7 +19,7 @@ pub trait CoreApi: Send + Sync {
1819
async fn new<M: TryIntoModel, A: TryIntoAdapter>(m: M, a: A) -> Result<Self>
1920
where
2021
Self: Sized;
21-
fn add_function(&mut self, fname: &str, f: fn(String, String) -> bool);
22+
fn add_function(&mut self, fname: &str, f: fn(ImmutableString, ImmutableString) -> bool);
2223
fn get_model(&self) -> &dyn Model;
2324
fn get_mut_model(&mut self) -> &mut dyn Model;
2425
fn get_adapter(&self) -> &dyn Adapter;
@@ -35,7 +36,6 @@ pub trait CoreApi: Send + Sync {
3536
fn get_logger(&self) -> &dyn Logger;
3637
#[cfg(feature = "logging")]
3738
fn set_logger(&mut self, logger: Box<dyn Logger>);
38-
fn add_matching_fn(&mut self, f: fn(&str, &str) -> bool) -> Result<()>;
3939
async fn set_model<M: TryIntoModel>(&mut self, m: M) -> Result<()>;
4040
async fn set_adapter<A: TryIntoAdapter>(&mut self, a: A) -> Result<()>;
4141
fn set_effector(&mut self, e: Box<dyn Effector>);

0 commit comments

Comments
 (0)