Skip to main content

kian_plugin/hooks/
grants.rs

1//! Capability grants (PLUGIN-SPEC §5).
2//!
3//! The v1 closed set is eight grants; `mutate:*` names are **reserved**
4//! and refused (`unknown_capability`-shaped) so a future transform grammar
5//! cannot silently inherit today's configurations (§5.1, D2 as amended).
6//! A `veto:*` grant implies the matching `observe:*` and is refused
7//! without it — a handler cannot veto what it does not receive.
8//!
9//! [`GrantSet::from_names`] is the single constructor enforcing both
10//! rules, so the sidecar manifest validation (§6.2 rules 9/10) and the
11//! per-worker resolution (§8) both call it instead of re-deriving the
12//! checks.
13
14use std::collections::BTreeSet;
15
16use thiserror::Error;
17
18use super::ids::{HookClass, HookId, HookMode};
19
20/// One capability of the closed v1 grant set (§5.1).
21#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
22pub enum Grant {
23    ObserveAdmit,
24    ObserveTurn,
25    ObserveTool,
26    ObserveRecover,
27    ObserveSettle,
28    VetoAdmit,
29    VetoTool,
30    VetoSettle,
31}
32
33impl Grant {
34    pub fn as_str(self) -> &'static str {
35        match self {
36            Grant::ObserveAdmit => "observe:admit",
37            Grant::ObserveTurn => "observe:turn",
38            Grant::ObserveTool => "observe:tool",
39            Grant::ObserveRecover => "observe:recover",
40            Grant::ObserveSettle => "observe:settle",
41            Grant::VetoAdmit => "veto:admit",
42            Grant::VetoTool => "veto:tool",
43            Grant::VetoSettle => "veto:settle",
44        }
45    }
46}
47
48impl std::fmt::Display for Grant {
49    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
50        f.write_str(self.as_str())
51    }
52}
53
54impl Grant {
55    /// Parses a grant name; `None` for anything outside the closed set —
56    /// including the reserved `mutate:*` names (§5.1).
57    pub fn parse(name: &str) -> Option<Self> {
58        match name {
59            "observe:admit" => Some(Grant::ObserveAdmit),
60            "observe:turn" => Some(Grant::ObserveTurn),
61            "observe:tool" => Some(Grant::ObserveTool),
62            "observe:recover" => Some(Grant::ObserveRecover),
63            "observe:settle" => Some(Grant::ObserveSettle),
64            "veto:admit" => Some(Grant::VetoAdmit),
65            "veto:tool" => Some(Grant::VetoTool),
66            "veto:settle" => Some(Grant::VetoSettle),
67            _ => None,
68        }
69    }
70
71    /// The `observe:*` grant a `veto:*` grant implies (§5.1); observe
72    /// grants imply themselves for the `covers` check.
73    pub fn implied_observe(self) -> Option<Grant> {
74        match self {
75            Grant::VetoAdmit => Some(Grant::ObserveAdmit),
76            Grant::VetoTool => Some(Grant::ObserveTool),
77            Grant::VetoSettle => Some(Grant::ObserveSettle),
78            grant @ (Grant::ObserveAdmit
79            | Grant::ObserveTurn
80            | Grant::ObserveTool
81            | Grant::ObserveRecover
82            | Grant::ObserveSettle) => Some(grant),
83        }
84    }
85}
86
87/// Named constructor failures (§5.1's two refusal shapes).
88#[derive(Debug, Clone, PartialEq, Eq, Error)]
89pub enum GrantError {
90    /// A name outside the closed set — including the reserved `mutate:*`
91    /// names, refused `unknown_capability`-shaped so a manifest cannot
92    /// name a capability the contract removed (§5.1).
93    #[error("unknown capability `{name}` (the v1 set is closed; `mutate:*` names are reserved)")]
94    UnknownCapability { name: String },
95    /// A `veto:*` grant without its matching `observe:*` (§5.1: a handler
96    /// cannot veto what it does not receive).
97    #[error("grant `{veto}` requires its matching `{observe}`")]
98    MissingObserve { veto: Grant, observe: Grant },
99}
100
101/// A validated set of grants (§5.1). Construction through
102/// [`GrantSet::from_names`] is the shared validator.
103#[derive(Debug, Clone, Default, PartialEq, Eq)]
104pub struct GrantSet(BTreeSet<Grant>);
105
106impl GrantSet {
107    /// Builds a grant set from wire names, enforcing both §5.1 rules:
108    /// every name must be in the closed set, and every `veto:*` must be
109    /// accompanied by its matching `observe:*`.
110    pub fn from_names(names: &[&str]) -> Result<Self, GrantError> {
111        let mut grants = BTreeSet::new();
112        for name in names {
113            let grant = Grant::parse(name).ok_or_else(|| GrantError::UnknownCapability {
114                name: (*name).to_string(),
115            })?;
116            if let Some(observe) = veto_requires(grant)
117                && !names_contains(names, observe)
118            {
119                return Err(GrantError::MissingObserve {
120                    veto: grant,
121                    observe,
122                });
123            }
124            grants.insert(grant);
125        }
126        Ok(Self(grants))
127    }
128
129    /// A set from already-validated grants (no re-validation; used where
130    /// the grants were constructed as typed values).
131    pub fn from_grants(grants: impl IntoIterator<Item = Grant>) -> Self {
132        Self(grants.into_iter().collect())
133    }
134
135    pub fn contains(&self, grant: Grant) -> bool {
136        self.0.contains(&grant)
137    }
138
139    pub fn is_empty(&self) -> bool {
140        self.0.is_empty()
141    }
142
143    pub fn iter(&self) -> impl Iterator<Item = Grant> + '_ {
144        self.0.iter().copied()
145    }
146
147    /// Whether the set's `observe:*` coverage includes `class` (§5.2's
148    /// boot check: every subscribed hook must be covered).
149    pub fn observes_class(&self, class: HookClass) -> bool {
150        match observe_grant_for_class(class) {
151            Some(grant) => self.contains(grant),
152            None => false,
153        }
154    }
155}
156
157impl IntoIterator for &GrantSet {
158    type Item = Grant;
159    type IntoIter = std::collections::btree_set::IntoIter<Grant>;
160
161    fn into_iter(self) -> Self::IntoIter {
162        self.0
163            .iter()
164            .copied()
165            .collect::<BTreeSet<Grant>>()
166            .into_iter()
167    }
168}
169
170fn veto_requires(grant: Grant) -> Option<Grant> {
171    grant.implied_observe().filter(|_| {
172        matches!(
173            grant,
174            Grant::VetoAdmit | Grant::VetoTool | Grant::VetoSettle
175        )
176    })
177}
178
179fn names_contains(names: &[&str], grant: Grant) -> bool {
180    names.iter().any(|n| *n == grant.as_str())
181}
182
183/// The `observe:*` grant covering a hook class (§5.1's "Requires
184/// subscription to" column). `None` for classes no observe grant covers
185/// (`Harness`, `Plugin` — neither is subscribable through grants in v1).
186pub fn observe_grant_for_class(class: HookClass) -> Option<Grant> {
187    match class {
188        HookClass::Admit => Some(Grant::ObserveAdmit),
189        HookClass::Turn => Some(Grant::ObserveTurn),
190        HookClass::Tool => Some(Grant::ObserveTool),
191        HookClass::Recover => Some(Grant::ObserveRecover),
192        HookClass::Settle => Some(Grant::ObserveSettle),
193        HookClass::Harness | HookClass::Plugin => None,
194    }
195}
196
197/// The `veto:*` grant that makes a hook's verdict reachable (§5.1, §11.1:
198/// a class default belongs to a `veto:*` grant, not to a hook id). `None`
199/// for classes with no veto-capable hook in v1.
200pub fn veto_grant_for_class(class: HookClass) -> Option<Grant> {
201    match class {
202        HookClass::Admit => Some(Grant::VetoAdmit),
203        HookClass::Tool => Some(Grant::VetoTool),
204        HookClass::Settle => Some(Grant::VetoSettle),
205        HookClass::Turn | HookClass::Recover | HookClass::Harness | HookClass::Plugin => None,
206    }
207}
208
209/// The reply → required-grant map (§3.3's "Capability required by the
210/// reply" column): which grant a reply variant must hold to be an opinion
211/// at all. `None` replies (ack / next / abstain) require none.
212///
213/// Takes the reply as a shape discriminator so both the tier-0 bus and
214/// the C3 sidecar frame decoder classify through one function.
215pub fn reply_required_grant(hook: &HookId, reply_shape: ReplyShape) -> Option<Grant> {
216    match reply_shape {
217        ReplyShape::Ack | ReplyShape::FlowNext | ReplyShape::BailNone => None,
218        ReplyShape::FlowStop => {
219            // Only `admit/pre` is a flow hook; a stop there is `veto:admit`.
220            match hook {
221                HookId::AdmitPre => Some(Grant::VetoAdmit),
222                _ => None,
223            }
224        }
225        ReplyShape::BailDeny => match hook {
226            HookId::ToolPre => Some(Grant::VetoTool),
227            HookId::SettlePre => Some(Grant::VetoSettle),
228            _ => None,
229        },
230    }
231}
232
233/// The shape of a reply, independent of its payload — the discriminator
234/// [`reply_required_grant`] and the mode check (§3.3) both classify on.
235#[derive(Debug, Clone, Copy, PartialEq, Eq)]
236pub enum ReplyShape {
237    Ack,
238    FlowNext,
239    FlowStop,
240    BailNone,
241    BailDeny,
242}
243
244impl ReplyShape {
245    /// Whether this shape is a legal reply at `mode` (§3.3's mode table;
246    /// wrong-mode replies are speech defects, §5.2).
247    pub fn legal_at(self, mode: HookMode) -> bool {
248        matches!(
249            (self, mode),
250            (ReplyShape::Ack, HookMode::Emit)
251                | (ReplyShape::FlowNext | ReplyShape::FlowStop, HookMode::Flow)
252                | (ReplyShape::BailNone | ReplyShape::BailDeny, HookMode::Bail)
253        )
254    }
255}
256
257#[cfg(test)]
258mod tests {
259    use super::*;
260
261    #[test]
262    fn reserved_mutate_names_are_refused() {
263        // §5.1: `mutate:*` names are reserved — refused as unknown
264        // capability, so a future transform grammar cannot silently
265        // inherit today's configurations.
266        for name in [
267            "mutate:context",
268            "mutate:admit",
269            "mutate:tool",
270            "mutate:whatever",
271        ] {
272            let err = GrantSet::from_names(&[name]).expect_err("{name} must be refused");
273            assert_eq!(
274                err,
275                GrantError::UnknownCapability {
276                    name: name.to_string()
277                },
278                "mutate names are unknown-capability shaped"
279            );
280        }
281        // And so is any other non-grant.
282        assert!(matches!(
283            GrantSet::from_names(&["sudo"]),
284            Err(GrantError::UnknownCapability { .. })
285        ));
286        assert!(GrantSet::from_names(&[]).unwrap().is_empty());
287    }
288
289    #[test]
290    fn veto_implies_observe() {
291        // §5.1: a `veto:*` grant is refused without its matching
292        // `observe:*` — both missing directions.
293        assert!(matches!(
294            GrantSet::from_names(&["veto:admit"]),
295            Err(GrantError::MissingObserve { .. })
296        ));
297        assert!(matches!(
298            GrantSet::from_names(&["veto:tool", "observe:admit"]),
299            Err(GrantError::MissingObserve { .. })
300        ));
301        // A veto does not satisfy another veto's requirement either.
302        assert!(matches!(
303            GrantSet::from_names(&["veto:settle", "veto:admit", "observe:admit"]),
304            Err(GrantError::MissingObserve { .. })
305        ));
306        // With the matching observe, each veto is accepted.
307        for ok in [
308            &["veto:admit", "observe:admit"][..],
309            &["veto:tool", "observe:tool"][..],
310            &["veto:settle", "observe:settle"][..],
311        ] {
312            GrantSet::from_names(ok).expect("veto with matching observe is valid");
313        }
314        // Observe alone is fine and covers its class.
315        let set = GrantSet::from_names(&["observe:tool"]).unwrap();
316        assert!(set.observes_class(HookClass::Tool));
317        assert!(!set.observes_class(HookClass::Admit));
318    }
319
320    #[test]
321    fn reply_requires_exactly_one_grant() {
322        // §3.3's table: exactly the veto rows require a grant; ack / next
323        // / abstain never do.
324        let admit_pre = HookId::parse("admit/pre").unwrap();
325        let tool_pre = HookId::parse("tool/pre").unwrap();
326        let settle_pre = HookId::parse("settle/pre").unwrap();
327        let turn_request = HookId::parse("turn/request").unwrap();
328
329        assert_eq!(
330            reply_required_grant(&admit_pre, ReplyShape::FlowStop),
331            Some(Grant::VetoAdmit)
332        );
333        assert_eq!(
334            reply_required_grant(&tool_pre, ReplyShape::BailDeny),
335            Some(Grant::VetoTool)
336        );
337        assert_eq!(
338            reply_required_grant(&settle_pre, ReplyShape::BailDeny),
339            Some(Grant::VetoSettle)
340        );
341        for (hook, shape) in [
342            (&admit_pre, ReplyShape::Ack),
343            (&admit_pre, ReplyShape::FlowNext),
344            (&admit_pre, ReplyShape::BailNone),
345            (&tool_pre, ReplyShape::BailNone),
346            (&settle_pre, ReplyShape::BailNone),
347            (&turn_request, ReplyShape::Ack),
348        ] {
349            assert_eq!(
350                reply_required_grant(hook, shape),
351                None,
352                "no-opinion reply requires no grant"
353            );
354        }
355        // A stop/deny at a hook that cannot carry it maps to no grant —
356        // the mode check classifies it as a wrong-mode defect instead.
357        assert_eq!(
358            reply_required_grant(&turn_request, ReplyShape::FlowStop),
359            None
360        );
361        assert_eq!(
362            reply_required_grant(&turn_request, ReplyShape::BailDeny),
363            None
364        );
365
366        // Mode legality (§3.3): only the mode's own reply shapes are legal.
367        assert!(ReplyShape::Ack.legal_at(HookMode::Emit));
368        assert!(!ReplyShape::Ack.legal_at(HookMode::Bail));
369        assert!(ReplyShape::FlowStop.legal_at(HookMode::Flow));
370        assert!(!ReplyShape::FlowStop.legal_at(HookMode::Emit));
371        assert!(ReplyShape::BailDeny.legal_at(HookMode::Bail));
372        assert!(!ReplyShape::BailDeny.legal_at(HookMode::Flow));
373        assert!(ReplyShape::FlowNext.legal_at(HookMode::Flow));
374        assert!(!ReplyShape::BailNone.legal_at(HookMode::Emit));
375    }
376}