Skip to main content

hyprstream_workers/dbus/
policy.rs

1//! D-Bus policy resource formatters for Casbin integration
2//!
3//! Builds resource strings for policy checks in the format:
4//! `dbus:<bus>:<destination>:<interface>:<member>`
5//!
6//! # Resource Format
7//!
8//! - Method calls: `dbus:session:org.freedesktop.Notifications:Notifications:Notify`
9//! - Properties (get): `dbus:session:org.mpris.MediaPlayer2:Player:@PlaybackStatus`
10//! - Properties (set): `dbus:session:org.mpris.MediaPlayer2:Player:@Volume`
11//! - Signals: `dbus:session:org.freedesktop.DBus:DBus:#NameOwnerChanged`
12//!
13//! The `@` prefix indicates properties, `#` prefix indicates signals.
14//!
15//! # Policy Examples
16//!
17//! ```csv
18//! # Allow sending desktop notifications
19//! p, container:gui, dbus:session:org.freedesktop.Notifications:Notifications:Notify, call, allow
20//!
21//! # Allow reading any MPRIS property
22//! p, container:gui, dbus:session:org.mpris.MediaPlayer2.*:*:@*, read, allow
23//!
24//! # Allow subscribing to NetworkManager state changes
25//! p, container:gui, dbus:system:org.freedesktop.NetworkManager:NetworkManager:#StateChanged, subscribe, allow
26//!
27//! # Deny all D-Bus by default
28//! p, container:*, dbus:*, *, deny
29//! ```
30
31use super::protocol::BusType;
32
33/// D-Bus operation types for policy checks
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum DbusOperation {
36    /// Method call
37    Call,
38    /// Property read (Get)
39    Read,
40    /// Property write (Set)
41    Write,
42    /// Signal subscription
43    Subscribe,
44}
45
46impl DbusOperation {
47    /// Get the operation string for policy checks
48    pub fn as_str(&self) -> &'static str {
49        match self {
50            DbusOperation::Call => "call",
51            DbusOperation::Read => "read",
52            DbusOperation::Write => "write",
53            DbusOperation::Subscribe => "subscribe",
54        }
55    }
56}
57
58impl std::fmt::Display for DbusOperation {
59    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
60        write!(f, "{}", self.as_str())
61    }
62}
63
64/// D-Bus resource identifier for policy checks
65#[derive(Debug, Clone, PartialEq, Eq)]
66pub struct DbusResource {
67    /// Bus type (system or session)
68    pub bus: BusType,
69
70    /// Destination bus name (e.g., "org.freedesktop.Notifications")
71    pub destination: String,
72
73    /// Interface name (e.g., "org.freedesktop.Notifications")
74    pub interface: String,
75
76    /// Member name with type prefix (method, @property, or #signal)
77    pub member: String,
78}
79
80impl DbusResource {
81    /// Create a resource for a method call
82    ///
83    /// # Arguments
84    /// * `bus` - Bus type (system or session)
85    /// * `destination` - Destination bus name
86    /// * `interface` - Interface containing the method
87    /// * `method` - Method name
88    ///
89    /// # Example
90    /// ```ignore
91    /// let resource = DbusResource::method_call(
92    ///     BusType::Session,
93    ///     "org.freedesktop.Notifications",
94    ///     "org.freedesktop.Notifications",
95    ///     "Notify",
96    /// );
97    /// assert_eq!(
98    ///     resource.to_string(),
99    ///     "dbus:session:org.freedesktop.Notifications:org.freedesktop.Notifications:Notify"
100    /// );
101    /// ```
102    pub fn method_call(
103        bus: BusType,
104        destination: impl Into<String>,
105        interface: impl Into<String>,
106        method: impl Into<String>,
107    ) -> Self {
108        Self {
109            bus,
110            destination: destination.into(),
111            interface: interface.into(),
112            member: method.into(),
113        }
114    }
115
116    /// Create a resource for a property read
117    ///
118    /// Properties are prefixed with `@` in the resource string.
119    pub fn property_read(
120        bus: BusType,
121        destination: impl Into<String>,
122        interface: impl Into<String>,
123        property: impl Into<String>,
124    ) -> Self {
125        Self {
126            bus,
127            destination: destination.into(),
128            interface: interface.into(),
129            member: format!("@{}", property.into()),
130        }
131    }
132
133    /// Create a resource for a property write
134    ///
135    /// Properties are prefixed with `@` in the resource string.
136    pub fn property_write(
137        bus: BusType,
138        destination: impl Into<String>,
139        interface: impl Into<String>,
140        property: impl Into<String>,
141    ) -> Self {
142        Self {
143            bus,
144            destination: destination.into(),
145            interface: interface.into(),
146            member: format!("@{}", property.into()),
147        }
148    }
149
150    /// Create a resource for a signal subscription
151    ///
152    /// Signals are prefixed with `#` in the resource string.
153    pub fn signal(
154        bus: BusType,
155        destination: impl Into<String>,
156        interface: impl Into<String>,
157        signal: impl Into<String>,
158    ) -> Self {
159        Self {
160            bus,
161            destination: destination.into(),
162            interface: interface.into(),
163            member: format!("#{}", signal.into()),
164        }
165    }
166
167    /// Convert to resource string for policy checks
168    ///
169    /// Format: `dbus:<bus>:<destination>:<interface>:<member>`
170    pub fn to_resource_string(&self) -> String {
171        format!(
172            "dbus:{}:{}:{}:{}",
173            self.bus, self.destination, self.interface, self.member
174        )
175    }
176
177    /// Check if this resource matches a pattern
178    ///
179    /// Supports wildcards (*) in patterns.
180    pub fn matches_pattern(&self, pattern: &str) -> bool {
181        let resource = self.to_resource_string();
182        pattern_matches(&resource, pattern)
183    }
184}
185
186impl std::fmt::Display for DbusResource {
187    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
188        write!(f, "{}", self.to_resource_string())
189    }
190}
191
192/// Simple wildcard pattern matching
193///
194/// Supports `*` as wildcard that matches any sequence of characters.
195fn pattern_matches(text: &str, pattern: &str) -> bool {
196    if pattern == "*" {
197        return true;
198    }
199
200    let pattern_parts: Vec<&str> = pattern.split('*').collect();
201
202    if pattern_parts.len() == 1 {
203        // No wildcards, exact match
204        return text == pattern;
205    }
206
207    let mut pos = 0;
208
209    for (i, part) in pattern_parts.iter().enumerate() {
210        if part.is_empty() {
211            continue;
212        }
213
214        if let Some(found) = text[pos..].find(part) {
215            if i == 0 && found != 0 {
216                // First part must match at start
217                return false;
218            }
219            pos += found + part.len();
220        } else {
221            return false;
222        }
223    }
224
225    // If pattern doesn't end with *, text must end exactly
226    if !pattern.ends_with('*') && pos != text.len() {
227        return false;
228    }
229
230    true
231}
232
233/// Build a subject identifier for policy checks
234///
235/// Format: `container:<sandbox_id>` or `container:<sandbox_id>:<container_id>`
236pub fn container_subject(sandbox_id: &str, container_id: Option<&str>) -> String {
237    match container_id {
238        Some(cid) => format!("container:{sandbox_id}:{cid}"),
239        None => format!("container:{sandbox_id}"),
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246
247    #[test]
248    fn test_method_call_resource() {
249        let resource = DbusResource::method_call(
250            BusType::Session,
251            "org.freedesktop.Notifications",
252            "org.freedesktop.Notifications",
253            "Notify",
254        );
255
256        assert_eq!(
257            resource.to_resource_string(),
258            "dbus:session:org.freedesktop.Notifications:org.freedesktop.Notifications:Notify"
259        );
260    }
261
262    #[test]
263    fn test_property_read_resource() {
264        let resource = DbusResource::property_read(
265            BusType::Session,
266            "org.mpris.MediaPlayer2.spotify",
267            "org.mpris.MediaPlayer2.Player",
268            "PlaybackStatus",
269        );
270
271        assert_eq!(
272            resource.to_resource_string(),
273            "dbus:session:org.mpris.MediaPlayer2.spotify:org.mpris.MediaPlayer2.Player:@PlaybackStatus"
274        );
275    }
276
277    #[test]
278    fn test_property_write_resource() {
279        let resource = DbusResource::property_write(
280            BusType::Session,
281            "org.mpris.MediaPlayer2.spotify",
282            "org.mpris.MediaPlayer2.Player",
283            "Volume",
284        );
285
286        assert_eq!(
287            resource.to_resource_string(),
288            "dbus:session:org.mpris.MediaPlayer2.spotify:org.mpris.MediaPlayer2.Player:@Volume"
289        );
290    }
291
292    #[test]
293    fn test_signal_resource() {
294        let resource = DbusResource::signal(
295            BusType::System,
296            "org.freedesktop.NetworkManager",
297            "org.freedesktop.NetworkManager",
298            "StateChanged",
299        );
300
301        assert_eq!(
302            resource.to_resource_string(),
303            "dbus:system:org.freedesktop.NetworkManager:org.freedesktop.NetworkManager:#StateChanged"
304        );
305    }
306
307    #[test]
308    fn test_pattern_matching() {
309        // Exact match
310        assert!(pattern_matches(
311            "dbus:session:org.test:iface:Method",
312            "dbus:session:org.test:iface:Method"
313        ));
314
315        // Wildcard at end
316        assert!(pattern_matches(
317            "dbus:session:org.test:iface:Method",
318            "dbus:session:org.test:*"
319        ));
320
321        // Wildcard in middle
322        assert!(pattern_matches(
323            "dbus:session:org.test:iface:Method",
324            "dbus:session:*:Method"
325        ));
326
327        // Full wildcard
328        assert!(pattern_matches("dbus:session:org.test:iface:Method", "*"));
329
330        // No match
331        assert!(!pattern_matches(
332            "dbus:session:org.test:iface:Method",
333            "dbus:system:*"
334        ));
335    }
336
337    #[test]
338    fn test_resource_matches_pattern() {
339        let resource = DbusResource::method_call(
340            BusType::Session,
341            "org.freedesktop.Notifications",
342            "org.freedesktop.Notifications",
343            "Notify",
344        );
345
346        assert!(resource.matches_pattern("dbus:session:org.freedesktop.Notifications:*"));
347        assert!(resource.matches_pattern("dbus:session:*:Notify"));
348        assert!(resource.matches_pattern("dbus:*"));
349        assert!(!resource.matches_pattern("dbus:system:*"));
350    }
351
352    #[test]
353    fn test_container_subject() {
354        assert_eq!(
355            container_subject("sandbox-123", None),
356            "container:sandbox-123"
357        );
358
359        assert_eq!(
360            container_subject("sandbox-123", Some("container-456")),
361            "container:sandbox-123:container-456"
362        );
363    }
364
365    #[test]
366    fn test_dbus_operation_display() {
367        assert_eq!(DbusOperation::Call.as_str(), "call");
368        assert_eq!(DbusOperation::Read.as_str(), "read");
369        assert_eq!(DbusOperation::Write.as_str(), "write");
370        assert_eq!(DbusOperation::Subscribe.as_str(), "subscribe");
371    }
372}