Skip to main content

kernel/
permissions.rs

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