Files
leleka/control-plane/src/service_unit.rs
T

156 lines
5.2 KiB
Rust

//! Render only: installation and lifecycle remain explicit operator actions.
use std::path::Path;
pub fn render(
executable: &Path,
config: &Path,
working_dir: &Path,
env_file: Option<&Path>,
) -> Result<String, String> {
let executable = quoted_executable(executable)?;
let config = quote(&checked_path(config, false)?);
let working_dir = working_directory(working_dir)?;
let environment = environment_line(env_file)?;
Ok(unit_text(&working_dir, &environment, &executable, &config))
}
/// The executable path as a systemd `ExecStart` word.
fn quoted_executable(executable: &Path) -> Result<String, String> {
let executable = checked_path(executable, false)?;
if executable.contains(['\'', '"', '\\']) {
return Err(
"systemd executable paths cannot contain quotes or backslashes; relocate the binary"
.into(),
);
}
Ok(quote(&executable))
}
fn working_directory(working_dir: &Path) -> Result<String, String> {
checked_path(working_dir, true)?;
let canonical_dir = working_dir.canonicalize().map_err(|e| e.to_string())?;
// These path directives are not shell-style token lists. Quotes and
// backslashes are literal; a final '/.' prevents line continuation/trim.
Ok(format!(
"{}/.",
checked_path(&canonical_dir, true)?.trim_end_matches('/')
)
.replace('%', "%%"))
}
fn environment_line(env_file: Option<&Path>) -> Result<String, String> {
let Some(path) = env_file else {
return Ok(String::new());
};
let value = checked_path(path, false)?;
// EnvironmentFile supports globs. Fail rather than load a different
// file, or silently treat a missing optional file as success.
if value.contains(['*', '?', '[', '\\']) || value.ends_with(char::is_whitespace) {
return Err(concat!(
"environment-file paths cannot contain glob characters/backslashes ",
"or end in whitespace"
)
.into());
}
Ok(format!("EnvironmentFile={}\n", value.replace('%', "%%")))
}
fn unit_text(working_dir: &str, environment: &str, executable: &str, config: &str) -> String {
// ':' disables ExecStart environment-variable substitution; %% escapes
// specifiers. Do not wrap this in a shell or reset the worker restart budget.
format!(
"# Generated by strata-next service-unit; install as a user unit.\n\
[Unit]\n\
Description=Strata Next native Responses runtime\n\
\n\
[Service]\n\
Type=exec\n\
WorkingDirectory={working_dir}\n\
{environment}\
ExecStart=:{executable} serve --config {config}\n\
UMask=0077\n\
NoNewPrivileges=yes\n\
KillSignal=SIGTERM\n\
KillMode=mixed\n\
TimeoutStopSec=45\n\
SendSIGKILL=yes\n\
Restart=no\n\
StandardOutput=journal\n\
StandardError=journal\n\
\n\
[Install]\n\
WantedBy=default.target\n"
)
}
fn checked_path(path: &Path, directory: bool) -> Result<String, String> {
let value = path.to_str().ok_or("service paths must be valid UTF-8")?;
if !path.is_absolute() || value.chars().any(char::is_control) {
return Err("service paths must be absolute and contain no control characters".into());
}
if if directory {
!path.is_dir()
} else {
!path.is_file()
} {
return Err(format!(
"service path has wrong type or does not exist: {value}"
));
}
Ok(value.to_owned())
}
fn quote(value: &str) -> String {
format!(
"\"{}\"",
value
.replace('\\', "\\\\")
.replace('"', "\\\"")
.replace('%', "%%")
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn special_characters_are_literal() {
assert_eq!(
quote("/srv/a b/%n/${HOME}/\"quoted\"/back\\slash"),
"\"/srv/a b/%%n/${HOME}/\\\"quoted\\\"/back\\\\slash\""
);
}
#[test]
fn refuses_relative_control_and_missing_paths() {
for path in ["relative.json", "/tmp/line\nbreak", "/tmp/zero\0byte"] {
assert!(checked_path(Path::new(path), false).is_err());
}
let missing = std::env::temp_dir().join(format!(
"strata-service-missing-{}-{}",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
assert!(checked_path(&missing, false).is_err());
}
#[cfg(unix)] // systemd unit text
#[test]
fn render_does_not_require_or_launch_an_engine() {
let executable = std::env::current_exe().unwrap();
let directory = executable.parent().unwrap();
let unit = render(&executable, &executable, directory, Some(&executable)).unwrap();
assert!(unit.contains("ExecStart=:"));
assert!(unit.contains(" serve --config "));
assert!(unit.contains("EnvironmentFile="));
assert!(unit.contains("KillMode=mixed\nTimeoutStopSec=45\n"));
assert!(unit.contains("Restart=no\n"));
assert!(render(&executable, directory, directory, None).is_err());
assert!(render(&executable, &executable, &executable, None).is_err());
}
}