1use std::collections::{BTreeMap, BTreeSet, HashMap};
2use std::fmt;
3
4use serde::{Deserialize, Serialize};
5
6use crate::attr::{Attributes, Value};
7use crate::graph;
8use crate::resource::GLOBAL;
9
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12#[serde(rename_all = "camelCase")]
13pub struct PermissionDef {
14 pub key: String,
15 pub targets: Vec<String>,
17 #[serde(default, skip_serializing_if = "Option::is_none")]
18 pub label: Option<String>,
19 #[serde(default, skip_serializing_if = "Option::is_none")]
20 pub description: Option<String>,
21 #[serde(default, skip_serializing_if = "Vec::is_empty")]
23 pub implied_by: Vec<String>,
24 #[serde(default, skip_serializing_if = "Attributes::is_empty")]
27 pub meta: Attributes,
28}
29
30impl PermissionDef {
31 pub fn new(key: impl Into<String>) -> Self {
32 Self {
33 key: key.into(),
34 targets: Vec::new(),
35 label: None,
36 description: None,
37 implied_by: Vec::new(),
38 meta: Attributes::new(),
39 }
40 }
41
42 pub fn targets<I, S>(mut self, targets: I) -> Self
43 where
44 I: IntoIterator<Item = S>,
45 S: Into<String>,
46 {
47 self.targets.extend(targets.into_iter().map(Into::into));
48 self
49 }
50
51 pub fn label(mut self, label: impl Into<String>) -> Self {
52 self.label = Some(label.into());
53 self
54 }
55
56 pub fn description(mut self, description: impl Into<String>) -> Self {
57 self.description = Some(description.into());
58 self
59 }
60
61 pub fn implied_by<I, S>(mut self, parents: I) -> Self
62 where
63 I: IntoIterator<Item = S>,
64 S: Into<String>,
65 {
66 self.implied_by.extend(parents.into_iter().map(Into::into));
67 self
68 }
69
70 pub fn meta(mut self, key: impl Into<String>, value: impl Into<Value>) -> Self {
71 self.meta.insert(key.into(), value.into());
72 self
73 }
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
77pub enum CatalogError {
78 #[error("chave inválida '{0}': use segmentos [a-z0-9_] separados por ponto")]
79 InvalidKey(String),
80 #[error("chave duplicada '{0}'")]
81 DuplicateKey(String),
82 #[error("'{key}' é implicada por chave inexistente '{parent}'")]
83 UnknownParent { key: String, parent: String },
84 #[error("'{key}' mira tipo de alvo não registrado '{target}'")]
85 UnknownTarget { key: String, target: String },
86 #[error("'{0}' não declara nenhum alvo")]
87 NoTargets(String),
88 #[error("ciclo de implicação: {}", .0.join(" -> "))]
89 Cycle(Vec<String>),
90 #[error("'{key}' viola a regra {rule}: {message}")]
91 Rule { rule: String, key: String, message: String },
92}
93
94#[derive(Debug, Clone, PartialEq, Eq)]
96pub struct CatalogErrors(pub Vec<CatalogError>);
97
98impl fmt::Display for CatalogErrors {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 writeln!(f, "catálogo inválido ({} erro(s)):", self.0.len())?;
101 for error in &self.0 {
102 writeln!(f, " - {error}")?;
103 }
104 Ok(())
105 }
106}
107
108impl std::error::Error for CatalogErrors {}
109
110pub trait CatalogRule {
113 fn name(&self) -> &str;
114 fn check(&self, def: &PermissionDef) -> Option<String>;
116}
117
118#[derive(Debug, Clone)]
121pub struct RequireMeta {
122 name: String,
123 meta: String,
124 suffix: Option<String>,
125 allowed: Vec<Value>,
126}
127
128impl RequireMeta {
129 pub fn new(meta: impl Into<String>) -> Self {
130 let meta = meta.into();
131 Self {
132 name: format!("require_meta:{meta}"),
133 meta,
134 suffix: None,
135 allowed: Vec::new(),
136 }
137 }
138
139 pub fn for_suffix(mut self, suffix: impl Into<String>) -> Self {
140 self.suffix = Some(suffix.into());
141 self
142 }
143
144 pub fn one_of<I, V>(mut self, values: I) -> Self
145 where
146 I: IntoIterator<Item = V>,
147 V: Into<Value>,
148 {
149 self.allowed = values.into_iter().map(Into::into).collect();
150 self
151 }
152}
153
154impl CatalogRule for RequireMeta {
155 fn name(&self) -> &str {
156 &self.name
157 }
158
159 fn check(&self, def: &PermissionDef) -> Option<String> {
160 if self.suffix.as_ref().is_some_and(|s| !def.key.ends_with(s.as_str())) {
161 return None;
162 }
163 match def.meta.get(&self.meta) {
164 None => Some(format!("falta o metadado '{}'", self.meta)),
165 Some(value) if !self.allowed.is_empty() && !self.allowed.contains(value) => {
166 Some(format!("'{}' fora dos valores aceitos: {value:?}", self.meta))
167 }
168 Some(_) => None,
169 }
170 }
171}
172
173pub struct FnRule<F> {
175 name: String,
176 f: F,
177}
178
179impl<F: Fn(&PermissionDef) -> Option<String>> FnRule<F> {
180 pub fn new(name: impl Into<String>, f: F) -> Self {
181 Self { name: name.into(), f }
182 }
183}
184
185impl<F: Fn(&PermissionDef) -> Option<String>> CatalogRule for FnRule<F> {
186 fn name(&self) -> &str {
187 &self.name
188 }
189
190 fn check(&self, def: &PermissionDef) -> Option<String> {
191 (self.f)(def)
192 }
193}
194
195#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
197#[serde(rename_all = "camelCase")]
198pub struct CatalogExport {
199 pub target_kinds: Vec<String>,
200 #[serde(default)]
201 pub broad_targets: Vec<String>,
202 pub permissions: Vec<PermissionDef>,
203}
204
205#[derive(Default)]
206pub struct CatalogBuilder {
207 target_kinds: Vec<String>,
208 broad_targets: Vec<String>,
209 rules: Vec<Box<dyn CatalogRule>>,
210 defs: Vec<PermissionDef>,
211}
212
213impl fmt::Debug for CatalogBuilder {
214 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
215 f.debug_struct("CatalogBuilder")
216 .field("target_kinds", &self.target_kinds)
217 .field("broad_targets", &self.broad_targets)
218 .field("rules", &self.rules.iter().map(|r| r.name()).collect::<Vec<_>>())
219 .field("defs", &self.defs.len())
220 .finish()
221 }
222}
223
224impl CatalogBuilder {
225 pub fn target_kind(mut self, kind: impl Into<String>) -> Self {
226 self.target_kinds.push(kind.into());
227 self
228 }
229
230 pub fn target_kinds<I, S>(mut self, kinds: I) -> Self
231 where
232 I: IntoIterator<Item = S>,
233 S: Into<String>,
234 {
235 self.target_kinds.extend(kinds.into_iter().map(Into::into));
236 self
237 }
238
239 pub fn broad_target(mut self, kind: impl Into<String>) -> Self {
242 self.broad_targets.push(kind.into());
243 self
244 }
245
246 pub fn rule(mut self, rule: impl CatalogRule + 'static) -> Self {
247 self.rules.push(Box::new(rule));
248 self
249 }
250
251 pub fn permission(mut self, def: PermissionDef) -> Self {
252 self.defs.push(def);
253 self
254 }
255
256 pub fn permissions(mut self, defs: impl IntoIterator<Item = PermissionDef>) -> Self {
258 self.defs.extend(defs);
259 self
260 }
261
262 pub fn build(self) -> Result<Catalog, CatalogErrors> {
263 let mut broad_targets: BTreeSet<String> = self.broad_targets.into_iter().collect();
264 broad_targets.insert(GLOBAL.to_string());
265 let mut target_kinds: BTreeSet<String> = self.target_kinds.into_iter().collect();
266 target_kinds.extend(broad_targets.iter().cloned());
267
268 let mut errors = Vec::new();
269 let mut index = HashMap::new();
270 for (i, def) in self.defs.iter().enumerate() {
271 if !valid_key(&def.key) {
272 errors.push(CatalogError::InvalidKey(def.key.clone()));
273 }
274 if index.insert(def.key.clone(), i).is_some() {
275 errors.push(CatalogError::DuplicateKey(def.key.clone()));
276 }
277 if def.targets.is_empty() {
278 errors.push(CatalogError::NoTargets(def.key.clone()));
279 }
280 for target in def.targets.iter().filter(|t| !target_kinds.contains(*t)) {
281 errors.push(CatalogError::UnknownTarget {
282 key: def.key.clone(),
283 target: target.clone(),
284 });
285 }
286 for rule in &self.rules {
287 if let Some(message) = rule.check(def) {
288 errors.push(CatalogError::Rule {
289 rule: rule.name().to_string(),
290 key: def.key.clone(),
291 message,
292 });
293 }
294 }
295 }
296 for def in &self.defs {
297 for parent in def.implied_by.iter().filter(|p| !index.contains_key(*p)) {
298 errors.push(CatalogError::UnknownParent {
299 key: def.key.clone(),
300 parent: parent.clone(),
301 });
302 }
303 }
304 if !errors.is_empty() {
305 return Err(CatalogErrors(errors));
306 }
307
308 let parents: BTreeMap<String, Vec<String>> = self
309 .defs
310 .iter()
311 .map(|d| (d.key.clone(), d.implied_by.clone()))
312 .collect();
313 if let Some(cycle) = graph::find_cycle(&parents) {
314 return Err(CatalogErrors(vec![CatalogError::Cycle(cycle)]));
315 }
316 let effective = parents
317 .keys()
318 .map(|k| (k.clone(), graph::reachable(k, &parents)))
319 .collect();
320
321 let mut children: BTreeMap<String, Vec<String>> = BTreeMap::new();
322 for def in &self.defs {
323 for parent in &def.implied_by {
324 children.entry(parent.clone()).or_default().push(def.key.clone());
325 }
326 }
327
328 Ok(Catalog {
329 defs: self.defs,
330 index,
331 effective,
332 children,
333 target_kinds,
334 broad_targets,
335 })
336 }
337}
338
339fn valid_key(key: &str) -> bool {
340 !key.is_empty()
341 && key.split('.').all(|segment| {
342 !segment.is_empty()
343 && segment
344 .chars()
345 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '_')
346 })
347}
348
349#[derive(Debug, Clone)]
351pub struct Catalog {
352 defs: Vec<PermissionDef>,
353 index: HashMap<String, usize>,
354 effective: HashMap<String, BTreeSet<String>>,
355 children: BTreeMap<String, Vec<String>>,
356 target_kinds: BTreeSet<String>,
357 broad_targets: BTreeSet<String>,
358}
359
360impl Catalog {
361 pub fn builder() -> CatalogBuilder {
362 CatalogBuilder::default()
363 }
364
365 pub fn builder_from(export: CatalogExport) -> CatalogBuilder {
367 let mut builder = Self::builder().target_kinds(export.target_kinds);
368 for kind in export.broad_targets {
369 builder = builder.broad_target(kind);
370 }
371 builder.permissions(export.permissions)
372 }
373
374 pub fn from_export(export: CatalogExport) -> Result<Self, CatalogErrors> {
375 Self::builder_from(export).build()
376 }
377
378 pub fn export(&self) -> CatalogExport {
379 CatalogExport {
380 target_kinds: self.target_kinds.iter().cloned().collect(),
381 broad_targets: self.broad_targets.iter().cloned().collect(),
382 permissions: self.defs.clone(),
383 }
384 }
385
386 pub fn get(&self, key: &str) -> Option<&PermissionDef> {
387 self.index.get(key).map(|i| &self.defs[*i])
388 }
389
390 pub fn contains(&self, key: &str) -> bool {
391 self.index.contains_key(key)
392 }
393
394 pub fn all(&self) -> &[PermissionDef] {
395 &self.defs
396 }
397
398 pub fn len(&self) -> usize {
399 self.defs.len()
400 }
401
402 pub fn is_empty(&self) -> bool {
403 self.defs.is_empty()
404 }
405
406 pub fn effective(&self, key: &str) -> Option<&BTreeSet<String>> {
408 self.effective.get(key)
409 }
410
411 pub fn implies(&self, general: &str, specific: &str) -> bool {
413 self.effective(specific).is_some_and(|set| set.contains(general))
414 }
415
416 pub fn children(&self, key: &str) -> &[String] {
418 self.children.get(key).map(Vec::as_slice).unwrap_or(&[])
419 }
420
421 pub fn descendants(&self, key: &str) -> BTreeSet<String> {
423 let mut set = graph::reachable(key, &self.children);
424 set.remove(key);
425 set
426 }
427
428 pub fn is_target_kind(&self, kind: &str) -> bool {
429 self.target_kinds.contains(kind)
430 }
431
432 pub fn is_broad_target(&self, kind: &str) -> bool {
433 self.broad_targets.contains(kind)
434 }
435
436 pub fn allows_target(&self, key: &str, kind: &str) -> bool {
438 self.is_broad_target(kind) || self.get(key).is_some_and(|d| d.targets.iter().any(|t| t == kind))
439 }
440}
441
442#[cfg(test)]
443mod tests {
444 use super::*;
445
446 fn base() -> CatalogBuilder {
447 Catalog::builder()
448 .target_kinds(["project", "document"])
449 .broad_target("org")
450 }
451
452 #[test]
453 fn effective_contains_key_and_ancestors() {
454 let cat = base()
455 .permission(PermissionDef::new("project.view").targets(["project"]))
456 .permission(
457 PermissionDef::new("document.view")
458 .targets(["project"])
459 .implied_by(["project.view"]),
460 )
461 .permission(
462 PermissionDef::new("document.report.view")
463 .targets(["document"])
464 .implied_by(["document.view"]),
465 )
466 .build()
467 .unwrap();
468 let eff = cat.effective("document.report.view").unwrap();
469 assert_eq!(eff.len(), 3);
470 assert!(cat.implies("project.view", "document.report.view"));
471 assert!(!cat.implies("document.report.view", "project.view"));
472 assert_eq!(cat.descendants("project.view").len(), 2);
473 assert_eq!(cat.children("project.view"), ["document.view"]);
474 }
475
476 #[test]
477 fn collects_every_error() {
478 let errors = base()
479 .rule(
480 RequireMeta::new("visibility")
481 .for_suffix(".view")
482 .one_of(["hide", "redact"]),
483 )
484 .permission(PermissionDef::new("Bad Key").targets(["project"]))
485 .permission(
486 PermissionDef::new("a.edit")
487 .targets(["nowhere"])
488 .implied_by(["missing"]),
489 )
490 .permission(PermissionDef::new("a.edit").targets(["project"]))
491 .permission(PermissionDef::new("a.view").targets(["project"]))
492 .permission(
493 PermissionDef::new("b.view")
494 .targets(["project"])
495 .meta("visibility", "blur"),
496 )
497 .permission(PermissionDef::new("a.run"))
498 .build()
499 .unwrap_err();
500 let has = |pred: fn(&CatalogError) -> bool| errors.0.iter().any(pred);
501 assert!(has(|e| matches!(e, CatalogError::InvalidKey(_))));
502 assert!(has(|e| matches!(e, CatalogError::DuplicateKey(_))));
503 assert!(has(|e| matches!(e, CatalogError::UnknownTarget { .. })));
504 assert!(has(|e| matches!(e, CatalogError::UnknownParent { .. })));
505 assert!(has(|e| matches!(e, CatalogError::NoTargets(_))));
506 let rule_errors: Vec<_> = errors
507 .0
508 .iter()
509 .filter_map(|e| match e {
510 CatalogError::Rule { key, .. } => Some(key.as_str()),
511 _ => None,
512 })
513 .collect();
514 assert_eq!(rule_errors, ["a.view", "b.view"]);
515 }
516
517 #[test]
518 fn closure_rule() {
519 let errors = base()
520 .rule(FnRule::new("has_label", |def: &PermissionDef| {
521 def.label.is_none().then(|| "sem rótulo".to_string())
522 }))
523 .permission(PermissionDef::new("a.edit").targets(["project"]))
524 .build()
525 .unwrap_err();
526 assert!(matches!(&errors.0[..], [CatalogError::Rule { rule, .. }] if rule == "has_label"));
527 }
528
529 #[test]
530 fn rejects_implication_cycle() {
531 let errors = base()
532 .permission(PermissionDef::new("a.x").targets(["project"]).implied_by(["a.y"]))
533 .permission(PermissionDef::new("a.y").targets(["project"]).implied_by(["a.x"]))
534 .build()
535 .unwrap_err();
536 assert!(matches!(errors.0.as_slice(), [CatalogError::Cycle(_)]));
537 }
538
539 #[test]
540 fn broad_targets_accept_any_permission() {
541 let cat = base()
542 .permission(PermissionDef::new("a.edit").targets(["project"]))
543 .build()
544 .unwrap();
545 assert!(cat.allows_target("a.edit", "org"));
546 assert!(cat.allows_target("a.edit", GLOBAL));
547 assert!(!cat.allows_target("a.edit", "document"));
548 }
549
550 #[test]
551 fn export_round_trip() {
552 let cat = base()
553 .permission(
554 PermissionDef::new("a.edit")
555 .targets(["project"])
556 .label("Editar")
557 .meta("group", "a"),
558 )
559 .build()
560 .unwrap();
561 let json = serde_json::to_string(&cat.export()).unwrap();
562 let back = Catalog::from_export(serde_json::from_str(&json).unwrap()).unwrap();
563 assert_eq!(back.export(), cat.export());
564 }
565}