Skip to main content

logicaffeine_language/analysis/
policy.rs

1//! Security Policy Registry.
2//!
3//! Stores predicate and capability definitions parsed from `## Policy` blocks.
4//! These are used to generate security methods on structs and enforce them
5//! with the `Check` statement.
6
7use logicaffeine_base::Symbol;
8use std::collections::HashMap;
9
10/// Condition in a policy definition.
11/// Represents the predicate logic for security rules.
12#[derive(Debug, Clone)]
13pub enum PolicyCondition {
14    /// Field comparison: `the user's role equals "admin"`
15    FieldEquals {
16        field: Symbol,
17        value: Symbol,
18        /// Whether the value came from a string literal (needs quotes in codegen)
19        is_string_literal: bool,
20    },
21    /// Boolean field: `the user's verified equals true`
22    FieldBool { field: Symbol, value: bool },
23    /// Predicate call: `the user is admin`
24    Predicate { subject: Symbol, predicate: Symbol },
25    /// Whole-subject vs object field: `the user equals the document's owner`
26    /// (the object field shares the subject's type). Compiles to `self == &object.field`.
27    ObjectFieldEquals {
28        subject: Symbol,
29        object: Symbol,
30        field: Symbol,
31    },
32    /// Cross-field comparison: `the user's name equals the document's owner`.
33    /// Compiles to `self.<subject_field> == <object>.<object_field>`.
34    SubjectFieldEqualsObjectField {
35        subject_field: Symbol,
36        object: Symbol,
37        object_field: Symbol,
38    },
39    /// Logical OR: `A OR B`
40    Or(Box<PolicyCondition>, Box<PolicyCondition>),
41    /// Logical AND: `A AND B`
42    And(Box<PolicyCondition>, Box<PolicyCondition>),
43}
44
45/// A predicate definition: `A User is admin if the user's role equals "admin".`
46#[derive(Debug, Clone)]
47pub struct PredicateDef {
48    /// The type this predicate applies to (e.g., "User")
49    pub subject_type: Symbol,
50    /// The predicate name (e.g., "admin")
51    pub predicate_name: Symbol,
52    /// The condition that must be true
53    pub condition: PolicyCondition,
54}
55
56/// A capability definition: `A User can publish the Document if...`
57#[derive(Debug, Clone)]
58pub struct CapabilityDef {
59    /// The type that has this capability (e.g., "User")
60    pub subject_type: Symbol,
61    /// The action name (e.g., "publish")
62    pub action: Symbol,
63    /// The object type the action applies to (e.g., "Document")
64    pub object_type: Symbol,
65    /// The condition that must be true
66    pub condition: PolicyCondition,
67}
68
69/// Registry for security policies defined in `## Policy` blocks.
70#[derive(Debug, Default, Clone)]
71pub struct PolicyRegistry {
72    /// Predicates indexed by subject type
73    predicates: HashMap<Symbol, Vec<PredicateDef>>,
74    /// Capabilities indexed by subject type
75    capabilities: HashMap<Symbol, Vec<CapabilityDef>>,
76}
77
78impl PolicyRegistry {
79    pub fn new() -> Self {
80        Self::default()
81    }
82
83    /// Register a predicate definition
84    pub fn register_predicate(&mut self, def: PredicateDef) {
85        self.predicates
86            .entry(def.subject_type)
87            .or_insert_with(Vec::new)
88            .push(def);
89    }
90
91    /// Register a capability definition
92    pub fn register_capability(&mut self, def: CapabilityDef) {
93        self.capabilities
94            .entry(def.subject_type)
95            .or_insert_with(Vec::new)
96            .push(def);
97    }
98
99    /// Get predicates for a type
100    pub fn get_predicates(&self, subject_type: Symbol) -> Option<&[PredicateDef]> {
101        self.predicates.get(&subject_type).map(|v| v.as_slice())
102    }
103
104    /// Get capabilities for a type
105    pub fn get_capabilities(&self, subject_type: Symbol) -> Option<&[CapabilityDef]> {
106        self.capabilities.get(&subject_type).map(|v| v.as_slice())
107    }
108
109    /// Check if a type has any predicates
110    pub fn has_predicates(&self, subject_type: Symbol) -> bool {
111        self.predicates.contains_key(&subject_type)
112    }
113
114    /// Check if a type has any capabilities
115    pub fn has_capabilities(&self, subject_type: Symbol) -> bool {
116        self.capabilities.contains_key(&subject_type)
117    }
118
119    /// Iterate over all types with predicates (for codegen)
120    pub fn iter_predicates(&self) -> impl Iterator<Item = (&Symbol, &Vec<PredicateDef>)> {
121        self.predicates.iter()
122    }
123
124    /// Iterate over all types with capabilities (for codegen)
125    pub fn iter_capabilities(&self) -> impl Iterator<Item = (&Symbol, &Vec<CapabilityDef>)> {
126        self.capabilities.iter()
127    }
128
129    /// Check if registry has any policies
130    pub fn is_empty(&self) -> bool {
131        self.predicates.is_empty() && self.capabilities.is_empty()
132    }
133}
134
135#[cfg(test)]
136#[path = "../../../logicaffeine_tests/unit/logicaffeine_language/analysis/policy/tests.rs"]
137mod tests;