1use std::collections::{BTreeMap, BTreeSet};
2
3use crate::graph;
4
5#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
6pub enum RbacError {
7 #[error("ciclo de herança de papéis: {}", .0.join(" -> "))]
8 Cycle(Vec<String>),
9}
10
11#[derive(Debug, Clone, Default)]
13pub struct RoleGraph {
14 inherits: BTreeMap<String, Vec<String>>,
15}
16
17#[derive(Debug, Default)]
18pub struct RoleGraphBuilder {
19 inherits: BTreeMap<String, Vec<String>>,
20}
21
22impl RoleGraphBuilder {
23 pub fn inherit(mut self, role: impl Into<String>, parent: impl Into<String>) -> Self {
25 let parent = parent.into();
26 self.inherits.entry(parent.clone()).or_default();
27 self.inherits.entry(role.into()).or_default().push(parent);
28 self
29 }
30
31 pub fn build(self) -> Result<RoleGraph, RbacError> {
32 match graph::find_cycle(&self.inherits) {
33 Some(cycle) => Err(RbacError::Cycle(cycle)),
34 None => Ok(RoleGraph {
35 inherits: self.inherits,
36 }),
37 }
38 }
39}
40
41impl RoleGraph {
42 pub fn builder() -> RoleGraphBuilder {
43 RoleGraphBuilder::default()
44 }
45
46 pub fn contains(&self, role: &str) -> bool {
48 self.inherits.contains_key(role)
49 }
50
51 pub fn expand<'a>(&self, roles: impl IntoIterator<Item = &'a str>) -> BTreeSet<String> {
53 let mut out = BTreeSet::new();
54 for role in roles {
55 if out.contains(role) {
56 continue;
57 }
58 out.extend(graph::reachable(role, &self.inherits));
59 }
60 out
61 }
62}
63
64#[cfg(test)]
65mod tests {
66 use super::*;
67
68 #[test]
69 fn expands_transitively() {
70 let g = RoleGraph::builder()
71 .inherit("admin", "editor")
72 .inherit("editor", "viewer")
73 .build()
74 .unwrap();
75 assert_eq!(
76 g.expand(["admin"]).into_iter().collect::<Vec<_>>(),
77 ["admin", "editor", "viewer"]
78 );
79 assert_eq!(g.expand(["guest"]).into_iter().collect::<Vec<_>>(), ["guest"]);
80 assert!(g.contains("admin") && g.contains("viewer") && !g.contains("guest"));
81 }
82
83 #[test]
84 fn rejects_cycle() {
85 let err = RoleGraph::builder()
86 .inherit("a", "b")
87 .inherit("b", "a")
88 .build()
89 .unwrap_err();
90 assert!(matches!(err, RbacError::Cycle(_)));
91 }
92}