From 286a6e76e526b6cb81f8284fd6f684731f11ee61 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 16:02:33 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat:=20kur=20sets=20itself=20up=20?= =?UTF-8?q?on=20first=20run=20(or=20with=20kur=20setup):=20copies=20itself?= =?UTF-8?q?=20to=20~/bin,=20writes=20a=20starter=20config,=20installs=20an?= =?UTF-8?q?d=20starts=20the=20user=20timer;=20refuses=20root?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 52 +++++----- deploy/user/kur.service | 1 - src/config.rs | 22 +++-- src/install.rs | 4 +- src/main.rs | 34 ++++++- src/setup.rs | 210 ++++++++++++++++++++++++++++++++++++++++ 6 files changed, 286 insertions(+), 37 deletions(-) create mode 100644 src/setup.rs diff --git a/README.md b/README.md index ddde56a..c7b5894 100644 --- a/README.md +++ b/README.md @@ -41,38 +41,41 @@ file. To retry a build, delete its line, or delete the file to clear the list fo ## Install -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: +kur and the apps it installs run as one unprivileged account, for example `apps`. Do not run kur as +root. Get a working user session for the account first. Plain `sudo -u apps` does not work, because it +has no `XDG_RUNTIME_DIR` and `systemctl --user` fails there. Use `machinectl`: ```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 +sudo machinectl shell apps@ ``` -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: +As that account, in the directory with the release file for this machine (`kur-x86_64-linux`, or +`kur-aarch64-linux` on aarch64 hosts): ```sh -sudo machinectl shell apps@ +sha256sum -c SHA256SUMS # verify the download; add --ignore-missing if you fetched one binary only +chmod +x kur-x86_64-linux +./kur-x86_64-linux # first run: sets kur up ``` -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: +With no command, kur runs setup when the config file is missing, and otherwise behaves like +`kur status`. Setup is idempotent and does this, printing one line per step: -```sh -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' > ~/.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 -``` +1. Refuses to run as root. +2. Copies the binary to `~/bin/kur` (skipped if the same file is already there). +3. Writes a starter config to `~/.config/kur/kur.toml` (mode 0600). It contains kur itself as an app. + An existing config is never touched. +4. Writes `kur.service` and `kur.timer` to `~/.config/systemd/user/` (only if missing or different). +5. Runs `systemctl --user daemon-reload` and `systemctl --user enable --now kur.timer`. +6. Prints the config path and the done line. -The config file must be mode 0600. If `token_file` is set, the token file must be mode 0600 too. +Then add your apps to the config. Each one needs a `[[app]]` table (see the reference below). The +config file must be mode 0600. If `token_file` is set, the token file must be mode 0600 too. For +private repos, put a read-only forge token in `~/.config/kur/token` with mode 0600, and set +`token_file = "~/.config/kur/token"` in the config. + +`kur setup` runs setup explicitly. Use it to repair or reinstall: it puts back any missing binary, +config or unit, and it changes nothing that is already in place. 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 @@ -104,6 +107,8 @@ journalctl _SYSTEMD_USER_UNIT=kur.service ## Commands ``` +kur first run: sets up if the config file is missing, else same as status +kur setup set up kur (idempotent); see Install kur run process every app once kur run process one app kur status show installed and newest versions; changes nothing @@ -111,6 +116,9 @@ kur --version print "kur " kur help print usage (also used for unknown commands, exit 2) ``` +A bare `kur` runs setup when the config file does not exist, and otherwise does the same as +`kur status`. `kur run` and `kur status` never run setup. + Global option: `--config `, placed before the command. Otherwise `KUR_CONFIG` is used, then `$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 diff --git a/deploy/user/kur.service b/deploy/user/kur.service index 0022b64..10e3407 100644 --- a/deploy/user/kur.service +++ b/deploy/user/kur.service @@ -3,7 +3,6 @@ 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 diff --git a/src/config.rs b/src/config.rs index 2e43a72..010f5a9 100644 --- a/src/config.rs +++ b/src/config.rs @@ -89,7 +89,7 @@ fn env_value(name: &str) -> Option { } /// `$HOME`, if set and not empty. -fn home_dir() -> Option { +pub(crate) fn home_dir() -> Option { env_value("HOME").map(PathBuf::from) } @@ -104,15 +104,17 @@ pub fn config_path(cli: Option) -> Res { /// 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")) + Ok(config_base()?.join("kur").join("kur.toml")) +} + +/// `$XDG_CONFIG_HOME`, else `$HOME/.config`. Base for kur's config and the systemd user units. +pub(crate) fn config_base() -> Res { + match env_value("XDG_CONFIG_HOME") { + Some(dir) => Ok(PathBuf::from(dir)), + None => home_dir().map(|home| home.join(".config")).ok_or_else(|| { + "neither XDG_CONFIG_HOME nor HOME is set; use --config or KUR_CONFIG".to_string() + }), + } } /// Default `state_dir`: `$XDG_STATE_HOME/kur`, else `$HOME/.local/state/kur`. diff --git a/src/install.rs b/src/install.rs index 5baa715..5ea05ce 100644 --- a/src/install.rs +++ b/src/install.rs @@ -105,7 +105,7 @@ fn short(sha: &str) -> &str { } /// Lowercase hex sha256 of the file at `path`, or None if it does not exist. -fn file_sha256(path: &Path) -> Res> { +pub(crate) fn file_sha256(path: &Path) -> Res> { let mut file = match File::open(path) { Ok(file) => file, Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None), @@ -253,7 +253,7 @@ fn is_active(unit: &str) -> bool { } /// Runs `systemctl --user` with `args`. Only the user manager of the account kur runs as is used. -fn systemctl(args: &[&str]) -> Result<(), String> { +pub(crate) fn systemctl(args: &[&str]) -> Result<(), String> { let status = Command::new("systemctl") .arg("--user") .args(args) diff --git a/src/main.rs b/src/main.rs index b418447..0403f5d 100644 --- a/src/main.rs +++ b/src/main.rs @@ -6,21 +6,24 @@ mod config; mod forge; mod install; mod migrate; +mod setup; use crate::config::{App, Config}; use crate::forge::Forge; use std::env; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::ExitCode; /// Crate-wide result type; errors are human-readable messages. pub type Res = Result; -const USAGE: &str = "usage: kur [--config ] +const USAGE: &str = "usage: kur [--config ] [command] commands: + (none) first run: set up if the config file is missing, else the same as status run [app] install newer releases (all apps, or only ) status show installed and newest releases; changes nothing + setup set up kur (idempotent): install the binary, write the config, install the timer --version print the version "; @@ -43,9 +46,24 @@ fn main() -> ExitCode { } let words: Vec<&str> = words.iter().map(String::as_str).collect(); let (only, status) = match words.as_slice() { + ["setup"] => return setup_command(cli_config.as_deref()), ["run"] => (None, false), ["run", name] => (Some(*name), false), ["status"] => (None, true), + [] => match config::config_path(cli_config.clone()) { + Ok(path) => match path.try_exists() { + Ok(true) => (None, true), + Ok(false) => return setup_command(Some(&path)), + Err(e) => { + eprintln!("kur: cannot check {}: {e}", path.display()); + return ExitCode::FAILURE; + } + }, + Err(e) => { + eprintln!("kur: {e}"); + return ExitCode::FAILURE; + } + }, _ => return usage(), }; @@ -125,6 +143,18 @@ fn process_apps(cfg: &Config, apps: &[&App], status: bool) -> ExitCode { } } +/// Runs first-run setup for the resolved config path (`cli` overrides it, as `--config` does). +fn setup_command(cli: Option<&Path>) -> ExitCode { + let result = config::config_path(cli.map(Path::to_path_buf)).and_then(|path| setup::run(&path)); + match result { + Ok(()) => ExitCode::SUCCESS, + Err(e) => { + eprintln!("kur: setup: {e}"); + ExitCode::FAILURE + } + } +} + /// Prints usage and returns exit code 2 (bad invocation). fn usage() -> ExitCode { eprint!("{USAGE}"); diff --git a/src/setup.rs b/src/setup.rs new file mode 100644 index 0000000..6f2fd6e --- /dev/null +++ b/src/setup.rs @@ -0,0 +1,210 @@ +//! First-run setup, run by `kur setup` and by a bare `kur` when the config file is missing. +//! Each step is idempotent, so running it again repairs or reinstalls whatever is missing. + +use crate::Res; +use crate::config; +use crate::install::{file_sha256, systemctl}; +use std::env; +use std::fs::{self, DirBuilder, File, OpenOptions, Permissions}; +use std::io::{self, Write}; +use std::os::unix::fs::{DirBuilderExt, MetadataExt, OpenOptionsExt, PermissionsExt}; +use std::path::Path; + +/// Starter config. Must parse with `config::load`; the commented-out entry must stay fully commented. +const CONFIG_TEMPLATE: &str = r##"# kur config, written by `kur setup`. Field reference: README.md. +# Paths may start with ~/, which expands to $HOME/. This file is mode 0600: keep it that way. + +# 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 = "~/.config/kur/token" + +# kur updates itself. There is no unit: the new binary is swapped in and used from the next +# timer run on. kur runs `kur --version` on the new build before swapping it in, so a broken +# build is never installed. +[[app]] +name = "kur" +repo = "Tahinli/kur" +asset = "kur-{arch}-linux" +path = "~/bin/kur" +check = ["--version"] + +# Uncomment once im runs as a user unit of this account and has a v* release. +# [[app]] +# name = "im" +# repo = "Tahinli/im" +# asset = "im-{arch}-linux" +# path = "~/bin/im" +# unit = "im.service" +# health_url = "http://127.0.0.1:7650/healthz" +"##; + +const KUR_SERVICE: &str = include_str!("../deploy/user/kur.service"); +const KUR_TIMER: &str = include_str!("../deploy/user/kur.timer"); + +const ROOT_MSG: &str = "run kur as the account that runs the apps, not as root"; +const SYSTEMCTL_MSG: &str = "systemctl --user failed; kur needs a login session of this account (for example: sudo machinectl shell @)"; + +/// Runs every setup step in order and stops at the first error. +pub fn run(config_path: &Path) -> Res<()> { + refuse_root()?; + let home = config::home_dir().ok_or("HOME is not set")?; + install_binary(&home)?; + write_config(config_path)?; + write_units(&config::config_base()?.join("systemd").join("user"))?; + enable_timer()?; + println!("kur: setup: config file {}", config_path.display()); + println!("kur: setup: done; kur checks for updates every 5 minutes (journalctl --user -u kur)"); + Ok(()) +} + +/// Step 1: refuses to run as root. +fn refuse_root() -> Res<()> { + let uid = fs::metadata("/proc/self") + .map_err(|e| format!("cannot read /proc/self: {e}"))? + .uid(); + if uid == 0 { + return Err(ROOT_MSG.into()); + } + Ok(()) +} + +/// Step 2: copies the running binary to `$HOME/bin/kur` unless the target already matches. +fn install_binary(home: &Path) -> Res<()> { + let source = + env::current_exe().map_err(|e| format!("cannot find the running kur binary: {e}"))?; + let bin_dir = home.join("bin"); + let target = bin_dir.join("kur"); + let display = target.display(); + + let same_file = matches!( + (fs::canonicalize(&source), fs::canonicalize(&target)), + (Ok(a), Ok(b)) if a == b + ); + if same_file { + println!("kur: setup: binary already in place ({display})"); + return Ok(()); + } + let source_sha = file_sha256(&source)?.ok_or("cannot read the running kur binary")?; + if file_sha256(&target)?.as_deref() == Some(source_sha.as_str()) { + println!("kur: setup: binary already in place ({display})"); + return Ok(()); + } + + if !bin_dir.is_dir() { + DirBuilder::new() + .mode(0o755) + .create(&bin_dir) + .and_then(|()| fs::set_permissions(&bin_dir, Permissions::from_mode(0o755))) + .map_err(|e| format!("create {}: {e}", bin_dir.display()))?; + } + let bytes = fs::read(&source).map_err(|e| format!("read {}: {e}", source.display()))?; + write_atomic(&target, &bytes, 0o755).map_err(|e| format!("install {display}: {e}"))?; + println!("kur: setup: installed binary to {display}"); + Ok(()) +} + +/// Step 3: writes the starter config if the file does not exist. An existing file is never touched. +fn write_config(path: &Path) -> Res<()> { + let display = path.display(); + if path + .try_exists() + .map_err(|e| format!("cannot check {display}: {e}"))? + { + println!("kur: setup: config already in place ({display})"); + return Ok(()); + } + if let Some(dir) = path.parent().filter(|dir| !dir.as_os_str().is_empty()) { + DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(dir) + .map_err(|e| format!("create {}: {e}", dir.display()))?; + } + // Mode 0600 from creation, so the file is never readable by others. + let result = OpenOptions::new() + .write(true) + .create_new(true) + .mode(0o600) + .open(path) + .and_then(|mut file| { + file.write_all(CONFIG_TEMPLATE.as_bytes())?; + file.sync_all() + }); + result.map_err(|e| format!("write config {display}: {e}"))?; + println!("kur: setup: wrote starter config {display}"); + Ok(()) +} + +/// Step 4: writes the embedded user units into `dir`, only where missing or different. +fn write_units(dir: &Path) -> Res<()> { + DirBuilder::new() + .recursive(true) + .mode(0o755) + .create(dir) + .map_err(|e| format!("create {}: {e}", dir.display()))?; + let mut changed = false; + for (name, content) in [("kur.service", KUR_SERVICE), ("kur.timer", KUR_TIMER)] { + let path = dir.join(name); + if fs::read_to_string(&path).ok().as_deref() == Some(content) { + continue; + } + write_atomic(&path, content.as_bytes(), 0o644) + .map_err(|e| format!("write {}: {e}", path.display()))?; + changed = true; + } + if changed { + println!("kur: setup: wrote user units to {}", dir.display()); + } else { + println!( + "kur: setup: user units already in place ({})", + dir.display() + ); + } + Ok(()) +} + +/// Step 5: reloads the user manager and enables the timer. Needs a login session of this account. +fn enable_timer() -> Res<()> { + // Without XDG_RUNTIME_DIR there is no user manager to talk to, so fail before calling systemctl. + if env::var_os("XDG_RUNTIME_DIR").is_none_or(|value| value.is_empty()) { + return Err(SYSTEMCTL_MSG.into()); + } + systemctl(&["daemon-reload"]).map_err(|_| SYSTEMCTL_MSG.to_string())?; + systemctl(&["enable", "--now", "kur.timer"]).map_err(|_| SYSTEMCTL_MSG.to_string())?; + println!("kur: setup: kur.timer enabled and started"); + Ok(()) +} + +/// Writes `bytes` to a temp file next to `path` with `mode`, fsyncs it, then renames it over `path`. +fn write_atomic(path: &Path, bytes: &[u8], mode: u32) -> io::Result<()> { + let mut name = path.file_name().unwrap_or_default().to_os_string(); + name.push(".kur-new"); + let tmp = path.with_file_name(name); + let _ = fs::remove_file(&tmp); + let result = write_tmp_and_rename(&tmp, path, bytes, mode); + if result.is_err() { + let _ = fs::remove_file(&tmp); + } + result +} + +fn write_tmp_and_rename(tmp: &Path, path: &Path, bytes: &[u8], mode: u32) -> io::Result<()> { + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .mode(mode) + .open(tmp)?; + file.write_all(bytes)?; + file.set_permissions(Permissions::from_mode(mode))?; + file.sync_all()?; + drop(file); + fs::rename(tmp, path)?; + let parent = match path.parent() { + Some(dir) if !dir.as_os_str().is_empty() => dir, + _ => Path::new("."), + }; + File::open(parent)?.sync_all() +}