Skip to main content

hyprstream_service/service/manager/
systemd.rs

1//! Systemd service manager implementation
2//!
3//! Uses D-Bus to control systemd units via zbus_systemd.
4
5use super::{units, ServiceManager};
6use crate::service::spawner::{Spawnable, SpawnedService};
7use anyhow::{anyhow, Context as _, Result};
8use async_trait::async_trait;
9use std::path::PathBuf;
10use tracing::{debug, info};
11use zbus_systemd::login1::ManagerProxy as LoginProxy;
12use zbus_systemd::systemd1::ManagerProxy;
13use zbus_systemd::zbus::Connection;
14
15/// Connect to the user D-Bus instance for systemd management.
16///
17/// Tries `$DBUS_SESSION_BUS_ADDRESS` first (set by PAM on both desktop and
18/// headless SSH logins when `systemd --user` is running). Falls back to the
19/// well-known socket path `/run/user/$UID/bus` for environments where the env
20/// var is absent but the socket exists (e.g. running from a cron job or
21/// service that didn't inherit the PAM environment).
22///
23/// Does NOT use the systemd private bus (`/run/user/$UID/systemd/private/bus`)
24/// — that path is an internal bind-mount not accessible from outside systemd.
25async fn user_systemd_connection() -> Result<Connection> {
26    // Primary: $DBUS_SESSION_BUS_ADDRESS (set by pam_systemd on any login).
27    if let Ok(conn) = Connection::session().await {
28        return Ok(conn);
29    }
30
31    // Fallback: well-known socket path that systemd --user maintains.
32    let uid = nix::unistd::getuid().as_raw();
33    let rt = std::env::var("XDG_RUNTIME_DIR").unwrap_or_else(|_| format!("/run/user/{uid}"));
34    let bus_path = format!("{rt}/bus");
35    zbus_systemd::zbus::ConnectionBuilder::address(format!("unix:path={bus_path}").as_str())?
36        .build()
37        .await
38        .with_context(|| {
39            format!(
40                "could not connect to user D-Bus (tried $DBUS_SESSION_BUS_ADDRESS and {bus_path})"
41            )
42        })
43}
44
45/// Systemd-based user service manager
46///
47/// Manages per-user services via D-Bus calls to the systemd user instance.
48/// Units are installed to `~/.config/systemd/user/`.
49pub struct SystemdManager {
50    #[allow(dead_code)]
51    connection: Connection,
52    systemd: ManagerProxy<'static>,
53}
54
55impl SystemdManager {
56    /// Create a new SystemdManager.
57    ///
58    /// Connects to the user session D-Bus for systemd1 and the system D-Bus
59    /// for login1 (logind). logind lives on the system bus only — connecting
60    /// LoginProxy to the session bus caused set_user_linger() to hang forever
61    /// waiting for a response that never arrives. Enabling user linger keeps
62    /// services persisting across logouts on headless machines.
63    pub async fn new() -> Result<Self> {
64        let connection = user_systemd_connection().await?;
65        let systemd = ManagerProxy::new(&connection).await?;
66
67        // Enable linger via the system bus (org.freedesktop.login1 is system-only).
68        // This keeps the user systemd instance running after logout so services
69        // registered with WantedBy=default.target survive reboots.
70        let system_connection = Connection::system().await?;
71        let login = LoginProxy::new(&system_connection).await?;
72        let uid = nix::unistd::getuid().as_raw();
73        if let Err(e) = login.set_user_linger(uid, true, false).await {
74            debug!(
75                "Failed to enable user linger (may already be enabled): {}",
76                e
77            );
78        } else {
79            debug!("User lingering enabled");
80        }
81
82        Ok(Self {
83            connection,
84            systemd,
85        })
86    }
87
88    /// Create a new SystemdManager using the D-Bus session bus.
89    ///
90    /// Only for session-scoped services (e.g. the TUI multiplexer) that should
91    /// be tied to an active login session.  Do NOT use for long-lived public
92    /// service daemons — the session bus disappears on logout.
93    pub async fn new_session() -> Result<Self> {
94        let connection = Connection::session().await.context(
95            "could not connect to D-Bus session bus (is $DBUS_SESSION_BUS_ADDRESS set?)",
96        )?;
97        let systemd = ManagerProxy::new(&connection).await?;
98        Ok(Self {
99            connection,
100            systemd,
101        })
102    }
103
104    #[allow(dead_code)]
105    fn socket_unit(service: &str) -> String {
106        format!("hyprstream-{service}.socket")
107    }
108
109    fn service_unit(service: &str) -> String {
110        format!("hyprstream-{service}.service")
111    }
112
113    fn units_dir() -> Result<PathBuf> {
114        dirs::config_dir()
115            .map(|d| d.join("systemd/user"))
116            .ok_or_else(|| anyhow!("cannot determine config directory"))
117    }
118}
119
120/// Systemd-based system-wide service manager (requires root)
121///
122/// Manages system services via the system D-Bus. Units are installed to
123/// `/etc/systemd/system/` and run under a dedicated `hyprstream` system user.
124pub struct SystemdSystemManager {
125    #[allow(dead_code)]
126    connection: Connection,
127    systemd: ManagerProxy<'static>,
128}
129
130impl SystemdSystemManager {
131    pub async fn new() -> Result<Self> {
132        let connection = Connection::system().await?;
133        let systemd = ManagerProxy::new(&connection).await?;
134        Ok(Self {
135            connection,
136            systemd,
137        })
138    }
139
140    fn service_unit(service: &str) -> String {
141        format!("hyprstream-{service}.service")
142    }
143
144    fn units_dir() -> PathBuf {
145        PathBuf::from("/etc/systemd/system")
146    }
147}
148
149#[async_trait]
150impl ServiceManager for SystemdSystemManager {
151    async fn install(&self, service: &str) -> Result<()> {
152        let units_dir = Self::units_dir();
153        std::fs::create_dir_all(&units_dir)?;
154
155        let depends_on = crate::service::factory::get_factory(service)
156            .map(|f| f.depends_on)
157            .unwrap_or(&[]);
158
159        let service_content = units::system_service_unit(service, depends_on)?;
160        let service_path = units_dir.join(Self::service_unit(service));
161
162        if std::fs::read_to_string(&service_path).ok().as_deref() != Some(&service_content) {
163            std::fs::write(&service_path, &service_content)?;
164            info!("Installed system service unit: {}", service_path.display());
165            self.reload().await?;
166        }
167
168        Ok(())
169    }
170
171    async fn uninstall(&self, service: &str) -> Result<()> {
172        let _ = self.stop(service).await;
173        let path = Self::units_dir().join(Self::service_unit(service));
174        if path.exists() {
175            std::fs::remove_file(&path)?;
176            info!("Removed: {}", path.display());
177        }
178        self.reload().await
179    }
180
181    async fn start(&self, service: &str) -> Result<()> {
182        self.systemd
183            .start_unit(Self::service_unit(service), "replace".into())
184            .await?;
185        info!(
186            "Started system service unit: {}",
187            Self::service_unit(service)
188        );
189        Ok(())
190    }
191
192    async fn stop(&self, service: &str) -> Result<()> {
193        self.systemd
194            .stop_unit(Self::service_unit(service), "replace".into())
195            .await?;
196        info!(
197            "Stopped system service unit: {}",
198            Self::service_unit(service)
199        );
200        Ok(())
201    }
202
203    async fn is_active(&self, service: &str) -> Result<bool> {
204        match self.systemd.get_unit(Self::service_unit(service)).await {
205            Ok(unit_path) => {
206                let unit =
207                    zbus_systemd::systemd1::UnitProxy::builder(self.systemd.inner().connection())
208                        .path(unit_path)?
209                        .build()
210                        .await?;
211                let state = unit.active_state().await?;
212                Ok(state == "active")
213            }
214            Err(_) => Ok(false),
215        }
216    }
217
218    async fn reload(&self) -> Result<()> {
219        let status = tokio::process::Command::new("systemctl")
220            .arg("daemon-reload")
221            .status()
222            .await
223            .context("failed to spawn systemctl daemon-reload")?;
224        if !status.success() {
225            anyhow::bail!("systemctl daemon-reload failed (exit {})", status);
226        }
227        debug!("Reloaded systemd system daemon");
228        Ok(())
229    }
230
231    async fn enable(&self, service: &str) -> Result<()> {
232        let status = tokio::process::Command::new("systemctl")
233            .args(["enable", &Self::service_unit(service)])
234            .status()
235            .await
236            .context("failed to spawn systemctl enable")?;
237        if !status.success() {
238            anyhow::bail!(
239                "systemctl enable {} failed (exit {})",
240                Self::service_unit(service),
241                status
242            );
243        }
244        debug!(
245            "Enabled system service unit: {}",
246            Self::service_unit(service)
247        );
248        Ok(())
249    }
250
251    async fn spawn(&self, service: Box<dyn Spawnable>) -> Result<SpawnedService> {
252        self.ensure(service.name()).await?;
253        Ok(SpawnedService::dummy())
254    }
255}
256
257#[async_trait]
258impl ServiceManager for SystemdManager {
259    async fn install(&self, service: &str) -> Result<()> {
260        let units_dir = Self::units_dir()?;
261        std::fs::create_dir_all(&units_dir)?;
262
263        // Check whether credentials have already been encrypted into the systemd
264        // credstore. The caller (handle_service_install in hyprstream) is expected
265        // to call encrypt_credentials_if_available() BEFORE calling install(),
266        // so by the time we generate the unit the .cred files should be present.
267        let use_creds = credstore_has_credentials();
268
269        // Look up the factory to get depends_on for this service.
270        let depends_on = crate::service::factory::get_factory(service)
271            .map(|f| f.depends_on)
272            .unwrap_or(&[]);
273
274        let service_content = units::service_unit(service, use_creds, depends_on)?;
275        let service_path = units_dir.join(Self::service_unit(service));
276
277        // Write service unit if changed (idempotent), then reload so systemd
278        // sees the new unit before any subsequent start() or enable() call.
279        if std::fs::read_to_string(&service_path).ok().as_deref() != Some(&service_content) {
280            std::fs::write(&service_path, &service_content)?;
281            info!("Installed service unit: {}", service_path.display());
282            self.reload().await?;
283        }
284
285        Ok(())
286    }
287
288    async fn start(&self, service: &str) -> Result<()> {
289        self.systemd
290            .start_unit(Self::service_unit(service), "replace".into())
291            .await?;
292        info!("Started service unit: {}", Self::service_unit(service));
293        Ok(())
294    }
295
296    async fn stop(&self, service: &str) -> Result<()> {
297        self.systemd
298            .stop_unit(Self::service_unit(service), "replace".into())
299            .await?;
300        info!("Stopped service unit: {}", Self::service_unit(service));
301        Ok(())
302    }
303
304    async fn is_active(&self, service: &str) -> Result<bool> {
305        // Check if the SERVICE unit is active, not the socket unit
306        match self.systemd.get_unit(Self::service_unit(service)).await {
307            Ok(unit_path) => {
308                // Query the unit's ActiveState property via D-Bus
309                let unit =
310                    zbus_systemd::systemd1::UnitProxy::builder(self.systemd.inner().connection())
311                        .path(unit_path)?
312                        .build()
313                        .await?;
314                let state = unit.active_state().await?;
315                Ok(state == "active")
316            }
317            Err(_) => Ok(false),
318        }
319    }
320
321    async fn reload(&self) -> Result<()> {
322        // Use systemctl subprocess rather than the D-Bus Reload() call.
323        // The D-Bus call hangs on systemd 258+ (Fedora 43) during daemon-reload
324        // when called from a non-session context.
325        let status = tokio::process::Command::new("systemctl")
326            .args(["--user", "daemon-reload"])
327            .status()
328            .await
329            .context("failed to spawn systemctl --user daemon-reload")?;
330        if !status.success() {
331            anyhow::bail!("systemctl --user daemon-reload failed (exit {})", status);
332        }
333        debug!("Reloaded systemd user daemon");
334        Ok(())
335    }
336
337    async fn enable(&self, service: &str) -> Result<()> {
338        let status = tokio::process::Command::new("systemctl")
339            .args(["--user", "enable", &Self::service_unit(service)])
340            .status()
341            .await
342            .context("failed to spawn systemctl --user enable")?;
343        if !status.success() {
344            anyhow::bail!(
345                "systemctl --user enable {} failed (exit {})",
346                Self::service_unit(service),
347                status
348            );
349        }
350        debug!("Enabled service unit: {}", Self::service_unit(service));
351        Ok(())
352    }
353
354    async fn uninstall(&self, service: &str) -> Result<()> {
355        // Stop the service first
356        let _ = self.stop(service).await;
357
358        // Remove service unit file
359        let units_dir = Self::units_dir()?;
360        let service_path = units_dir.join(Self::service_unit(service));
361
362        if service_path.exists() {
363            std::fs::remove_file(&service_path)?;
364            info!("Removed: {}", service_path.display());
365        }
366
367        self.reload().await
368    }
369
370    async fn spawn(&self, service: Box<dyn Spawnable>) -> Result<SpawnedService> {
371        // Call existing ensure() to install and start systemd unit
372        self.ensure(service.name()).await?;
373        Ok(SpawnedService::dummy())
374    }
375}
376
377// ─── Systemd credential helpers ─────────────────────────────────────────────
378
379/// Check whether any of the managed credentials exist in the systemd user
380/// credstore (`~/.config/credstore.encrypted/`).
381///
382/// Used by `install()` to decide whether to generate units with
383/// `ImportCredential=` directives.  Callers are expected to invoke
384/// [`encrypt_credentials_if_available`] first so the `.cred` files are present.
385fn credstore_has_credentials() -> bool {
386    let Some(credstore) = dirs::config_dir().map(|d| d.join("credstore.encrypted")) else {
387        return false;
388    };
389    if !credstore.exists() {
390        return false;
391    }
392    units::ALL_CREDENTIAL_NAMES
393        .iter()
394        .any(|name| credstore.join(name).exists())
395}
396
397// ─── Systemd credential encryption ──────────────────────────────────────────
398
399/// Check whether `systemd-creds` is available on `$PATH`.
400fn has_systemd_creds() -> bool {
401    std::process::Command::new("systemd-creds")
402        .arg("--version")
403        .stdout(std::process::Stdio::null())
404        .stderr(std::process::Stdio::null())
405        .status()
406        .map(|s| s.success())
407        .unwrap_or(false)
408}
409
410/// Encrypt a single secret into the systemd user credstore.
411///
412/// Runs: `systemd-creds encrypt --user --name=<name> --with-key=auto - <output>`
413/// reading the plaintext from stdin and writing the encrypted `.cred` file.
414fn systemd_creds_encrypt(name: &str, plaintext: &[u8], credstore: &std::path::Path) -> Result<()> {
415    use std::io::Write as _;
416    let output_path = credstore.join(name);
417    let mut child = std::process::Command::new("systemd-creds")
418        .args([
419            "encrypt",
420            "--user",
421            &format!("--name={name}"),
422            "--with-key=auto",
423            "-", // read from stdin
424            output_path.to_str().unwrap_or("-"),
425        ])
426        .stdin(std::process::Stdio::piped())
427        .stdout(std::process::Stdio::null())
428        .stderr(std::process::Stdio::piped())
429        .spawn()
430        .with_context(|| format!("failed to spawn systemd-creds for '{name}'"))?;
431
432    child
433        .stdin
434        .as_mut()
435        .ok_or_else(|| anyhow!("no stdin on systemd-creds"))?
436        .write_all(plaintext)
437        .context("failed to write plaintext to systemd-creds stdin")?;
438
439    let output = child
440        .wait_with_output()
441        .with_context(|| format!("systemd-creds failed for '{name}'"))?;
442
443    if !output.status.success() {
444        let stderr = String::from_utf8_lossy(&output.stderr);
445        anyhow::bail!("systemd-creds encrypt failed for '{name}': {stderr}");
446    }
447
448    debug!("Encrypted credential '{name}' → {}", output_path.display());
449    Ok(())
450}
451
452/// Encrypt all secrets from `secrets_dir` into the systemd user credstore
453/// (`~/.config/credstore.encrypted/`).
454///
455/// Returns `true` if at least one credential was encrypted successfully and the
456/// generated service unit should include `ImportCredential=` directives.
457/// Returns `false` if `systemd-creds` is unavailable or no secrets were found.
458///
459/// Pass `None` for `secrets_dir` to use the default: the instance-namespaced
460/// `~/.config/hyprstream[/instances/{inst}]/credentials`.
461///
462/// # Best-effort defense-in-depth (#808)
463///
464/// The plaintext 0600 files in `secrets_dir` remain the authoritative copy and
465/// are NOT deleted: per-service `LoadCredential=` sources and CLI tooling read
466/// them directly. The encrypted credstore is an additional TPM2/host-key-bound
467/// copy consumed via `ImportCredential=` — protection here is best-effort
468/// defense-in-depth, not the sole at-rest control.
469pub fn encrypt_credentials_if_available(secrets_dir: Option<&std::path::Path>) -> bool {
470    if !has_systemd_creds() {
471        tracing::warn!(
472            "systemd-creds not found on $PATH; service unit will not use ImportCredential=.\n\
473             Secret files will be stored as plain files (mode 0600).\n\
474             Install systemd 250+ and re-run 'hyprstream service install' to enable \
475             TPM2/host-key-backed credential protection."
476        );
477        return false;
478    }
479
480    let default_dir;
481    let dir: &std::path::Path = match secrets_dir {
482        Some(d) => d,
483        None => {
484            default_dir = match units::hyprstream_config_dir() {
485                Ok(dir) => dir.map(|d| d.join("credentials")),
486                Err(error) => {
487                    tracing::error!(
488                        "Invalid instance name while resolving credentials directory: {error}"
489                    );
490                    return false;
491                }
492            };
493            match default_dir.as_deref() {
494                Some(d) => d,
495                None => {
496                    tracing::warn!(
497                        "Could not determine config dir for secrets; skipping credential encryption"
498                    );
499                    return false;
500                }
501            }
502        }
503    };
504
505    let credstore = match dirs::config_dir() {
506        Some(d) => d.join("credstore.encrypted"),
507        None => {
508            tracing::warn!(
509                "Could not determine config dir for credstore; skipping credential encryption"
510            );
511            return false;
512        }
513    };
514
515    if let Err(e) = std::fs::create_dir_all(&credstore) {
516        tracing::warn!(
517            "Could not create credstore directory '{}': {e}",
518            credstore.display()
519        );
520        return false;
521    }
522
523    let mut encrypted_count = 0usize;
524
525    // Encrypt node-level credentials (flat: signing-key, ca-pubkey,
526    // ca-mldsa-pubkey, bootstrap-pubkeys, rsa-key, TLS)
527    // Note: signing-key is written as a copy of the CA key so PolicyService can load it
528    for name in units::NODE_CREDENTIAL_NAMES
529        .iter()
530        .chain(std::iter::once(&"signing-key"))
531    {
532        let secret_path = dir.join(name);
533        if !secret_path.exists() {
534            debug!("Skipping node credential '{}' (not yet generated)", name);
535            continue;
536        }
537        let plaintext = match std::fs::read(&secret_path) {
538            Ok(b) => b,
539            Err(e) => {
540                tracing::warn!("Could not read secret '{}': {e}", secret_path.display());
541                continue;
542            }
543        };
544        match systemd_creds_encrypt(name, &plaintext, &credstore) {
545            Ok(()) => encrypted_count += 1,
546            Err(e) => tracing::warn!("Failed to encrypt credential '{name}': {e}"),
547        }
548    }
549
550    // Encrypt per-service credentials with service-prefixed names
551    // e.g., credentials/model/signing-key → credstore.encrypted/model-signing-key
552    if let Ok(entries) = std::fs::read_dir(dir) {
553        for entry in entries.flatten() {
554            let path = entry.path();
555            if !path.is_dir() {
556                continue;
557            }
558            let service_name = match entry.file_name().to_str() {
559                Some(n) => n.to_owned(),
560                None => continue,
561            };
562            for name in units::SERVICE_CREDENTIAL_NAMES {
563                let secret_path = path.join(name);
564                if !secret_path.exists() {
565                    continue;
566                }
567                let plaintext = match std::fs::read(&secret_path) {
568                    Ok(b) => b,
569                    Err(e) => {
570                        tracing::warn!("Could not read secret '{}': {e}", secret_path.display());
571                        continue;
572                    }
573                };
574                let prefixed_name = format!("{service_name}-{name}");
575                match systemd_creds_encrypt(&prefixed_name, &plaintext, &credstore) {
576                    Ok(()) => encrypted_count += 1,
577                    Err(e) => tracing::warn!("Failed to encrypt credential '{prefixed_name}': {e}"),
578                }
579            }
580        }
581    }
582    // Note: per-service credentials are now stored with prefixed names in the
583    // flat credstore (e.g., model-signing-key, model-service-jwt) so that
584    // ImportCredential can decrypt them. Subdirectory encryption was removed
585    // because SetLoadCredential doesn't decrypt systemd-creds encrypted files.
586
587    // Encrypt policy-only credentials (ca-key)
588    for name in units::POLICY_CREDENTIAL_NAMES {
589        let secret_path = dir.join(name);
590        if !secret_path.exists() {
591            continue;
592        }
593        let plaintext = match std::fs::read(&secret_path) {
594            Ok(b) => b,
595            Err(e) => {
596                tracing::warn!("Could not read secret '{}': {e}", secret_path.display());
597                continue;
598            }
599        };
600        match systemd_creds_encrypt(name, &plaintext, &credstore) {
601            Ok(()) => encrypted_count += 1,
602            Err(e) => tracing::warn!("Failed to encrypt credential '{name}': {e}"),
603        }
604    }
605
606    if encrypted_count > 0 {
607        info!(
608            "Encrypted {encrypted_count} credential(s) into '{}'",
609            credstore.display()
610        );
611        true
612    } else {
613        tracing::warn!("No credentials found to encrypt; units will not use ImportCredential=");
614        false
615    }
616}