1use alloc::vec::Vec;
4use core::fmt;
5
6use coqui_access::{Person, Subject};
7
8use crate::condition::{Conditions, Truth};
9use crate::entry::{Acl, Effect, Entry, ItemAcl, Mode};
10use crate::error::AclError;
11use crate::options::Options;
12use crate::principal::Principal;
13use crate::rights::{Rights, RightsSchema};
14
15#[derive(Clone)]
18pub struct Context<'a> {
19 pub(crate) schema: &'a RightsSchema,
20 pub(crate) person: Option<&'a Person>,
21 pub(crate) owner: Option<&'a Subject>,
22 pub(crate) owner_group: Option<&'a Subject>,
23 pub(crate) owner_rights: Rights,
24 pub(crate) conditions: Option<&'a dyn Conditions>,
25 pub(crate) item: &'a str,
26 pub(crate) options: Options,
27}
28
29impl fmt::Debug for Context<'_> {
30 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
31 formatter
32 .debug_struct("Context")
33 .field("signed_in", &self.person.is_some())
34 .field("owner", &self.owner)
35 .field("owner_group", &self.owner_group)
36 .field("owner_rights", &self.owner_rights)
37 .field("conditions", &self.conditions.is_some())
38 .field("options", &self.options)
39 .finish_non_exhaustive()
40 }
41}
42
43impl<'a> Context<'a> {
44 pub fn new(schema: &'a RightsSchema) -> Self {
46 Self {
47 schema,
48 person: None,
49 owner: None,
50 owner_group: None,
51 owner_rights: Rights::new(),
52 conditions: None,
53 item: "",
54 options: Options::default(),
55 }
56 }
57
58 #[must_use]
60 pub fn person(mut self, person: &'a Person) -> Self {
61 self.person = Some(person);
62 self
63 }
64
65 #[must_use]
67 pub fn owner(mut self, owner: Option<&'a Subject>) -> Self {
68 self.owner = owner;
69 self
70 }
71
72 #[must_use]
74 pub fn owner_group(mut self, group: Option<&'a Subject>) -> Self {
75 self.owner_group = group;
76 self
77 }
78
79 #[must_use]
83 pub fn owner_rights(mut self, rights: Rights) -> Self {
84 self.owner_rights = rights;
85 self
86 }
87
88 #[must_use]
90 pub fn conditions(mut self, conditions: &'a dyn Conditions) -> Self {
91 self.conditions = Some(conditions);
92 self
93 }
94
95 #[must_use]
97 pub fn item(mut self, item: &'a str) -> Self {
98 self.item = item;
99 self
100 }
101
102 #[must_use]
104 pub fn options(mut self, options: Options) -> Self {
105 self.options = options;
106 self
107 }
108
109 fn truth(&self, condition: &str) -> Truth {
110 match (self.conditions, self.person) {
111 (Some(conditions), Some(person)) => conditions.holds(condition, self.item, person),
112 _ => Truth::Unknown,
113 }
114 }
115
116 fn is(&self, principal: &Principal) -> bool {
117 principal.matches(self.person, self.owner, self.owner_group)
118 }
119
120 pub(crate) fn applies(&self, entry: &Entry) -> bool {
123 self.is(&entry.principal)
124 && entry.condition.as_deref().is_none_or(|condition| {
125 match (entry.effect, self.truth(condition)) {
126 (_, Truth::True) => true,
127 (_, Truth::False) => false,
128 (Effect::Allow, Truth::Unknown) => false,
129 (Effect::Deny, Truth::Unknown) => true,
130 }
131 })
132 }
133
134 pub(crate) fn owner_grant(&self, acl: &Acl) -> Rights {
136 let named = acl
137 .entries
138 .iter()
139 .any(|entry| entry.principal == Principal::Owner);
140 if !named && self.is(&Principal::Owner) {
141 self.owner_rights.clone()
142 } else {
143 Rights::new()
144 }
145 }
146}
147
148#[derive(Debug, Clone, PartialEq, Eq)]
150#[non_exhaustive]
151pub struct Decision {
152 pub allowed: bool,
154 pub wanted: Rights,
156 pub granted: Rights,
158 pub denied: Rights,
160 pub deciding: Option<usize>,
163 pub cancelled: bool,
165}
166
167impl Decision {
168 pub(crate) fn nothing(wanted: &Rights) -> Self {
169 Self::from_sets(wanted, Rights::new(), Rights::new(), None)
170 }
171
172 pub(crate) fn from_sets(
173 wanted: &Rights,
174 granted: Rights,
175 denied: Rights,
176 deciding: Option<usize>,
177 ) -> Self {
178 Self {
179 allowed: wanted.is_subset(&granted),
180 wanted: wanted.clone(),
181 granted,
182 denied,
183 deciding,
184 cancelled: false,
185 }
186 }
187
188 pub(crate) fn cancelled(schema: &RightsSchema, wanted: &Rights, entry: usize) -> Self {
189 Self {
190 allowed: false,
191 wanted: wanted.clone(),
192 granted: Rights::new(),
193 denied: schema.all(),
194 deciding: Some(entry),
195 cancelled: true,
196 }
197 }
198
199 #[must_use]
204 pub fn intersect(&self, other: &Decision) -> Decision {
205 let deciding = if !self.allowed || other.allowed {
206 self.deciding
207 } else {
208 other.deciding
209 };
210 Decision {
211 allowed: self.allowed && other.allowed,
212 wanted: &self.wanted | &other.wanted,
213 granted: &self.granted & &other.granted,
214 denied: &self.denied | &other.denied,
215 deciding,
216 cancelled: self.cancelled || other.cancelled,
217 }
218 }
219
220 #[must_use]
224 pub fn union_where_unset(&self, other: &Decision) -> Decision {
225 if self.cancelled {
226 return self.clone();
227 }
228 if other.cancelled {
229 return other.clone();
230 }
231 let set = &self.granted | &self.denied;
232 let granted = &self.granted | &(&other.granted - &set);
233 let denied = &self.denied | &(&other.denied - &set);
234 let wanted = &self.wanted | &other.wanted;
235 let deciding = if wanted.is_subset(&set) {
236 self.deciding
237 } else {
238 other.deciding.or(self.deciding)
239 };
240 Decision::from_sets(&wanted, granted, denied, deciding)
241 }
242}
243
244pub(crate) struct Compiled {
246 pub(crate) rights: Rights,
247 pub(crate) cancels: bool,
248}
249
250impl Acl {
251 pub fn validate(&self, schema: &RightsSchema, options: &Options) -> Result<(), AclError> {
257 self.compile(schema, options).map(drop)
258 }
259
260 pub(crate) fn compile(
261 &self,
262 schema: &RightsSchema,
263 options: &Options,
264 ) -> Result<Vec<Compiled>, AclError> {
265 if options
266 .limits
267 .entries
268 .is_some_and(|max| self.entries.len() > max)
269 {
270 return Err(AclError::TooManyEntries);
271 }
272 let mut masks = [0u8; 2];
273 self.entries
274 .iter()
275 .enumerate()
276 .map(|(at, entry)| {
277 let denies = !matches!(self.mode, Mode::Ordered | Mode::DenyOverrides);
278 if denies && entry.effect == Effect::Deny {
279 return Err(AclError::DenyNotAllowed { entry: at });
280 }
281 let posix = self.mode == Mode::Posix;
282 let refused = match entry.principal {
283 Principal::Mask => {
285 let slot = usize::from(entry.inherit.inherit_only);
286 masks[slot] += 1;
287 !posix || masks[slot] > 1
288 }
289 Principal::Authenticated => posix,
290 _ => false,
291 };
292 if refused {
293 return Err(AclError::PrincipalNotAllowed { entry: at });
294 }
295 let (rights, cancels) =
296 schema
297 .compile(&entry.rights)
298 .map_err(|name| AclError::UnknownRight {
299 entry: Some(at),
300 at: name,
301 })?;
302 Ok(Compiled { rights, cancels })
303 })
304 .collect()
305 }
306
307 pub fn check(&self, context: &Context<'_>, wanted: &Rights) -> Result<Decision, AclError> {
319 let compiled = self.compile(context.schema, &context.options)?;
320 let applicable: Vec<(usize, &Entry, &Compiled)> = self
321 .entries
322 .iter()
323 .zip(&compiled)
324 .enumerate()
325 .filter(|(_, (entry, _))| !entry.inherit.inherit_only && context.applies(entry))
326 .map(|(at, (entry, compiled))| (at, entry, compiled))
327 .collect();
328 if self.mode != Mode::MostSpecific
329 && let Some((at, ..)) = applicable.iter().find(|(_, _, compiled)| compiled.cancels)
330 {
331 return Ok(Decision::cancelled(context.schema, wanted, *at));
332 }
333 let owner = context.owner_grant(self);
334 Ok(match self.mode {
335 Mode::Ordered => ordered(&applicable, owner, wanted),
336 Mode::Posix => {
337 let mask = self
338 .entries
339 .iter()
340 .zip(&compiled)
341 .find(|(entry, _)| {
342 entry.principal == Principal::Mask && !entry.inherit.inherit_only
343 })
344 .map(|(_, compiled)| &compiled.rights);
345 posix(&applicable, mask, context, owner, wanted)
346 }
347 Mode::MostSpecific => match level(&applicable) {
348 Some(Level {
349 cancel: Some(at), ..
350 }) => Decision::cancelled(context.schema, wanted, at),
351 Some(level) => Decision::from_sets(
352 wanted,
353 &level.rights | &owner,
354 Rights::new(),
355 level.deciding,
356 ),
357 None => Decision::from_sets(wanted, owner, Rights::new(), None),
358 },
359 Mode::DenyOverrides | Mode::Additive => deny_overrides(&applicable, owner, wanted),
360 })
361 }
362}
363
364impl ItemAcl {
365 pub fn check(&self, context: &Context<'_>, wanted: &Rights) -> Result<Decision, AclError> {
371 self.acl.check(&context.for_item(self), wanted)
372 }
373}
374
375type Applicable<'a> = [(usize, &'a Entry, &'a Compiled)];
376
377fn ordered(applicable: &Applicable<'_>, owner: Rights, wanted: &Rights) -> Decision {
379 let mut granted = owner;
380 let mut denied = Rights::new();
381 let mut deciding = None;
382 for (at, entry, compiled) in applicable {
383 let fresh = &compiled.rights - &(&granted | &denied);
384 match entry.effect {
385 Effect::Allow => granted |= &fresh,
386 Effect::Deny => denied |= &fresh,
387 }
388 if deciding.is_none() && !fresh.is_disjoint(wanted) {
389 let refused = entry.effect == Effect::Deny;
390 if refused || wanted.is_subset(&granted) {
391 deciding = Some(*at);
392 }
393 }
394 }
395 Decision::from_sets(wanted, granted, denied, deciding)
396}
397
398fn deny_overrides(applicable: &Applicable<'_>, owner: Rights, wanted: &Rights) -> Decision {
401 let mut denied = Rights::new();
402 for (_, entry, compiled) in applicable {
403 if entry.effect == Effect::Deny {
404 denied |= &compiled.rights;
405 }
406 }
407 let first_deny = applicable.iter().find(|(_, entry, compiled)| {
408 entry.effect == Effect::Deny && !compiled.rights.is_disjoint(wanted)
409 });
410 let mut granted = owner.clone();
411 let mut deciding = first_deny.map(|(at, ..)| *at);
412 for (at, entry, compiled) in applicable {
413 if entry.effect == Effect::Allow {
414 granted |= &(&compiled.rights - &denied);
415 if deciding.is_none() && wanted.is_subset(&granted) && !wanted.is_subset(&owner) {
416 deciding = Some(*at);
417 }
418 }
419 }
420 Decision::from_sets(wanted, granted, &denied - &owner, deciding)
421}
422
423fn posix(
427 applicable: &Applicable<'_>,
428 mask: Option<&Rights>,
429 context: &Context<'_>,
430 owner: Rights,
431 wanted: &Rights,
432) -> Decision {
433 let capped = |rights: &Rights| match mask {
434 Some(mask) => rights & mask,
435 None => rights.clone(),
436 };
437 let of = |want: fn(&Principal) -> bool| {
438 applicable
439 .iter()
440 .filter(move |(_, entry, _)| want(&entry.principal))
441 };
442 if context.is(&Principal::Owner) {
443 let entry = of(|principal| *principal == Principal::Owner).next();
444 let rights = entry.map_or_else(Rights::new, |(_, _, compiled)| compiled.rights.clone());
445 return Decision::from_sets(wanted, &rights | &owner, Rights::new(), entry.map(|e| e.0));
446 }
447 let named_user = |principal: &Principal| {
448 matches!(
449 principal,
450 Principal::Subject(Subject::Account(_) | Subject::Person(_))
451 )
452 };
453 if let Some((at, _, compiled)) = of(named_user).next() {
454 return Decision::from_sets(wanted, capped(&compiled.rights), Rights::new(), Some(*at));
455 }
456 let group = |principal: &Principal| {
457 matches!(
458 principal,
459 Principal::OwnerGroup | Principal::Subject(Subject::Group(_))
460 )
461 };
462 let groups: Vec<_> = of(group).collect();
463 if !groups.is_empty() {
464 let granted = groups.iter().fold(Rights::new(), |all, (_, _, compiled)| {
465 &all | &capped(&compiled.rights)
466 });
467 let holding = groups
468 .iter()
469 .find(|(_, _, compiled)| wanted.is_subset(&capped(&compiled.rights)));
470 let mut decision = Decision::from_sets(
471 wanted,
472 granted,
473 Rights::new(),
474 holding.or(groups.first()).map(|(at, ..)| *at),
475 );
476 decision.allowed = holding.is_some();
477 return decision;
478 }
479 match of(|principal| *principal == Principal::Everyone).next() {
480 Some((at, _, compiled)) => {
481 Decision::from_sets(wanted, compiled.rights.clone(), Rights::new(), Some(*at))
482 }
483 None => Decision::nothing(wanted),
484 }
485}
486
487pub(crate) struct Level {
489 pub(crate) rights: Rights,
490 pub(crate) cancel: Option<usize>,
491 pub(crate) deciding: Option<usize>,
492}
493
494pub(crate) fn level(applicable: &Applicable<'_>) -> Option<Level> {
498 let personal = |entry: &Entry| {
499 matches!(
500 entry.principal,
501 Principal::Owner | Principal::Subject(Subject::Account(_) | Subject::Person(_))
502 )
503 };
504 let tier: Vec<_> = if applicable.iter().any(|(_, entry, _)| personal(entry)) {
505 applicable
506 .iter()
507 .filter(|(_, entry, _)| personal(entry))
508 .collect()
509 } else {
510 applicable.iter().collect()
511 };
512 let first = tier.first()?;
513 Some(Level {
514 rights: tier.iter().fold(Rights::new(), |all, (_, _, compiled)| {
515 &all | &compiled.rights
516 }),
517 cancel: tier
518 .iter()
519 .find(|(_, _, compiled)| compiled.cancels)
520 .map(|(at, ..)| *at),
521 deciding: Some(first.0),
522 })
523}
524
525impl<'a> Context<'a> {
526 pub(crate) fn for_item<'b>(&self, item: &'b ItemAcl) -> Context<'b>
527 where
528 'a: 'b,
529 {
530 let context: Context<'b> = self.clone();
531 context
532 .owner(item.owner.as_ref())
533 .owner_group(item.owner_group.as_ref())
534 }
535}