Kur runs as an unprivileged account with systemd user units: systemctl --user, XDG default paths, ~/ in config paths, deploy/user units, README install for a lingering app account
Browse files at this commit4725f2bff9bba55c6ef919ba44a6fe2a03e37478Parent: 7345a4fAll checks have passed
Show checks
ci/buildSucceededDetails
- refactor
- kur runs as an unprivileged account with systemd user units: systemctl --user, XDG default paths, ~/ in config paths, deploy/user units, README install for a lingering app account
8 changed files +186 -74
- README.md +71 -21
- config/kur.example.toml +7 -7
- deploy/kur.service +0 -30
- deploy/user/kur.service +13 -0
- deploy/kur.timer → deploy/user/kur.timer +1 -1
- src/config.rs +81 -11
- src/install.rs +2 -0
- src/main.rs +11 -4
README.mdmodified+71 -21
| @@ -1,10 +1,10 @@ | |||
| 1 | # kur | 1 | # kur |
| 2 | 2 | ||
| 3 | kur ("install" in Turkish) installs the newest release of each configured app on a server. It runs | 3 | kur ("install" in Turkish) installs the newest release of each configured app on a server. It runs |
| 4 | -from a systemd timer, reads releases from a self-hosted forge (git.tahinli.com), and swaps a binary | 4 | +from a systemd user timer, reads releases from a self-hosted forge (git.tahinli.com), and swaps a binary |
| 5 | in only when the release asset differs from the installed file. After a swap it restarts the app's | 5 | in only when the release asset differs from the installed file. After a swap it restarts the app's |
| 6 | -systemd unit and health-checks it, and it rolls back to the previous binary if the check fails. It is | 6 | +systemd user unit and health-checks it, and it rolls back to the previous binary if the check fails. It is |
| 7 | -one binary that runs as root and has no daemon. | 7 | +one binary that runs as an unprivileged user and has no daemon. It never runs as root. |
| 8 | 8 | ||
| 9 | ## Releases | 9 | ## Releases |
| 10 | 10 | ||
| @@ -23,15 +23,16 @@ For each app, in order: | |||
| 23 | 4. Download to `{path}.kur-new`, hashing while writing. Mode 0755, fsync. | 23 | 4. Download to `{path}.kur-new`, hashing while writing. Mode 0755, fsync. |
| 24 | 5. If `check` is set, run the new file with those arguments (10 s limit). Failure marks the build bad. | 24 | 5. If `check` is set, run the new file with those arguments (10 s limit). Failure marks the build bad. |
| 25 | 6. Rename the installed binary to `{path}.prev` and the new file to `{path}`. | 25 | 6. Rename the installed binary to `{path}.prev` and the new file to `{path}`. |
| 26 | -7. If `unit` is set, restart it and wait until `systemctl is-active` succeeds, `health_url` returns 2xx, | 26 | +7. If `unit` is set, restart it with `systemctl --user` and wait until `systemctl --user is-active` |
| 27 | - and the unit is still active 5 s later. Times out after `health_timeout_secs`. | 27 | + succeeds, `health_url` returns 2xx, and the unit is still active 5 s later. Times out after |
| 28 | + `health_timeout_secs`. | ||
| 28 | 8. On health failure, the build's sha256 is appended to `{name}.bad`. If `{path}.prev` exists, it is | 29 | 8. On health failure, the build's sha256 is appended to `{name}.bad`. If `{path}.prev` exists, it is |
| 29 | renamed back to `{path}` and the unit is restarted. Otherwise the run reports that there was no | 30 | renamed back to `{path}` and the unit is restarted. Otherwise the run reports that there was no |
| 30 | previous binary to restore. | 31 | previous binary to restore. |
| 31 | 32 | ||
| 32 | A run holds a lock on `{state_dir}/lock`, so a manual `kur run` exits at once while the timer's run is | 33 | A run holds a lock on `{state_dir}/lock`, so a manual `kur run` exits at once while the timer's run is |
| 33 | -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 | 34 | +in progress. `kur status` takes no lock. One app failing does not stop the others. Output goes to stdout |
| 34 | -collects. | 35 | +and errors to stderr, which the journal collects. |
| 35 | 36 | ||
| 36 | ### The bad list | 37 | ### The bad list |
| 37 | 38 | ||
| @@ -40,21 +41,65 @@ file. To retry a build, delete its line, or delete the file to clear the list fo | |||
| 40 | 41 | ||
| 41 | ## Install | 42 | ## Install |
| 42 | 43 | ||
| 43 | -Run as root on the app server. | 44 | +kur and the apps it installs run as one unprivileged account, for example `apps`. Root is needed once, |
| 45 | +to create the account and enable lingering. Everything after that is done as the account. | ||
| 46 | + | ||
| 47 | +As root, once: | ||
| 48 | + | ||
| 49 | +```sh | ||
| 50 | +useradd -m apps # any name works; the examples use apps | ||
| 51 | +loginctl enable-linger apps # keeps the account's user manager running without a login | ||
| 52 | +``` | ||
| 53 | + | ||
| 54 | +Then get a working user session for the account. Plain `sudo -u apps` does not work for this: it has | ||
| 55 | +no `XDG_RUNTIME_DIR`, so `systemctl --user` fails there. Use `machinectl` instead: | ||
| 56 | + | ||
| 57 | +```sh | ||
| 58 | +sudo machinectl shell apps@ | ||
| 59 | +``` | ||
| 60 | + | ||
| 61 | +As that user, from a checkout of this repo (or with the files copied over), with the kur release binary | ||
| 62 | +for this machine in the current directory: | ||
| 44 | 63 | ||
| 45 | ```sh | 64 | ```sh |
| 46 | -install -m 0755 kur /usr/local/bin/kur | 65 | +install -d ~/bin ~/.config/kur ~/.config/systemd/user |
| 47 | -install -d -m 0755 /etc/kur | 66 | +install -m 0755 kur-x86_64-linux ~/bin/kur # aarch64 hosts use kur-aarch64-linux |
| 48 | -install -m 0600 config/kur.example.toml /etc/kur/kur.toml # then edit it | 67 | +install -m 0600 config/kur.example.toml ~/.config/kur/kur.toml # then edit it |
| 49 | # Optional, for private repos. Use a read-only token. | 68 | # Optional, for private repos. Use a read-only token. |
| 50 | -(umask 077; printf '%s\n' 'TOKEN' > /etc/kur/token) | 69 | +(umask 077; printf '%s\n' 'TOKEN' > ~/.config/kur/token) |
| 51 | -install -m 0644 deploy/kur.service deploy/kur.timer /etc/systemd/system/ | 70 | +install -m 0644 deploy/user/kur.service deploy/user/kur.timer ~/.config/systemd/user/ |
| 52 | -systemctl daemon-reload | 71 | +systemctl --user daemon-reload |
| 53 | -systemctl enable --now kur.timer | 72 | +systemctl --user enable --now kur.timer |
| 54 | ``` | 73 | ``` |
| 55 | 74 | ||
| 56 | -The app units (for example `im.service`) are not part of this repo. They must exist before kur runs | 75 | +The config file must be mode 0600. If `token_file` is set, the token file must be mode 0600 too. |
| 57 | -for that app. If `token_file` is set in the config, the token file must be mode 0600. | 76 | + |
| 77 | +Each app must be a user unit of the same account. Its binary lives under `~/bin`, and its unit goes in | ||
| 78 | +`~/.config/systemd/user/`. The app units are not part of this repo. For example, im's unit is | ||
| 79 | +`deploy/user/im.service` in the im repo, installed the same way: | ||
| 80 | + | ||
| 81 | +```sh | ||
| 82 | +install -m 0644 deploy/user/im.service ~/.config/systemd/user/ | ||
| 83 | +systemctl --user daemon-reload | ||
| 84 | +systemctl --user enable --now im.service | ||
| 85 | +``` | ||
| 86 | + | ||
| 87 | +An app's unit must exist before kur runs for that app. Do not set `User=` in these units: they run as the | ||
| 88 | +account already. | ||
| 89 | + | ||
| 90 | +### Logs | ||
| 91 | + | ||
| 92 | +```sh | ||
| 93 | +journalctl --user -u kur | ||
| 94 | +``` | ||
| 95 | + | ||
| 96 | +On some distros the user journal needs persistent journald storage. If `journalctl --user` shows | ||
| 97 | +nothing, create `/var/log/journal` as root and restart `systemd-journald`. Until then, read the logs as | ||
| 98 | +root with: | ||
| 99 | + | ||
| 100 | +```sh | ||
| 101 | +journalctl _SYSTEMD_USER_UNIT=kur.service | ||
| 102 | +``` | ||
| 58 | 103 | ||
| 59 | ## Commands | 104 | ## Commands |
| 60 | 105 | ||
| @@ -67,19 +112,24 @@ kur help print usage (also used for unknown commands, exit 2) | |||
| 67 | ``` | 112 | ``` |
| 68 | 113 | ||
| 69 | Global option: `--config <path>`, placed before the command. Otherwise `KUR_CONFIG` is used, then | 114 | Global option: `--config <path>`, placed before the command. Otherwise `KUR_CONFIG` is used, then |
| 70 | -`/etc/kur/kur.toml`. | 115 | +`$XDG_CONFIG_HOME/kur/kur.toml`, or `~/.config/kur/kur.toml` when `XDG_CONFIG_HOME` is not set. Empty |
| 116 | +environment variables count as unset. If neither `XDG_CONFIG_HOME` nor `HOME` is set, kur prints an | ||
| 117 | +error and exits 1. | ||
| 71 | 118 | ||
| 72 | Exit code is 0 when every app succeeded or was up to date, and 1 if any app failed. | 119 | Exit code is 0 when every app succeeded or was up to date, and 1 if any app failed. |
| 73 | 120 | ||
| 74 | ## Config reference | 121 | ## Config reference |
| 75 | 122 | ||
| 123 | +Paths may start with `~/`, which expands to `$HOME/`. Only a leading `~/` is expanded. After expansion, | ||
| 124 | +`path`, `state_dir` and `token_file` must be absolute, so a bare `~` or `~user/...` is an error. | ||
| 125 | + | ||
| 76 | Top level: | 126 | Top level: |
| 77 | 127 | ||
| 78 | | Key | Required | Default | Meaning | | 128 | | Key | Required | Default | Meaning | |
| 79 | |---|---|---|---| | 129 | |---|---|---|---| |
| 80 | | `forge` | yes | none | Forge base URL, `https://` or `http://`. Trailing slash is trimmed. | | 130 | | `forge` | yes | none | Forge base URL, `https://` or `http://`. Trailing slash is trimmed. | |
| 81 | | `token_file` | no | none | File with a forge token for private repos. Read once, trimmed. Unreadable file is a config error. | | 131 | | `token_file` | no | none | File with a forge token for private repos. Read once, trimmed. Unreadable file is a config error. | |
| 82 | -| `state_dir` | no | `/var/lib/kur` | Directory for `.bad` and `.tag` files and the run lock. Created with mode 0700 if missing. | | 132 | +| `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. | |
| 83 | 133 | ||
| 84 | Each `[[app]]` table: | 134 | Each `[[app]]` table: |
| 85 | 135 | ||
| @@ -88,8 +138,8 @@ Each `[[app]]` table: | |||
| 88 | | `name` | yes | none | Unique. Must match `^[a-z0-9][a-z0-9_-]{0,39}$`. | | 138 | | `name` | yes | none | Unique. Must match `^[a-z0-9][a-z0-9_-]{0,39}$`. | |
| 89 | | `repo` | yes | none | Forge repo as `owner/name`. | | 139 | | `repo` | yes | none | Forge repo as `owner/name`. | |
| 90 | | `asset` | yes | none | Asset file name. `{arch}` is replaced by the machine architecture. | | 140 | | `asset` | yes | none | Asset file name. `{arch}` is replaced by the machine architecture. | |
| 91 | -| `path` | yes | none | Absolute path of the installed binary. | | 141 | +| `path` | yes | none | Path of the installed binary, absolute after `~/` expansion, e.g. `~/bin/im`. | |
| 92 | -| `unit` | no | none | systemd unit to restart and health-check. Without it kur only swaps the file. | | 142 | +| `unit` | no | none | systemd user unit to restart (`systemctl --user`) and health-check. Without it kur only swaps the file. | |
| 93 | | `prerelease` | no | `false` | Also accept prerelease releases. | | 143 | | `prerelease` | no | `false` | Also accept prerelease releases. | |
| 94 | | `check` | no | none | Arguments for the new binary, run before the swap. Must exit 0 within 10 s. | | 144 | | `check` | no | none | Arguments for the new binary, run before the swap. Must exit 0 within 10 s. | |
| 95 | | `health_url` | no | none | URL that must return 2xx after restart. No token is sent. | | 145 | | `health_url` | no | none | URL that must return 2xx after restart. No token is sent. | |
config/kur.example.tomlmodified+7 -7
| @@ -1,23 +1,23 @@ | |||
| 1 | -# Example kur config. Install it as /etc/kur/kur.toml (mode 0600). | 1 | +# Example kur config. Install it as ~/.config/kur/kur.toml (mode 0600). |
| 2 | -# Field reference: README.md. | 2 | +# Field reference: README.md. Paths may start with ~/, which expands to $HOME/. |
| 3 | 3 | ||
| 4 | # Forge base URL. A trailing slash is fine. | 4 | # Forge base URL. A trailing slash is fine. |
| 5 | forge = "https://git.tahinli.com" | 5 | forge = "https://git.tahinli.com" |
| 6 | 6 | ||
| 7 | # Optional: file holding a forge token for private repos. Read once at start, trimmed. | 7 | # Optional: file holding a forge token for private repos. Read once at start, trimmed. |
| 8 | # Use a read-only token. Must be mode 0600. | 8 | # Use a read-only token. Must be mode 0600. |
| 9 | -# token_file = "/etc/kur/token" | 9 | +# token_file = "~/.config/kur/token" |
| 10 | 10 | ||
| 11 | # Optional: where kur keeps .bad and .tag files. Default shown. | 11 | # Optional: where kur keeps .bad and .tag files. Default shown. |
| 12 | -# state_dir = "/var/lib/kur" | 12 | +# state_dir = "~/.local/state/kur" |
| 13 | 13 | ||
| 14 | -# The im server. Its unit is im.service, which kur restarts after a swap. | 14 | +# The im server. Its unit is the user unit im.service, which kur restarts after a swap. |
| 15 | [[app]] | 15 | [[app]] |
| 16 | name = "im" | 16 | name = "im" |
| 17 | repo = "Tahinli/im" | 17 | repo = "Tahinli/im" |
| 18 | # {arch} is replaced by the machine architecture (x86_64, aarch64). | 18 | # {arch} is replaced by the machine architecture (x86_64, aarch64). |
| 19 | asset = "im-{arch}-linux" | 19 | asset = "im-{arch}-linux" |
| 20 | -path = "/usr/local/bin/im" | 20 | +path = "~/bin/im" |
| 21 | unit = "im.service" | 21 | unit = "im.service" |
| 22 | # im has no --version flag, so there is no pre-swap check. | 22 | # im has no --version flag, so there is no pre-swap check. |
| 23 | # health_url must match the listen address in im's config. | 23 | # health_url must match the listen address in im's config. |
| @@ -32,5 +32,5 @@ health_url = "http://127.0.0.1:7650/healthz" | |||
| 32 | name = "kur" | 32 | name = "kur" |
| 33 | repo = "Tahinli/kur" | 33 | repo = "Tahinli/kur" |
| 34 | asset = "kur-{arch}-linux" | 34 | asset = "kur-{arch}-linux" |
| 35 | -path = "/usr/local/bin/kur" | 35 | +path = "~/bin/kur" |
| 36 | check = ["--version"] | 36 | check = ["--version"] |
deploy/kur.servicedeleted+0 -30
| @@ -1,30 +0,0 @@ | |||
| 1 | -[Unit] | ||
| 2 | -Description=kur: install newest forge releases of configured apps | ||
| 3 | -Wants=network-online.target | ||
| 4 | -After=network-online.target | ||
| 5 | - | ||
| 6 | -[Service] | ||
| 7 | -Type=oneshot | ||
| 8 | -# Runs as root: it replaces binaries in /usr/local/bin and restarts units. | ||
| 9 | -ExecStart=/usr/local/bin/kur run | ||
| 10 | -Environment=KUR_CONFIG=/etc/kur/kur.toml | ||
| 11 | -# /var/lib/kur, mode 0700 (.bad, .tag files). | ||
| 12 | -StateDirectory=kur | ||
| 13 | -StateDirectoryMode=0700 | ||
| 14 | -# Installed binaries must be 0755. kur sets the mode itself, but keep the umask | ||
| 15 | -# from making anything more private than that. | ||
| 16 | -UMask=0022 | ||
| 17 | - | ||
| 18 | -# Light hardening only. ProtectSystem= is deliberately left unset: "strict" and | ||
| 19 | -# "full" make /usr read-only, and /usr/local/bin is under /usr, so kur could not | ||
| 20 | -# replace app binaries. PrivateTmp, ProtectHome and the rest do not touch | ||
| 21 | -# /usr/local/bin or systemctl. | ||
| 22 | -NoNewPrivileges=yes | ||
| 23 | -PrivateTmp=yes | ||
| 24 | -ProtectHome=yes | ||
| 25 | -ProtectKernelTunables=yes | ||
| 26 | -ProtectKernelModules=yes | ||
| 27 | -ProtectKernelLogs=yes | ||
| 28 | -ProtectControlGroups=yes | ||
| 29 | -RestrictSUIDSGID=yes | ||
| 30 | -LockPersonality=yes | ||
deploy/user/kur.serviceadded+13 -0
| @@ -0,0 +1,13 @@ | |||
| 1 | +[Unit] | ||
| 2 | +Description=kur: install newest forge releases of configured apps | ||
| 3 | + | ||
| 4 | +[Service] | ||
| 5 | +# User unit for the shared app account (for example "apps"). It runs as that account, never as root. | ||
| 6 | +# The account needs `loginctl enable-linger <account>` so the timer runs without a login session. | ||
| 7 | +# The config is read from the default path, ~/.config/kur/kur.toml (or $XDG_CONFIG_HOME). | ||
| 8 | +Type=oneshot | ||
| 9 | +ExecStart=%h/bin/kur run | ||
| 10 | +# Installed binaries must be 0755. kur sets the mode itself, but keep the umask | ||
| 11 | +# from making anything more private than that. | ||
| 12 | +UMask=0022 | ||
| 13 | +NoNewPrivileges=yes | ||
deploy/kur.timer → deploy/user/kur.timerrenamed+1 -1
| @@ -2,7 +2,7 @@ | |||
| 2 | Description=Run kur every 5 minutes | 2 | Description=Run kur every 5 minutes |
| 3 | 3 | ||
| 4 | [Timer] | 4 | [Timer] |
| 5 | -# First run 2 minutes after boot, then 5 minutes after each run starts. | 5 | +# First run 2 minutes after the user manager starts, then 5 minutes after each run starts. |
| 6 | OnBootSec=2min | 6 | OnBootSec=2min |
| 7 | OnUnitActiveSec=5min | 7 | OnUnitActiveSec=5min |
| 8 | RandomizedDelaySec=30s | 8 | RandomizedDelaySec=30s |
src/config.rsmodified+81 -11
| @@ -3,14 +3,13 @@ | |||
| 3 | use crate::{Res, migrate}; | 3 | use crate::{Res, migrate}; |
| 4 | use serde::Deserialize; | 4 | use serde::Deserialize; |
| 5 | use std::collections::HashSet; | 5 | use std::collections::HashSet; |
| 6 | +use std::env; | ||
| 7 | +use std::ffi::OsString; | ||
| 6 | use std::fs::{self, OpenOptions}; | 8 | use std::fs::{self, OpenOptions}; |
| 7 | use std::io::{self, Write}; | 9 | use std::io::{self, Write}; |
| 8 | use std::os::unix::fs::OpenOptionsExt; | 10 | use std::os::unix::fs::OpenOptionsExt; |
| 9 | use std::path::{Path, PathBuf}; | 11 | use std::path::{Path, PathBuf}; |
| 10 | 12 | ||
| 11 | -/// Config path used when neither `--config` nor `KUR_CONFIG` is given. | ||
| 12 | -pub const DEFAULT_PATH: &str = "/etc/kur/kur.toml"; | ||
| 13 | -const DEFAULT_STATE_DIR: &str = "/var/lib/kur"; | ||
| 14 | /// Top-level keys; must match the `Raw` fields. | 13 | /// Top-level keys; must match the `Raw` fields. |
| 15 | const KNOWN_TOP_KEYS: &[&str] = &["forge", "token_file", "state_dir", "app"]; | 14 | const KNOWN_TOP_KEYS: &[&str] = &["forge", "token_file", "state_dir", "app"]; |
| 16 | /// Keys in each `[[app]]` table; must match the `App` fields. | 15 | /// Keys in each `[[app]]` table; must match the `App` fields. |
| @@ -84,6 +83,71 @@ impl App { | |||
| 84 | } | 83 | } |
| 85 | } | 84 | } |
| 86 | 85 | ||
| 86 | +/// Value of environment variable `name`, or None if it is unset or empty. | ||
| 87 | +fn env_value(name: &str) -> Option<OsString> { | ||
| 88 | + env::var_os(name).filter(|value| !value.is_empty()) | ||
| 89 | +} | ||
| 90 | + | ||
| 91 | +/// `$HOME`, if set and not empty. | ||
| 92 | +fn home_dir() -> Option<PathBuf> { | ||
| 93 | + env_value("HOME").map(PathBuf::from) | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +/// Config path for a run: `cli` (from `--config`), else `KUR_CONFIG`, else `default_path()`. | ||
| 97 | +pub fn config_path(cli: Option<PathBuf>) -> Res<PathBuf> { | ||
| 98 | + match cli.or_else(|| env_value("KUR_CONFIG").map(PathBuf::from)) { | ||
| 99 | + Some(path) => Ok(path), | ||
| 100 | + None => default_path(), | ||
| 101 | + } | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +/// Config file used when neither `--config` nor `KUR_CONFIG` is set: | ||
| 105 | +/// `$XDG_CONFIG_HOME/kur/kur.toml`, else `$HOME/.config/kur/kur.toml`. | ||
| 106 | +pub fn default_path() -> Res<PathBuf> { | ||
| 107 | + let base = match env_value("XDG_CONFIG_HOME") { | ||
| 108 | + Some(dir) => PathBuf::from(dir), | ||
| 109 | + None => home_dir() | ||
| 110 | + .ok_or_else(|| { | ||
| 111 | + "neither XDG_CONFIG_HOME nor HOME is set; use --config or KUR_CONFIG".to_string() | ||
| 112 | + })? | ||
| 113 | + .join(".config"), | ||
| 114 | + }; | ||
| 115 | + Ok(base.join("kur").join("kur.toml")) | ||
| 116 | +} | ||
| 117 | + | ||
| 118 | +/// Default `state_dir`: `$XDG_STATE_HOME/kur`, else `$HOME/.local/state/kur`. | ||
| 119 | +fn default_state_dir() -> Res<PathBuf> { | ||
| 120 | + let base = match env_value("XDG_STATE_HOME") { | ||
| 121 | + Some(dir) => PathBuf::from(dir), | ||
| 122 | + None => home_dir() | ||
| 123 | + .ok_or_else(|| { | ||
| 124 | + "neither XDG_STATE_HOME nor HOME is set; set state_dir in the config".to_string() | ||
| 125 | + })? | ||
| 126 | + .join(".local") | ||
| 127 | + .join("state"), | ||
| 128 | + }; | ||
| 129 | + let dir = base.join("kur"); | ||
| 130 | + if !dir.is_absolute() { | ||
| 131 | + return Err("state_dir must be absolute".into()); | ||
| 132 | + } | ||
| 133 | + Ok(dir) | ||
| 134 | +} | ||
| 135 | + | ||
| 136 | +/// Expands a leading `~/` to `$HOME/` (and nothing else), then requires an absolute path. | ||
| 137 | +/// `what` names the setting in error messages. | ||
| 138 | +fn absolute_path(path: &Path, what: &str) -> Res<PathBuf> { | ||
| 139 | + let expanded = match path.to_str().and_then(|s| s.strip_prefix("~/")) { | ||
| 140 | + Some(rest) => home_dir() | ||
| 141 | + .ok_or_else(|| format!("{what}: cannot expand ~/ because HOME is not set"))? | ||
| 142 | + .join(rest.trim_start_matches('/')), | ||
| 143 | + None => path.to_path_buf(), | ||
| 144 | + }; | ||
| 145 | + if !expanded.is_absolute() { | ||
| 146 | + return Err(format!("{what} must be absolute")); | ||
| 147 | + } | ||
| 148 | + Ok(expanded) | ||
| 149 | +} | ||
| 150 | + | ||
| 87 | /// Reads and validates the config file at `path`, renaming keys listed in `migrate::RENAMES`. | 151 | /// Reads and validates the config file at `path`, renaming keys listed in `migrate::RENAMES`. |
| 88 | /// If anything was renamed and `write` is set, the file is rewritten once the config is valid. | 152 | /// If anything was renamed and `write` is set, the file is rewritten once the config is valid. |
| 89 | pub fn load(path: &Path, write: bool) -> Res<Config> { | 153 | pub fn load(path: &Path, write: bool) -> Res<Config> { |
| @@ -100,7 +164,7 @@ pub fn load(path: &Path, write: bool) -> Res<Config> { | |||
| 100 | let table: toml::Table = | 164 | let table: toml::Table = |
| 101 | toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; | 165 | toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; |
| 102 | let mut warnings = unknown_key_warnings(&table); | 166 | let mut warnings = unknown_key_warnings(&table); |
| 103 | - let raw: Raw = toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; | 167 | + let mut raw: Raw = toml::from_str(&text).map_err(|e| format!("{}: {e}", path.display()))?; |
| 104 | 168 | ||
| 105 | let forge = raw.forge.trim_end_matches('/').to_string(); | 169 | let forge = raw.forge.trim_end_matches('/').to_string(); |
| 106 | if !forge.starts_with("https://") && !forge.starts_with("http://") { | 170 | if !forge.starts_with("https://") && !forge.starts_with("http://") { |
| @@ -121,15 +185,21 @@ pub fn load(path: &Path, write: bool) -> Res<Config> { | |||
| 121 | if parts.len() != 2 || parts.iter().any(|p| p.is_empty()) { | 185 | if parts.len() != 2 || parts.iter().any(|p| p.is_empty()) { |
| 122 | return Err(format!("{}: repo must be owner/name", app.name)); | 186 | return Err(format!("{}: repo must be owner/name", app.name)); |
| 123 | } | 187 | } |
| 124 | - if !app.path.is_absolute() { | 188 | + } |
| 125 | - return Err(format!("{}: path must be absolute", app.name)); | 189 | + for app in &mut raw.apps { |
| 126 | - } | 190 | + app.path = absolute_path(&app.path, &format!("{}: path", app.name))?; |
| 127 | } | 191 | } |
| 128 | 192 | ||
| 129 | - let token = raw.token_file.as_deref().map(read_token).transpose()?; | 193 | + let token_file = raw |
| 130 | - let state_dir = raw | 194 | + .token_file |
| 131 | - .state_dir | 195 | + .as_deref() |
| 132 | - .unwrap_or_else(|| PathBuf::from(DEFAULT_STATE_DIR)); | 196 | + .map(|file| absolute_path(file, "token_file")) |
| 197 | + .transpose()?; | ||
| 198 | + let token = token_file.as_deref().map(read_token).transpose()?; | ||
| 199 | + let state_dir = match raw.state_dir.as_deref() { | ||
| 200 | + Some(dir) => absolute_path(dir, "state_dir")?, | ||
| 201 | + None => default_state_dir()?, | ||
| 202 | + }; | ||
| 133 | if !migrated.is_empty() | 203 | if !migrated.is_empty() |
| 134 | && write | 204 | && write |
| 135 | && let Err(e) = rewrite_config(path, &text) | 205 | && let Err(e) = rewrite_config(path, &text) |
src/install.rsmodified+2 -0
| @@ -252,8 +252,10 @@ fn is_active(unit: &str) -> bool { | |||
| 252 | systemctl(&["is-active", "--quiet", unit]).is_ok() | 252 | systemctl(&["is-active", "--quiet", unit]).is_ok() |
| 253 | } | 253 | } |
| 254 | 254 | ||
| 255 | +/// Runs `systemctl --user` with `args`. Only the user manager of the account kur runs as is used. | ||
| 255 | fn systemctl(args: &[&str]) -> Result<(), String> { | 256 | fn systemctl(args: &[&str]) -> Result<(), String> { |
| 256 | let status = Command::new("systemctl") | 257 | let status = Command::new("systemctl") |
| 258 | + .arg("--user") | ||
| 257 | .args(args) | 259 | .args(args) |
| 258 | .stdout(Stdio::null()) | 260 | .stdout(Stdio::null()) |
| 259 | .status() | 261 | .status() |
src/main.rsmodified+11 -4
| @@ -1,5 +1,6 @@ | |||
| 1 | //! kur: installs the newest forge release of each configured app on this host, with rollback. | 1 | //! kur: installs the newest forge release of each configured app on this host, with rollback. |
| 2 | -//! Runs from a systemd timer as root; prints one line per app on stdout, errors on stderr. | 2 | +//! Runs from a systemd user timer as the unprivileged account that owns the apps (never root). |
| 3 | +//! Prints one line per app on stdout, errors on stderr. | ||
| 3 | 4 | ||
| 4 | mod config; | 5 | mod config; |
| 5 | mod forge; | 6 | mod forge; |
| @@ -25,13 +26,12 @@ commands: | |||
| 25 | 26 | ||
| 26 | fn main() -> ExitCode { | 27 | fn main() -> ExitCode { |
| 27 | let mut args = env::args().skip(1); | 28 | let mut args = env::args().skip(1); |
| 28 | - let mut config_path = env::var_os("KUR_CONFIG") | 29 | + let mut cli_config: Option<PathBuf> = None; |
| 29 | - .map_or_else(|| PathBuf::from(config::DEFAULT_PATH), PathBuf::from); | ||
| 30 | let mut words = Vec::new(); | 30 | let mut words = Vec::new(); |
| 31 | while let Some(arg) = args.next() { | 31 | while let Some(arg) = args.next() { |
| 32 | match arg.as_str() { | 32 | match arg.as_str() { |
| 33 | "--config" => match args.next() { | 33 | "--config" => match args.next() { |
| 34 | - Some(path) => config_path = path.into(), | 34 | + Some(path) => cli_config = Some(path.into()), |
| 35 | None => return usage(), | 35 | None => return usage(), |
| 36 | }, | 36 | }, |
| 37 | "--version" => { | 37 | "--version" => { |
| @@ -49,6 +49,13 @@ fn main() -> ExitCode { | |||
| 49 | _ => return usage(), | 49 | _ => return usage(), |
| 50 | }; | 50 | }; |
| 51 | 51 | ||
| 52 | + let config_path = match config::config_path(cli_config) { | ||
| 53 | + Ok(path) => path, | ||
| 54 | + Err(e) => { | ||
| 55 | + eprintln!("kur: {e}"); | ||
| 56 | + return ExitCode::FAILURE; | ||
| 57 | + } | ||
| 58 | + }; | ||
| 52 | // Status never writes, so a renamed key is only reported. | 59 | // Status never writes, so a renamed key is only reported. |
| 53 | let cfg = match config::load(&config_path, !status) { | 60 | let cfg = match config::load(&config_path, !status) { |
| 54 | Ok(cfg) => cfg, | 61 | Ok(cfg) => cfg, |