Skip to main content

coqui_roles/
lib.rs

1//! A first-match role authorizer, built in code.
2//!
3//! A policy is named roles that list actions, and ordered rules that bind one
4//! `account:<name>`, `person:<id>` or `group:<name>`, or every signed-in subject
5//! (`any:signed-in`), to a role at one scope. A scope is `*`
6//! (everything) or `<kind>:<id>`, where the kinds a deployment uses are configured, for
7//! example `site` or `project`; the library has no scope vocabulary of its own. A rule's
8//! scope matches a request when it is `*`, when it equals the request's `resource` as an
9//! exact string, or when the request names it among its `ancestors` and the rule propagates
10//! (the default), so a grant on a parent reaches what sits under it.
11//!
12//! The first rule whose subject and scope match is decisive: when its role lacks the
13//! requested action, access is denied. With no matching rule access is denied. A child
14//! narrows its parent's grant with a rule placed before the parent's.
15//!
16//! ```
17//! use coqui_roles::{RoleAuthorizer, Rule};
18//!
19//! let authorizer = RoleAuthorizer::builder()
20//!     .scope_kinds(["site"])
21//!     .role("viewer", ["document.read"])
22//!     .rule(Rule::new("group:staff", "site:north", "viewer"))
23//!     .build()
24//!     .unwrap();
25//! # let _ = authorizer;
26//! ```
27//!
28//! [`RolePolicy`] is the same thing as plain data with guatiao's value traits, so a caller
29//! keeps it in any format; it is also the configuration [`RoleAuthorizer`] takes as the
30//! `coqui_roles` provider, which `coqui-roles-plugin` exports.
31#![forbid(unsafe_code)]
32#![warn(missing_docs)]
33
34use std::collections::{BTreeMap, BTreeSet};
35use std::fmt;
36
37use coqui_builder::Describe;
38use guatiao_builder::Described;
39
40use coqui_access::guatiao::Provider;
41use coqui_access::guatiao::library::ProviderError;
42use coqui_access::{
43    AuthorizationDecision, AuthorizationRequest, Authorizer, Limit, Subject, error,
44};
45
46/// Bounds on a policy, each a [`Limit`] the caller can change or lift ([`Limit::UNBOUNDED`]).
47///
48/// They bound the work and memory a policy costs, not who may do what: the rule scan per
49/// request, and the tables built once. By default at most 256 roles, 256 actions per role,
50/// 10 000 rules, 64 scope kinds, names of 256 bytes, and 64 ancestors in one request.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Describe)]
52#[map(deny_unknown_fields)]
53#[non_exhaustive]
54pub struct RoleLimits {
55    /// Roles a policy defines.
56    #[map(default = Limit::at(256))]
57    pub roles: Limit,
58    /// Actions one role lists.
59    #[map(default = Limit::at(256))]
60    pub actions_per_role: Limit,
61    /// Rules a policy holds.
62    #[map(default = Limit::at(10_000))]
63    pub rules: Limit,
64    /// Scope kinds a policy allows.
65    #[map(default = Limit::at(64))]
66    pub scope_kinds: Limit,
67    /// Bytes in a role, action, subject value, scope kind or scope id.
68    #[map(default = Limit::at(256))]
69    pub name_bytes: Limit,
70    /// Ancestors one request names; a request naming more is an error, never a denial.
71    #[map(default = Limit::at(64))]
72    pub ancestors: Limit,
73}
74
75impl Default for RoleLimits {
76    fn default() -> Self {
77        Self {
78            roles: Limit::at(256),
79            actions_per_role: Limit::at(256),
80            rules: Limit::at(10_000),
81            scope_kinds: Limit::at(64),
82            name_bytes: Limit::at(256),
83            ancestors: Limit::at(64),
84        }
85    }
86}
87
88impl RoleLimits {
89    /// No bound at all.
90    pub const UNBOUNDED: Self = Self {
91        roles: Limit::UNBOUNDED,
92        actions_per_role: Limit::UNBOUNDED,
93        rules: Limit::UNBOUNDED,
94        scope_kinds: Limit::UNBOUNDED,
95        name_bytes: Limit::UNBOUNDED,
96        ancestors: Limit::UNBOUNDED,
97    };
98
99    /// These limits with `roles`.
100    #[must_use]
101    pub const fn roles(mut self, roles: Limit) -> Self {
102        self.roles = roles;
103        self
104    }
105
106    /// These limits with `actions_per_role`.
107    #[must_use]
108    pub const fn actions_per_role(mut self, actions: Limit) -> Self {
109        self.actions_per_role = actions;
110        self
111    }
112
113    /// These limits with `rules`.
114    #[must_use]
115    pub const fn rules(mut self, rules: Limit) -> Self {
116        self.rules = rules;
117        self
118    }
119
120    /// These limits with `scope_kinds`.
121    #[must_use]
122    pub const fn scope_kinds(mut self, kinds: Limit) -> Self {
123        self.scope_kinds = kinds;
124        self
125    }
126
127    /// These limits with `name_bytes`.
128    #[must_use]
129    pub const fn name_bytes(mut self, bytes: Limit) -> Self {
130        self.name_bytes = bytes;
131        self
132    }
133
134    /// These limits with `ancestors`.
135    #[must_use]
136    pub const fn ancestors(mut self, ancestors: Limit) -> Self {
137        self.ancestors = ancestors;
138        self
139    }
140}
141
142/// A named set of actions.
143#[derive(Debug, Clone, PartialEq, Eq, Describe)]
144#[map(deny_unknown_fields)]
145#[non_exhaustive]
146pub struct Role {
147    /// The name rules refer to.
148    pub name: String,
149    /// The actions it allows, such as `document.read`; none twice.
150    pub actions: Vec<String>,
151}
152
153impl Role {
154    /// A role allowing `actions`.
155    pub fn new(
156        name: impl Into<String>,
157        actions: impl IntoIterator<Item = impl Into<String>>,
158    ) -> Self {
159        Self {
160            name: name.into(),
161            actions: actions.into_iter().map(Into::into).collect(),
162        }
163    }
164}
165
166/// Binds a subject to a role at a scope.
167#[derive(Debug, Clone, PartialEq, Eq, Describe)]
168#[map(deny_unknown_fields)]
169#[non_exhaustive]
170pub struct Rule {
171    /// `account:<name>`, `person:<id>`, `group:<name>` or `any:signed-in`, the last matching
172    /// every subject a sign-in or key resolved (never one with no identity). No other
173    /// `any:` name exists.
174    pub subject: String,
175    /// `*`, or `<kind>:<id>` with the kind among the policy's scope kinds.
176    pub scope: String,
177    /// The name of a role the policy defines.
178    pub role: String,
179    /// Whether it also matches a request that names `scope` among its `ancestors`; true
180    /// unless configured. `*` matches every request either way.
181    #[map(default = true)]
182    pub propagate: bool,
183}
184
185impl Rule {
186    /// A rule: `subject` holds `role` at `scope` and at whatever sits under it.
187    pub fn new(
188        subject: impl Into<String>,
189        scope: impl Into<String>,
190        role: impl Into<String>,
191    ) -> Self {
192        Self {
193            subject: subject.into(),
194            scope: scope.into(),
195            role: role.into(),
196            propagate: true,
197        }
198    }
199
200    /// This rule, reaching what sits under its scope or (`false`) its scope alone.
201    #[must_use]
202    pub fn propagate(mut self, propagate: bool) -> Self {
203        self.propagate = propagate;
204        self
205    }
206}
207
208/// A role policy as plain data: what [`RoleAuthorizer::new`] checks and compiles.
209#[derive(Debug, Clone, Default, PartialEq, Eq, Describe)]
210#[map(deny_unknown_fields)]
211#[non_exhaustive]
212pub struct RolePolicy {
213    /// The kinds a rule scope may use (`site` allows `site:north`); empty allows any kind.
214    /// `*` is always allowed.
215    #[map(default)]
216    pub scope_kinds: Vec<String>,
217    /// The roles.
218    #[map(default)]
219    pub roles: Vec<Role>,
220    /// The rules, in the order they are tried.
221    #[map(default)]
222    pub rules: Vec<Rule>,
223    /// Bounds on the policy's size; [`RoleLimits::default`] when absent.
224    #[map(default)]
225    pub limits: RoleLimits,
226}
227
228impl RolePolicy {
229    /// An empty policy, which denies everything.
230    pub fn new() -> Self {
231        Self::default()
232    }
233}
234
235/// Builds a [`RoleAuthorizer`]; rules are tried in the order they are added.
236#[derive(Debug, Clone, Default)]
237pub struct RoleAuthorizerBuilder {
238    policy: RolePolicy,
239}
240
241impl RoleAuthorizerBuilder {
242    /// Allows these scope kinds in rules; without any, every kind is allowed.
243    #[must_use]
244    pub fn scope_kinds(mut self, kinds: impl IntoIterator<Item = impl Into<String>>) -> Self {
245        self.policy.scope_kinds = kinds.into_iter().map(Into::into).collect();
246        self
247    }
248
249    /// Defines a role.
250    #[must_use]
251    pub fn role(
252        mut self,
253        name: impl Into<String>,
254        actions: impl IntoIterator<Item = impl Into<String>>,
255    ) -> Self {
256        self.policy.roles.push(Role::new(name, actions));
257        self
258    }
259
260    /// Adds a rule after the ones already added.
261    #[must_use]
262    pub fn rule(mut self, rule: Rule) -> Self {
263        self.policy.rules.push(rule);
264        self
265    }
266
267    /// Bounds the policy's size. Default [`RoleLimits::default`].
268    #[must_use]
269    pub fn limits(mut self, limits: RoleLimits) -> Self {
270        self.policy.limits = limits;
271        self
272    }
273
274    /// Checks the policy and compiles it.
275    ///
276    /// # Errors
277    ///
278    /// As [`RoleAuthorizer::new`].
279    pub fn build(self) -> Result<RoleAuthorizer, RolePolicyError> {
280        RoleAuthorizer::new(self.policy)
281    }
282}
283
284/// First-match role authorizer, and the `coqui_roles` provider, configured with a
285/// [`RolePolicy`].
286#[derive(Clone, Provider)]
287#[provider(
288    Authorizer,
289    id = "coqui_roles",
290    name = "Role authorizer",
291    config = Described<RolePolicy>,
292    crate = ::coqui_access::guatiao
293)]
294pub struct RoleAuthorizer {
295    roles: BTreeMap<String, BTreeSet<String>>,
296    rules: Vec<CompiledRule>,
297    ancestors: Limit,
298}
299
300/// The empty policy, which denies everything, with the default limits.
301impl Default for RoleAuthorizer {
302    fn default() -> Self {
303        Self {
304            roles: BTreeMap::new(),
305            rules: Vec::new(),
306            ancestors: RoleLimits::default().ancestors,
307        }
308    }
309}
310
311#[derive(Clone)]
312struct CompiledRule {
313    subject: Subject,
314    scope: String,
315    role: String,
316    propagate: bool,
317}
318
319/// An invalid role policy.
320#[derive(Debug, Clone, PartialEq, Eq)]
321#[non_exhaustive]
322pub struct RolePolicyError(String);
323
324impl fmt::Display for RolePolicyError {
325    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
326        formatter.write_str(&self.0)
327    }
328}
329
330impl core::error::Error for RolePolicyError {}
331
332/// A policy refused while building the provider is a bad configuration value.
333impl From<RolePolicyError> for ProviderError {
334    fn from(error: RolePolicyError) -> Self {
335        error::bad_value(&error.0)
336    }
337}
338
339impl TryFrom<Described<RolePolicy>> for RoleAuthorizer {
340    type Error = RolePolicyError;
341
342    fn try_from(policy: Described<RolePolicy>) -> Result<Self, RolePolicyError> {
343        Self::new(policy.0)
344    }
345}
346
347impl TryFrom<RolePolicy> for RoleAuthorizer {
348    type Error = RolePolicyError;
349
350    fn try_from(policy: RolePolicy) -> Result<Self, RolePolicyError> {
351        Self::new(policy)
352    }
353}
354
355impl fmt::Debug for RoleAuthorizer {
356    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
357        formatter
358            .debug_struct("RoleAuthorizer")
359            .field("roles", &self.roles.len())
360            .field("rules", &self.rules.len())
361            .finish()
362    }
363}
364
365impl RoleAuthorizer {
366    /// Starts a policy in code; add roles and rules, then [`build`](RoleAuthorizerBuilder::build).
367    pub fn builder() -> RoleAuthorizerBuilder {
368        RoleAuthorizerBuilder::default()
369    }
370
371    /// Checks `policy` and compiles it.
372    ///
373    /// # Errors
374    ///
375    /// Returns an error for unknown roles, duplicate role names or actions, malformed
376    /// subjects or scopes, a scope kind that is not allowed, or a policy past its
377    /// [`RoleLimits`].
378    pub fn new(policy: RolePolicy) -> Result<Self, RolePolicyError> {
379        let fail = |message: &str| RolePolicyError(message.to_owned());
380        let limits = policy.limits;
381        let name = |value: &str| name(value, limits.name_bytes);
382        let scope_kinds = &policy.scope_kinds;
383        if !limits.scope_kinds.allows(scope_kinds.len())
384            || !scope_kinds.iter().all(|kind| name(kind))
385        {
386            return Err(fail("scope kinds are invalid"));
387        }
388        if !limits.roles.allows(policy.roles.len()) || !limits.rules.allows(policy.rules.len()) {
389            return Err(fail("policy has too many roles or rules"));
390        }
391        let mut roles = BTreeMap::new();
392        for role in &policy.roles {
393            if !name(&role.name) || role.actions.is_empty() {
394                return Err(RolePolicyError(format!("invalid role {:?}", role.name)));
395            }
396            if !limits.actions_per_role.allows(role.actions.len()) {
397                return Err(RolePolicyError(format!(
398                    "role {:?} has too many actions",
399                    role.name
400                )));
401            }
402            let mut actions = BTreeSet::new();
403            for action in &role.actions {
404                if !name(action) || !actions.insert(action.clone()) {
405                    return Err(RolePolicyError(format!(
406                        "invalid or duplicate action {action:?} in role {:?}",
407                        role.name
408                    )));
409                }
410            }
411            if roles.insert(role.name.clone(), actions).is_some() {
412                return Err(RolePolicyError(format!(
413                    "role {:?} is defined twice",
414                    role.name
415                )));
416            }
417        }
418
419        let mut rules = Vec::with_capacity(policy.rules.len());
420        for rule in policy.rules {
421            let subject: Subject = rule.subject.parse().map_err(|_| {
422                if rule.subject.starts_with("any:") {
423                    fail("the only any: subject is any:signed-in")
424                } else {
425                    fail(
426                        "rule subject must be account, person or group:<value> (not empty, no control character, no leading or trailing whitespace), or any:signed-in",
427                    )
428                }
429            })?;
430            // `Subject` already refuses an empty value, a control character and whitespace at
431            // either end; inner spaces stay, since directory group names hold them.
432            if subject != Subject::AnySignedIn && !limits.name_bytes.allows(subject.value().len()) {
433                return Err(fail("rule subject value is longer than the name limit"));
434            }
435            if rule.scope != "*" {
436                let allowed = rule.scope.split_once(':').is_some_and(|(kind, id)| {
437                    name(id)
438                        && name(kind)
439                        && (scope_kinds.is_empty() || scope_kinds.iter().any(|k| k == kind))
440                });
441                if !allowed {
442                    return Err(RolePolicyError(format!(
443                        "rule scope must be * or <kind>:<id> with kind in {scope_kinds:?}"
444                    )));
445                }
446            }
447            if !roles.contains_key(&rule.role) {
448                return Err(RolePolicyError(format!(
449                    "rule references unknown role {:?}",
450                    rule.role
451                )));
452            }
453            rules.push(CompiledRule {
454                subject,
455                scope: rule.scope,
456                role: rule.role,
457                propagate: rule.propagate,
458            });
459        }
460        Ok(Self {
461            roles,
462            rules,
463            ancestors: limits.ancestors,
464        })
465    }
466
467    fn decision(
468        &self,
469        request: &AuthorizationRequest,
470    ) -> Result<AuthorizationDecision, ProviderError> {
471        if !self.ancestors.allows(request.ancestors.len()) {
472            return Err(error::bad_value(
473                "the request names more ancestors than the policy's limits allow",
474            ));
475        }
476        let allowed = self
477            .rules
478            .iter()
479            .find(|rule| {
480                (rule.scope == "*"
481                    || rule.scope == request.resource
482                    || (rule.propagate && request.ancestors.contains(&rule.scope)))
483                    && rule.subject.matches(&request.person)
484            })
485            .is_some_and(|rule| {
486                self.roles
487                    .get(&rule.role)
488                    .is_some_and(|actions| actions.contains(&request.action))
489            });
490        Ok(AuthorizationDecision {
491            allowed,
492            limits: BTreeMap::new(),
493        })
494    }
495}
496
497impl Authorizer for RoleAuthorizer {
498    /// # Errors
499    ///
500    /// A request naming more `ancestors` than [`RoleLimits::ancestors`] allows.
501    fn authorize(
502        &self,
503        request: AuthorizationRequest,
504    ) -> Result<AuthorizationDecision, ProviderError> {
505        self.decision(&request)
506    }
507}
508
509fn name(value: &str, most: Limit) -> bool {
510    !value.is_empty()
511        && most.allows(value.len())
512        && !value.chars().any(char::is_control)
513        && !value.chars().any(char::is_whitespace)
514}
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519    use coqui_access::Person;
520
521    fn person(id: &str, name: &str, groups: &[&str]) -> Person {
522        Person {
523            id: id.to_owned(),
524            name: name.to_owned(),
525            groups: groups.iter().map(|group| (*group).to_owned()).collect(),
526            ..Person::default()
527        }
528    }
529
530    fn allowed(policy: &RoleAuthorizer, person: &Person, action: &str, resource: &str) -> bool {
531        under(policy, person, action, resource, &[]).unwrap()
532    }
533
534    fn under(
535        policy: &RoleAuthorizer,
536        person: &Person,
537        action: &str,
538        resource: &str,
539        ancestors: &[&str],
540    ) -> Result<bool, ProviderError> {
541        policy
542            .authorize(AuthorizationRequest {
543                person: person.clone(),
544                action: action.to_owned(),
545                resource: resource.to_owned(),
546                ancestors: ancestors.iter().map(|scope| (*scope).to_owned()).collect(),
547            })
548            .map(|decision| decision.allowed)
549    }
550
551    #[test]
552    fn a_group_rule_applies_to_a_person_whose_group_differs_only_in_case() {
553        let policy = RoleAuthorizer::builder()
554            .scope_kinds(["site"])
555            .role("viewer", ["document.read"])
556            .rule(Rule::new("group:Domain-Users", "site:north", "viewer"))
557            .build()
558            .unwrap();
559        let lowercase = person("a", "alice", &["domain-users"]);
560        let other = person("b", "bob", &["domain-admins"]);
561        assert!(allowed(&policy, &lowercase, "document.read", "site:north"));
562        assert!(!allowed(&policy, &other, "document.read", "site:north"));
563    }
564
565    #[test]
566    fn a_rule_subject_may_hold_inner_spaces_and_matches_a_group_in_either_case() {
567        let policy = RoleAuthorizer::builder()
568            .scope_kinds(["site"])
569            .role("viewer", ["document.read"])
570            .rule(Rule::new("group:Domain Users", "site:north", "viewer"))
571            .rule(Rule::new("account:Ana María", "site:south", "viewer"))
572            .build()
573            .unwrap();
574        let lowercase = person("a", "alice", &["domain users"]);
575        let other = person("b", "bob", &["domain  users", "domain admins"]);
576        assert!(allowed(&policy, &lowercase, "document.read", "site:north"));
577        assert!(!allowed(&policy, &other, "document.read", "site:north"));
578        let ana = person("c", "Ana María", &[]);
579        assert!(allowed(&policy, &ana, "document.read", "site:south"));
580    }
581
582    #[test]
583    fn a_rule_subject_with_edge_whitespace_or_a_control_character_is_refused() {
584        for subject in [
585            "group: Domain Users",
586            "group:Domain Users ",
587            "group:Domain Users\u{a0}",
588            "group: ",
589            "group:Domain\nUsers",
590            "group:Domain\tUsers",
591            "account:a\u{0}b",
592        ] {
593            let built = RoleAuthorizer::builder()
594                .role("r", ["a"])
595                .rule(Rule::new(subject, "*", "r"))
596                .build();
597            assert!(built.is_err(), "{subject:?}");
598        }
599        let long = format!("group:{}", "a b".repeat(100));
600        let built = RoleAuthorizer::builder()
601            .role("r", ["a"])
602            .rule(Rule::new(long, "*", "r"))
603            .build();
604        assert!(built.is_err(), "the name_bytes limit still holds");
605    }
606
607    #[test]
608    fn a_grant_on_an_ancestor_reaches_what_sits_under_it_unless_it_does_not_propagate() {
609        let policy = RoleAuthorizer::builder()
610            .scope_kinds(["site"])
611            .role("viewer", ["document.read"])
612            .role("none", ["x.nothing"])
613            .rule(Rule::new("group:staff", "site:secret", "none"))
614            .rule(Rule::new("group:staff", "site:europe", "viewer"))
615            .rule(Rule::new("group:guests", "site:europe", "viewer").propagate(false))
616            .build()
617            .unwrap();
618        let staff = person("s", "staff", &["staff"]);
619        let guest = person("g", "guest", &["guests"]);
620        let lineage = ["site:europe", "site:world"];
621        assert!(under(&policy, &staff, "document.read", "site:north", &lineage).unwrap());
622        assert!(
623            !under(&policy, &staff, "document.read", "site:north", &[]).unwrap(),
624            "without its ancestry a request reaches only direct rules"
625        );
626        assert!(!under(&policy, &guest, "document.read", "site:north", &lineage).unwrap());
627        assert!(
628            under(
629                &policy,
630                &guest,
631                "document.read",
632                "site:europe",
633                &["site:world"]
634            )
635            .unwrap()
636        );
637        assert!(
638            !under(
639                &policy,
640                &staff,
641                "document.read",
642                "site:north",
643                &["site:secret", "site:europe"]
644            )
645            .unwrap(),
646            "an earlier rule on a nearer ancestor narrows the later grant"
647        );
648
649        let deep: Vec<String> = (0..65).map(|level| format!("site:l{level}")).collect();
650        let deep: Vec<&str> = deep.iter().map(String::as_str).collect();
651        assert!(under(&policy, &staff, "document.read", "site:north", &deep[..64]).is_ok());
652        assert!(
653            under(&policy, &staff, "document.read", "site:north", &deep).is_err(),
654            "65 ancestors is an error by default, never a denial"
655        );
656        let lifted = RoleAuthorizer::builder()
657            .role("viewer", ["document.read"])
658            .rule(Rule::new("group:staff", "site:l64", "viewer"))
659            .limits(RoleLimits::default().ancestors(Limit::UNBOUNDED))
660            .build()
661            .unwrap();
662        assert!(under(&lifted, &staff, "document.read", "site:north", &deep).unwrap());
663    }
664
665    fn standard() -> RoleAuthorizerBuilder {
666        RoleAuthorizer::builder()
667            .scope_kinds(["site"])
668            .role("viewer", ["document.read", "audit.read"])
669            .role("editor", ["document.read", "document.write"])
670            .rule(Rule::new("group:staff", "site:north", "viewer"))
671            .rule(Rule::new("person:p-editor", "site:north", "editor"))
672            .rule(Rule::new("account:admin", "*", "editor"))
673    }
674
675    #[test]
676    fn scopes_roles_and_default_deny() {
677        let policy = standard().build().unwrap();
678        let debug = format!("{policy:?}");
679        assert!(!debug.contains("p-editor") && !debug.contains("staff"));
680        let viewer = person("p-viewer", "viewer", &["staff"]);
681        let editor = person("p-editor", "editor", &[]);
682        assert!(allowed(&policy, &viewer, "document.read", "site:north"));
683        assert!(!allowed(&policy, &viewer, "document.write", "site:north"));
684        assert!(!allowed(&policy, &viewer, "document.read", "site:south"));
685        assert!(allowed(&policy, &editor, "document.write", "site:north"));
686        assert!(!allowed(&policy, &editor, "document.write", "site:south"));
687        assert!(allowed(
688            &policy,
689            &person("p", "admin", &[]),
690            "document.write",
691            "site:any"
692        ));
693        assert!(!allowed(
694            &policy,
695            &person("p", "nobody", &[]),
696            "document.read",
697            "site:north"
698        ));
699        assert!(!allowed(
700            &RoleAuthorizer::builder().build().unwrap(),
701            &editor,
702            "document.read",
703            "*"
704        ));
705    }
706
707    #[test]
708    fn any_signed_in_matches_a_resolved_subject_and_never_an_anonymous_one() {
709        let policy = RoleAuthorizer::builder()
710            .role("viewer", ["document.read"])
711            .role("none", ["x.nothing"])
712            .rule(Rule::new("group:blocked", "*", "none"))
713            .rule(Rule::new("any:signed-in", "*", "viewer"))
714            .build()
715            .unwrap();
716        let directory_person = person("cn=a,dc=x", "alice", &["staff"]);
717        let key_account = person("key-1", "ci-key", &[]);
718        assert!(allowed(&policy, &directory_person, "document.read", "x"));
719        assert!(allowed(&policy, &key_account, "document.read", "x"));
720        assert!(!allowed(&policy, &directory_person, "document.write", "x"));
721        assert!(
722            !allowed(&policy, &Person::default(), "document.read", "x"),
723            "no identity, no match"
724        );
725        assert!(
726            !allowed(
727                &policy,
728                &person("", "named-only", &["g"]),
729                "document.read",
730                "x"
731            ),
732            "a name with no id is not a resolved subject"
733        );
734        assert!(
735            !allowed(
736                &policy,
737                &person("i", "n", &["blocked"]),
738                "document.read",
739                "x"
740            ),
741            "first match order is unchanged"
742        );
743        let scoped = RoleAuthorizer::builder()
744            .scope_kinds(["site"])
745            .role("viewer", ["document.read"])
746            .rule(Rule::new("any:signed-in", "site:north", "viewer"))
747            .build()
748            .unwrap();
749        assert!(allowed(
750            &scoped,
751            &key_account,
752            "document.read",
753            "site:north"
754        ));
755        assert!(!allowed(
756            &scoped,
757            &key_account,
758            "document.read",
759            "site:south"
760        ));
761        assert!(
762            !allowed(
763                &RoleAuthorizer::builder().build().unwrap(),
764                &key_account,
765                "document.read",
766                "x"
767            ),
768            "it grants nothing by itself"
769        );
770    }
771
772    #[test]
773    fn an_unknown_any_subject_is_refused() {
774        for subject in [
775            "any:other",
776            "any:person",
777            "any:",
778            "any:signed-in:x",
779            "ANY:signed-in",
780            "any:Signed-in",
781        ] {
782            let built = RoleAuthorizer::builder()
783                .role("r", ["a"])
784                .rule(Rule::new(subject, "*", "r"))
785                .build();
786            assert!(built.is_err(), "{subject}");
787        }
788        // An ordinary name `any` is unambiguous: the kind comes first.
789        assert!(
790            RoleAuthorizer::builder()
791                .role("r", ["a"])
792                .rule(Rule::new("account:any", "*", "r"))
793                .rule(Rule::new("group:any:signed-in", "*", "r"))
794                .build()
795                .is_ok()
796        );
797    }
798
799    #[test]
800    fn a_policy_value_builds_the_same_authorizer() {
801        let mut policy = RolePolicy::new();
802        policy.scope_kinds = vec!["site".to_owned()];
803        policy.roles = vec![Role::new("viewer", ["document.read"])];
804        policy.rules = vec![Rule::new("group:staff", "site:north", "viewer")];
805        let policy = RoleAuthorizer::new(policy).unwrap();
806        assert!(allowed(
807            &policy,
808            &person("i", "n", &["staff"]),
809            "document.read",
810            "site:north"
811        ));
812    }
813
814    #[test]
815    fn the_first_matching_rule_is_decisive() {
816        let policy = RoleAuthorizer::builder()
817            .role("none", ["x.nothing"])
818            .role("all", ["x.read"])
819            .rule(Rule::new("group:g", "*", "none"))
820            .rule(Rule::new("group:g", "*", "all"))
821            .build()
822            .unwrap();
823        assert!(!allowed(
824            &policy,
825            &person("i", "n", &["g"]),
826            "x.read",
827            "anything"
828        ));
829    }
830
831    #[test]
832    fn scope_kinds_are_configurable_and_everything_else_is_refused() {
833        // Another vocabulary works with no change to the library.
834        let policy = RoleAuthorizer::builder()
835            .scope_kinds(["project"])
836            .role("r", ["a.b"])
837            .rule(Rule::new("account:x", "project:p1", "r"))
838            .build()
839            .unwrap();
840        assert!(allowed(
841            &policy,
842            &person("i", "x", &[]),
843            "a.b",
844            "project:p1"
845        ));
846        let with_scope = |scope: &str, kinds: &[&str]| {
847            RoleAuthorizer::builder()
848                .scope_kinds(kinds.iter().copied())
849                .role("r", ["a.b"])
850                .rule(Rule::new("account:x", scope, "r"))
851                .build()
852        };
853        assert!(with_scope("project:p1", &["site"]).is_err());
854        assert!(with_scope("site", &["site"]).is_err());
855        assert!(with_scope("project:p1", &[]).is_ok());
856        assert!(
857            RoleAuthorizer::builder()
858                .rule(Rule::new("account:x", "*", "missing"))
859                .build()
860                .is_err()
861        );
862        assert!(
863            RoleAuthorizer::builder()
864                .role("r", ["a", "a"])
865                .build()
866                .is_err()
867        );
868        assert!(
869            RoleAuthorizer::builder()
870                .role("r", ["a"])
871                .role("r", ["b"])
872                .build()
873                .is_err()
874        );
875        assert!(
876            RoleAuthorizer::builder()
877                .role("r", ["a"])
878                .rule(Rule::new("nobody", "*", "r"))
879                .build()
880                .is_err()
881        );
882        assert!(
883            RoleAuthorizer::builder()
884                .role("r", ["a"])
885                .rule(Rule::new("robot:x", "*", "r"))
886                .build()
887                .is_err()
888        );
889    }
890
891    #[test]
892    fn the_bounds_hold() {
893        const ROLES: usize = 256;
894        const ROLE_ACTIONS: usize = 256;
895        const RULES: usize = 10_000;
896        const SCOPE_KINDS: usize = 64;
897        let many_rules = (0..=RULES).fold(RoleAuthorizer::builder().role("r", ["a"]), |b, n| {
898            b.rule(Rule::new(format!("account:u{n}"), "*", "r"))
899        });
900        assert!(many_rules.build().is_err());
901        let many_roles = (0..=ROLES).fold(RoleAuthorizer::builder(), |b, n| {
902            b.role(format!("r{n}"), ["a"])
903        });
904        assert!(many_roles.build().is_err());
905        let actions = (0..=ROLE_ACTIONS).map(|n| format!("a{n}"));
906        assert!(
907            RoleAuthorizer::builder()
908                .role("r", actions)
909                .build()
910                .is_err()
911        );
912        let kinds = (0..=SCOPE_KINDS).map(|n| format!("k{n}"));
913        assert!(
914            RoleAuthorizer::builder()
915                .scope_kinds(kinds)
916                .build()
917                .is_err()
918        );
919        // At the bounds is fine.
920        let actions = (0..ROLE_ACTIONS).map(|n| format!("a{n}"));
921        assert!(RoleAuthorizer::builder().role("r", actions).build().is_ok());
922    }
923
924    #[test]
925    fn the_bounds_are_options_and_none_lifts_one() {
926        let rules = |limits: RoleLimits| {
927            (0..10_001)
928                .fold(RoleAuthorizer::builder().role("r", ["a"]), |b, n| {
929                    b.rule(Rule::new(format!("account:u{n}"), "*", "r"))
930                })
931                .limits(limits)
932                .build()
933        };
934        assert!(rules(RoleLimits::default()).is_err());
935        assert!(rules(RoleLimits::default().rules(Limit::UNBOUNDED)).is_ok());
936        let long = "x".repeat(300);
937        let named = |limits: RoleLimits| {
938            RoleAuthorizer::builder()
939                .role(long.clone(), ["a"])
940                .limits(limits)
941                .build()
942        };
943        assert!(named(RoleLimits::default()).is_err());
944        assert!(named(RoleLimits::default().name_bytes(Limit::at(300))).is_ok());
945        let tight = RoleAuthorizer::builder()
946            .role("r", ["a", "b"])
947            .limits(RoleLimits::UNBOUNDED.actions_per_role(Limit::at(1)))
948            .build();
949        assert!(tight.is_err());
950    }
951
952    fn policy_from(keys: &[(&str, &str)]) -> Result<RolePolicy, String> {
953        let mut partial = coqui_builder::Partial::<RolePolicy>::new();
954        for (key, text) in keys {
955            partial.set(key, text).map_err(|error| error.to_string())?;
956        }
957        partial.build().map_err(|error| error.to_string())
958    }
959
960    #[test]
961    fn the_limits_read_from_configuration() {
962        let read = policy_from(&[("limits.rules", "none"), ("limits.roles", "2")])
963            .unwrap()
964            .limits;
965        assert_eq!(read.rules, Limit::UNBOUNDED);
966        assert_eq!(read.roles, Limit::at(2));
967        assert_eq!(read.scope_kinds, Limit::at(64));
968        assert_eq!(policy_from(&[]).unwrap().limits, RoleLimits::default());
969    }
970
971    #[test]
972    fn a_policy_is_plain_data_that_any_format_carries() {
973        let mut policy = RolePolicy::new();
974        policy.scope_kinds = vec!["site".to_owned()];
975        policy.roles = vec![Role::new("viewer", ["document.read"])];
976        policy.rules = vec![Rule::new("group:staff", "site:north", "viewer")];
977        let read = policy_from(&[
978            ("scope_kinds[0]", "site"),
979            ("roles[0].name", "viewer"),
980            ("roles[0].actions[0]", "document.read"),
981            ("rules[0].subject", "group:staff"),
982            ("rules[0].scope", "site:north"),
983            ("rules[0].role", "viewer"),
984        ])
985        .unwrap();
986        assert_eq!(read, policy);
987        let authorizer = RoleAuthorizer::try_from(policy).unwrap();
988        assert!(allowed(
989            &authorizer,
990            &person("i", "n", &["staff"]),
991            "document.read",
992            "site:north"
993        ));
994        assert!(policy_from(&[("surprise", "true")]).is_err());
995        assert_eq!(policy_from(&[]).unwrap(), RolePolicy::new());
996    }
997
998    #[test]
999    fn a_refused_policy_is_a_bad_value_for_the_host() {
1000        let refused = RoleAuthorizer::builder()
1001            .rule(Rule::new("account:x", "*", "missing"))
1002            .build()
1003            .unwrap_err();
1004        let error = ProviderError::from(refused);
1005        assert_eq!(
1006            error.status,
1007            coqui_access::guatiao::Status::GUATIAO_ERR_BAD_VALUE
1008        );
1009    }
1010}