Skip to main content

hyprstream_service/service/manager/
units.rs

1//! Systemd unit file generation
2//!
3//! Generates socket and service unit files for hyprstream services.
4
5use anyhow::{anyhow, Context, Result};
6
7use hyprstream_rpc::paths;
8
9const SECRETS_PROFILE_ENV: &str = "HYPRSTREAM_SECRETS_PROFILE";
10const PER_SERVICE_SCOPED_PROFILE: &str = "per-service-scoped";
11
12/// Generate a systemd socket unit for a service
13///
14/// The socket listens on `$XDG_RUNTIME_DIR/hyprstream/{service}.sock`
15/// and activates the corresponding service unit on connection.
16pub fn socket_unit(service: &str) -> String {
17    format!(
18        r#"[Unit]
19Description=Hyprstream {service} Socket
20
21[Socket]
22ListenStream=%t/hyprstream/{service}.sock
23SocketMode=0600
24
25[Install]
26WantedBy=sockets.target
27"#
28    )
29}
30
31/// Node-level credentials — every service on this node needs these.
32///
33/// These are infrastructure secrets shared across services:
34/// signing-key (CA key, also used by PolicyService), RSA key, TLS materials.
35/// Per-service signing keys are stored in per-service subdirectories and loaded
36/// via SetLoadCredential.
37pub const NODE_CREDENTIAL_NAMES: &[&str] = &[
38    "rsa-key",
39    "tls-key",
40    "tls-cert",
41    "quic-key",
42    "quic-cert",
43    "ca-pubkey",
44    "ca-mldsa-pubkey",
45    "bootstrap-pubkeys",
46];
47
48/// Per-service credentials — each service gets its own subdirectory.
49///
50/// Stored under `credentials/{service_name}/`:
51/// - `signing-key` — service's own independent Ed25519 private key
52///   (loaded via SetLoadCredential from per-service credstore subdirectory)
53/// - `service-jwt` — CA-signed JWT certificate binding name → pubkey
54///
55/// Note: `signing-key` is also in NODE_CREDENTIAL_NAMES (flat credstore) as
56/// the CA key for PolicyService. Non-policy services use SetLoadCredential
57/// to override with their independent per-service key.
58pub const SERVICE_CREDENTIAL_NAMES: &[&str] = &["signing-key", "service-jwt"];
59
60/// Policy-service-only credentials.
61///
62/// The CA private key is only available to PolicyService (the CA).
63pub const POLICY_CREDENTIAL_NAMES: &[&str] = &["ca-key"];
64
65/// All managed credential names (node + service).
66///
67/// Used by `encrypt_credentials_if_available` to encrypt all secrets
68/// from the secrets directory into the systemd credstore.
69///
70/// `user-signing-key` is deliberately absent: it is a CLI-side client
71/// credential (challenge-response enrollment) with no service-side consumer,
72/// so no unit imports it. The `credential-store-key` name was removed — it had
73/// no producer or consumer anywhere in the tree (#808).
74pub const ALL_CREDENTIAL_NAMES: &[&str] = &[
75    "signing-key",
76    "rsa-key",
77    "tls-key",
78    "tls-cert",
79    "quic-key",
80    "quic-cert",
81    "ca-key",
82    "ca-pubkey",
83    "ca-mldsa-pubkey",
84    "bootstrap-pubkeys",
85    "service-jwt",
86];
87
88/// Build credential directives for a service unit.
89///
90/// This is the single, path-independent fail-closed guard shared by both the
91/// user-unit (`service_unit`) and system-unit (`system_service_unit`) emission
92/// paths. A non-policy service must have its own plaintext signing key
93/// available for `LoadCredential=`. Falling through to
94/// `ImportCredential=signing-key` would import the node/CA root key from the
95/// flat credstore into that service.
96fn credential_directives(
97    service: &str,
98    names: &[&str],
99    credstore: &std::path::Path,
100    plain_creds: &std::path::Path,
101) -> Result<String> {
102    let mut import_lines = String::new();
103
104    for name in names {
105        // Per-service credentials (signing-key, service-jwt): each service
106        // has its own independent Ed25519 key stored in a subdirectory.
107        //
108        // ImportCredential requires the credstore file name to match the
109        // runtime name, but per-service creds are encrypted with prefixed
110        // names (e.g. model-signing-key). Use LoadCredential to load from
111        // the plaintext file directly, making it available as the unprefixed
112        // name the runtime expects.
113        //
114        // Policy is special: its "signing-key" IS the CA key, stored flat
115        // in the encrypted credstore, so ImportCredential works for it.
116        if SERVICE_CREDENTIAL_NAMES.contains(name) && service != "policy" {
117            let plain_path = plain_creds.join(service).join(name);
118            if plain_path.is_file() {
119                import_lines.push_str(&format!("LoadCredential={name}:{}\n", plain_path.display()));
120                continue;
121            }
122            if *name == "signing-key" {
123                anyhow::bail!(
124                    "per-service signing key '{}' is missing; refusing to import the node/CA root key as service '{}'. Re-run 'hyprstream service install' after provisioning service credentials",
125                    plain_path.display(),
126                    service
127                );
128            }
129        }
130        if credstore.join(name).exists() {
131            import_lines.push_str(&format!("ImportCredential={name}\n"));
132        }
133    }
134
135    Ok(import_lines)
136}
137
138/// Build the credential section for a system-wide service unit.
139///
140/// Kept separate from `system_service_unit` so the system path can be tested
141/// with injectable paths while still routing every credential through the
142/// shared [`credential_directives`] fail-closed guard.
143fn system_creds_section(
144    service: &str,
145    is_appimage: bool,
146    credstore: &std::path::Path,
147    plain_creds: &std::path::Path,
148) -> Result<String> {
149    let mut names: Vec<&'static str> = NODE_CREDENTIAL_NAMES.to_vec();
150    names.extend(SERVICE_CREDENTIAL_NAMES.iter().copied());
151    if service == "policy" {
152        names.extend(POLICY_CREDENTIAL_NAMES.iter().copied());
153    }
154
155    let import_lines = credential_directives(service, &names, credstore, plain_creds)?;
156
157    Ok(if import_lines.is_empty() {
158        String::new()
159    } else {
160        let private_mounts = if is_appimage {
161            ""
162        } else {
163            "\nPrivateMounts=yes"
164        };
165        format!(
166            "\n{import_lines}Environment=HYPRSTREAM__SECRETS__PATH=%d\n\
167             Environment={SECRETS_PROFILE_ENV}={PER_SERVICE_SCOPED_PROFILE}{private_mounts}"
168        )
169    })
170}
171
172/// Instance-namespaced hyprstream config directory.
173///
174/// Mirrors the `StoragePaths` prefixing used by the bootstrap/config writers
175/// (`$XDG_CONFIG_HOME/hyprstream/instances/{inst}` when `HYPRSTREAM_INSTANCE`
176/// is set) so generated units reference the same credential paths that were
177/// actually provisioned (#808).
178///
179/// Note: the systemd *credstore* itself (`$XDG_CONFIG_HOME/credstore.encrypted`)
180/// is a fixed, systemd-owned location and is intentionally NOT namespaced.
181fn validated_instance_name() -> Result<Option<String>> {
182    match std::env::var("HYPRSTREAM_INSTANCE") {
183        Ok(inst) if !inst.is_empty() => {
184            if inst.contains('/') || inst.contains("..") {
185                return Err(anyhow!(
186                    "HYPRSTREAM_INSTANCE must not contain '/' or '..': {:?}",
187                    inst
188                ));
189            }
190            Ok(Some(inst))
191        }
192        _ => Ok(None),
193    }
194}
195
196pub(crate) fn hyprstream_config_dir() -> Result<Option<std::path::PathBuf>> {
197    let Some(base) = dirs::config_dir().map(|dir| dir.join("hyprstream")) else {
198        return Ok(None);
199    };
200    Ok(match validated_instance_name()? {
201        Some(inst) => Some(base.join("instances").join(inst)),
202        None => Some(base),
203    })
204}
205
206/// Generate a systemd service unit for a service.
207///
208/// # Arguments
209///
210/// * `service` — service name (e.g., "policy", "oauth")
211/// * `use_systemd_creds` — whether to emit `ImportCredential=` directives
212/// * `depends_on` — service names that must start before this one
213///
214/// # Credential scoping
215///
216/// All services receive node-level credentials (signing key, TLS/QUIC
217/// materials) plus their per-service credentials; only `policy` additionally
218/// receives the CA private key.
219///
220/// # Startup ordering
221///
222/// When `depends_on` is non-empty, the unit includes `After=` and
223/// `Requires=` directives so systemd enforces the dependency graph.
224pub fn service_unit(service: &str, use_systemd_creds: bool, depends_on: &[&str]) -> Result<String> {
225    // Prefer installed binary for systemd units (stable location)
226    let exec = paths::installed_executable_path()
227        .map(Ok)
228        .unwrap_or_else(paths::executable_path)
229        .context("Failed to get executable path")?;
230
231    // AppImages bundle libtorch and configure LD_LIBRARY_PATH themselves via
232    // AppRun. Emitting LD_LIBRARY_PATH/LIBTORCH from the installer's environment
233    // would hardcode a stale /tmp/.mount_hyprst*/ path that is invalid when
234    // services start. Skip those vars if the target binary is an AppImage.
235    let is_appimage = std::env::var("APPIMAGE").is_ok()
236        || exec
237            .extension()
238            .map(|e| e.eq_ignore_ascii_case("appimage"))
239            .unwrap_or(false)
240        || exec
241            .read_link()
242            .ok()
243            .and_then(|t| t.extension().map(|e| e.eq_ignore_ascii_case("appimage")))
244            .unwrap_or(false);
245
246    let hyprstream_instance = validated_instance_name()?;
247
248    // Build Environment= directives
249    let env_directives = if is_appimage {
250        // AppImage manages its own libtorch — only forward instance namespace.
251        vec![hyprstream_instance.map(|v| format!("Environment=HYPRSTREAM_INSTANCE={v}"))]
252    } else {
253        vec![
254            std::env::var("LD_LIBRARY_PATH")
255                .ok()
256                .map(|v| format!("Environment=LD_LIBRARY_PATH={v}")),
257            std::env::var("LIBTORCH")
258                .ok()
259                .map(|v| format!("Environment=LIBTORCH={v}")),
260            hyprstream_instance.map(|v| format!("Environment=HYPRSTREAM_INSTANCE={v}")),
261        ]
262    }
263    .into_iter()
264    .flatten()
265    .collect::<Vec<_>>()
266    .join("\n");
267
268    let env_section = if env_directives.is_empty() {
269        String::new()
270    } else {
271        format!("\n{env_directives}")
272    };
273
274    // Build systemd credentials section — only import credentials that
275    // actually exist in the credstore.
276    let creds_section = if use_systemd_creds {
277        let credstore = dirs::config_dir()
278            .map(|d| d.join("credstore.encrypted"))
279            .unwrap_or_default();
280
281        // Node-level credentials for all services; add per-service credentials
282        // from the service's subdirectory; add CA private key for policy.
283        let mut names: Vec<&'static str> = NODE_CREDENTIAL_NAMES.to_vec();
284        names.extend(SERVICE_CREDENTIAL_NAMES.iter().copied());
285        if service == "policy" {
286            names.extend(POLICY_CREDENTIAL_NAMES.iter().copied());
287        }
288
289        // Plaintext credential directory (wizard-written files), instance-
290        // namespaced to match StoragePaths (#808):
291        //   ~/.config/hyprstream[/instances/{inst}]/credentials/{service}/signing-key
292        let plain_creds = hyprstream_config_dir()?
293            .map(|d| d.join("credentials"))
294            .unwrap_or_default();
295
296        let all_cred_lines = credential_directives(service, &names, &credstore, &plain_creds)?;
297
298        if all_cred_lines.is_empty() {
299            String::new()
300        } else {
301            // PrivateMounts=yes is recommended for credential users, but it
302            // creates a private mount namespace that prevents AppImage FUSE
303            // mounts.  Only enable it for non-AppImage executables.
304            let private_mounts = if is_appimage {
305                ""
306            } else {
307                "\nPrivateMounts=yes"
308            };
309            format!(
310                "\n{}Environment=HYPRSTREAM__SECRETS__PATH=%d\n\
311                 Environment={SECRETS_PROFILE_ENV}={PER_SERVICE_SCOPED_PROFILE}{private_mounts}",
312                all_cred_lines
313            )
314        }
315    } else {
316        String::new()
317    };
318
319    // Build dependency directives for [Unit] section.
320    let dep_section = if depends_on.is_empty() {
321        String::new()
322    } else {
323        let units: Vec<String> = depends_on
324            .iter()
325            .map(|dep| format!("hyprstream-{dep}.service"))
326            .collect();
327        let unit_list = units.join(" ");
328        format!("\nAfter={unit_list}\nRequires={unit_list}")
329    };
330
331    // Security hardening directives.
332    let hardening = format!(
333        "\nLimitCORE=0\nProtectProc=invisible\nProcSubset=pid{}",
334        if is_appimage { "" } else { "\nPrivateTmp=yes" }
335    );
336
337    Ok(format!(
338        r#"[Unit]
339Description=Hyprstream {service} Service{dep_section}
340
341[Service]
342Type=notify
343# Writable state home ($STATE_DIRECTORY) for JWT rotation state — the
344# credentials ramfs ($CREDENTIALS_DIRECTORY) is read-only (#803).
345StateDirectory=hyprstream
346ExecStart={exec} service start {service} --foreground{env_section}{creds_section}{hardening}
347Restart=on-failure
348RestartSec=2s
349
350[Install]
351WantedBy=default.target
352"#,
353        exec = exec.display(),
354        dep_section = dep_section,
355        env_section = env_section,
356        creds_section = creds_section,
357        hardening = hardening,
358    ))
359}
360
361/// Generate a systemd socket unit for system-wide (root) installation.
362///
363/// Socket listens on `/run/hyprstream/{service}.sock` and activates the
364/// corresponding service unit on connection.
365pub fn system_socket_unit(service: &str) -> String {
366    format!(
367        r#"[Unit]
368Description=Hyprstream {service} Socket (system)
369
370[Socket]
371ListenStream=/run/hyprstream/{service}.sock
372SocketMode=0660
373SocketGroup=hyprstream
374
375[Install]
376WantedBy=sockets.target
377"#
378    )
379}
380
381/// Generate a systemd service unit for system-wide (root) installation.
382///
383/// The unit runs as the `hyprstream` system user and uses
384/// `RuntimeDirectory=hyprstream` (→ `/run/hyprstream/`) for sockets.
385/// Boots automatically via `WantedBy=multi-user.target`.
386pub fn system_service_unit(service: &str, depends_on: &[&str]) -> Result<String> {
387    let exec = paths::installed_executable_path()
388        .map(Ok)
389        .unwrap_or_else(paths::executable_path)
390        .context("Failed to get executable path")?;
391
392    let is_appimage = std::env::var("APPIMAGE").is_ok()
393        || exec
394            .extension()
395            .map(|e| e.eq_ignore_ascii_case("appimage"))
396            .unwrap_or(false)
397        || exec
398            .read_link()
399            .ok()
400            .and_then(|t| t.extension().map(|e| e.eq_ignore_ascii_case("appimage")))
401            .unwrap_or(false);
402
403    let hyprstream_instance = validated_instance_name()?;
404
405    let env_directives = if is_appimage {
406        vec![hyprstream_instance
407            .as_ref()
408            .map(|v| format!("Environment=HYPRSTREAM_INSTANCE={v}"))]
409    } else {
410        vec![
411            std::env::var("LD_LIBRARY_PATH")
412                .ok()
413                .map(|v| format!("Environment=LD_LIBRARY_PATH={v}")),
414            std::env::var("LIBTORCH")
415                .ok()
416                .map(|v| format!("Environment=LIBTORCH={v}")),
417            hyprstream_instance
418                .as_ref()
419                .map(|v| format!("Environment=HYPRSTREAM_INSTANCE={v}")),
420        ]
421    }
422    .into_iter()
423    .flatten()
424    .collect::<Vec<_>>()
425    .join("\n");
426
427    let env_section = if env_directives.is_empty() {
428        String::new()
429    } else {
430        format!("\n{env_directives}")
431    };
432
433    // System-wide credential plumbing (#808): mirrors the user-unit logic with
434    // FHS system paths. `LoadCredential=`/`ImportCredential=` sources are read
435    // by PID 1 (root) and passed to the service through the private, access-
436    // restricted credentials ramfs ($CREDENTIALS_DIRECTORY), so the
437    // `hyprstream` user never needs read access to the on-disk originals.
438    let creds_section = {
439        let credstore = std::path::PathBuf::from("/etc/credstore.encrypted");
440        let plain_creds = match hyprstream_instance {
441            Some(ref inst) => std::path::PathBuf::from("/etc/hyprstream")
442                .join("instances")
443                .join(inst)
444                .join("credentials"),
445            _ => std::path::PathBuf::from("/etc/hyprstream/credentials"),
446        };
447
448        system_creds_section(service, is_appimage, &credstore, &plain_creds)?
449    };
450
451    let dep_section = if depends_on.is_empty() {
452        String::new()
453    } else {
454        let units: Vec<String> = depends_on
455            .iter()
456            .map(|dep| format!("hyprstream-{dep}.service"))
457            .collect();
458        let unit_list = units.join(" ");
459        format!("\nAfter={unit_list}\nRequires={unit_list}")
460    };
461
462    let hardening = format!(
463        "\nLimitCORE=0\nProtectProc=invisible\nProcSubset=pid{}",
464        if is_appimage { "" } else { "\nPrivateTmp=yes" }
465    );
466
467    Ok(format!(
468        r#"[Unit]
469Description=Hyprstream {service} Service (system){dep_section}
470
471[Service]
472Type=notify
473User=hyprstream
474RuntimeDirectory=hyprstream
475RuntimeDirectoryMode=0750
476# Writable state home ($STATE_DIRECTORY) for JWT rotation state — the
477# credentials ramfs ($CREDENTIALS_DIRECTORY) is read-only (#803).
478StateDirectory=hyprstream
479ExecStart={exec} service start {service} --foreground{env_section}{creds_section}{hardening}
480Restart=on-failure
481RestartSec=2s
482
483[Install]
484WantedBy=multi-user.target
485"#,
486        exec = exec.display(),
487    ))
488}
489
490#[cfg(test)]
491mod tests {
492    use super::*;
493
494    static INSTANCE_ENV_LOCK: parking_lot::Mutex<()> = parking_lot::Mutex::new(());
495
496    struct EnvVarGuard {
497        previous: Option<String>,
498    }
499
500    impl EnvVarGuard {
501        fn set(value: &str) -> Self {
502            let previous = std::env::var("HYPRSTREAM_INSTANCE").ok();
503            std::env::set_var("HYPRSTREAM_INSTANCE", value);
504            Self { previous }
505        }
506    }
507
508    impl Drop for EnvVarGuard {
509        fn drop(&mut self) {
510            match &self.previous {
511                Some(value) => std::env::set_var("HYPRSTREAM_INSTANCE", value),
512                None => std::env::remove_var("HYPRSTREAM_INSTANCE"),
513            }
514        }
515    }
516
517    #[test]
518    fn config_dir_rejects_instance_path_traversal() -> Result<()> {
519        let _serial = INSTANCE_ENV_LOCK.lock();
520        for invalid in ["../other", "nested/name", "name..suffix"] {
521            let _instance = EnvVarGuard::set(invalid);
522            let error = match hyprstream_config_dir() {
523                Err(error) => error,
524                Ok(path) => anyhow::bail!("invalid instance resolved to {path:?}"),
525            };
526            assert!(error.to_string().contains("must not contain '/' or '..'"));
527        }
528        Ok(())
529    }
530
531    #[test]
532    fn missing_service_signing_key_never_falls_back_to_node_key() -> Result<()> {
533        let temp = tempfile::TempDir::new()?;
534        let credstore = temp.path().join("credstore.encrypted");
535        let plain_creds = temp.path().join("credentials");
536        std::fs::create_dir_all(&credstore)?;
537        std::fs::create_dir_all(plain_creds.join("model"))?;
538
539        // This is the dangerous fallback credential: the node/CA root key is
540        // present under the runtime name expected by the service.
541        std::fs::write(credstore.join("signing-key"), b"encrypted-root-key")?;
542
543        let error = match credential_directives(
544            "model",
545            SERVICE_CREDENTIAL_NAMES,
546            &credstore,
547            &plain_creds,
548        ) {
549            Err(error) => error,
550            Ok(lines) => anyhow::bail!("dangerous signing-key fallback returned: {lines}"),
551        };
552        let message = error.to_string();
553        assert!(message.contains("per-service signing key"));
554        assert!(message.contains("refusing to import the node/CA root key"));
555        Ok(())
556    }
557
558    #[test]
559    fn system_unit_missing_service_signing_key_never_falls_back_to_node_key() -> Result<()> {
560        let temp = tempfile::TempDir::new()?;
561        let credstore = temp.path().join("credstore.encrypted");
562        let plain_creds = temp.path().join("credentials");
563        std::fs::create_dir_all(&credstore)?;
564        std::fs::create_dir_all(plain_creds.join("model"))?;
565
566        // The dangerous fallback credential: node/CA root key present under
567        // the flat runtime name a non-policy system service could import.
568        std::fs::write(credstore.join("signing-key"), b"encrypted-root-key")?;
569
570        let error = match system_creds_section("model", false, &credstore, &plain_creds) {
571            Err(error) => error,
572            Ok(section) => {
573                anyhow::bail!("system-unit signing-key fallback returned: {section:?}")
574            }
575        };
576        let message = error.to_string();
577        assert!(message.contains("per-service signing key"));
578        assert!(message.contains("refusing to import the node/CA root key"));
579        Ok(())
580    }
581
582    #[test]
583    fn system_unit_loads_present_per_service_key_without_root_fallback() -> Result<()> {
584        let temp = tempfile::TempDir::new()?;
585        let credstore = temp.path().join("credstore.encrypted");
586        let plain_creds = temp.path().join("credentials");
587        std::fs::create_dir_all(&credstore)?;
588        std::fs::create_dir_all(plain_creds.join("model"))?;
589        std::fs::write(credstore.join("signing-key"), b"encrypted-root-key")?;
590        std::fs::write(plain_creds.join("model").join("signing-key"), b"svc-key")?;
591
592        let section = system_creds_section("model", false, &credstore, &plain_creds)?;
593        assert!(section.contains("LoadCredential=signing-key:"));
594        assert!(section.contains("Environment=HYPRSTREAM_SECRETS_PROFILE=per-service-scoped"));
595        assert!(
596            !section.contains("ImportCredential=signing-key"),
597            "must never import the flat node/CA root key for a non-policy service: {section}"
598        );
599        Ok(())
600    }
601}