kernel/permissions.rs
1// Copyright 2026 Mark AB (markik)
2// SPDX-License-Identifier: MIT OR Apache-2.0
3
4//! Settings/permissions scope hierarchy and the narrowing rule.
5//!
6//! Adopted from the donor `graphshell` `settings_and_permissions_spine_spec.md`
7//! (per the [adoption roadmap](../../../../../design_docs/mere_docs/implementation_strategy/2026-05-27_adoption_roadmap.md)
8//! R0). This is the host-agnostic *policy core*: the scope vocabulary plus the
9//! resolution rule. Storage of per-scope values and the host wiring that gates
10//! surfaces/mods consume this; they are not here.
11//!
12//! ## The five scopes
13//!
14//! [`SettingScope`] is a hierarchy from broadest to narrowest, grounded in
15//! Mere's own structure (a persona owns sessions; a session/window hosts graphs;
16//! a graph hosts surfaces/tiles):
17//!
18//! 1. `App` — installation-wide defaults.
19//! 2. `Persona` — one human's persona (work / research / throwaway).
20//! 3. `Session` — a session, i.e. a graph-shaped window.
21//! 4. `Graph` — a specific graph (orrery / moot) within a session.
22//! 5. `Surface` — a tile / pane / surface within a graph.
23//!
24//! The same hierarchy serves *settings* (where the narrower scope simply
25//! overrides) and *permissions* (where the narrower scope may only narrow).
26//! This module implements the **permission** resolution; a settings-override
27//! resolver is a future sibling that reuses [`SettingScope`].
28//!
29//! ## The narrowing rule (the R0 invariant)
30//!
31//! **A narrower scope can only narrow a permission, never broaden it.** No
32//! persona, session, graph, or surface can grant itself more than a broader
33//! scope allows. This is defense in depth: tighten centrally and trust that
34//! nothing downstream loosens it.
35//!
36//! The rule is enforced *structurally*, not by convention: [`resolve_permission`]
37//! returns the **most restrictive** opinion across the chain
38//! (`Allow` < `Prompt` < `Deny`). Because resolution is a maximum over
39//! restrictiveness, a narrower scope's `Allow` can never override a broader
40//! scope's `Deny` — there is no code path that broadens.
41//!
42//! This supersedes the earlier capability-gate-catalogue "first-match-wins"
43//! framing for permissions (first-match can let an earlier, broader opinion win
44//! over a stricter later one — wrong direction for security). `RequireConsent`
45//! from that brief is preserved as the [`Permission::Prompt`] middle state.
46
47use serde::{Deserialize, Serialize};
48
49/// The scope a setting or permission is declared at, broadest to narrowest.
50/// The discriminant order *is* the breadth order (`App` broadest).
51#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
52pub enum SettingScope {
53 App,
54 Persona,
55 Session,
56 Graph,
57 Surface,
58}
59
60impl SettingScope {
61 /// The scopes broadest-to-narrowest. Callers assemble a permission chain in
62 /// this order (omitting scopes with no opinion, or marking them
63 /// [`Permission::Inherit`]).
64 pub const BROAD_TO_NARROW: [SettingScope; 5] = [
65 Self::App,
66 Self::Persona,
67 Self::Session,
68 Self::Graph,
69 Self::Surface,
70 ];
71}
72
73/// A permission opinion at one scope.
74///
75/// Restrictiveness orders `Allow` < `Prompt` < `Deny`; [`Inherit`](Self::Inherit)
76/// is "no opinion, defer to the rest of the chain".
77#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
78pub enum Permission {
79 /// No opinion at this scope; defer to other scopes (and the default).
80 Inherit,
81 /// Permitted (unless a scope narrows it).
82 Allow,
83 /// Permitted only after explicit user consent (the capability-gate brief's
84 /// `RequireConsent`). More restrictive than `Allow`, less than `Deny`.
85 Prompt,
86 /// Forbidden. The most restrictive opinion; no scope can broaden past it.
87 Deny,
88}
89
90impl Permission {
91 /// Restrictiveness rank for resolution. `None` for [`Self::Inherit`]
92 /// (excluded from the maximum). Higher = more restrictive.
93 fn restrictiveness(self) -> Option<u8> {
94 match self {
95 Self::Inherit => None,
96 Self::Allow => Some(0),
97 Self::Prompt => Some(1),
98 Self::Deny => Some(2),
99 }
100 }
101}
102
103/// One scope's opinion in a resolution chain.
104#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
105pub struct ScopedPermission {
106 pub scope: SettingScope,
107 pub permission: Permission,
108}
109
110impl ScopedPermission {
111 pub fn new(scope: SettingScope, permission: Permission) -> Self {
112 Self { scope, permission }
113 }
114}
115
116/// The outcome of [`resolve_permission`].
117#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
118pub struct ResolvedPermission {
119 /// The effective permission after applying the narrowing rule. Never
120 /// [`Permission::Inherit`] (Inherit folds into the default).
121 pub effective: Permission,
122 /// The scope whose opinion decided the result, if any opinion was expressed
123 /// (the narrowest scope among the most-restrictive opinions). `None` when
124 /// every scope inherited and the default applied.
125 pub decided_by: Option<SettingScope>,
126}
127
128/// Resolve a permission across a scope `chain` per the narrowing rule: the
129/// effective permission is the **most restrictive** non-[`Permission::Inherit`]
130/// opinion in the chain. `default` applies when every scope inherits.
131///
132/// `chain` should be ordered broadest-to-narrowest (see
133/// [`SettingScope::BROAD_TO_NARROW`]); among equally-restrictive opinions the
134/// narrowest (latest) is reported as `decided_by`, which is the most useful one
135/// to surface to the user ("denied for this tile").
136pub fn resolve_permission(chain: &[ScopedPermission], default: Permission) -> ResolvedPermission {
137 let winner = chain
138 .iter()
139 .filter(|scoped| scoped.permission.restrictiveness().is_some())
140 .max_by_key(|scoped| scoped.permission.restrictiveness().unwrap_or(0));
141
142 match winner {
143 Some(scoped) => ResolvedPermission {
144 effective: scoped.permission,
145 decided_by: Some(scoped.scope),
146 },
147 None => ResolvedPermission {
148 effective: default,
149 decided_by: None,
150 },
151 }
152}
153
154#[cfg(test)]
155mod tests {
156 use super::*;
157 use SettingScope::*;
158
159 fn chain(items: &[(SettingScope, Permission)]) -> Vec<ScopedPermission> {
160 items
161 .iter()
162 .map(|&(scope, permission)| ScopedPermission::new(scope, permission))
163 .collect()
164 }
165
166 #[test]
167 fn narrower_deny_overrides_broader_allow() {
168 let c = chain(&[(App, Permission::Allow), (Session, Permission::Deny)]);
169 let r = resolve_permission(&c, Permission::Allow);
170 assert_eq!(r.effective, Permission::Deny);
171 assert_eq!(r.decided_by, Some(Session));
172 }
173
174 #[test]
175 fn narrower_allow_cannot_broaden_a_broader_deny() {
176 // The crux of the narrowing rule: a Surface saying Allow does NOT
177 // override an App-level Deny.
178 let c = chain(&[(App, Permission::Deny), (Surface, Permission::Allow)]);
179 let r = resolve_permission(&c, Permission::Allow);
180 assert_eq!(
181 r.effective,
182 Permission::Deny,
183 "narrower scope broadened a Deny"
184 );
185 assert_eq!(r.decided_by, Some(App));
186 }
187
188 #[test]
189 fn prompt_sits_between_allow_and_deny() {
190 let c = chain(&[(App, Permission::Allow), (Persona, Permission::Prompt)]);
191 assert_eq!(
192 resolve_permission(&c, Permission::Allow).effective,
193 Permission::Prompt
194 );
195
196 // ...but Deny still wins over Prompt.
197 let c = chain(&[(Persona, Permission::Prompt), (Graph, Permission::Deny)]);
198 assert_eq!(
199 resolve_permission(&c, Permission::Allow).effective,
200 Permission::Deny
201 );
202 }
203
204 #[test]
205 fn all_inherit_falls_back_to_default() {
206 let c = chain(&[(App, Permission::Inherit), (Session, Permission::Inherit)]);
207 let r = resolve_permission(&c, Permission::Prompt);
208 assert_eq!(r.effective, Permission::Prompt);
209 assert_eq!(r.decided_by, None);
210 }
211
212 #[test]
213 fn decided_by_is_the_narrowest_among_equally_restrictive() {
214 // Two Denies: the narrower (Surface) is the more useful explanation.
215 let c = chain(&[(Session, Permission::Deny), (Surface, Permission::Deny)]);
216 assert_eq!(
217 resolve_permission(&c, Permission::Allow).decided_by,
218 Some(Surface)
219 );
220 }
221
222 #[test]
223 fn scopes_are_ordered_broad_to_narrow() {
224 assert!(App < Persona && Persona < Session && Session < Graph && Graph < Surface);
225 assert_eq!(SettingScope::BROAD_TO_NARROW.len(), 5);
226 }
227}