Skip to main content

qualia_core_db/q42/app_manifest/
permissions.rs

1//! Closed permission-intent set and grant-ceiling checks.
2//!
3//! Unknown permission wire values fail closed. Presentation hints are never
4//! consulted when deciding authority — see [`authority_from_presentation_hints`].
5
6use super::error::AppManifestError;
7
8/// Allowlisted permission kinds a portable app may declare as intents.
9///
10/// Wire values outside this set decode as [`AppManifestError::UnknownPermission`].
11#[repr(u8)]
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
13#[serde(rename_all = "snake_case")]
14pub enum PermissionKind {
15    ReadLocalState = 1,
16    WriteLocalState = 2,
17    ReadLocalAsset = 3,
18    NetworkEgress = 4,
19    CameraCapture = 5,
20    MicrophoneCapture = 6,
21    IdentityRead = 7,
22    ConsentDisclose = 8,
23}
24
25impl PermissionKind {
26    /// Parse a known wire byte. Unknown values fail closed.
27    pub fn from_u8(value: u8) -> Result<Self, AppManifestError> {
28        match value {
29            1 => Ok(Self::ReadLocalState),
30            2 => Ok(Self::WriteLocalState),
31            3 => Ok(Self::ReadLocalAsset),
32            4 => Ok(Self::NetworkEgress),
33            5 => Ok(Self::CameraCapture),
34            6 => Ok(Self::MicrophoneCapture),
35            7 => Ok(Self::IdentityRead),
36            8 => Ok(Self::ConsentDisclose),
37            _ => Err(AppManifestError::UnknownPermission),
38        }
39    }
40
41    /// Stable tag for logs / cold JSON. Unknown tags fail closed to [`None`].
42    pub fn parse(tag: &str) -> Option<Self> {
43        match tag.trim().to_ascii_lowercase().as_str() {
44            "read_local_state" => Some(Self::ReadLocalState),
45            "write_local_state" => Some(Self::WriteLocalState),
46            "read_local_asset" => Some(Self::ReadLocalAsset),
47            "network_egress" => Some(Self::NetworkEgress),
48            "camera_capture" => Some(Self::CameraCapture),
49            "microphone_capture" => Some(Self::MicrophoneCapture),
50            "identity_read" => Some(Self::IdentityRead),
51            "consent_disclose" => Some(Self::ConsentDisclose),
52            _ => None,
53        }
54    }
55
56    /// Stable string form.
57    pub const fn as_str(self) -> &'static str {
58        match self {
59            Self::ReadLocalState => "read_local_state",
60            Self::WriteLocalState => "write_local_state",
61            Self::ReadLocalAsset => "read_local_asset",
62            Self::NetworkEgress => "network_egress",
63            Self::CameraCapture => "camera_capture",
64            Self::MicrophoneCapture => "microphone_capture",
65            Self::IdentityRead => "identity_read",
66            Self::ConsentDisclose => "consent_disclose",
67        }
68    }
69
70    /// Privilege rank used for escalation checks (higher = more powerful).
71    pub const fn privilege_rank(self) -> u8 {
72        match self {
73            Self::ReadLocalState | Self::ReadLocalAsset | Self::IdentityRead => 1,
74            Self::WriteLocalState | Self::ConsentDisclose => 2,
75            Self::CameraCapture | Self::MicrophoneCapture => 3,
76            Self::NetworkEgress => 4,
77        }
78    }
79}
80
81/// Declared permission intent inside a portable application manifest.
82#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
83pub struct PermissionIntent {
84    pub kind: PermissionKind,
85    /// Scope string (asset id, state path, or `*`). Not a Host invoke ID.
86    pub scope: String,
87    /// When true, host may withhold without failing install validation.
88    pub optional: bool,
89}
90
91/// Decorative / layout suggestion. **Inert for authorization.**
92///
93/// Hints must never be read by grant evaluation, capability gating, or
94/// lifecycle launch decisions. See [`authority_from_presentation_hints`].
95#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
96pub struct PresentationHint {
97    pub key: String,
98    pub value: String,
99}
100
101/// Host-side grant ceiling for an installed app (not stored in the manifest).
102#[derive(Debug, Clone, PartialEq, Eq, Default)]
103pub struct PermissionGrant {
104    pub allowed: Vec<PermissionKind>,
105}
106
107impl PermissionGrant {
108    /// `true` when the manifest allows the op.
109    pub fn allows(&self, kind: PermissionKind) -> bool {
110        self.allowed.contains(&kind)
111    }
112
113    /// Maximum privilege rank among granted kinds (0 if empty).
114    pub fn max_rank(&self) -> u8 {
115        self.allowed
116            .iter()
117            .map(|k| k.privilege_rank())
118            .max()
119            .unwrap_or(0)
120    }
121}
122
123/// Fail closed when any required intent is absent from the grant.
124pub fn check_permission_intents(
125    intents: &[PermissionIntent],
126    grant: &PermissionGrant,
127) -> Result<(), AppManifestError> {
128    for intent in intents {
129        if intent.optional {
130            continue;
131        }
132        if !grant.allows(intent.kind) {
133            return Err(AppManifestError::PermissionEscalation);
134        }
135    }
136    Ok(())
137}
138
139/// Presentation hints are decorative only and **never** contribute authority.
140///
141/// Callers must not treat hint key/value pairs as grants, capabilities, or
142/// permission escalations. This function always returns an empty grant.
143pub fn authority_from_presentation_hints(_hints: &[PresentationHint]) -> PermissionGrant {
144    PermissionGrant {
145        allowed: Vec::new(),
146    }
147}
148
149#[cfg(test)]
150mod tests {
151    use super::*;
152
153    #[test]
154    fn unknown_permission_byte_fails_closed() {
155        assert_eq!(
156            PermissionKind::from_u8(0),
157            Err(AppManifestError::UnknownPermission)
158        );
159        assert_eq!(
160            PermissionKind::from_u8(255),
161            Err(AppManifestError::UnknownPermission)
162        );
163        assert!(PermissionKind::parse("admin").is_none());
164        assert!(PermissionKind::parse("shell_exec").is_none());
165    }
166}