1use std::sync::Arc;
7use std::time::Duration;
8
9use dashmap::DashMap;
10use tokio::sync::RwLock;
11use uuid::Uuid;
12
13use super::policy::{container_subject, DbusOperation, DbusResource};
14use super::protocol::{
15 BusType, DbusCallRequest, DbusCallResponse, DbusGetPropertyRequest, DbusRequest, DbusResponse,
16 DbusSetPropertyRequest, DbusSubscribeRequest, DbusValue,
17};
18use crate::error::{Result, WorkerError};
19
20#[derive(Debug, Clone)]
22pub struct DbusBridgeConfig {
23 pub allow_system_bus: bool,
25
26 pub allow_session_bus: bool,
28
29 pub default_timeout_ms: u32,
31
32 pub max_subscriptions_per_container: usize,
34}
35
36impl Default for DbusBridgeConfig {
37 fn default() -> Self {
38 Self {
39 allow_system_bus: true,
40 allow_session_bus: true,
41 default_timeout_ms: 30_000,
42 max_subscriptions_per_container: 100,
43 }
44 }
45}
46
47#[derive(Debug)]
49#[allow(dead_code)]
50struct SignalSubscription {
51 id: String,
53
54 container_id: String,
56
57 bus: BusType,
59
60 interface: String,
62
63 signal: String,
65}
66
67#[cfg(feature = "dbus")]
72pub struct DbusBridgeService {
73 config: DbusBridgeConfig,
75
76 system_bus: RwLock<Option<zbus::Connection>>,
78
79 session_bus: RwLock<Option<zbus::Connection>>,
81
82 subscriptions: DashMap<String, SignalSubscription>,
84
85 policy_check: Arc<dyn PolicyChecker>,
87}
88
89pub trait PolicyChecker: Send + Sync {
91 fn check(&self, subject: &str, resource: &str, operation: &str) -> bool;
93}
94
95pub struct DenyAllPolicy;
97
98impl PolicyChecker for DenyAllPolicy {
99 fn check(&self, _subject: &str, _resource: &str, _operation: &str) -> bool {
100 false
101 }
102}
103
104pub struct AllowAllPolicy;
106
107impl PolicyChecker for AllowAllPolicy {
108 fn check(&self, _subject: &str, _resource: &str, _operation: &str) -> bool {
109 true
110 }
111}
112
113#[cfg(feature = "dbus")]
114impl DbusBridgeService {
115 pub async fn new(config: DbusBridgeConfig) -> Result<Self> {
117 Self::with_policy(config, Arc::new(DenyAllPolicy)).await
118 }
119
120 pub async fn with_policy(
122 config: DbusBridgeConfig,
123 policy_check: Arc<dyn PolicyChecker>,
124 ) -> Result<Self> {
125 Ok(Self {
126 config,
127 system_bus: RwLock::new(None),
128 session_bus: RwLock::new(None),
129 subscriptions: DashMap::new(),
130 policy_check,
131 })
132 }
133
134 async fn ensure_connected(&self, bus: BusType) -> Result<zbus::Connection> {
136 match bus {
137 BusType::System => {
138 let mut guard = self.system_bus.write().await;
139 if let Some(conn) = guard.as_ref() {
140 return Ok(conn.clone());
141 }
142
143 if !self.config.allow_system_bus {
144 return Err(WorkerError::ConfigError(
145 "System bus access not allowed".to_owned(),
146 ));
147 }
148
149 let conn = zbus::Connection::system().await.map_err(|e| {
150 WorkerError::Internal(format!("Failed to connect to system bus: {e}"))
151 })?;
152
153 *guard = Some(conn.clone());
154 Ok(conn)
155 }
156 BusType::Session => {
157 let mut guard = self.session_bus.write().await;
158 if let Some(conn) = guard.as_ref() {
159 return Ok(conn.clone());
160 }
161
162 if !self.config.allow_session_bus {
163 return Err(WorkerError::ConfigError(
164 "Session bus access not allowed".to_owned(),
165 ));
166 }
167
168 let conn = zbus::Connection::session().await.map_err(|e| {
169 WorkerError::Internal(format!("Failed to connect to session bus: {e}"))
170 })?;
171
172 *guard = Some(conn.clone());
173 Ok(conn)
174 }
175 }
176 }
177
178 pub async fn handle_request(&self, container_id: &str, request: DbusRequest) -> DbusResponse {
180 let subject = container_subject(container_id, None);
181
182 match request {
183 DbusRequest::Call(call) => self.handle_call(&subject, call).await,
184 DbusRequest::GetProperty(get) => self.handle_get_property(&subject, get).await,
185 DbusRequest::SetProperty(set) => self.handle_set_property(&subject, set).await,
186 DbusRequest::Subscribe(sub) => self.handle_subscribe(&subject, container_id, sub).await,
187 DbusRequest::Unsubscribe { subscription_id } => {
188 self.handle_unsubscribe(&subject, container_id, &subscription_id)
189 .await
190 }
191 }
192 }
193
194 async fn handle_call(&self, subject: &str, call: DbusCallRequest) -> DbusResponse {
196 let resource =
198 DbusResource::method_call(call.bus, &call.destination, &call.interface, &call.method);
199
200 if !self.policy_check.check(
201 subject,
202 &resource.to_resource_string(),
203 DbusOperation::Call.as_str(),
204 ) {
205 tracing::warn!(
206 subject = %subject,
207 resource = %resource,
208 "D-Bus call denied by policy"
209 );
210 return DbusResponse::access_denied(&resource.to_resource_string());
211 }
212
213 let conn = match self.ensure_connected(call.bus).await {
215 Ok(c) => c,
216 Err(e) => {
217 return DbusResponse::error("org.freedesktop.DBus.Error.Failed", e.to_string());
218 }
219 };
220
221 let timeout = if call.timeout_ms > 0 {
223 Duration::from_millis(call.timeout_ms as u64)
224 } else {
225 Duration::from_millis(self.config.default_timeout_ms as u64)
226 };
227
228 match self.forward_call(&conn, &call, timeout).await {
232 Ok(values) => DbusResponse::Return(DbusCallResponse::new(values)),
233 Err(e) => DbusResponse::error("org.freedesktop.DBus.Error.Failed", e.to_string()),
234 }
235 }
236
237 async fn forward_call(
239 &self,
240 conn: &zbus::Connection,
241 call: &DbusCallRequest,
242 timeout: Duration,
243 ) -> Result<Vec<DbusValue>> {
244 use zbus::names::{BusName, InterfaceName, MemberName};
245 use zbus::zvariant::ObjectPath;
246
247 let destination: BusName = call
249 .destination
250 .as_str()
251 .try_into()
252 .map_err(|e| WorkerError::Internal(format!("Invalid destination: {e}")))?;
253
254 let interface: InterfaceName = call
256 .interface
257 .as_str()
258 .try_into()
259 .map_err(|e| WorkerError::Internal(format!("Invalid interface: {e}")))?;
260
261 let path: ObjectPath = call
263 .path
264 .as_str()
265 .try_into()
266 .map_err(|e| WorkerError::Internal(format!("Invalid object path: {e}")))?;
267
268 let method: MemberName = call
270 .method
271 .as_str()
272 .try_into()
273 .map_err(|e| WorkerError::Internal(format!("Invalid method name: {e}")))?;
274
275 let call_future = conn.call_method(Some(destination), path, Some(interface), method, &());
278
279 let reply = tokio::time::timeout(timeout, call_future)
280 .await
281 .map_err(|_| {
282 WorkerError::Internal(format!("D-Bus call timed out after {timeout:?}"))
283 })?;
284
285 match reply {
286 Ok(_msg) => {
287 Ok(Vec::new())
289 }
290 Err(e) => Err(WorkerError::Internal(format!("D-Bus call failed: {e}"))),
291 }
292 }
293
294 async fn handle_get_property(
296 &self,
297 subject: &str,
298 get: DbusGetPropertyRequest,
299 ) -> DbusResponse {
300 let resource =
301 DbusResource::property_read(get.bus, &get.destination, &get.interface, &get.property);
302
303 if !self.policy_check.check(
304 subject,
305 &resource.to_resource_string(),
306 DbusOperation::Read.as_str(),
307 ) {
308 return DbusResponse::access_denied(&resource.to_resource_string());
309 }
310
311 let conn = match self.ensure_connected(get.bus).await {
313 Ok(c) => c,
314 Err(e) => {
315 return DbusResponse::error("org.freedesktop.DBus.Error.Failed", e.to_string());
316 }
317 };
318
319 match self.forward_get_property(&conn, &get).await {
321 Ok(value) => DbusResponse::Property { value },
322 Err(e) => DbusResponse::error("org.freedesktop.DBus.Error.Failed", e.to_string()),
323 }
324 }
325
326 async fn forward_get_property(
328 &self,
329 conn: &zbus::Connection,
330 get: &DbusGetPropertyRequest,
331 ) -> Result<DbusValue> {
332 use zbus::names::{BusName, InterfaceName, MemberName};
333 use zbus::zvariant::ObjectPath;
334
335 let destination: BusName = get
337 .destination
338 .as_str()
339 .try_into()
340 .map_err(|e| WorkerError::Internal(format!("Invalid destination: {e}")))?;
341
342 let path: ObjectPath = get
344 .path
345 .as_str()
346 .try_into()
347 .map_err(|e| WorkerError::Internal(format!("Invalid object path: {e}")))?;
348
349 let interface: InterfaceName = get
351 .interface
352 .as_str()
353 .try_into()
354 .map_err(|e| WorkerError::Internal(format!("Invalid interface: {e}")))?;
355
356 let property: MemberName = get
358 .property
359 .as_str()
360 .try_into()
361 .map_err(|e| WorkerError::Internal(format!("Invalid property name: {e}")))?;
362
363 let properties_interface: InterfaceName = "org.freedesktop.DBus.Properties"
365 .try_into()
366 .map_err(|e| WorkerError::Internal(format!("Invalid interface name: {e}")))?;
367 let get_method: MemberName = "Get"
368 .try_into()
369 .map_err(|e| WorkerError::Internal(format!("Invalid method name: {e}")))?;
370
371 let reply = conn
372 .call_method(
373 Some(destination),
374 path,
375 Some(properties_interface),
376 get_method,
377 &(interface.as_str(), property.as_str()),
378 )
379 .await
380 .map_err(|e| WorkerError::Internal(format!("D-Bus property get failed: {e}")))?;
381
382 let body = reply.body();
386 Ok(DbusValue::String(format!("{body:?}")))
387 }
388
389 async fn handle_set_property(
391 &self,
392 subject: &str,
393 set: DbusSetPropertyRequest,
394 ) -> DbusResponse {
395 let resource =
396 DbusResource::property_write(set.bus, &set.destination, &set.interface, &set.property);
397
398 if !self.policy_check.check(
399 subject,
400 &resource.to_resource_string(),
401 DbusOperation::Write.as_str(),
402 ) {
403 return DbusResponse::access_denied(&resource.to_resource_string());
404 }
405
406 let conn = match self.ensure_connected(set.bus).await {
408 Ok(c) => c,
409 Err(e) => {
410 return DbusResponse::error("org.freedesktop.DBus.Error.Failed", e.to_string());
411 }
412 };
413
414 match self.forward_set_property(&conn, &set).await {
416 Ok(()) => DbusResponse::Return(DbusCallResponse::empty()),
417 Err(e) => DbusResponse::error("org.freedesktop.DBus.Error.Failed", e.to_string()),
418 }
419 }
420
421 async fn forward_set_property(
423 &self,
424 conn: &zbus::Connection,
425 set: &DbusSetPropertyRequest,
426 ) -> Result<()> {
427 use zbus::names::{BusName, InterfaceName, MemberName};
428 use zbus::zvariant::{ObjectPath, Value};
429
430 let destination: BusName = set
432 .destination
433 .as_str()
434 .try_into()
435 .map_err(|e| WorkerError::Internal(format!("Invalid destination: {e}")))?;
436
437 let path: ObjectPath = set
439 .path
440 .as_str()
441 .try_into()
442 .map_err(|e| WorkerError::Internal(format!("Invalid object path: {e}")))?;
443
444 let interface: InterfaceName = set
446 .interface
447 .as_str()
448 .try_into()
449 .map_err(|e| WorkerError::Internal(format!("Invalid interface: {e}")))?;
450
451 let property: MemberName = set
453 .property
454 .as_str()
455 .try_into()
456 .map_err(|e| WorkerError::Internal(format!("Invalid property name: {e}")))?;
457
458 let zvalue = dbus_value_to_zvariant(&set.value)?;
460
461 let properties_interface: InterfaceName = "org.freedesktop.DBus.Properties"
463 .try_into()
464 .map_err(|e| WorkerError::Internal(format!("Invalid interface name: {e}")))?;
465 let set_method: MemberName = "Set"
466 .try_into()
467 .map_err(|e| WorkerError::Internal(format!("Invalid method name: {e}")))?;
468
469 conn.call_method(
470 Some(destination),
471 path,
472 Some(properties_interface),
473 set_method,
474 &(interface.as_str(), property.as_str(), Value::from(zvalue)),
475 )
476 .await
477 .map_err(|e| WorkerError::Internal(format!("D-Bus property set failed: {e}")))?;
478
479 Ok(())
480 }
481
482 async fn handle_subscribe(
484 &self,
485 subject: &str,
486 container_id: &str,
487 sub: DbusSubscribeRequest,
488 ) -> DbusResponse {
489 let resource = DbusResource::signal(
490 sub.bus,
491 sub.sender.as_deref().unwrap_or("*"),
492 &sub.interface,
493 &sub.signal,
494 );
495
496 if !self.policy_check.check(
497 subject,
498 &resource.to_resource_string(),
499 DbusOperation::Subscribe.as_str(),
500 ) {
501 return DbusResponse::access_denied(&resource.to_resource_string());
502 }
503
504 let container_subs: usize = self
506 .subscriptions
507 .iter()
508 .filter(|s| s.container_id == container_id)
509 .count();
510
511 if container_subs >= self.config.max_subscriptions_per_container {
512 return DbusResponse::error(
513 "org.freedesktop.DBus.Error.LimitsExceeded",
514 format!(
515 "Maximum subscriptions ({}) exceeded",
516 self.config.max_subscriptions_per_container
517 ),
518 );
519 }
520
521 let subscription_id = Uuid::new_v4().to_string();
523
524 self.subscriptions.insert(
525 subscription_id.clone(),
526 SignalSubscription {
527 id: subscription_id.clone(),
528 container_id: container_id.to_owned(),
529 bus: sub.bus,
530 interface: sub.interface,
531 signal: sub.signal,
532 },
533 );
534
535 DbusResponse::Subscribed { subscription_id }
539 }
540
541 async fn handle_unsubscribe(
543 &self,
544 _subject: &str,
545 container_id: &str,
546 subscription_id: &str,
547 ) -> DbusResponse {
548 if let Some((_, sub)) = self.subscriptions.remove(subscription_id) {
550 if sub.container_id != container_id {
551 self.subscriptions.insert(subscription_id.to_owned(), sub);
553 return DbusResponse::error(
554 "org.freedesktop.DBus.Error.AccessDenied",
555 "Cannot unsubscribe from another container's subscription",
556 );
557 }
558 }
559
560 DbusResponse::Unsubscribed
561 }
562
563 pub fn subscription_count(&self) -> usize {
565 self.subscriptions.len()
566 }
567
568 pub fn cleanup_container(&self, container_id: &str) {
570 self.subscriptions
571 .retain(|_, sub| sub.container_id != container_id);
572 }
573}
574
575#[cfg(not(feature = "dbus"))]
577pub struct DbusBridgeService {
578 _private: (),
579}
580
581#[cfg(not(feature = "dbus"))]
582impl DbusBridgeService {
583 pub async fn new(_config: DbusBridgeConfig) -> Result<Self> {
585 Err(WorkerError::ConfigError(
586 "D-Bus bridge requires the 'dbus' feature to be enabled".to_owned(),
587 ))
588 }
589}
590
591#[cfg(feature = "dbus")]
596fn dbus_value_to_zvariant(value: &DbusValue) -> Result<String> {
597 match value {
598 DbusValue::String(s) => Ok(s.clone()),
599 DbusValue::Bool(b) => Ok(b.to_string()),
600 DbusValue::Int32(n) => Ok(n.to_string()),
601 DbusValue::Uint32(n) => Ok(n.to_string()),
602 DbusValue::Int64(n) => Ok(n.to_string()),
603 DbusValue::Uint64(n) => Ok(n.to_string()),
604 DbusValue::Double(n) => Ok(n.to_string()),
605 DbusValue::ObjectPath(p) => Ok(p.clone()),
606 DbusValue::Variant(inner) => dbus_value_to_zvariant(inner),
607 DbusValue::Array(_) | DbusValue::Dict(_) | DbusValue::Bytes(_) => {
608 Err(WorkerError::Internal(
609 "Complex D-Bus types (Array, Dict, Bytes) not yet supported for property set"
610 .to_owned(),
611 ))
612 }
613 }
614}
615
616#[cfg(all(test, feature = "dbus"))]
617mod tests {
618 use super::*;
619
620 #[tokio::test]
621 async fn test_bridge_creation() -> Result<()> {
622 let config = DbusBridgeConfig::default();
623 let bridge = DbusBridgeService::with_policy(config, Arc::new(AllowAllPolicy)).await?;
624
625 assert_eq!(bridge.subscription_count(), 0);
626 Ok(())
627 }
628
629 #[tokio::test]
630 async fn test_policy_denied() -> Result<()> {
631 let config = DbusBridgeConfig::default();
632 let bridge = DbusBridgeService::with_policy(config, Arc::new(DenyAllPolicy)).await?;
633
634 let request = DbusRequest::Call(DbusCallRequest::new(
635 "org.freedesktop.Notifications",
636 "/org/freedesktop/Notifications",
637 "org.freedesktop.Notifications",
638 "Notify",
639 ));
640
641 let response = bridge.handle_request("container-1", request).await;
642
643 match response {
644 DbusResponse::Error(err) => {
645 assert!(err.name.contains("AccessDenied"));
646 }
647 _ => panic!("Expected error response"),
648 }
649 Ok(())
650 }
651
652 #[tokio::test]
653 async fn test_subscribe_unsubscribe() -> Result<()> {
654 let config = DbusBridgeConfig::default();
655 let bridge = DbusBridgeService::with_policy(config, Arc::new(AllowAllPolicy)).await?;
656
657 let request = DbusRequest::Subscribe(DbusSubscribeRequest {
659 bus: BusType::Session,
660 sender: None,
661 path: None,
662 interface: "org.freedesktop.DBus".to_owned(),
663 signal: "NameOwnerChanged".to_owned(),
664 });
665
666 let response = bridge.handle_request("container-1", request).await;
667
668 let subscription_id = match response {
669 DbusResponse::Subscribed { subscription_id } => subscription_id,
670 _ => panic!("Expected subscribed response"),
671 };
672
673 assert_eq!(bridge.subscription_count(), 1);
674
675 let request = DbusRequest::Unsubscribe { subscription_id };
677 let response = bridge.handle_request("container-1", request).await;
678
679 match response {
680 DbusResponse::Unsubscribed => {}
681 _ => panic!("Expected unsubscribed response"),
682 }
683
684 assert_eq!(bridge.subscription_count(), 0);
685 Ok(())
686 }
687
688 #[tokio::test]
689 async fn test_cleanup_container() -> Result<()> {
690 let config = DbusBridgeConfig::default();
691 let bridge = DbusBridgeService::with_policy(config, Arc::new(AllowAllPolicy)).await?;
692
693 for container in ["container-1", "container-2"] {
695 let request = DbusRequest::Subscribe(DbusSubscribeRequest {
696 bus: BusType::Session,
697 sender: None,
698 path: None,
699 interface: "org.test".to_owned(),
700 signal: "Test".to_owned(),
701 });
702 bridge.handle_request(container, request).await;
703 }
704
705 assert_eq!(bridge.subscription_count(), 2);
706
707 bridge.cleanup_container("container-1");
709
710 assert_eq!(bridge.subscription_count(), 1);
711 Ok(())
712 }
713}
714
715#[cfg(all(test, not(feature = "dbus")))]
716mod tests {
717 use super::*;
718
719 #[tokio::test]
720 async fn test_bridge_disabled() {
721 let config = DbusBridgeConfig::default();
722 let result = DbusBridgeService::new(config).await;
723 assert!(result.is_err());
724 }
725}