From 4725f2bff9bba55c6ef919ba44a6fe2a03e37478 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 4 Nov 2026 12:43:07 +0300 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20refactor:=20kur=20runs=20a?= =?UTF-8?q?s=20an=20unprivileged=20account=20with=20systemd=20user=20units?= =?UTF-8?q?:=20systemctl=20--user,=20XDG=20default=20paths,=20~/=20in=20co?= =?UTF-8?q?nfig=20paths,=20deploy/user=20units,=20README=20install=20for?= =?UTF-8?q?=20a=20lingering=20app=20account?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 92 ++++++++++++++++++++++++++++--------- config/kur.example.toml | 14 +++--- deploy/kur.service | 30 ------------ deploy/user/kur.service | 13 ++++++ deploy/{ => user}/kur.timer | 2 +- src/config.rs | 92 ++++++++++++++++++++++++++++++++----- src/install.rs | 2 + src/main.rs | 15 ++++-- 8 files changed, 186 insertions(+), 74 deletions(-) delete mode 100644 deploy/kur.service create mode 100644 deploy/user/kur.service rename deploy/{ => user}/kur.timer (69%) diff --git a/README.md b/README.md index 1011587..ddde56a 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,10 @@ # kur kur ("install" in Turkish) installs the newest release of each configured app on a server. It runs -from a systemd timer, reads releases from a self-hosted forge (git.tahinli.com), and swaps a binary +from a systemd user timer, reads releases from a self-hosted forge (git.tahinli.com), and swaps a binary in only when the release asset differs from the installed file. After a swap it restarts the app's -systemd unit and health-checks it, and it rolls back to the previous binary if the check fails. It is -one binary that runs as root and has no daemon. +systemd user unit and health-checks it, and it rolls back to the previous binary if the check fails. It is +one binary that runs as an unprivileged user and has no daemon. It never runs as root. ## Releases @@ -23,15 +23,16 @@ For each app, in order: 4. Download to `{path}.kur-new`, hashing while writing. Mode 0755, fsync. 5. If `check` is set, run the new file with those arguments (10 s limit). Failure marks the build bad. 6. Rename the installed binary to `{path}.prev` and the new file to `{path}`. -7. If `unit` is set, restart it and wait until `systemctl is-active` succeeds, `health_url` returns 2xx, - and the unit is still active 5 s later. Times out after `health_timeout_secs`. +7. If `unit` is set, restart it with `systemctl --user` and wait until `systemctl --user is-active` + succeeds, `health_url` returns 2xx, and the unit is still active 5 s later. Times out after + `health_timeout_secs`. 8. On health failure, the build's sha256 is appended to `{name}.bad`. If `{path}.prev` exists, it is renamed back to `{path}` and the unit is restarted. Otherwise the run reports that there was no previous binary to restore. A run holds a lock on `{state_dir}/lock`, so a manual `kur run` exits at once while the timer's run is -in progress. `kur status` takes no lock. One app failing does not stop the others. Output goes to stdout and errors to stderr, which journald -collects. +in progress. `kur status` takes no lock. One app failing does not stop the others. Output goes to stdout +and errors to stderr, which the journal collects. ### The bad list @@ -40,21 +41,65 @@ file. To retry a build, delete its line, or delete the file to clear the list fo ## Install -Run as root on the app server. +kur and the apps it installs run as one unprivileged account, for example `apps`. Root is needed once, +to create the account and enable lingering. Everything after that is done as the account. + +As root, once: + +```sh +useradd -m apps # any name works; the examples use apps +loginctl enable-linger apps # keeps the account's user manager running without a login +``` + +Then get a working user session for the account. Plain `sudo -u apps` does not work for this: it has +no `XDG_RUNTIME_DIR`, so `systemctl --user` fails there. Use `machinectl` instead: + +```sh +sudo machinectl shell apps@ +``` + +As that user, from a checkout of this repo (or with the files copied over), with the kur release binary +for this machine in the current directory: ```sh -install -m 0755 kur /usr/local/bin/kur -install -d -m 0755 /etc/kur -install -m 0600 config/kur.example.toml /etc/kur/kur.toml # then edit it +install -d ~/bin ~/.config/kur ~/.config/systemd/user +install -m 0755 kur-x86_64-linux ~/bin/kur # aarch64 hosts use kur-aarch64-linux +install -m 0600 config/kur.example.toml ~/.config/kur/kur.toml # then edit it # Optional, for private repos. Use a read-only token. -(umask 077; printf '%s\n' 'TOKEN' > /etc/kur/token) -install -m 0644 deploy/kur.service deploy/kur.timer /etc/systemd/system/ -systemctl daemon-reload -systemctl enable --now kur.timer +(umask 077; printf '%s\n' 'TOKEN' > ~/.config/kur/token) +install -m 0644 deploy/user/kur.service deploy/user/kur.timer ~/.config/systemd/user/ +systemctl --user daemon-reload +systemctl --user enable --now kur.timer ``` -The app units (for example `im.service`) are not part of this repo. They must exist before kur runs -for that app. If `token_file` is set in the config, the token file must be mode 0600. +The config file must be mode 0600. If `token_file` is set, the token file must be mode 0600 too. + +Each app must be a user unit of the same account. Its binary lives under `~/bin`, and its unit goes in +`~/.config/systemd/user/`. The app units are not part of this repo. For example, im's unit is +`deploy/user/im.service` in the im repo, installed the same way: + +```sh +install -m 0644 deploy/user/im.service ~/.config/systemd/user/ +systemctl --user daemon-reload +systemctl --user enable --now im.service +``` + +An app's unit must exist before kur runs for that app. Do not set `User=` in these units: they run as the +account already. + +### Logs + +```sh +journalctl --user -u kur +``` + +On some distros the user journal needs persistent journald storage. If `journalctl --user` shows +nothing, create `/var/log/journal` as root and restart `systemd-journald`. Until then, read the logs as +root with: + +```sh +journalctl _SYSTEMD_USER_UNIT=kur.service +``` ## Commands @@ -67,19 +112,24 @@ kur help print usage (also used for unknown commands, exit 2) ``` Global option: `--config `, placed before the command. Otherwise `KUR_CONFIG` is used, then -`/etc/kur/kur.toml`. +`$XDG_CONFIG_HOME/kur/kur.toml`, or `~/.config/kur/kur.toml` when `XDG_CONFIG_HOME` is not set. Empty +environment variables count as unset. If neither `XDG_CONFIG_HOME` nor `HOME` is set, kur prints an +error and exits 1. Exit code is 0 when every app succeeded or was up to date, and 1 if any app failed. ## Config reference +Paths may start with `~/`, which expands to `$HOME/`. Only a leading `~/` is expanded. After expansion, +`path`, `state_dir` and `token_file` must be absolute, so a bare `~` or `~user/...` is an error. + Top level: | Key | Required | Default | Meaning | |---|---|---|---| | `forge` | yes | none | Forge base URL, `https://` or `http://`. Trailing slash is trimmed. | | `token_file` | no | none | File with a forge token for private repos. Read once, trimmed. Unreadable file is a config error. | -| `state_dir` | no | `/var/lib/kur` | Directory for `.bad` and `.tag` files and the run lock. Created with mode 0700 if missing. | +| `state_dir` | no | `$XDG_STATE_HOME/kur`, else `~/.local/state/kur` | Directory for `.bad` and `.tag` files and the run lock. Created with mode 0700 if missing. | Each `[[app]]` table: @@ -88,8 +138,8 @@ Each `[[app]]` table: | `name` | yes | none | Unique. Must match `^[a-z0-9][a-z0-9_-]{0,39}$`. | | `repo` | yes | none | Forge repo as `owner/name`. | | `asset` | yes | none | Asset file name. `{arch}` is replaced by the machine architecture. | -| `path` | yes | none | Absolute path of the installed binary. | -| `unit` | no | none | systemd unit to restart and health-check. Without it kur only swaps the file. | +| `path` | yes | none | Path of the installed binary, absolute after `~/` expansion, e.g. `~/bin/im`. | +| `unit` | no | none | systemd user unit to restart (`systemctl --user`) and health-check. Without it kur only swaps the file. | | `prerelease` | no | `false` | Also accept prerelease releases. | | `check` | no | none | Arguments for the new binary, run before the swap. Must exit 0 within 10 s. | | `health_url` | no | none | URL that must return 2xx after restart. No token is sent. | diff --git a/config/kur.example.toml b/config/kur.example.toml index 2009274..0036416 100644 --- a/config/kur.example.toml +++ b/config/kur.example.toml @@ -1,23 +1,23 @@ -# Example kur config. Install it as /etc/kur/kur.toml (mode 0600). -# Field reference: README.md. +# Example kur config. Install it as ~/.config/kur/kur.toml (mode 0600). +# Field reference: README.md. Paths may start with ~/, which expands to $HOME/. # Forge base URL. A trailing slash is fine. forge = "https://git.tahinli.com" # Optional: file holding a forge token for private repos. Read once at start, trimmed. # Use a read-only token. Must be mode 0600. -# token_file = "/etc/kur/token" +# token_file = "~/.config/kur/token" # Optional: where kur keeps .bad and .tag files. Default shown. -# state_dir = "/var/lib/kur" +# state_dir = "~/.local/state/kur" -# The im server. Its unit is im.service, which kur restarts after a swap. +# The im server. Its unit is the user unit im.service, which kur restarts after a swap. [[app]] name = "im" repo = "Tahinli/im" # {arch} is replaced by the machine architecture (x86_64, aarch64). asset = "im-{arch}-linux" -path = "/usr/local/bin/im" +path = "~/bin/im" unit = "im.service" # im has no --version flag, so there is no pre-swap check. # health_url must match the listen address in im's config. @@ -32,5 +32,5 @@ health_url = "http://127.0.0.1:7650/healthz" name = "kur" repo = "Tahinli/kur" asset = "kur-{arch}-linux" -path = "/usr/local/bin/kur" +path = "~/bin/kur" check = ["--version"] diff --git a/deploy/kur.service b/deploy/kur.service deleted file mode 100644 index fd96fc5..0000000 --- a/deploy/kur.service +++ /dev/null @@ -1,30 +0,0 @@ -[Unit] -Description=kur: install newest forge releases of configured apps -Wants=network-online.target -After=network-online.target - -[Service] -Type=oneshot -# Runs as root: it replaces binaries in /usr/local/bin and restarts units. -ExecStart=/usr/local/bin/kur run -Environment=KUR_CONFIG=/etc/kur/kur.toml -# /var/lib/kur, mode 0700 (.bad, .tag files). -StateDirectory=kur -StateDirectoryMode=0700 -# Installed binaries must be 0755. kur sets the mode itself, but keep the umask -# from making anything more private than that. -UMask=0022 - -# Light hardening only. ProtectSystem= is deliberately left unset: "strict" and -# "full" make /usr read-only, and /usr/local/bin is under /usr, so kur could not -# replace app binaries. PrivateTmp, ProtectHome and the rest do not touch -# /usr/local/bin or systemctl. -NoNewPrivileges=yes -PrivateTmp=yes -ProtectHome=yes -ProtectKernelTunables=yes -ProtectKernelModules=yes -ProtectKernelLogs=yes -ProtectControlGroups=yes -RestrictSUIDSGID=yes -LockPersonality=yes diff --git a/deploy/user/kur.service b/deploy/user/kur.service new file mode 100644 index 0000000..0022b64 --- /dev/null +++ b/deploy/user/kur.service @@ -0,0 +1,13 @@ +[Unit] +Description=kur: install newest forge releases of configured apps + +[Service] +# User unit for the shared app account (for example "apps"). It runs as that account, never as root. +# The account needs `loginctl enable-linger ` so the timer runs without a login session. +# The config is read from the default path, ~/.config/kur/kur.toml (or $XDG_CONFIG_HOME). +Type=oneshot +ExecStart=%h/bin/kur run +# Installed binaries must be 0755. kur sets the mode itself, but keep the umask +# from making anything more private than that. +UMask=0022 +NoNewPrivileges=yes diff --git a/deploy/kur.timer b/deploy/user/kur.timer similarity index 69% rename from deploy/kur.timer rename to deploy/user/kur.timer index 55f00e7..db3b37a 100644 --- a/deploy/kur.timer +++ b/deploy/user/kur.timer @@ -2,7 +2,7 @@ Description=Run kur every 5 minutes [Timer] -# First run 2 minutes after boot, then 5 minutes after each run starts. +# First run 2 minutes after the user manager starts, then 5 minutes after each run starts. OnBootSec=2min OnUnitActiveSec=5min RandomizedDelaySec=30s diff --git a/src/config.rs b/src/config.rs index 9159220..2e43a72 100644 --- a/src/config.rs +++ b/src/config.rs @@ -3,14 +3,13 @@ use crate::{Res, migrate}; use serde::Deserialize; use std::collections::HashSet; +use std::env; +use std::ffi::OsString; use std::fs::{self, OpenOptions}; use std::io::{self, Write}; use std::os::unix::fs::OpenOptionsExt; use std::path::{Path, PathBuf}; -/// Config path used when neither `--config` nor `KUR_CONFIG` is given. -pub const DEFAULT_PATH: &str = "/etc/kur/kur.toml"; -const DEFAULT_STATE_DIR: &str = "/var/lib/kur"; /// Top-level keys; must match the `Raw` fields. const KNOWN_TOP_KEYS: &[&str] = &["forge", "token_file", "state_dir", "app"]; /// Keys in each `[[app]]` table; must match the `App` fields. @@ -84,6 +83,71 @@ impl App { } } +/// Value of environment variable `name`, or None if it is unset or empty. +fn env_value(name: &str) -> Option { + env::var_os(name).filter(|value| !value.is_empty()) +} + +/// `$HOME`, if set and not empty. +fn home_dir() -> Option { + env_value("HOME").map(PathBuf::from) +} + +/// Config path for a run: `cli` (from `--config`), else `KUR_CONFIG`, else `default_path()`. +pub fn config_path(cli: Option) -> Res { + match cli.or_else(|| env_value("KUR_CONFIG").map(PathBuf::from)) { + Some(path) => Ok(path), + None => default_path(), + } +} + +/// Config file used when neither `--config` nor `KUR_CONFIG` is set: +/// `$XDG_CONFIG_HOME/kur/kur.toml`, else `$HOME/.config/kur/kur.toml`. +pub fn default_path() -> Res { + let base = match env_value("XDG_CONFIG_HOME") { + Some(dir) => PathBuf::from(dir), + None => home_dir() + .ok_or_else(|| { + "neither XDG_CONFIG_HOME nor HOME is set; use --config or KUR_CONFIG".to_string() + })? + .join(".config"), + }; + Ok(base.join("kur").join("kur.toml")) +} + +/// Default `state_dir`: `$XDG_STATE_HOME/kur`, else `$HOME/.local/state/kur`. +fn default_state_dir() -> Res { + let base = match env_value("XDG_STATE_HOME") { + Some(dir) => PathBuf::from(dir), + None => home_dir() + .ok_or_else(|| { + "neither XDG_STATE_HOME nor HOME is set; set state_dir in the config".to_string() + })? + .join(".local") + .join("state"), + }; + let dir = base.join("kur"); + if !dir.is_absolute() { + return Err("state_dir must be absolute".into()); + } + Ok(dir) +} + +/// Expands a leading `~/` to `$HOME/` (and nothing else), then requires an absolute path. +/// `what` names the setting in error messages. +fn absolute_path(path: &Path, what: &str) -> Res { + let expanded = match path.to_str().and_then(|s| s.strip_prefix("~/")) { + Some(rest) => home_dir() + .ok_or_else(|| format!("{what}: cannot expand ~/ because HOME is not set"))? + .join(rest.trim_start_matches('/')), + None => path.to_path_buf(), + }; + if !expanded.is_absolute() { + return Err(format!("{what} must be absolute")); + } + Ok(expanded) +} + /// Reads and validates the config file at `path`, renaming keys listed in `migrate::RENAMES`. /// If anything was renamed and `write` is set, the file is rewritten once the config is valid. pub fn load(path: &Path, write: bool) -> Res { @@ -100,7 +164,7 @@ pub fn load(path: &Path, write: bool) -> Res { let table: toml::Table = toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; let mut warnings = unknown_key_warnings(&table); - let raw: Raw = toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; + let mut raw: Raw = toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; let forge = raw.forge.trim_end_matches('/').to_string(); if !forge.starts_with("https://") && !forge.starts_with("http://") { @@ -121,15 +185,21 @@ pub fn load(path: &Path, write: bool) -> Res { if parts.len() != 2 || parts.iter().any(|p| p.is_empty()) { return Err(format!("{}: repo must be owner/name", app.name)); } - if !app.path.is_absolute() { - return Err(format!("{}: path must be absolute", app.name)); - } + } + for app in &mut raw.apps { + app.path = absolute_path(&app.path, &format!("{}: path", app.name))?; } - let token = raw.token_file.as_deref().map(read_token).transpose()?; - let state_dir = raw - .state_dir - .unwrap_or_else(|| PathBuf::from(DEFAULT_STATE_DIR)); + let token_file = raw + .token_file + .as_deref() + .map(|file| absolute_path(file, "token_file")) + .transpose()?; + let token = token_file.as_deref().map(read_token).transpose()?; + let state_dir = match raw.state_dir.as_deref() { + Some(dir) => absolute_path(dir, "state_dir")?, + None => default_state_dir()?, + }; if !migrated.is_empty() && write && let Err(e) = rewrite_config(path, &text) diff --git a/src/install.rs b/src/install.rs index e40ccf0..5baa715 100644 --- a/src/install.rs +++ b/src/install.rs @@ -252,8 +252,10 @@ fn is_active(unit: &str) -> bool { systemctl(&["is-active", "--quiet", unit]).is_ok() } +/// Runs `systemctl --user` with `args`. Only the user manager of the account kur runs as is used. fn systemctl(args: &[&str]) -> Result<(), String> { let status = Command::new("systemctl") + .arg("--user") .args(args) .stdout(Stdio::null()) .status() diff --git a/src/main.rs b/src/main.rs index 3a74a53..b418447 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,5 +1,6 @@ //! kur: installs the newest forge release of each configured app on this host, with rollback. -//! Runs from a systemd timer as root; prints one line per app on stdout, errors on stderr. +//! Runs from a systemd user timer as the unprivileged account that owns the apps (never root). +//! Prints one line per app on stdout, errors on stderr. mod config; mod forge; @@ -25,13 +26,12 @@ commands: fn main() -> ExitCode { let mut args = env::args().skip(1); - let mut config_path = env::var_os("KUR_CONFIG") - .map_or_else(|| PathBuf::from(config::DEFAULT_PATH), PathBuf::from); + let mut cli_config: Option = None; let mut words = Vec::new(); while let Some(arg) = args.next() { match arg.as_str() { "--config" => match args.next() { - Some(path) => config_path = path.into(), + Some(path) => cli_config = Some(path.into()), None => return usage(), }, "--version" => { @@ -49,6 +49,13 @@ fn main() -> ExitCode { _ => return usage(), }; + let config_path = match config::config_path(cli_config) { + Ok(path) => path, + Err(e) => { + eprintln!("kur: {e}"); + return ExitCode::FAILURE; + } + }; // Status never writes, so a renamed key is only reported. let cfg = match config::load(&config_path, !status) { Ok(cfg) => cfg,