Skip to main content

gent_protocol/
administration.rs

1//! Scoped permission administration. Grants never confer discovery or further
2//! delegation. Endpoints must authenticate the administrator and peer visibility.
3use super::*;
4
5pub const MAX_ADMIN_GRANT_LIFETIME: u64 = 7 * 24 * 60 * 60;
6pub const MAX_PERMISSION_CHANGES: usize = 32;
7
8#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
9#[serde(rename_all = "snake_case")]
10pub enum GroupAction {
11    Add,
12    Remove,
13}
14
15/// Membership authority affects every policy use of this group, including
16/// existing administration scopes. It never creates or modifies another grant.
17#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
18#[serde(deny_unknown_fields)]
19pub struct GroupAdminGrant {
20    pub administrator: String,
21    pub group: String,
22    /// SameNode compares a candidate member with the administrator's node.
23    pub members: Selector,
24    pub actions: Vec<GroupAction>,
25    pub issued_at: u64,
26    pub expires_at: u64,
27}
28
29#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
30#[serde(deny_unknown_fields)]
31pub struct GroupChange {
32    pub grant_id: String,
33    pub group: String,
34    pub member: String,
35    pub action: GroupAction,
36}
37
38#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
39#[serde(deny_unknown_fields)]
40pub struct AdminGrant {
41    pub administrator: String,
42    pub actor: Selector,
43    pub peer: Selector,
44    pub permissions: Vec<Permission>,
45    /// Separate opt-in to manage selector rules, including future matches.
46    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
47    pub selector_rules: bool,
48    pub issued_at: u64,
49    pub expires_at: u64,
50}
51
52#[cfg(test)]
53mod tests;
54
55#[derive(Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq)]
56#[serde(rename_all = "snake_case")]
57pub enum RuleDecision {
58    Allow,
59    Deny,
60    Inherit,
61}
62
63#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
64#[serde(deny_unknown_fields)]
65pub struct PermissionChange {
66    pub grant_id: String,
67    pub actor: String,
68    pub peer: String,
69    pub permission: Permission,
70    pub decision: RuleDecision,
71}
72
73#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
74#[serde(deny_unknown_fields)]
75pub struct PermissionRuleChange {
76    pub grant_id: String,
77    pub actor: Selector,
78    pub peer: Selector,
79    pub permission: Permission,
80    pub decision: RuleDecision,
81}
82
83impl Policy {
84    pub fn group_admin_allows(
85        &self,
86        grant: &GroupAdminGrant,
87        administrator: &Agent,
88        member: &Agent,
89        action: GroupAction,
90        now: u64,
91    ) -> bool {
92        !administrator.revoked
93            && !member.revoked
94            && grant.administrator == administrator.id
95            && grant.issued_at <= now
96            && now < grant.expires_at
97            && grant.actions.contains(&action)
98            && self.matches(&grant.members, member, administrator)
99    }
100
101    pub fn admin_allows(
102        &self,
103        grant: &AdminGrant,
104        administrator: &Agent,
105        actor: &Agent,
106        peer: &Agent,
107        permission: Permission,
108        now: u64,
109    ) -> bool {
110        !administrator.revoked
111            && !actor.revoked
112            && !peer.revoked
113            && actor.id != peer.id
114            && grant.administrator == administrator.id
115            && grant.issued_at <= now
116            && now < grant.expires_at
117            && grant.permissions.contains(&permission)
118            && self.matches(&grant.actor, actor, peer)
119            && self.matches(&grant.peer, peer, actor)
120    }
121
122    /// Caller must authenticate and validate the ENTIRE batch against the
123    /// original policy before invoking this. Only exact chat-pair rules change.
124    pub fn apply_permission_changes(&mut self, changes: &[PermissionChange]) {
125        for change in changes {
126            self.replace_rule(
127                Selector::Agent(change.actor.clone()),
128                Selector::Agent(change.peer.clone()),
129                change.permission,
130                change.decision,
131            );
132        }
133    }
134    pub fn apply_permission_rules(&mut self, changes: &[PermissionRuleChange]) {
135        for change in changes {
136            self.replace_rule(
137                change.actor.clone(),
138                change.peer.clone(),
139                change.permission,
140                change.decision,
141            );
142        }
143    }
144    fn replace_rule(
145        &mut self,
146        actor: Selector,
147        peer: Selector,
148        permission: Permission,
149        decision: RuleDecision,
150    ) {
151        self.rules
152            .retain(|r| r.actor != actor || r.peer != peer || r.permission != permission);
153        let effect = match decision {
154            RuleDecision::Allow => Some(Effect::Allow),
155            RuleDecision::Deny => Some(Effect::Deny),
156            RuleDecision::Inherit => None,
157        };
158        if let Some(effect) = effect {
159            self.rules.push(Rule {
160                actor,
161                peer,
162                permission,
163                effect,
164            });
165        }
166    }
167    pub fn admin_allows_rule(
168        &self,
169        grant: &AdminGrant,
170        administrator: &Agent,
171        change: &PermissionRuleChange,
172        known: &BTreeMap<String, Agent>,
173        now: u64,
174    ) -> bool {
175        !administrator.revoked
176            && grant.administrator == administrator.id
177            && grant.selector_rules
178            && grant.issued_at <= now
179            && now < grant.expires_at
180            && grant.permissions.contains(&change.permission)
181            && self.selector_within(&grant.actor, &change.actor, &change.peer, known)
182            && self.selector_within(&grant.peer, &change.peer, &change.actor, known)
183    }
184    fn selector_within(
185        &self,
186        scope: &Selector,
187        subject: &Selector,
188        other: &Selector,
189        known: &BTreeMap<String, Agent>,
190    ) -> bool {
191        if *scope == Selector::All || scope == subject {
192            return true;
193        }
194        match (scope, subject) {
195            (Selector::Node(node), Selector::Agent(id)) => {
196                known.get(id).is_some_and(|a| a.node_id == *node)
197            }
198            (Selector::Group(group), Selector::Agent(id)) => self
199                .groups
200                .get(group)
201                .is_some_and(|members| members.contains(id)),
202            (Selector::SameNode, _) => {
203                if *other == Selector::SameNode {
204                    return true;
205                }
206                let node = |selector: &Selector| match selector {
207                    Selector::Node(id) => Some(id.clone()),
208                    Selector::Agent(id) => known.get(id).map(|a| a.node_id.clone()),
209                    _ => None,
210                };
211                node(subject).is_some_and(|n| Some(n) == node(other))
212            }
213            _ => false,
214        }
215    }
216}