diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 9b617ec..9db55f1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -20,3 +20,5 @@ jobs: run: cargo test - if: ${{ !cancelled() }} run: tests/wrappers/run.sh + - if: ${{ !cancelled() }} + run: tests/service/run.sh diff --git a/README.md b/README.md index 947feee..a3347e5 100644 --- a/README.md +++ b/README.md @@ -56,16 +56,16 @@ Open a new shell, start the proxy on the wrappers' port (`soze --port 48731 ...` - **Known limit:** the proxy address is fixed when the agent starts. If soze stops mid-session, that session loses its connection; start a new one. - `agent` (Cursor) gets the proxy only: its host is tunnelled, so nothing is parsed from it. -## The always-on service (macOS) +## The always-on service (macOS and Linux) -A launchd user agent keeps one `soze` running on port 48731, the port the wrappers use. `task dev` listens on 48732, so both can run at once. +A launchd user agent (macOS) or a `systemd --user` unit (Linux) keeps one `soze` running on port 48731, the port the wrappers use. `task dev` listens on 48732, so both can run at once. Linux requires systemd 240 or newer, a reachable user manager/session bus and `/bin/kill` for reload (`procps` on Debian); no root access is needed. Other Linux supervisors are not managed by these tasks. ```sh task service:install # build the debug binary, copy it into place, rotate the log, (re)start task service:status # state, pid, and the sha, branch, dirty flag and time of the install task service:logs # tail -F soze.log task service:reload # SIGHUP: re-read the live logging settings -task service:restart # kickstart the service +task service:restart # restart the service, cutting in-flight streams task service:uninstall # stop and remove the service and binary ``` @@ -74,18 +74,45 @@ Layout, all under your home directory: | Path | Holds | | --- | --- | | `~/Library/LaunchAgents/com.killallgit.soze.plist` | the launchd job, label `com.killallgit.soze` | +| `~/.config/systemd/user/soze.service` | the Linux user unit (`$XDG_CONFIG_HOME/systemd/user/` if set) | | `~/.local/share/soze/bin/soze`, `bin/install.json` | the installed binary and what it was built from | | `~/.local/share/soze/logs/soze.log`, `soze.log.1` | the service's stdout and stderr, and the previous generation | | `~/.local/share/soze/tap.jsonl`, `shapes.jsonl`, `debug.jsonl` | the tap, shape and debug files | | `~/.config/soze/config.toml` | settings; written on first install with `log_format = "human"` and `live = true`, never overwritten | - **Update the service** by re-running `task service:install`. It rebuilds the debug binary, copies it over the installed one, moves `soze.log` to `soze.log.1`, and restarts the service. +- **Linux startup and recovery.** Installation enables `soze.service` for user-manager startup, normally at login. It runs continuously, without socket activation, and restarts on failure after five seconds. To run from boot and after logout, explicitly opt into lingering with `loginctl enable-linger "$USER"` (authorization depends on your system). The installer never enables lingering or changes system proxy/certificate trust settings. +- **Linux unit paths.** The unit directory must be in the running user manager's search path. Install and uninstall reject caller-only overrides and a different same-named loaded definition before changing the installation. - **Restart is abrupt.** In-flight streams are cut and agents must reconnect. The new process has a new `run_id`, which marks the restart in the tap. - **Logs.** `task service:logs` tails `soze.log` only. It never reads the tap, because message content must not reach a terminal. -- **Uninstall** removes the plist, binary and `install.json`, and keeps captures, logs and config. `task service:uninstall -- --purge` also lists every path under `~/.local/share/soze/`, then deletes the directory; `~/.config/soze` stays. +- **Uninstall** stops and removes the supervisor definition, binary and `install.json` (and disables the Linux unit), keeping captures, logs and config. `task service:uninstall -- --purge` also lists every path under `~/.local/share/soze/`, then deletes the directory; `~/.config/soze` stays. Linux uninstall requires a reachable user manager when the unit is installed. It does not change lingering, which may support other user services. - **`live = true` in `config.toml`** applies to `task dev` too, so `LIVE=0 task dev` no longer turns live lines off. Pass `-- --live=false`, or edit the file. - **Smoke test.** `task test:smoke` checks that the installed service is running, accepts connections, proxies one `claude -p` call and captures it in the tap without new `connect_failed` lines; it needs the installed service and a logged-in `claude`, and prints counts and ids only. -- **Tests.** The service tests in `tests/service/` are local shell tests with a fake `launchctl`. `task check` runs them; CI does not. +- **Tests.** `tests/service/` exercises both platforms with fake `launchctl`, `systemctl` and throwaway homes, without changing the installed service. `task check` and Linux CI run them. + +### Test real systemd with Docker + +```sh +docker context show # check which Docker host will run the privileged test container +task test:systemd +``` + +This is a **test image, not a deployment image**. Production Soze remains a native host +service. The target builds the actual debug Linux binary, boots systemd as PID 1, starts a +non-root user manager and tests installation, enablement, status, synthetic proxy traffic, +SIGHUP reload, restart, crash recovery, update, uninstall and purge. + +Use a trusted, rootful Linux Docker daemon with cgroup v2. The container runs with +`--privileged` and a private cgroup namespace so systemd can manage its hierarchy; this is +not a security sandbox. No host directories or Docker socket are mounted, no ports are +published, and runtime networking is disabled except for container loopback. A Dockerfile-specific +allowlist excludes captures, credentials, Git/Beads state and agent folders from the build context. + +Each invocation tests its own immutable image, even when builds run concurrently. Commands +are bounded, and cleanup removes the container on success, failure or interruption, including +its scratch captures and CA. Failed cleanup is reported. The test image/build cache remains available +for subsequent runs. This opt-in target is separate from `task check` and the mocked service +tests in CI. ## Configuration @@ -134,7 +161,7 @@ Terminal stream detail has a budget of 20 records per one-second window; summari Every dev task also writes `target/dev/debug.jsonl` through a separate logger transport. It resets when the service starts, always selects debug metadata (even with terminal logging off), and does not apply the terminal rate filter. It includes full run/exchange ids, role counts, status/timing/loss counters, and adapter `decision` reasons. `endpoint` is a known API route or `other`; arbitrary paths and query values are excluded. New files are created with mode `0600`. The binary enables this transport with `--log-file `; its parent directory must already exist. Starting a second service on an occupied port leaves the active debug file intact. A debug file cannot alias the tap or shape file, including through dangling symbolic links. -The debug file stops accepting records at 16 MiB per run and reports `debug_file_limit` on stderr; it resumes after the next start resets the file. Open/write/flush failures also report safe diagnostics on stderr while the proxy keeps running. Its independent 256-record queue can drop under load, and abrupt shutdown may lose queued records. This is a disposable debug log, not a durable audit trail. The tap and shape files are bounded separately (see [The tap file](#the-tap-file)); the debug file and `soze.log` (launchd stderr, rotated one generation by the service install) are excluded from that retention. +The debug file stops accepting records at 16 MiB per run and reports `debug_file_limit` on stderr; it resumes after the next start resets the file. Open/write/flush failures also report safe diagnostics on stderr while the proxy keeps running. Its independent 256-record queue can drop under load, and abrupt shutdown may lose queued records. This is a disposable debug log, not a durable audit trail. The tap and shape files are bounded separately (see [The tap file](#the-tap-file)); the debug file and `soze.log` (supervised stdout/stderr, rotated one generation by the service install) are excluded from that retention. ```sh tail -f target/dev/debug.jsonl # metadata only; safe to inspect while developing @@ -183,7 +210,8 @@ Run `task --list`. Tasks run from any directory in the repo. - `task dev:stream:json`: real-time metadata as JSON logs. - `task test:smoke`: one real `claude` call through the installed always-on service; local only, not part of `task check`. - `task test:wrappers`: shell tests for the wrappers and their installer, run under every shell installed. `task check` runs them too. -- `task service:install`, `service:status`, `service:logs`, `service:reload`, `service:restart`, `service:uninstall`: the always-on macOS service, see above. +- `task test:systemd`: build and exercise the native Linux user service under real systemd in a disposable privileged Docker container; opt-in, see above. +- `task service:install`, `service:status`, `service:logs`, `service:reload`, `service:restart`, `service:uninstall`: the always-on macOS or Linux user service, see above. ## Build disk use diff --git a/Taskfile.yml b/Taskfile.yml index 8b8e018..74f5ec4 100644 --- a/Taskfile.yml +++ b/Taskfile.yml @@ -26,6 +26,11 @@ tasks: cmds: - tests/wrappers/run.sh + test:systemd: + desc: Build a debug Linux binary and test its real systemd user service in a disposable privileged Docker container + cmds: + - sh tests/systemd/run.sh + test:smoke: desc: Check the installed always-on service with one real claude call; needs the service and a logged-in claude cmds: @@ -57,7 +62,7 @@ tasks: - scripts/dev.sh --stream --log-format json {{.CLI_ARGS}} service:install: - desc: Build the debug binary, install it as the always-on macOS service on port 48731, and restart it + desc: Build the debug binary, install it as a macOS or Linux user service on port 48731, and restart it vars: BINARY: sh: cargo metadata --format-version 1 --no-deps | jq -r '.target_directory + "/debug/soze"' diff --git a/docs/architecture/service-lifecycle.md b/docs/architecture/service-lifecycle.md index a219992..f017217 100644 --- a/docs/architecture/service-lifecycle.md +++ b/docs/architecture/service-lifecycle.md @@ -7,16 +7,20 @@ architecture diagram and capture pipeline. ## Platform support -**macOS service management is implemented. Linux service management is proposed, not -implemented.** The current installer calls `launchctl` directly; `task service:*` is not a -cross-platform service interface. - -| Concern | Current macOS behavior | Proposed Linux equivalent | +`task service:*` manages a macOS LaunchAgent or a Linux systemd user unit. Linux requires +systemd 240 or newer (for file-log append support), a reachable user manager/session bus +and `/bin/kill` for reload (`procps` on Debian). +The installer checks manager access, unit-directory visibility and any loaded definition's +identity before changing installed files. A custom `XDG_CONFIG_HOME` must agree with the +running user manager's unit search path and cannot select a shadowed, same-named unit. +The effective definition is checked again before restart. No root access is needed. + +| Concern | macOS | Linux | | --- | --- | --- | | Supervisor | `launchd` user LaunchAgent | `systemd --user` service | -| Definition | `~/Library/LaunchAgents/com.killallgit.soze.plist` | `~/.config/systemd/user/soze.service` | +| Definition | `~/Library/LaunchAgents/com.killallgit.soze.plist` | `${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/soze.service` | | Startup | GUI user login; job uses `RunAtLoad` | User-manager startup, normally login | -| Automatic recovery | `KeepAlive` | `Restart=on-failure` with a restart delay | +| Automatic recovery | `KeepAlive` | `Restart=on-failure`, five-second delay | | Run without a login session | Not supplied by the current GUI-domain installer | Explicitly enable user lingering | | Logging reload | SIGHUP | SIGHUP through `ExecReload` | @@ -27,9 +31,9 @@ service backend is implemented; the foreground binary can be managed by another One service per user avoids sharing CA private keys and captured conversations across users. The default port is still shared by the machine: two users cannot both bind `127.0.0.1:48731`. Multi-user deployment would need distinct ports and matching wrapper -settings; the macOS installer currently fixes its service port at 48731. +settings; both installers currently fix the service port at 48731. -## macOS operations +## Service operations Run these commands from a checkout with Task installed: @@ -42,6 +46,17 @@ task service:restart # abruptly restart the process task service:uninstall # remove the job and binary; keep captures, logs and config ``` +Linux installation writes `soze.service`, reloads the user manager, enables the unit for +`default.target` and restarts it. It runs the foreground binary continuously, not through +socket activation. stdout and stderr append to the same `soze.log` used on macOS; the logs +command does not read journald or capture output. New Linux directories and non-executable +files are private to the user, and the unit applies `UMask=0077` to runtime files. + +To keep the Linux user manager running from boot and after logout, explicitly enable +lingering with `loginctl enable-linger "$USER"`; authorization depends on local policy. +Installation and removal never change lingering, which can also support other user services. +Without it, service lifetime follows the system's user-manager/session policy. + Installation copies the binary to `~/.local/share/soze/bin/soze`, so changing checkout branches or rebuilding a development binary does not replace the running installation. Re-running `task service:install` updates the installed binary and restarts the service. It records the @@ -64,6 +79,7 @@ Use `SOZE_PORT=48732` when launching a wrapped agent against the development pro | Path | Contents | | --- | --- | | `~/Library/LaunchAgents/com.killallgit.soze.plist` | macOS supervisor definition | +| `~/.config/systemd/user/soze.service` | Linux supervisor definition; follows `XDG_CONFIG_HOME` if set | | `~/.local/share/soze/bin/soze` | Installed executable | | `~/.local/share/soze/bin/install.json` | Installed-build provenance | | `~/.local/share/soze/tap.jsonl` and numbered segments | Captured events, content, records and graph edges | @@ -77,7 +93,10 @@ The first install creates `config.toml` with `log_format = "human"` and `live = file is absent. Later installs preserve it. The CA is made on the binary's first run, not installed into a trust store. -Normal uninstall keeps captures, logs, configuration and CA material. +Normal uninstall keeps captures, logs, configuration and CA material. On Linux it first +verifies that the caller's unit path matches the manager's loaded definition, then disables +and stops the unit before deleting it and reloading the manager. A mismatched path or stop +failure aborts removal, so files are not deleted from underneath a possibly running service. `task service:uninstall -- --purge` additionally lists and deletes the entire `~/.local/share/soze/` directory. It still keeps `~/.config/soze/`. @@ -109,7 +128,7 @@ subcommands and exposes no management or health API. | Information | Available interface | | --- | --- | -| Supervisor state and PID | `task service:status`, macOS only | +| Supervisor state and PID | `task service:status`, macOS and Linux | | Installed source SHA, branch, dirty flag and installation time | Same command, from `bin/install.json` | | Content-free operational activity | `task service:logs` | | Capture and log disk usage | Filesystem tools; no built-in aggregate report | @@ -119,6 +138,28 @@ Supervisor state and a listening TCP port do not prove successful upstream reque complete capture. The existing status command reports the supervisor and installation, not an application-level health assessment. +Linux status maps systemd's service substate to `state` (for example, `running`, `dead` or +`failed`), reports an empty PID when no process is running, and uses `not loaded` for a missing +unit. An unreachable user manager fails the command rather than looking like an absent unit. + +## Testing supervision + +`task check` and Linux CI run isolated shell tests of both service backends using fake OS +commands. `task test:systemd` separately builds a debug Linux binary and boots a disposable +systemd Docker image, exercising the real installer and proxy under a non-root user manager. +It checks enablement, state/PID, proxy forwarding, reload, restart, automatic recovery, +update and retained data after uninstall, followed by purge. + +Docker is only the integration-test environment; it does not replace native host supervision. +The test needs a trusted rootful Linux Docker daemon with cgroup v2 and uses a privileged +container with a private cgroup namespace. No host directories or sockets are mounted, no +ports are published and runtime networking is loopback-only. The container and its generated +capture/CA files are removed after the test. See the [Docker test +instructions](../../README.md#test-real-systemd-with-docker) before running against a local or +remote Docker context. + +## Inspecting disk usage + These commands report disk usage without printing captured content: ```sh diff --git a/docs/architecture/system-overview.md b/docs/architecture/system-overview.md index d4b0e43..5ce8dd2 100644 --- a/docs/architecture/system-overview.md +++ b/docs/architecture/system-overview.md @@ -4,9 +4,8 @@ Soze is a local, per-user HTTPS proxy with a non-blocking capture pipeline. Codi communicate with their providers through it; a separate tap converts copied traffic into the [common event format](../common-format.md). -This document describes the current implementation. The Linux service supervisor in the -diagram is a proposal, not an implemented service backend. See [service lifecycle and -storage](service-lifecycle.md) for platform behavior, commands and retention. +This document describes the current implementation. See [service lifecycle and +storage](service-lifecycle.md) for macOS and Linux platform behavior, commands and retention. ## Architecture diagram @@ -35,7 +34,7 @@ flowchart TB ShapeFiles[("Shape files
shapes.jsonl + rotated segments")] LogFiles[("Operational and debug logs
soze.log · debug.jsonl")] Mac["macOS launchd LaunchAgent
Implemented"] - Linux["Linux systemd user service
Proposed, not implemented"] + Linux["Linux systemd user service
Implemented"] Wrappers -->|"Launch with environment settings"| Agents Agents <-->|"HTTPS CONNECT"| Listener @@ -55,7 +54,7 @@ flowchart TB Config --> Service CA --> Intercept Mac -->|"Start and supervise"| Service - Linux -.->|"Proposed supervision"| Service + Linux -->|"Start and supervise"| Service end Models["Model APIs
Anthropic · OpenAI / ChatGPT"] @@ -63,12 +62,10 @@ flowchart TB Intercept <-->|"Upstream TLS"| Models Tunnel <-->|"Encrypted traffic"| Other - classDef proposed fill:#fff4d6,stroke:#9a6700,stroke-dasharray:5 5; - class Linux proposed; ``` Dashed data-path arrows show copied traffic, observations or metadata, not forwarding -dependencies. The separately styled Linux supervisor is the only proposed component. +dependencies. The diagram groups related responsibilities; it is not a task-by-task execution graph. ## Agent integration @@ -137,10 +134,10 @@ the proxy from starting. Soze is one Rust crate and one binary. It does not own the agent's tool-execution loop or run the model. The intended service deployment is one proxy per user, without root privileges; -the current installer implements that on macOS only. +the installer implements that on macOS and Linux with systemd. The CLI starts the proxy and accepts configuration flags, but has no status, storage-usage or -session-listing subcommands. The macOS task commands query the supervisor separately; see +session-listing subcommands. The service task commands query the supervisor separately; see [management and visibility](service-lifecycle.md#management-and-visibility). How other applications receive the common format remains undecided. This architecture assumes diff --git a/scripts/service.sh b/scripts/service.sh index 34fc054..9b3110f 100755 --- a/scripts/service.sh +++ b/scripts/service.sh @@ -1,14 +1,27 @@ #!/bin/sh -# Runs soze as a launchd user agent from a binary built by the caller. +# Runs soze under launchd (macOS) or systemd --user (Linux) from a caller-built binary. # Usage: service.sh install | restart | reload | status | logs | uninstall [--purge] set -e root=$(cd "$(dirname "$0")/.." && pwd) usage="usage: service.sh install | restart | reload | status | logs | uninstall [--purge]" +# An empty HOME would put installation and purge paths under /. +[ -n "$HOME" ] || { echo "HOME is empty: nothing changed" >&2; exit 2; } +platform=$(uname -s) +case "$platform" in + Darwin) ;; + Linux) + command -v systemctl >/dev/null 2>&1 || + { echo "Linux service management requires systemd --user" >&2; exit 2; } + ;; + *) echo "unsupported service platform: $platform" >&2; exit 2 ;; +esac + label=com.killallgit.soze domain="gui/$(id -u)" data=$HOME/.local/share/soze plist=$HOME/Library/LaunchAgents/$label.plist +unit=${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/soze.service config=$HOME/.config/soze/config.toml # launchd_field : a value from the top level of `launchctl print` on stdin @@ -19,7 +32,14 @@ launchd_field() { show_status() { state="not loaded" pid= - if printed=$(launchctl print "$domain/$label" 2>/dev/null); then + if [ "$platform" = Linux ]; then + printed=$(systemctl --user show soze.service --property=LoadState --property=SubState --property=MainPID) || return + if [ "$(printf '%s\n' "$printed" | sed -n 's/^LoadState=//p')" != not-found ]; then + state=$(printf '%s\n' "$printed" | sed -n 's/^SubState=//p') + pid=$(printf '%s\n' "$printed" | sed -n 's/^MainPID=//p') + [ "$pid" != 0 ] || pid= + fi + elif printed=$(launchctl print "$domain/$label" 2>/dev/null); then state=$(printf '%s\n' "$printed" | launchd_field state) pid=$(printf '%s\n' "$printed" | launchd_field pid) fi @@ -28,11 +48,41 @@ show_status() { sed -n '/^ "/{s/,$//;s/^ "\([a-z_]*\)": /\1=/;s/="\(.*\)"$/=\1/;p;}' "$data/bin/install.json" } -# an empty HOME would put the plist and the data dir under / +installation_exists() { + [ -e "$unit" ] || [ -e "$data/bin/soze" ] || [ -e "$data/bin/install.json" ] +} + +verify_unit_identity() { + # Search visibility does not establish which same-named definition the manager loaded. + fragment=$(systemctl --user show soze.service --property=FragmentPath --value) + expected_unit=$(printf '%s\n' "$unit" | sed 's://*:/:g') + [ "$fragment" != "$expected_unit" ] || return 0 + if [ "$1" = new ] && [ -z "$fragment" ] && ! installation_exists; then + # Only a genuinely absent unit may lack an identity before the first write. + identity=$(systemctl --user show soze.service --property=LoadState --property=MainPID) + if [ "$(printf '%s\n' "$identity" | sed -n 's/^LoadState=//p')" = not-found ] && + [ "$(printf '%s\n' "$identity" | sed -n 's/^MainPID=//p')" = 0 ]; then + return 0 + fi + fi + echo "unit identity does not match the user manager: refusing service operation" >&2 + exit 2 +} + uninstall() { - [ -n "$HOME" ] || { echo "HOME is empty: nothing changed" >&2; exit 2; } - launchctl bootout "$domain/$label" 2>/dev/null || true - rm -f "$plist" "$data/bin/soze" "$data/bin/install.json" + if [ "$platform" = Linux ]; then + if installation_exists; then + verify_unit_identity existing + # Do not remove files if the manager could not stop the running service. + systemctl --user disable --now soze.service + rm -f "$unit" + systemctl --user daemon-reload + fi + else + launchctl bootout "$domain/$label" 2>/dev/null || true + rm -f "$plist" + fi + rm -f "$data/bin/soze" "$data/bin/install.json" rmdir "$data/bin" 2>/dev/null || true } @@ -43,8 +93,14 @@ purge() { } case "$#:$*" in - 1:restart) exec launchctl kickstart -k "$domain/$label" ;; - 1:reload) exec launchctl kill HUP "$domain/$label" ;; + 1:restart) + [ "$platform" != Linux ] || exec systemctl --user restart soze.service + exec launchctl kickstart -k "$domain/$label" + ;; + 1:reload) + [ "$platform" != Linux ] || exec systemctl --user reload soze.service + exec launchctl kill HUP "$domain/$label" + ;; 1:status) show_status; exit ;; 1:logs) exec tail -F "$data/logs/soze.log" ;; 1:uninstall) uninstall; exit ;; @@ -113,7 +169,81 @@ write_plist() { PLIST } -mkdir -p "$data/bin" "$data/logs" "$(dirname "$plist")" "$(dirname "$config")" +write_unit() { + # %h is expanded by systemd, not a shell; quoted argv also supports homes containing spaces. + cat > "$unit.new" <<'UNIT' +[Unit] +Description=Soze local model API proxy + +[Service] +Type=simple +ExecStart="%h/.local/share/soze/bin/soze" --port 48731 --tap-file "%h/.local/share/soze/tap.jsonl" --shape-file "%h/.local/share/soze/shapes.jsonl" --log-file "%h/.local/share/soze/debug.jsonl" +ExecReload=/bin/kill -HUP $MAINPID +Restart=on-failure +RestartSec=5 +UMask=0077 +StandardOutput=append:%h/.local/share/soze/logs/soze.log +StandardError=inherit + +[Install] +WantedBy=default.target +UNIT +} + +if [ "$platform" = Linux ]; then + # Query the running manager, not the caller's potentially different XDG environment. + unit_paths=$(systemctl --user show --property=UnitPath --value) + # systemctl quotes string-array entries and backslash-escapes special characters. + # Decode those entries as data, never shell code, before comparing complete paths. + if ! printf '%s\n' "$unit_paths" | UNIT_DIRECTORY="${unit%/*}" awk ' + function matches_directory(value) { + gsub(/\/+/, "/", value) + sub(/\/$/, "", value) + return value == directory + } + BEGIN { + directory = ENVIRON["UNIT_DIRECTORY"] + gsub(/\/+/, "/", directory) + controls = sprintf("%c%c%c%c%c%c%c", 7, 8, 12, 10, 13, 9, 11) + } + { + if (NR != 1) { invalid = 1; next } + for (i = 1; i <= length($0); i++) { + c = substr($0, i, 1) + if (c == "\\") { + c = substr($0, ++i, 1) + octal = substr($0, i, 3) + if (octal ~ /^[0-3][0-7][0-7]$/) { + path = path sprintf("%c", substr(octal, 1, 1) * 64 + substr(octal, 2, 1) * 8 + substr(octal, 3, 1)) + i += 2 + } else if (c != "" && index("abfnrtv", c)) { + path = path substr(controls, index("abfnrtv", c), 1) + } else if (c == "\\" || c == "\"" || c == "$" || c == "`") { + path = path c + } else { invalid = 1; break } + } else if (c == "\"") { + quoted = !quoted + } else if (c ~ /[ \t]/ && !quoted) { + if (matches_directory(path)) found = 1 + path = "" + } else { + path = path c + } + } + if (matches_directory(path)) found = 1 + } + END { exit (invalid || quoted || !found) } + '; then + echo "unit directory is outside the user manager search path: nothing changed" >&2 + exit 2 + fi + verify_unit_identity new + umask 077 + definition=$unit +else + definition=$plist +fi +mkdir -p "$data/bin" "$data/logs" "$(dirname "$definition")" "$(dirname "$config")" # a rename gives the binary a new inode: overwriting a running signed binary can get it killed cp "$binary" "$data/bin/soze.new" chmod 755 "$data/bin/soze.new" @@ -121,6 +251,15 @@ mv -f "$data/bin/soze.new" "$data/bin/soze" write_record [ -e "$config" ] || printf 'log_format = "human"\nlive = true\n' > "$config" [ ! -e "$data/logs/soze.log" ] || mv -f "$data/logs/soze.log" "$data/logs/soze.log.1" +if [ "$platform" = Linux ]; then + write_unit + mv -f "$unit.new" "$unit" + systemctl --user daemon-reload + systemctl --user enable soze.service + # Reload/enable can change name resolution; never restart a different effective definition. + verify_unit_identity existing + exec systemctl --user restart soze.service +fi write_plist changed=0 cmp -s "$plist.new" "$plist" || changed=1 diff --git a/tests/service/lib.sh b/tests/service/lib.sh index 634c7f3..ccb71b5 100644 --- a/tests/service/lib.sh +++ b/tests/service/lib.sh @@ -1,21 +1,107 @@ . "$(dirname "$0")/../wrappers/lib.sh" -# Helpers for the service tests: a throwaway HOME with a fake launchctl and a fake git on PATH. +# Helpers for the service tests: a throwaway HOME with fake supervisors and git on PATH. new_home() { HOME=$(mktemp -d) export HOME mkdir -p "$HOME/bin" PATH="$HOME/bin:$ORIG_PATH" - unset SOZE_PORT + unset SOZE_PORT XDG_CONFIG_HOME LABEL=com.killallgit.soze DOMAIN="gui/$(id -u)" DATA="$HOME/.local/share/soze" PLIST="$HOME/Library/LaunchAgents/$LABEL.plist" + UNIT="$HOME/.config/systemd/user/soze.service" + fake_uname "${SERVICE_OS:-Darwin}" fake_launchctl + fake_systemctl fake_git touch "$HOME/.marker" } +fake_uname() { + printf '#!/bin/sh\nprintf "%%s\\n" "%s"\n' "$1" > "$HOME/bin/uname" + chmod +x "$HOME/bin/uname" +} + +# Records calls and models only the properties used by the installer. +fake_systemctl() { + cat > "$HOME/bin/systemctl" <<'FAKE' +#!/bin/sh +[ "$1" = --user ] || exit 2 +shift +echo "$*" >> "$HOME/systemctl.calls" +if [ -e "$HOME/systemctl.fail" ] && grep -qxF "$1" "$HOME/systemctl.fail"; then exit 1; fi +resolve_fragment() { + for candidate in "$HOME/.config/systemd/user/soze.service" \ + "${XDG_CONFIG_HOME:-$HOME/.config}/systemd/user/soze.service" \ + "$HOME/.local/share/systemd/user/soze.service"; do + [ -f "$candidate" ] || continue + printf '%s\n' "$candidate" | sed 's://*:/:g' + return + done +} +case "$*" in + 'show --property=UnitPath --value') + if [ -e "$HOME/systemctl.unit-paths" ]; then + cat "$HOME/systemctl.unit-paths" + else + printf '/etc/systemd/user "%s/.config/systemd/user" /usr/lib/systemd/user\n' "$HOME" + fi + ;; + 'daemon-reload') + resolve_fragment > "$HOME/systemctl.fragment-path" + if [ -e "$HOME/systemctl.fragment-after-reload" ]; then + cp "$HOME/systemctl.fragment-after-reload" "$HOME/systemctl.fragment-path" + fi + ;; + 'enable soze.service') touch "$HOME/systemctl.enabled" ;; + 'restart soze.service') + [ -e "$HOME/systemctl.enabled" ] || exit 1 + pid=4242 + [ ! -e "$HOME/systemctl.pid" ] || pid=$(($(cat "$HOME/systemctl.pid") + 1)) + printf '%s\n' "$pid" > "$HOME/systemctl.pid" + touch "$HOME/systemctl.running" + ;; + 'stop soze.service') rm -f "$HOME/systemctl.running" ;; + 'reload soze.service') [ -e "$HOME/systemctl.running" ] || exit 1 ;; + 'show soze.service --property=FragmentPath --value') + [ -e "$HOME/systemctl.fragment-path" ] || resolve_fragment > "$HOME/systemctl.fragment-path" + cat "$HOME/systemctl.fragment-path" + ;; + 'show soze.service --property=LoadState --property=MainPID') + if [ -e "$HOME/systemctl.load-state" ]; then + printf 'LoadState=' + cat "$HOME/systemctl.load-state" + elif [ -s "$HOME/systemctl.fragment-path" ]; then + printf 'LoadState=loaded\n' + else + printf 'LoadState=not-found\n' + fi + if [ -e "$HOME/systemctl.running" ]; then + printf 'MainPID=%s\n' "$(cat "$HOME/systemctl.pid")" + else + printf 'MainPID=0\n' + fi + ;; + 'show soze.service --property=LoadState --property=SubState --property=MainPID') + if [ -e "$HOME/systemctl.running" ]; then + printf 'LoadState=loaded\nSubState=running\nMainPID=%s\n' "$(cat "$HOME/systemctl.pid")" + elif [ -e "$HOME/systemctl.enabled" ]; then + printf 'LoadState=loaded\nSubState=failed\nMainPID=0\n' + else + printf 'LoadState=not-found\nSubState=dead\nMainPID=0\n' + fi + ;; + 'disable --now soze.service') + rm -f "$HOME/systemctl.enabled" "$HOME/systemctl.running" + ;; + *) exit 2 ;; +esac +FAKE + chmod +x "$HOME/bin/systemctl" +} + # Records every call; the agent is loaded while $HOME/launchctl.loaded exists, and a subcommand # named in $HOME/launchctl.fail exits 1. fake_launchctl() { diff --git a/tests/service/test_linux.sh b/tests/service/test_linux.sh new file mode 100644 index 0000000..735ba79 --- /dev/null +++ b/tests/service/test_linux.sh @@ -0,0 +1,565 @@ +. "$(dirname "$0")/lib.sh" +SERVICE_OS=Linux + +install_fake() { + fake_soze "$HOME/soze" "${1:-one}" + service install "$HOME/soze" +} + +systemctl_calls() { cat "$HOME/systemctl.calls"; } + +installed() { + install_fake + "$RM" "$HOME/systemctl.calls" +} + +exit_code() { + code=0 + service "$@" > "$HOME/out" 2>/dev/null || code=$? + echo "$code" +} + +installs_an_enabled_always_on_user_unit() { + install_fake + + # The user unit supervises the foreground binary, reloads logging and keeps output private. + [ -x "$DATA/bin/soze" ] + cmp "$HOME/soze" "$DATA/bin/soze" + eq "$(systemctl_calls)" "$(printf '%s\n' 'show --property=UnitPath --value' 'show soze.service --property=FragmentPath --value' 'show soze.service --property=LoadState --property=MainPID' daemon-reload 'enable soze.service' 'show soze.service --property=FragmentPath --value' 'restart soze.service')" "install calls" + eq "$(cat "$UNIT")" "$(cat <<'UNIT' +[Unit] +Description=Soze local model API proxy + +[Service] +Type=simple +ExecStart="%h/.local/share/soze/bin/soze" --port 48731 --tap-file "%h/.local/share/soze/tap.jsonl" --shape-file "%h/.local/share/soze/shapes.jsonl" --log-file "%h/.local/share/soze/debug.jsonl" +ExecReload=/bin/kill -HUP $MAINPID +Restart=on-failure +RestartSec=5 +UMask=0077 +StandardOutput=append:%h/.local/share/soze/logs/soze.log +StandardError=inherit + +[Install] +WantedBy=default.target +UNIT +)" "unit definition" + [ ! -e "$PLIST" ] + [ ! -e "$HOME/launchctl.calls" ] +} + +shares_config_and_provenance_with_macos() { + install_fake + service status > "$HOME/out" + + # Linux uses the same defaults and installation record, with the smoke-compatible state. + eq "$(cat "$HOME/.config/soze/config.toml")" "$(printf 'log_format = "human"\nlive = true')" config + grep -qx 'state=running' "$HOME/out" + grep -qx 'pid=4242' "$HOME/out" + grep -qx 'sha=0123456789abcdef0123456789abcdef01234567' "$HOME/out" + grep -qx 'branch=main' "$HOME/out" + grep -qx 'dirty=false' "$HOME/out" +} + +updates_the_binary_preserving_config_and_captures() { + installed + printf 'live = false\n' > "$HOME/.config/soze/config.toml" + cp "$HOME/.config/soze/config.toml" "$HOME/config.before" + printf '{"synthetic":true}\n' > "$DATA/tap.jsonl" + cp "$DATA/tap.jsonl" "$HOME/tap.before" + printf 'synthetic\n' > "$DATA/logs/soze.log" + cp "$DATA/logs/soze.log" "$HOME/log.before" + before=$(ls -i "$DATA/bin/soze" | awk '{print $1}') + + install_fake two + + # Updates replace the executable inode and rotate only the operational log. + cmp "$HOME/soze" "$DATA/bin/soze" + [ "$(ls -i "$DATA/bin/soze" | awk '{print $1}')" != "$before" ] + cmp "$HOME/config.before" "$HOME/.config/soze/config.toml" + cmp "$HOME/tap.before" "$DATA/tap.jsonl" + cmp "$HOME/log.before" "$DATA/logs/soze.log.1" + eq "$(systemctl_calls)" "$(printf '%s\n' 'show --property=UnitPath --value' 'show soze.service --property=FragmentPath --value' daemon-reload 'enable soze.service' 'show soze.service --property=FragmentPath --value' 'restart soze.service')" "update calls" +} + +uses_the_user_managers_config_directory() { + export XDG_CONFIG_HOME="$HOME/custom config" + printf '/etc/systemd/user "%s/systemd/user" /usr/lib/systemd/user\n' "$XDG_CONFIG_HOME" > "$HOME/systemctl.unit-paths" + install_fake + + # Only the supervisor definition follows XDG; Soze keeps its existing config/data contract. + [ -f "$XDG_CONFIG_HOME/systemd/user/soze.service" ] + [ ! -e "$UNIT" ] + [ -f "$HOME/.config/soze/config.toml" ] + service uninstall + [ ! -e "$XDG_CONFIG_HOME/systemd/user/soze.service" ] +} + +manager_paths_with_escaped_characters_remain_valid() { + export XDG_CONFIG_HOME="$HOME/custom \"config\\dir \$HOME" + printf '/etc/systemd/user "%s/custom \\"config\\\\dir \\$HOME/systemd/user"\n' "$HOME" > "$HOME/systemctl.unit-paths" + + install_fake + + # Quoting and escape sequences describe literal path characters, never shell expansions. + [ -f "$XDG_CONFIG_HOME/systemd/user/soze.service" ] + [ ! -e "$UNIT" ] + service uninstall + [ ! -e "$XDG_CONFIG_HOME/systemd/user/soze.service" ] +} + +config_directory_trailing_slashes_remain_valid() { + export XDG_CONFIG_HOME="$HOME/custom config/" + printf '"%s/custom config/systemd/user"\n' "$HOME" > "$HOME/systemctl.unit-paths" + + install_fake + + # A trailing XDG slash still addresses the directory searched by the manager. + [ -f "$XDG_CONFIG_HOME/systemd/user/soze.service" ] + service uninstall + [ ! -e "$XDG_CONFIG_HOME/systemd/user/soze.service" ] +} + +malformed_manager_paths_cannot_authorize_installation() { + printf '"%s/.config/systemd/user\n' "$HOME" > "$HOME/systemctl.unit-paths" + fake_soze "$HOME/soze" one + + code=$(exit_code install "$HOME/soze") + + # A partial quoted entry is not evidence that the manager searches that directory. + eq "$code" 2 "malformed unit path" + [ ! -e "$HOME/.local" ] + [ ! -e "$HOME/.config" ] +} + +caller_only_config_override_preserves_the_running_installation() { + installed + printf 'synthetic\n' > "$DATA/logs/soze.log" + printf '{"synthetic":true}\n' > "$DATA/tap.jsonl" + cp -Rp "$DATA" "$HOME/data.before" + cp "$UNIT" "$HOME/unit.before" + cp "$HOME/.config/soze/config.toml" "$HOME/config.before" + inode_before=$(ls -i "$DATA/bin/soze" | awk '{print $1}') + export XDG_CONFIG_HOME="$HOME/caller config" + fake_soze "$HOME/soze" two + + code=$(exit_code install "$HOME/soze") + + # A caller-only directory cannot replace files or disturb the already running service. + eq "$code" 2 "unsearchable unit directory" + diff -rq "$HOME/data.before" "$DATA" > /dev/null + cmp "$HOME/unit.before" "$UNIT" + cmp "$HOME/config.before" "$HOME/.config/soze/config.toml" + eq "$(ls -i "$DATA/bin/soze" | awk '{print $1}')" "$inode_before" "binary inode" + [ -e "$HOME/systemctl.running" ] + [ ! -e "$XDG_CONFIG_HOME" ] + eq "$(systemctl_calls)" 'show --property=UnitPath --value' "preflight calls only" +} + +manager_path_prefixes_do_not_authorize_a_new_installation() { + export XDG_CONFIG_HOME="$HOME/caller config" + printf '"%s/systemd/user-extra" "%s/systemd/user/nested"\n' "$XDG_CONFIG_HOME" "$XDG_CONFIG_HOME" > "$HOME/systemctl.unit-paths" + fake_soze "$HOME/soze" one + + code=$(exit_code install "$HOME/soze") + + # Only a complete search-path entry authorizes the unit directory, not a substring. + eq "$code" 2 "unsearchable unit directory" + [ ! -e "$HOME/.local" ] + [ ! -e "$HOME/.config" ] + [ ! -e "$XDG_CONFIG_HOME" ] +} + +a_searched_but_shadowed_directory_cannot_update_the_loaded_installation() { + installed + printf 'synthetic\n' > "$DATA/logs/soze.log" + printf '{"synthetic":true}\n' > "$DATA/tap.jsonl" + cp -Rp "$DATA" "$HOME/data.before" + cp "$UNIT" "$HOME/unit.before" + cp "$HOME/.config/soze/config.toml" "$HOME/config.before" + inode_before=$(ls -i "$DATA/bin/soze" | awk '{print $1}') + pid_before=$(cat "$HOME/systemctl.pid") + export XDG_CONFIG_HOME="$HOME/.local/share" + printf '"%s/.config/systemd/user" "%s/systemd/user"\n' "$HOME" "$XDG_CONFIG_HOME" > "$HOME/systemctl.unit-paths" + fake_soze "$HOME/soze" two + + code=$(exit_code install "$HOME/soze") + + # Both directories are searched, but only the already loaded definition owns shared files. + eq "$code" 2 "shadowed installation" + diff -rq "$HOME/data.before" "$DATA" > /dev/null + cmp "$HOME/unit.before" "$UNIT" + cmp "$HOME/config.before" "$HOME/.config/soze/config.toml" + eq "$(ls -i "$DATA/bin/soze" | awk '{print $1}')" "$inode_before" "binary inode" + eq "$(cat "$HOME/systemctl.pid")" "$pid_before" "running pid" + [ -e "$HOME/systemctl.running" ] + [ -e "$HOME/systemctl.enabled" ] + [ ! -e "$XDG_CONFIG_HOME/systemd/user/soze.service" ] + eq "$(systemctl_calls)" "$(printf '%s\n' 'show --property=UnitPath --value' 'show soze.service --property=FragmentPath --value')" "identity preflight only" +} + +an_empty_fragment_cannot_authorize_an_existing_installation_update() { + installed + : > "$HOME/systemctl.fragment-path" + cp -Rp "$DATA" "$HOME/data.before" + cp "$UNIT" "$HOME/unit.before" + fake_soze "$HOME/soze" two + + code=$(exit_code install "$HOME/soze") + + # Missing identity is acceptable only before the first installation, never for installed artifacts. + eq "$code" 2 "missing existing identity" + diff -rq "$HOME/data.before" "$DATA" > /dev/null + cmp "$HOME/unit.before" "$UNIT" + [ -e "$HOME/systemctl.running" ] +} + +a_masked_unit_is_not_a_genuinely_new_installation() { + echo masked > "$HOME/systemctl.load-state" + fake_soze "$HOME/soze" one + + code=$(exit_code install "$HOME/soze") + + # An empty FragmentPath does not prove absence when the manager reports another load state. + eq "$code" 2 "masked unit" + [ ! -e "$HOME/.local" ] + [ ! -e "$HOME/.config" ] +} + +an_identity_change_during_reload_prevents_restart() { + printf '%s/shadow/soze.service\n' "$HOME" > "$HOME/systemctl.fragment-after-reload" + fake_soze "$HOME/soze" one + + code=$(exit_code install "$HOME/soze") + + # The effective post-write identity must match even when the earlier absence check succeeded. + eq "$code" 2 "post-write identity mismatch" + [ ! -e "$HOME/systemctl.running" ] + [ ! -e "$HOME/systemctl.pid" ] + eq "$(systemctl_calls)" "$(printf '%s\n' 'show --property=UnitPath --value' 'show soze.service --property=FragmentPath --value' 'show soze.service --property=LoadState --property=MainPID' daemon-reload 'enable soze.service' 'show soze.service --property=FragmentPath --value')" "no shadowed restart" +} + +a_stopped_service_can_be_updated_with_its_existing_identity() { + installed + systemctl --user stop soze.service + fake_soze "$HOME/soze" two + + service install "$HOME/soze" + + # Stopped is not missing: the same loaded definition can still receive an ordinary update. + cmp "$HOME/soze" "$DATA/bin/soze" + [ -e "$HOME/systemctl.running" ] +} + +restart_and_reload_use_the_user_manager() { + installed + + service restart + service reload + + # Both operations target only this user's Soze unit. + eq "$(systemctl_calls)" "$(printf '%s\n' 'restart soze.service' 'reload soze.service')" "control calls" +} + +control_failures_propagate() { + # No unit is available to restart or reload. + [ "$(exit_code restart)" -ne 0 ] + [ "$(exit_code reload)" -ne 0 ] +} + +status_without_an_install_is_not_loaded() { + service status > "$HOME/out" + + # An absent unit is distinct from a failed installed unit. + eq "$(cat "$HOME/out")" "$(printf 'state=not loaded\npid=')" status +} + +status_reports_failed_units_without_a_pid() { + installed + "$RM" "$HOME/systemctl.running" + + service status > "$HOME/out" + + # A supervisor failure remains visible rather than being reported as not installed. + grep -qx 'state=failed' "$HOME/out" + grep -qx 'pid=' "$HOME/out" +} + +status_fails_when_the_user_manager_is_unavailable() { + echo show > "$HOME/systemctl.fail" + + # A missing user bus must not masquerade as an uninstalled service. + [ "$(exit_code status)" -ne 0 ] + [ ! -s "$HOME/out" ] +} + +logs_follow_only_the_operational_file() { + fake_tail + + service logs + + # Neither captures nor the journal can leak into the logs command. + eq "$(cat "$HOME/tail.args")" "$(printf '%s\n' -F "$DATA/logs/soze.log")" "tail arguments" +} + +uninstall_disables_the_unit_and_preserves_data() { + installed + printf '{"synthetic":true}\n' > "$DATA/tap.jsonl" + cp "$DATA/tap.jsonl" "$HOME/tap.before" + + service uninstall > "$HOME/out" + + # Stop/disable precedes removal and reload; captures and configuration survive. + eq "$(systemctl_calls)" "$(printf '%s\n' 'show soze.service --property=FragmentPath --value' 'disable --now soze.service' daemon-reload)" "uninstall calls" + [ ! -e "$UNIT" ] + [ ! -e "$DATA/bin" ] + [ ! -e "$HOME/systemctl.enabled" ] + [ ! -e "$HOME/systemctl.running" ] + cmp "$HOME/tap.before" "$DATA/tap.jsonl" + [ -e "$HOME/.config/soze/config.toml" ] + [ ! -s "$HOME/out" ] +} + +uninstall_is_idempotent() { + echo show > "$HOME/systemctl.fail" + service uninstall + service uninstall + + # No installed unit means no supervisor operation is needed. + [ ! -e "$HOME/systemctl.calls" ] + [ ! -e "$HOME/.local" ] +} + +rejects_uninstall_without_mutating_the_installation() { + expected_code=$1 + shift + printf 'synthetic\n' > "$DATA/logs/soze.log" + printf '{"synthetic":true}\n' > "$DATA/tap.jsonl" + cp -Rp "$DATA" "$HOME/data.before" + cp "$UNIT" "$HOME/unit.before" + cp "$HOME/.config/soze/config.toml" "$HOME/config.before" + inode_before=$(ls -i "$DATA/bin/soze" | awk '{print $1}') + + code=$(exit_code uninstall "$@") + + # Identity rejection or a failed query cannot stop/disable or change installed files/data. + eq "$code" "$expected_code" "uninstall exit status" + diff -rq "$HOME/data.before" "$DATA" > /dev/null + cmp "$HOME/unit.before" "$UNIT" + cmp "$HOME/config.before" "$HOME/.config/soze/config.toml" + eq "$(ls -i "$DATA/bin/soze" | awk '{print $1}')" "$inode_before" "binary inode" + [ -e "$HOME/systemctl.running" ] + [ -e "$HOME/systemctl.enabled" ] + eq "$(systemctl_calls)" 'show soze.service --property=FragmentPath --value' "identity query only" + [ ! -s "$HOME/out" ] +} + +caller_only_override_cannot_uninstall_the_running_service() { + installed + export XDG_CONFIG_HOME="$HOME/caller config" + + rejects_uninstall_without_mutating_the_installation 2 + + # An absent caller-only directory must remain absent. + [ ! -e "$XDG_CONFIG_HOME" ] +} + +caller_only_override_cannot_purge_the_running_service() { + installed + export XDG_CONFIG_HOME="$HOME/caller config" + + rejects_uninstall_without_mutating_the_installation 2 --purge + + # Purge cannot create or remove an unrelated caller-only directory. + [ ! -e "$XDG_CONFIG_HOME" ] +} + +an_absent_executable_does_not_bypass_the_identity_check() { + installed + "$RM" "$DATA/bin/soze" + export XDG_CONFIG_HOME="$HOME/caller config" + cp "$DATA/bin/install.json" "$HOME/record.before" + + code=$(exit_code uninstall --purge) + + # Remaining provenance still identifies an installation even if its executable was removed. + eq "$code" 2 "uninstall exit status" + cmp "$HOME/record.before" "$DATA/bin/install.json" + [ -f "$UNIT" ] + [ -e "$HOME/systemctl.running" ] + [ -e "$HOME/systemctl.enabled" ] + eq "$(systemctl_calls)" 'show soze.service --property=FragmentPath --value' "identity query only" +} + +a_searched_but_shadowed_definition_cannot_uninstall_the_loaded_unit() { + installed + export XDG_CONFIG_HOME="$HOME/other config" + printf '"%s/.config/systemd/user" "%s/systemd/user"\n' "$HOME" "$XDG_CONFIG_HOME" > "$HOME/systemctl.unit-paths" + mkdir -p "$XDG_CONFIG_HOME/systemd/user" + cp "$UNIT" "$XDG_CONFIG_HOME/systemd/user/soze.service" + cp "$UNIT" "$HOME/other-unit.before" + + rejects_uninstall_without_mutating_the_installation 2 + + # Search visibility and an identical definition do not prove which path is loaded. + cmp "$HOME/other-unit.before" "$XDG_CONFIG_HOME/systemd/user/soze.service" +} + +an_empty_fragment_identity_prevents_purging_the_installation() { + installed + : > "$HOME/systemctl.fragment-path" + + rejects_uninstall_without_mutating_the_installation 2 --purge +} + +an_unavailable_manager_prevents_uninstall_mutation() { + installed + echo show > "$HOME/systemctl.fail" + + rejects_uninstall_without_mutating_the_installation 1 --purge +} + +purge_deletes_only_the_data_directory() { + installed + printf '{"synthetic":true}\n' > "$DATA/tap.jsonl" + + service uninstall --purge > "$HOME/out" + + # Purge lists paths, not capture values, and keeps CA/config storage. + grep -qxF "$DATA/tap.jsonl" "$HOME/out" + eq "$(grep -c synthetic "$HOME/out")" 0 "capture content lines" + [ ! -e "$DATA" ] + [ ! -e "$UNIT" ] + [ -e "$HOME/.config/soze/config.toml" ] +} + +an_unavailable_manager_prevents_installation() { + echo show > "$HOME/systemctl.fail" + fake_soze "$HOME/soze" one + + # Preflight failure leaves the installed files untouched. + [ "$(exit_code install "$HOME/soze")" -ne 0 ] + [ ! -e "$HOME/.local" ] + [ ! -e "$HOME/.config" ] +} + +install_failures_propagate() { + fake_soze "$HOME/soze" one + for command in daemon-reload enable restart; do + echo "$command" > "$HOME/systemctl.fail" + + # Failure at any required supervisor step fails the install. + [ "$(exit_code install "$HOME/soze")" -ne 0 ] + done +} + +a_stop_failure_preserves_the_installation() { + installed + echo disable > "$HOME/systemctl.fail" + + # Do not remove or purge files while the supervisor may still own a running process. + [ "$(exit_code uninstall --purge)" -ne 0 ] + [ -e "$UNIT" ] + [ -x "$DATA/bin/soze" ] + [ -e "$HOME/systemctl.running" ] +} + +a_missing_unit_file_does_not_bypass_the_stop_check() { + installed + "$RM" "$UNIT" + echo disable > "$HOME/systemctl.fail" + printf '{"synthetic":true}\n' > "$DATA/tap.jsonl" + + # A deleted definition does not prove that the manager stopped the installed process. + [ "$(exit_code uninstall --purge)" -ne 0 ] + [ -x "$DATA/bin/soze" ] + [ -e "$DATA/tap.jsonl" ] + [ -e "$HOME/systemctl.running" ] + eq "$(systemctl_calls)" "$(printf '%s\n' 'show soze.service --property=FragmentPath --value' 'disable --now soze.service')" "missing definition still requires stop" +} + +a_removed_definition_can_be_uninstalled_using_the_cached_identity() { + installed + "$RM" "$UNIT" + + service uninstall + + # A cached matching FragmentPath still requires a successful stop before removing the binary. + [ ! -e "$DATA/bin" ] + [ ! -e "$HOME/systemctl.running" ] + [ ! -e "$HOME/systemctl.enabled" ] + eq "$(systemctl_calls)" "$(printf '%s\n' 'show soze.service --property=FragmentPath --value' 'disable --now soze.service' daemon-reload)" "removed definition uninstall calls" +} + +invalid_arguments_change_nothing() { + fake_soze "$HOME/soze" one + + # Invalid commands/binaries are rejected before contacting either supervisor. + eq "$(exit_code install "$HOME/missing")" 2 "bad binary" + eq "$(exit_code restart extra)" 2 "extra argument" + eq "$(exit_code uninstall --force)" 2 "unknown option" + [ ! -e "$HOME/systemctl.calls" ] + [ ! -e "$HOME/launchctl.calls" ] + [ ! -e "$HOME/.local" ] +} + +an_empty_home_changes_nothing() { + fake_soze "$HOME/soze" one + code=0 + + env HOME= sh "$ROOT/scripts/service.sh" install "$HOME/soze" > /dev/null 2>&1 || code=$? + + # Missing HOME cannot redirect installation into root-owned paths. + eq "$code" 2 "exit status" + [ ! -e "$HOME/systemctl.calls" ] +} + +an_unsupported_platform_changes_nothing() { + fake_uname FreeBSD + fake_soze "$HOME/soze" one + + # Unsupported platforms fail explicitly rather than selecting launchd. + eq "$(exit_code install "$HOME/soze")" 2 "exit status" + [ ! -e "$HOME/launchctl.calls" ] + [ ! -e "$HOME/systemctl.calls" ] + [ ! -e "$HOME/.local" ] +} + +case_run installs_an_enabled_always_on_user_unit installs_an_enabled_always_on_user_unit +case_run shares_config_and_provenance_with_macos shares_config_and_provenance_with_macos +case_run updates_the_binary_preserving_config_and_captures updates_the_binary_preserving_config_and_captures +case_run uses_the_user_managers_config_directory uses_the_user_managers_config_directory +case_run manager_paths_with_escaped_characters_remain_valid manager_paths_with_escaped_characters_remain_valid +case_run config_directory_trailing_slashes_remain_valid config_directory_trailing_slashes_remain_valid +case_run malformed_manager_paths_cannot_authorize_installation malformed_manager_paths_cannot_authorize_installation +case_run caller_only_config_override_preserves_the_running_installation caller_only_config_override_preserves_the_running_installation +case_run manager_path_prefixes_do_not_authorize_a_new_installation manager_path_prefixes_do_not_authorize_a_new_installation +case_run a_searched_but_shadowed_directory_cannot_update_the_loaded_installation a_searched_but_shadowed_directory_cannot_update_the_loaded_installation +case_run an_empty_fragment_cannot_authorize_an_existing_installation_update an_empty_fragment_cannot_authorize_an_existing_installation_update +case_run a_masked_unit_is_not_a_genuinely_new_installation a_masked_unit_is_not_a_genuinely_new_installation +case_run an_identity_change_during_reload_prevents_restart an_identity_change_during_reload_prevents_restart +case_run a_stopped_service_can_be_updated_with_its_existing_identity a_stopped_service_can_be_updated_with_its_existing_identity +case_run restart_and_reload_use_the_user_manager restart_and_reload_use_the_user_manager +case_run control_failures_propagate control_failures_propagate +case_run status_without_an_install_is_not_loaded status_without_an_install_is_not_loaded +case_run status_reports_failed_units_without_a_pid status_reports_failed_units_without_a_pid +case_run status_fails_when_the_user_manager_is_unavailable status_fails_when_the_user_manager_is_unavailable +case_run logs_follow_only_the_operational_file logs_follow_only_the_operational_file +case_run uninstall_disables_the_unit_and_preserves_data uninstall_disables_the_unit_and_preserves_data +case_run uninstall_is_idempotent uninstall_is_idempotent +case_run caller_only_override_cannot_uninstall_the_running_service caller_only_override_cannot_uninstall_the_running_service +case_run caller_only_override_cannot_purge_the_running_service caller_only_override_cannot_purge_the_running_service +case_run an_absent_executable_does_not_bypass_the_identity_check an_absent_executable_does_not_bypass_the_identity_check +case_run a_searched_but_shadowed_definition_cannot_uninstall_the_loaded_unit a_searched_but_shadowed_definition_cannot_uninstall_the_loaded_unit +case_run an_empty_fragment_identity_prevents_purging_the_installation an_empty_fragment_identity_prevents_purging_the_installation +case_run an_unavailable_manager_prevents_uninstall_mutation an_unavailable_manager_prevents_uninstall_mutation +case_run purge_deletes_only_the_data_directory purge_deletes_only_the_data_directory +case_run an_unavailable_manager_prevents_installation an_unavailable_manager_prevents_installation +case_run install_failures_propagate install_failures_propagate +case_run a_stop_failure_preserves_the_installation a_stop_failure_preserves_the_installation +case_run a_missing_unit_file_does_not_bypass_the_stop_check a_missing_unit_file_does_not_bypass_the_stop_check +case_run a_removed_definition_can_be_uninstalled_using_the_cached_identity a_removed_definition_can_be_uninstalled_using_the_cached_identity +case_run invalid_arguments_change_nothing invalid_arguments_change_nothing +case_run an_empty_home_changes_nothing an_empty_home_changes_nothing +case_run an_unsupported_platform_changes_nothing an_unsupported_platform_changes_nothing +finish diff --git a/tests/service/test_systemd_runner.sh b/tests/service/test_systemd_runner.sh new file mode 100644 index 0000000..c0314bf --- /dev/null +++ b/tests/service/test_systemd_runner.sh @@ -0,0 +1,213 @@ +. "$(dirname "$0")/lib.sh" + +runner_shell=sh +[ -z "${BASH_VERSION:-}" ] || runner_shell=bash +[ -z "${ZSH_VERSION:-}" ] || runner_shell=zsh + +fake_docker() { + mkdir -p "$HOME/work" + export TMPDIR="$HOME/work" + cat > "$HOME/bin/timeout" <<'FAKE' +#!/bin/sh +printf '%s\n' "$1" >> "$HOME/timeouts" +shift +exec "$@" +FAKE + cat > "$HOME/bin/docker" <<'FAKE' +#!/bin/sh +command=$1 +shift +printf '%s\n' "$@" > "$HOME/docker.$command" +case "$command" in + context) echo synthetic-context ;; + build) + [ ! -e "$HOME/build.fail" ] || exit 23 + while [ "$#" -gt 0 ]; do + case "$1" in + --iidfile) printf '%s\n' sha256:synthetic-image > "$2"; shift ;; + esac + shift + done + ;; + run) + cidfile= + name= + label= + while [ "$#" -gt 0 ]; do + case "$1" in + --cidfile) cidfile=$2; shift ;; + --name) name=$2; shift ;; + --label) label=$2; shift ;; + --tmpfs) shift ;; + --detach | --privileged | --cgroupns=private | --network=none) ;; + -*) exit 2 ;; + *) printf '%s\n' "$1" > "$HOME/image.used" ;; + esac + shift + done + printf '%s\n' "$name" > "$HOME/name.used" + printf '%s\n' "${label#*=}" > "$HOME/owner" + printf '%s\n' synthetic-container > "$HOME/container" + if [ -e "$HOME/name.collision" ]; then + echo foreign-owner > "$HOME/owner" + echo foreign-container > "$HOME/container" + exit 125 + fi + [ ! -e "$HOME/run.fail" ] || exit 41 + if [ -e "$HOME/run.interrupt" ]; then + kill -TERM "$PPID" + exit 0 + fi + printf '%s\n' synthetic-container > "$cidfile" + ;; + inspect) + [ -e "$HOME/container" ] || exit 1 + printf '%s %s\n' "$(cat "$HOME/container")" "$(cat "$HOME/owner")" + ;; + exec) [ ! -e "$HOME/exec.fail" ] || exit 37 ;; + rm) + [ "$1" = --force ] && [ "$2" = "$(cat "$HOME/container")" ] || exit 2 + [ ! -e "$HOME/remove.fail" ] || exit 17 + rm "$HOME/container" + ;; + *) exit 2 ;; +esac +FAKE + chmod +x "$HOME/bin/docker" "$HOME/bin/timeout" +} + +runner_code() { + code=0 + "$runner_shell" "$ROOT/tests/systemd/run.sh" > "$HOME/out" 2>&1 || code=$? + printf '%s\n' "$code" +} + +launches_the_built_immutable_image_in_isolation() { + fake_docker + + result=$(runner_code) + + # The launched image is the build's ID, with no shared mutable tag or host access. + eq "$result" 0 "exit status" + eq "$(cat "$HOME/image.used")" sha256:synthetic-image "immutable image" + [ -n "$(cat "$HOME/name.used")" ] + [ -n "$(cat "$HOME/owner")" ] + eq "$(cat "$HOME/docker.build")" "$(printf '%s\n' --file "$ROOT/tests/systemd/Dockerfile" --iidfile "$(cat "$HOME/owner")/image.id" "$ROOT")" "build arguments" + eq "$(cat "$HOME/docker.run")" "$(printf '%s\n' --detach --privileged --cgroupns=private --network=none --tmpfs /run --tmpfs /run/lock --tmpfs /tmp --name "$(cat "$HOME/name.used")" --label "com.killallgit.soze.systemd-test=$(cat "$HOME/owner")" --cidfile "$(cat "$HOME/owner")/container.id" sha256:synthetic-image)" "isolated run arguments" +} + +cleans_up_after_successful_exec() { + fake_docker + + result=$(runner_code) + + # Successful execution removes only its container and temporary build/CID files. + eq "$result" 0 "exit status" + eq "$(cat "$HOME/docker.exec")" "$(printf '%s\n' synthetic-container sh /opt/soze/tests/systemd/inside.sh)" "exec arguments" + eq "$(cat "$HOME/docker.rm")" "$(printf '%s\n' --force synthetic-container)" "removed container" + eq "$(cat "$HOME/timeouts")" "$(printf '%s\n' 300 30 120 30)" "command bounds" + [ ! -e "$HOME/container" ] + [ -z "$(ls -A "$HOME/work")" ] +} + +cleans_up_after_failed_exec() { + fake_docker + touch "$HOME/exec.fail" + + result=$(runner_code) + + # Cleanup does not replace the command's failing exit status. + eq "$result" 37 "exit status" + [ -e "$HOME/docker.rm" ] + [ ! -e "$HOME/container" ] + [ -z "$(ls -A "$HOME/work")" ] +} + +cleans_up_when_creation_fails_before_delivering_the_cid() { + fake_docker + touch "$HOME/run.fail" + + result=$(runner_code) + + # The ownership-checked name fallback removes the created container by ID. + eq "$result" 41 "exit status" + eq "$(cat "$HOME/docker.inspect")" "$(printf '%s\n' --format '{{.Id}} {{index .Config.Labels "com.killallgit.soze.systemd-test"}}' "$(cat "$HOME/name.used")")" "ownership inspection" + eq "$(cat "$HOME/docker.rm")" "$(printf '%s\n' --force synthetic-container)" "removed container" + [ ! -e "$HOME/docker.exec" ] + [ ! -e "$HOME/container" ] + [ -z "$(ls -A "$HOME/work")" ] +} + +cleans_up_when_interrupted_before_delivering_the_cid() { + fake_docker + touch "$HOME/run.interrupt" + + result=$(runner_code) + + # Termination uses the same ownership-checked fallback and preserves the signal status. + eq "$result" 143 "exit status" + eq "$(cat "$HOME/docker.rm")" "$(printf '%s\n' --force synthetic-container)" "removed container" + [ ! -e "$HOME/container" ] +} + +failed_build_never_attempts_container_cleanup() { + fake_docker + touch "$HOME/build.fail" + echo foreign-container > "$HOME/container" + + result=$(runner_code) + + # A failed build cannot authorize inspecting or deleting an unrelated container. + eq "$result" 23 "exit status" + [ ! -e "$HOME/docker.run" ] + [ ! -e "$HOME/docker.inspect" ] + [ ! -e "$HOME/docker.rm" ] + eq "$(cat "$HOME/container")" foreign-container "untouched container" + [ -z "$(ls -A "$HOME/work")" ] +} + +name_collision_never_deletes_the_existing_container() { + fake_docker + touch "$HOME/name.collision" + + result=$(runner_code) + + # A matching name without this invocation's ownership label is not ours to remove. + eq "$result" 125 "exit status" + [ ! -e "$HOME/docker.rm" ] + eq "$(cat "$HOME/container")" foreign-container "untouched container" + [ -z "$(ls -A "$HOME/work")" ] +} + +cleanup_failure_preserves_an_existing_failure() { + fake_docker + touch "$HOME/exec.fail" "$HOME/remove.fail" + + result=$(runner_code) + + # A cleanup failure must not hide the original failing command's exit status. + eq "$result" 37 "exit status" + [ -e "$HOME/docker.rm" ] +} + +cleanup_failure_fails_an_otherwise_successful_run() { + fake_docker + touch "$HOME/remove.fail" + + result=$(runner_code) + + # A leaked container makes an otherwise successful integration run fail. + eq "$result" 1 "exit status" + [ -e "$HOME/docker.rm" ] +} + +case_run launches_the_built_immutable_image_in_isolation launches_the_built_immutable_image_in_isolation +case_run cleans_up_after_successful_exec cleans_up_after_successful_exec +case_run cleans_up_after_failed_exec cleans_up_after_failed_exec +case_run cleans_up_when_creation_fails_before_delivering_the_cid cleans_up_when_creation_fails_before_delivering_the_cid +case_run cleans_up_when_interrupted_before_delivering_the_cid cleans_up_when_interrupted_before_delivering_the_cid +case_run failed_build_never_attempts_container_cleanup failed_build_never_attempts_container_cleanup +case_run name_collision_never_deletes_the_existing_container name_collision_never_deletes_the_existing_container +case_run cleanup_failure_preserves_an_existing_failure cleanup_failure_preserves_an_existing_failure +case_run cleanup_failure_fails_an_otherwise_successful_run cleanup_failure_fails_an_otherwise_successful_run +finish diff --git a/tests/systemd/Dockerfile b/tests/systemd/Dockerfile new file mode 100644 index 0000000..7d0ad8c --- /dev/null +++ b/tests/systemd/Dockerfile @@ -0,0 +1,25 @@ +FROM rust:1.99.0-bookworm@sha256:114c7a4425406451c2866b6aafe69fe29b1b298832db1277d411ac73c82d04d6 AS build +WORKDIR /build +COPY Cargo.toml Cargo.lock ./ +COPY src ./src +RUN cargo build --locked --bin soze + +FROM debian:12.12-slim@sha256:d5d3f9c23164ea16f31852f95bd5959aad1c5e854332fe00f7b3a20fcc9f635c +# Freeze OS dependencies too; this snapshot is over two weeks old. +RUN rm -f /etc/apt/sources.list.d/debian.sources \ + && printf '%s\n' \ + 'deb [check-valid-until=no] http://snapshot.debian.org/archive/debian/20261015T000000Z bookworm main' \ + 'deb [check-valid-until=no] http://snapshot.debian.org/archive/debian-security/20261015T000000Z bookworm-security main' \ + > /etc/apt/sources.list \ + && apt-get update \ + && DEBIAN_FRONTEND=noninteractive apt-get install --no-install-recommends -y \ + systemd systemd-sysv dbus-user-session procps python3 util-linux \ + && rm -rf /var/lib/apt/lists/* \ + && useradd --uid 1000 --create-home --shell /bin/sh sozetest + +COPY --from=build /build/target/debug/soze /opt/soze/soze +COPY scripts/service.sh /opt/soze/scripts/service.sh +COPY tests/systemd/inside.sh tests/systemd/test_service.py /opt/soze/tests/systemd/ +ENV container=docker +STOPSIGNAL SIGRTMIN+3 +CMD ["/sbin/init"] diff --git a/tests/systemd/Dockerfile.dockerignore b/tests/systemd/Dockerfile.dockerignore new file mode 100644 index 0000000..6bd92f5 --- /dev/null +++ b/tests/systemd/Dockerfile.dockerignore @@ -0,0 +1,11 @@ +** +!Cargo.toml +!Cargo.lock +!src/ +!src/** +!scripts/ +!scripts/service.sh +!tests/ +!tests/systemd/ +!tests/systemd/inside.sh +!tests/systemd/test_service.py diff --git a/tests/systemd/inside.sh b/tests/systemd/inside.sh new file mode 100644 index 0000000..28dd93d --- /dev/null +++ b/tests/systemd/inside.sh @@ -0,0 +1,11 @@ +#!/bin/sh +set -eu + +# Some hardware-oriented units may be unavailable in a container; a settled degraded boot is OK. +state=$(timeout 30 systemctl is-system-running --wait) || [ "$state" = degraded ] +systemctl start user@1000.service +exec runuser -u sozetest -- env \ + HOME=/home/sozetest \ + XDG_RUNTIME_DIR=/run/user/1000 \ + DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus \ + python3 /opt/soze/tests/systemd/test_service.py diff --git a/tests/systemd/run.sh b/tests/systemd/run.sh new file mode 100644 index 0000000..56b0873 --- /dev/null +++ b/tests/systemd/run.sh @@ -0,0 +1,45 @@ +#!/bin/sh +# Boots real systemd on the selected Docker daemon; never a production deployment. +set -eu +root=$(cd "$(dirname "$0")/../.." && pwd) +work=$(mktemp -d) +name="kaiser-soze-systemd-${work##*/}" +container_started=false + +cleanup() { + code=$? + trap - EXIT + container_id= + if [ -s "$work/container.id" ]; then + container_id=$(cat "$work/container.id") + elif [ "$container_started" = true ]; then + # Creation may succeed before Docker delivers the CID; a name alone is not proof of ownership. + container=$(timeout 30 docker inspect --format \ + '{{.Id}} {{index .Config.Labels "com.killallgit.soze.systemd-test"}}' "$name" 2>/dev/null) || container= + case "$container" in + *" $work") container_id=${container%" $work"} ;; + esac + fi + if [ -n "$container_id" ]; then + timeout 30 docker rm --force "$container_id" > /dev/null || { + [ "$code" -ne 0 ] || code=1 + } + fi + rm -f "$work/container.id" "$work/image.id" + rmdir "$work" + exit "$code" +} +trap cleanup EXIT +trap 'exit 130' INT +trap 'exit 143' TERM HUP + +printf 'Systemd integration tests use Docker context: %s\n' "$(docker context show)" +timeout 300 docker build --file "$root/tests/systemd/Dockerfile" --iidfile "$work/image.id" "$root" +image=$(cat "$work/image.id") +# No host paths, sockets or ports are shared. Privilege is for systemd's private cgroup hierarchy. +container_started=true +timeout 30 docker run --detach --privileged --cgroupns=private --network=none \ + --tmpfs /run --tmpfs /run/lock --tmpfs /tmp \ + --name "$name" --label "com.killallgit.soze.systemd-test=$work" \ + --cidfile "$work/container.id" "$image" > /dev/null +timeout 120 docker exec "$(cat "$work/container.id")" sh /opt/soze/tests/systemd/inside.sh diff --git a/tests/systemd/test_service.py b/tests/systemd/test_service.py new file mode 100644 index 0000000..b25cd3d --- /dev/null +++ b/tests/systemd/test_service.py @@ -0,0 +1,336 @@ +#!/usr/bin/env python3 +"""Real user-service integration tests; run only inside the disposable systemd image.""" + +import concurrent.futures +import hashlib +import http.client +import json +import os +from pathlib import Path +import selectors +import shlex +import socket +import subprocess +import tempfile +import time +import unittest + + +ROOT = Path("/opt/soze") +DATA = Path.home() / ".local/share/soze" +CONFIG = Path.home() / ".config/soze/config.toml" +UNIT = Path.home() / ".config/systemd/user/soze.service" +BINARY = ROOT / "soze" + + +class UserService(unittest.TestCase): + def setUp(self): + self.assertNotEqual(os.getuid(), 0) + self.assertEqual(Path("/proc/1/comm").read_text().strip(), "systemd") + self.run_command("systemctl", "--user", "reset-failed") + CONFIG.parent.mkdir(parents=True, exist_ok=True) + CONFIG.write_text('log_format = "json"\nlog_level = "info"\nlive = false\n') + self.addCleanup(self.service, "uninstall", "--purge") + + def run_command(self, *args): + result = subprocess.run(args, capture_output=True, timeout=20, check=False) + self.assertEqual(result.returncode, 0, f"command failed: {args[0]}") + return result.stdout.decode() + + def service(self, *args): + return self.run_command("sh", str(ROOT / "scripts/service.sh"), *args) + + def property(self, name): + return self.run_command( + "systemctl", "--user", "show", "soze.service", f"--property={name}", "--value" + ).strip() + + def until(self, predicate): + deadline = time.monotonic() + 15 + while time.monotonic() < deadline: + if predicate(): + return + time.sleep(0.1) + self.fail("service condition did not settle within 15 seconds") + + def listening(self): + with socket.socket() as connection: + connection.settimeout(0.2) + return connection.connect_ex(("127.0.0.1", 48731)) == 0 + + def install(self): + self.service("install", str(BINARY)) + self.until(self.listening) + + def events(self): + path = DATA / "debug.jsonl" + if not path.exists(): + return [] + # The writer may still be appending the last metadata record. + return [json.loads(line)["event"] for line in path.read_bytes().splitlines(keepends=True) if line.endswith(b"\n")] + + def relay(self): + payload = b"synthetic-systemd-probe" + with socket.socket() as upstream, concurrent.futures.ThreadPoolExecutor() as executor: + upstream.bind(("127.0.0.1", 0)) + upstream.listen(1) + upstream.settimeout(5) + + def echo(): + connection, _ = upstream.accept() + with connection: + connection.settimeout(5) + received = connection.makefile("rb").read(len(payload)) + connection.sendall(received) + + response = executor.submit(echo) + client = http.client.HTTPConnection("127.0.0.1", 48731, timeout=5) + client.set_tunnel("127.0.0.1", upstream.getsockname()[1]) + try: + client.connect() + client.sock.sendall(payload) + received = client.sock.makefile("rb").read(len(payload)) + self.assertTrue(received == payload, "tunnel changed the synthetic bytes") + finally: + client.close() + response.result(timeout=5) + self.until(lambda: (DATA / "tap.jsonl").stat().st_size > 0) + + def test_install_enables_a_real_non_root_service(self): + CONFIG.unlink() + + self.install() + + # Real systemd loads the unit, starts it as the test user and enables login startup. + self.assertEqual(self.property("ActiveState"), "active") + self.assertEqual(self.run_command("systemctl", "--user", "is-enabled", "soze.service").strip(), "enabled") + self.run_command("systemd-analyze", "--user", "verify", str(UNIT)) + pid = int(self.property("MainPID")) + uid = next(line.split()[1] for line in Path(f"/proc/{pid}/status").read_text().splitlines() if line.startswith("Uid:")) + self.assertEqual(int(uid), os.getuid()) + self.assertEqual(Path(f"/proc/{pid}/exe").resolve(), DATA / "bin/soze") + self.assertEqual(CONFIG.read_text(), 'log_format = "human"\nlive = true\n') + self.assertEqual((DATA / "logs/soze.log").stat().st_mode & 0o777, 0o600) + self.assertEqual((DATA / "tap.jsonl").stat().st_mode & 0o777, 0o600) + self.assertFalse((Path.home() / ".claude").exists()) + self.assertFalse((Path.home() / ".codex").exists()) + self.assertFalse((Path.home() / ".cursor").exists()) + + def test_status_reports_the_real_pid_and_installation(self): + self.install() + + status = dict(line.split("=", 1) for line in self.service("status").splitlines()) + + # The public status command agrees with the manager, including installation metadata. + self.assertEqual(status["state"], "running") + self.assertEqual(status["pid"], self.property("MainPID")) + self.assertEqual(status["source"], "local") + self.assertIn("installed_at", status) + + def test_proxy_relays_synthetic_traffic_under_systemd(self): + self.install() + + self.relay() + + # Running under systemd still forwards bytes and creates capture output. + self.assertGreater((DATA / "tap.jsonl").stat().st_size, 0) + self.assertGreater((DATA / "logs/soze.log").stat().st_size, 0) + + def test_reload_applies_logging_without_restarting(self): + self.install() + pid = self.property("MainPID") + CONFIG.write_text('log_format = "json"\nlog_level = "debug"\nlive = false\n') + + self.service("reload") + self.until(lambda: "config_reloaded" in self.events()) + + # ExecReload delivers SIGHUP to the same running process. + self.assertEqual(self.property("MainPID"), pid) + self.assertTrue(self.listening()) + + def test_logs_follow_operational_metadata(self): + self.install() + follower = subprocess.Popen( + ["sh", str(ROOT / "scripts/service.sh"), "logs"], + stdout=subprocess.PIPE, + stderr=subprocess.DEVNULL, + ) + try: + with selectors.DefaultSelector() as ready: + ready.register(follower.stdout, selectors.EVENT_READ) + self.assertTrue(ready.select(timeout=5), "no operational metadata arrived") + record = json.loads(follower.stdout.readline()) + finally: + follower.terminate() + follower.wait(timeout=5) + follower.stdout.close() + + # The real logs command follows structured operational output, not captured content. + self.assertIn(record["event"], self.events()) + + def test_restart_replaces_the_process(self): + self.install() + pid = self.property("MainPID") + + self.service("restart") + self.until(self.listening) + + # Explicit restart returns a new live process. + self.assertNotEqual(self.property("MainPID"), pid) + self.assertEqual(self.property("ActiveState"), "active") + + def test_systemd_recovers_after_a_crash(self): + self.install() + pid = self.property("MainPID") + + self.run_command("systemctl", "--user", "kill", "--kill-whom=main", "--signal=KILL", "soze.service") + self.until(lambda: self.property("MainPID") not in ("0", pid) and self.listening()) + + # Restart=on-failure recovers a killed proxy without the installer intervening. + self.assertEqual(self.property("ActiveState"), "active") + self.assertGreaterEqual(int(self.property("NRestarts")), 1) + + def test_update_preserves_config_and_rotates_existing_capture(self): + self.install() + self.relay() + self.run_command("systemctl", "--user", "stop", "soze.service") + config_before = CONFIG.read_bytes() + capture_before = hashlib.sha256((DATA / "tap.jsonl").read_bytes()).digest() + inode_before = (DATA / "bin/soze").stat().st_ino + + self.install() + + # Update replaces the binary inode and retains the old capture in a closed segment. + self.assertEqual(CONFIG.read_bytes(), config_before) + self.assertNotEqual((DATA / "bin/soze").stat().st_ino, inode_before) + self.assertTrue(any(hashlib.sha256(path.read_bytes()).digest() == capture_before for path in DATA.glob("tap.*.jsonl"))) + self.assertTrue((DATA / "logs/soze.log.1").is_file()) + + def test_caller_only_config_override_leaves_the_running_installation_untouched(self): + self.install() + self.relay() + pid = self.property("MainPID") + paths = [UNIT, *CONFIG.parent.rglob("*"), *DATA.rglob("*")] + before = { + path: (path.stat().st_ino, hashlib.sha256(path.read_bytes()).digest()) + for path in paths if path.is_file() + } + with tempfile.TemporaryDirectory(prefix="soze caller config ") as directory: + override = Path(directory) / "config" + environment = dict(os.environ, XDG_CONFIG_HOME=str(override)) + + result = subprocess.run( + ["sh", str(ROOT / "scripts/service.sh"), "install", str(BINARY)], + env=environment, capture_output=True, timeout=20, check=False, + ) + + # Rejection cannot replace service/config/data files, rotate logs, or restart the PID. + self.assertEqual(result.returncode, 2) + self.assertFalse(override.exists()) + after_paths = [UNIT, *CONFIG.parent.rglob("*"), *DATA.rglob("*")] + after = { + path: (path.stat().st_ino, hashlib.sha256(path.read_bytes()).digest()) + for path in after_paths if path.is_file() + } + self.assertTrue(before == after, "installed file identities and digests changed") + self.assertEqual(self.property("MainPID"), pid) + self.assertEqual(self.property("ActiveState"), "active") + self.assertTrue(self.listening()) + + def test_a_searched_but_shadowed_directory_cannot_update_the_loaded_installation(self): + self.install() + self.relay() + lower_config = Path.home() / ".local/share" + lower_unit = lower_config / "systemd/user/soze.service" + search_paths = shlex.split(self.run_command( + "systemctl", "--user", "show", "--property=UnitPath", "--value" + )) + self.assertIn(str(lower_unit.parent), search_paths) + self.assertLess(search_paths.index(str(UNIT.parent)), search_paths.index(str(lower_unit.parent))) + self.assertFalse(lower_unit.exists()) + pid = self.property("MainPID") + fragment = self.property("FragmentPath") + paths = [UNIT, *CONFIG.parent.rglob("*"), *DATA.rglob("*")] + before = { + path: (path.stat().st_ino, hashlib.sha256(path.read_bytes()).digest()) + for path in paths if path.is_file() + } + + result = subprocess.run( + ["sh", str(ROOT / "scripts/service.sh"), "install", str(BINARY)], + env=dict(os.environ, XDG_CONFIG_HOME=str(lower_config)), + capture_output=True, timeout=20, check=False, + ) + + # A lower-priority searched directory cannot replace shared files or restart the loaded unit. + self.assertEqual(result.returncode, 2) + self.assertFalse(lower_unit.exists()) + after_paths = [UNIT, *CONFIG.parent.rglob("*"), *DATA.rglob("*")] + after = { + path: (path.stat().st_ino, hashlib.sha256(path.read_bytes()).digest()) + for path in after_paths if path.is_file() + } + self.assertTrue(before == after, "installed file identities and digests changed") + self.assertEqual(self.property("MainPID"), pid) + self.assertEqual(self.property("FragmentPath"), fragment) + self.assertEqual(self.property("ActiveState"), "active") + self.assertEqual(self.run_command("systemctl", "--user", "is-enabled", "soze.service").strip(), "enabled") + + def test_uninstall_preserves_data_and_purge_removes_only_data(self): + self.install() + self.relay() + self.run_command("systemctl", "--user", "stop", "soze.service") + capture_before = hashlib.sha256((DATA / "tap.jsonl").read_bytes()).digest() + + self.service("uninstall") + + # Uninstall removes supervision and executable files, not captured data or CA/config. + self.assertEqual(self.property("LoadState"), "not-found") + self.assertEqual(self.service("status"), "state=not loaded\npid=\n") + self.assertFalse(UNIT.exists()) + self.assertFalse((DATA / "bin").exists()) + self.assertEqual(hashlib.sha256((DATA / "tap.jsonl").read_bytes()).digest(), capture_before) + self.assertTrue(CONFIG.exists()) + self.assertTrue((CONFIG.parent / "ca.pem").exists()) + self.service("uninstall", "--purge") + self.assertFalse(DATA.exists()) + self.assertTrue(CONFIG.exists()) + self.assertTrue((CONFIG.parent / "ca.pem").exists()) + + def test_caller_only_override_cannot_uninstall_or_purge_the_running_service(self): + self.install() + self.relay() + pid = self.property("MainPID") + fragment = self.property("FragmentPath") + paths = [UNIT, *CONFIG.parent.rglob("*"), *DATA.rglob("*")] + before = { + path: (path.stat().st_ino, hashlib.sha256(path.read_bytes()).digest()) + for path in paths if path.is_file() + } + with tempfile.TemporaryDirectory(prefix="soze caller config ") as directory: + override = Path(directory) / "config" + environment = dict(os.environ, XDG_CONFIG_HOME=str(override)) + for arguments in (("uninstall",), ("uninstall", "--purge")): + with self.subTest(arguments=arguments): + result = subprocess.run( + ["sh", str(ROOT / "scripts/service.sh"), *arguments], + env=environment, capture_output=True, timeout=20, check=False, + ) + + # A wrong caller path cannot stop, disable, remove, purge, or alter the service. + self.assertEqual(result.returncode, 2) + self.assertFalse(override.exists()) + after_paths = [UNIT, *CONFIG.parent.rglob("*"), *DATA.rglob("*")] + after = { + path: (path.stat().st_ino, hashlib.sha256(path.read_bytes()).digest()) + for path in after_paths if path.is_file() + } + self.assertTrue(before == after, "installed file identities and digests changed") + self.assertEqual(self.property("MainPID"), pid) + self.assertEqual(self.property("FragmentPath"), fragment) + self.assertEqual(self.property("ActiveState"), "active") + self.assertEqual(self.run_command("systemctl", "--user", "is-enabled", "soze.service").strip(), "enabled") + + +if __name__ == "__main__": + unittest.main(verbosity=2)