Skip to main content

merry_core/
access.rs

1//! Shared capability policy and approval scope contracts.
2//!
3//! These provider-neutral enums cross configuration, runtime admission,
4//! process sandboxes, file tools, and UI boundaries.
5
6use serde::{Deserialize, Deserializer, Serialize};
7use std::fmt;
8
9/// Three-state policy governing an external capability such as network access
10/// or a host integration (`ssh-agent`, `gpg-agent`, `dbus`).
11#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize)]
12#[serde(rename_all = "kebab-case")]
13pub enum CapabilityPolicy {
14    /// Capability is hard-disabled; requests are rejected before review.
15    Deny,
16    /// Capability starts closed and may be requested through permission review.
17    #[default]
18    Ask,
19    /// Capability is pre-authorized in the baseline without per-action review.
20    Allow,
21}
22
23impl CapabilityPolicy {
24    /// Returns the canonical kebab-case config/API spelling.
25    #[must_use]
26    pub const fn as_str(self) -> &'static str {
27        match self {
28            Self::Deny => "deny",
29            Self::Ask => "ask",
30            Self::Allow => "allow",
31        }
32    }
33
34    /// Returns whether this capability is hard-blocked.
35    #[must_use]
36    pub const fn is_denied(self) -> bool {
37        matches!(self, Self::Deny)
38    }
39
40    /// Returns whether this capability is pre-authorized without review.
41    #[must_use]
42    pub const fn is_preauthorized(self) -> bool {
43        matches!(self, Self::Allow)
44    }
45
46    /// Returns whether actions may request this capability at runtime.
47    #[must_use]
48    pub const fn allows_requests(self) -> bool {
49        !self.is_denied()
50    }
51}
52
53impl fmt::Display for CapabilityPolicy {
54    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
55        formatter.write_str(self.as_str())
56    }
57}
58
59impl<'de> Deserialize<'de> for CapabilityPolicy {
60    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
61    where
62        D: Deserializer<'de>,
63    {
64        let value = String::deserialize(deserializer)?;
65        match value.as_str() {
66            "deny" => Ok(Self::Deny),
67            "ask" => Ok(Self::Ask),
68            "allow" => Ok(Self::Allow),
69            other => Err(serde::de::Error::custom(format!(
70                "invalid capability policy `{other}`; expected \"deny\", \"ask\", or \"allow\""
71            ))),
72        }
73    }
74}
75
76/// Lifetime scope selected when approving a permission review request.
77#[derive(
78    Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
79)]
80#[serde(rename_all = "kebab-case")]
81pub enum ApprovalScope {
82    /// Authorizes strictly this single action and retains nothing afterward.
83    #[default]
84    Once,
85    /// Retains eligible capabilities or narrow local-action classes in memory
86    /// for the rest of the current runtime session.
87    Session,
88}
89
90impl ApprovalScope {
91    /// Returns the canonical kebab-case spelling.
92    #[must_use]
93    pub const fn as_str(self) -> &'static str {
94        match self {
95            Self::Once => "once",
96            Self::Session => "session",
97        }
98    }
99}
100
101impl fmt::Display for ApprovalScope {
102    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
103        formatter.write_str(self.as_str())
104    }
105}
106
107#[cfg(test)]
108mod tests {
109    use super::{ApprovalScope, CapabilityPolicy};
110
111    #[test]
112    fn capability_policy_round_trips_canonical_strings() {
113        for policy in [
114            CapabilityPolicy::Deny,
115            CapabilityPolicy::Ask,
116            CapabilityPolicy::Allow,
117        ] {
118            let encoded = serde_json::to_string(&policy).expect("serialize");
119            let decoded: CapabilityPolicy = serde_json::from_str(&encoded).expect("deserialize");
120            assert_eq!(decoded, policy);
121            assert_eq!(encoded, format!("\"{}\"", policy.as_str()));
122        }
123        assert!(serde_json::from_str::<CapabilityPolicy>("\"invalid\"").is_err());
124    }
125
126    #[test]
127    fn approval_scope_defaults_to_once_and_round_trips() {
128        assert_eq!(ApprovalScope::default(), ApprovalScope::Once);
129        for scope in [ApprovalScope::Once, ApprovalScope::Session] {
130            let encoded = serde_json::to_string(&scope).expect("serialize");
131            let decoded: ApprovalScope = serde_json::from_str(&encoded).expect("deserialize");
132            assert_eq!(decoded, scope);
133            assert_eq!(encoded, format!("\"{}\"", scope.as_str()));
134        }
135    }
136}