hyprstream_service/service/manager/
units.rs1use 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
12pub 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
31pub 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
48pub const SERVICE_CREDENTIAL_NAMES: &[&str] = &["signing-key", "service-jwt"];
59
60pub const POLICY_CREDENTIAL_NAMES: &[&str] = &["ca-key"];
64
65pub 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
88fn 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 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
138fn 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
172fn 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
206pub fn service_unit(service: &str, use_systemd_creds: bool, depends_on: &[&str]) -> Result<String> {
225 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 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 let env_directives = if is_appimage {
250 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 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 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 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 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 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 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
361pub 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
381pub 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 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 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 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}