coqui_access_acl/
authorizer.rs1use alloc::boxed::Box;
4use alloc::collections::BTreeMap;
5use alloc::string::ToString;
6use core::fmt;
7
8use coqui_access::guatiao::library::ProviderError;
9use coqui_access::{AuthorizationDecision, AuthorizationRequest, Authorizer, Person, error};
10
11use crate::check::{Context, Decision};
12use crate::condition::Conditions;
13use crate::error::AclError;
14use crate::options::Options;
15use crate::path::AclStore;
16use crate::rights::{Rights, RightsSchema};
17
18pub struct AclAuthorizer<S> {
26 store: S,
27 schema: RightsSchema,
28 options: Options,
29 owner_rights: Rights,
30 conditions: Option<Box<dyn Conditions>>,
31}
32
33impl<S> fmt::Debug for AclAuthorizer<S> {
34 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
35 formatter
36 .debug_struct("AclAuthorizer")
37 .field("rights", &self.schema.len())
38 .field("options", &self.options)
39 .field("owner_rights", &self.owner_rights)
40 .field("conditions", &self.conditions.is_some())
41 .finish_non_exhaustive()
42 }
43}
44
45impl<S: AclStore> AclAuthorizer<S> {
46 pub fn new(store: S, schema: RightsSchema) -> Self {
49 Self {
50 store,
51 schema,
52 options: Options::default(),
53 owner_rights: Rights::new(),
54 conditions: None,
55 }
56 }
57
58 #[must_use]
60 pub fn options(mut self, options: Options) -> Self {
61 self.options = options;
62 self
63 }
64
65 #[must_use]
68 pub fn owner_rights(mut self, rights: Rights) -> Self {
69 self.owner_rights = rights;
70 self
71 }
72
73 #[must_use]
75 pub fn conditions(mut self, conditions: impl Conditions + 'static) -> Self {
76 self.conditions = Some(Box::new(conditions));
77 self
78 }
79
80 pub fn store(&self) -> &S {
82 &self.store
83 }
84
85 pub fn schema(&self) -> &RightsSchema {
87 &self.schema
88 }
89
90 pub fn decide(&self, person: &Person, action: &str, item: &str) -> Result<Decision, AclError> {
98 let wanted = self.schema.rights([action])?;
99 let mut context = Context::new(&self.schema)
100 .person(person)
101 .owner_rights(self.owner_rights.clone())
102 .options(self.options);
103 if let Some(conditions) = &self.conditions {
104 context = context.conditions(conditions.as_ref());
105 }
106 self.store.check(item, &context, &wanted)
107 }
108}
109
110impl<S: AclStore + Send + Sync> Authorizer for AclAuthorizer<S> {
111 fn authorize(
112 &self,
113 request: AuthorizationRequest,
114 ) -> Result<AuthorizationDecision, ProviderError> {
115 let refused = || AuthorizationDecision {
116 allowed: false,
117 limits: BTreeMap::new(),
118 };
119 match self.schema.rights([&request.action]) {
120 Ok(wanted) if !wanted.is_empty() => {}
121 _ => return Ok(refused()),
122 }
123 match self.decide(&request.person, &request.action, &request.resource) {
124 Ok(decision) => Ok(AuthorizationDecision {
125 allowed: decision.allowed,
126 limits: BTreeMap::new(),
127 }),
128 Err(AclError::Store(error)) => Err(error),
129 Err(other) => Err(error::internal(&other.to_string())),
130 }
131 }
132}