From 8e630a826d1af673b9b6ad42eefb2100929c77c7 Mon Sep 17 00:00:00 2001 From: Hugo Costa Date: Mon, 14 Sep 2026 16:00:15 +0000 Subject: [PATCH] feat(service): prefer systemd user units --- README.md | 8 +- docs/guides/install.md | 96 +++-- docs/guides/remote-and-mobile.md | 114 +----- docs/system-specs/modules/cli.md | 55 +-- docs/system-specs/modules/security.md | 2 +- .../builtin_skills/kirocrew-commands/SKILL.md | 2 +- src/kiro_crew/cli.py | 10 +- src/kiro_crew/cli_help.py | 14 +- src/kiro_crew/cli_server.py | 38 +- src/kiro_crew/docs/getting-started.md | 7 +- src/kiro_crew/service/__init__.py | 10 +- src/kiro_crew/service/common.py | 19 +- src/kiro_crew/service/controller.py | 29 +- src/kiro_crew/service/linux.py | 333 ++++++++---------- src/kiro_crew/service/live_target.py | 4 +- src/kiro_crew/service/selinux.py | 5 +- test/test_cli_server_more_coverage.py | 23 ++ test/test_service.py | 144 ++++++-- test/test_service_selinux.py | 189 ++-------- 19 files changed, 474 insertions(+), 628 deletions(-) diff --git a/README.md b/README.md index 2df63305508a..7a1d3fbdff39 100644 --- a/README.md +++ b/README.md @@ -469,11 +469,9 @@ unit: KIROCREW_PORT=5477 kirocrew service install ``` -To change it later without reinstalling, edit `/etc/kirocrew/kirocrew.env` -(created by `service install`) and run `sudo systemctl restart kirocrew`. Units -installed by releases before v0.2.0 lack the `EnvironmentFile=` directive that -reads this file — re-run `kirocrew service install` or use a systemd drop-in; -see [the install guide](docs/guides/install.md#setting-the-service-port). +For a default user unit, re-run the install command with the new value. The +system-scope fallback also supports `/etc/kirocrew/kirocrew.env`; see +[the install guide](docs/guides/install.md#setting-the-service-port). The desktop app can use this local Gateway or connect to a remote one. For an always-on VPS, home server, or cloud VM in your account, follow the diff --git a/docs/guides/install.md b/docs/guides/install.md index 1f7970ebcbd5..25597b9c6773 100644 --- a/docs/guides/install.md +++ b/docs/guides/install.md @@ -645,18 +645,18 @@ kirocrew service status kirocrew service uninstall ``` -On Linux this writes `/etc/systemd/system/kirocrew.service` (sudo is prompted -for the unit file and the `systemctl` calls; the gateway itself runs as your own -user, never under sudo). When you are already root — a minimal container or -`root` login — no `sudo` binary is required. On macOS it writes a launchd plist -and needs no sudo. +On Linux, a fresh install first tries the invoking account's user manager. When +`systemctl --user` is usable it writes +`~/.config/systemd/user/kirocrew.service` and manages it without sudo. If that +manager is unavailable, it falls back to the system unit at +`/etc/systemd/system/kirocrew.service`. An existing unit keeps its current scope +when the command is re-run. On macOS the command writes a launchd plist. The gateway runs untrusted agent tools, so it must run as a **non-root** user: -the installer sets `User=` to the account behind `sudo` (`$SUDO_USER`, else -`$USER`), and **refuses to install a `User=root` service**. From a bare `root` -login (or `sudo` with no `$SUDO_USER`), first create or pick a normal account and -install as it, e.g. `sudo -u KIROCREW_KIRO_BIN=... kirocrew service -install` (the official Docker image already runs as the `kirocrew` user). +run `kirocrew service install` from that user's login session, without sudo. A +bare-root install is refused. User units start with the user's systemd manager; +to keep one running after logout and start it before the first login, an +administrator can enable lingering with `loginctl enable-linger `. ### SELinux-enforcing hosts with kirocrew under `$HOME` @@ -670,33 +670,24 @@ exhausts its restart limit. The binary is fine. `test -x` on it succeeds, the shebang is correct, and the permissions are right — the policy's execute check is the only thing that fails, which is why `203/EXEC` here looks identical to a genuinely missing or -non-executable path. `kirocrew service install` therefore asks the loaded policy -before writing anything, and if the unit provably cannot start it **refuses up -front** and prints a ready-to-paste per-user unit instead of leaving a -crash-looping service enabled at every boot. - -A per-user unit is not affected, because the per-user systemd manager does not -run in PID 1's domain. Follow the commands the refusal prints, then manage the -service with `systemctl --user status|restart kirocrew` and `journalctl --user -u -kirocrew -f`. Note that `kirocrew service status` / `uninstall` only look at the -system unit, so they will not see a user unit ([#7165] tracks adding a first-class -`--user` scope). Installing kirocrew onto a system-labelled path such as -`/usr/local/bin` also avoids the problem. - -[#7165]: https://github.com/kirodotdev/KiroCrew/issues/7165 +non-executable path. The default per-user unit is not affected because its +manager does not run in PID 1's domain. If no user manager is available and the +installer must fall back to system scope, it checks the loaded policy and +refuses before writing a unit that cannot start. Installing kirocrew onto a +system-labelled path such as `/usr/local/bin` also avoids the system-scope +restriction. ### Setting the service port -A system service inherits none of your shell environment, so `export -KIROCREW_PORT=…` in your shell does **not** reach it. Set the port when you -install so it is baked into the unit: +The service captures its environment when installed. Set the port on the +install command: ```bash KIROCREW_PORT=5477 kirocrew service install ``` -To change it later without reinstalling, edit the overrides file the installer -creates and restart: +For a user unit, re-run that command with the new value. The system-scope +fallback also creates an overrides file that can be edited without reinstalling: ```bash sudo sed -i 's/^#\?KIROCREW_PORT=.*/KIROCREW_PORT=5477/' /etc/kirocrew/kirocrew.env @@ -710,9 +701,9 @@ example by a local crew you also run on this host — there is one `kirocrew.service` unit, so re-running `service install` updates it in place rather than creating a second service). -**The `EnvironmentFile=` directive only exists in units written by v0.2.0 or -later.** Upgrading the package never rewrites an already-installed unit, so a -unit installed by an older release (v0.1.3 and earlier) silently ignores +**For system-scope installs, the `EnvironmentFile=` directive only exists in +units written by v0.2.0 or later.** Upgrading the package never rewrites an +already-installed unit, so a system unit installed by an older release silently ignores `/etc/kirocrew/kirocrew.env` — editing it changes nothing. Check which kind you have: @@ -727,12 +718,16 @@ which works on any unit version. ### Setting other environment variables (systemd drop-in) -For variables the seeded overrides file does not cover — proxy settings are the -common case — use a systemd drop-in. Drop-ins are systemd's own override -mechanism: they apply to the unit no matter which release wrote it, and they -survive reinstalls, `service install` re-runs, and even -`kirocrew service uninstall` (which removes the unit but never touches -`/etc/systemd/system/kirocrew.service.d/`). +For variables the seeded system-scope file does not cover — proxy settings are +the common case — use a systemd drop-in. For the default user unit: + +```bash +systemctl --user edit kirocrew +# Add a [Service] section with Environment= lines, then save. +systemctl --user restart kirocrew +``` + +For the system-scope fallback: ```bash sudo mkdir -p /etc/systemd/system/kirocrew.service.d @@ -746,10 +741,9 @@ sudo systemctl daemon-reload sudo systemctl restart kirocrew ``` -A new or edited drop-in is not picked up until `systemctl daemon-reload` runs — -restarting alone is not enough. Verify what the unit resolved to with -`systemctl cat kirocrew` (drop-ins are printed below the unit) or -`systemctl show kirocrew --property=Environment`. +A new or edited system-scope drop-in is not picked up until `systemctl +daemon-reload` runs — restarting alone is not enough. Inspect a user unit with +`systemctl --user cat kirocrew`, or a system unit with `systemctl cat kirocrew`. For remote hosts, see [remote-and-mobile.md](remote-and-mobile.md). @@ -788,11 +782,11 @@ gateway's sandbox probe (#3463) — the directive labels only the unit's own top-level process, and the probe runs in a child reached through a fork the directive's labelling never reaches. The directive is no longer used. -This uses the sudo prompt `service install` already needs for the unit file, so -it costs no additional privilege, and it **cannot fail your install**: if the -profile cannot be written, loaded, or verified, you get a warning and the -install continues. `kirocrew service uninstall` unloads and removes it, so a -host is left as it was found rather than carrying an orphaned userns permission. +Writing and loading this optional profile may prompt for sudo even when the unit +itself uses `systemctl --user`. It **cannot fail your install**: if the profile +cannot be written, loaded, or verified, you get a warning and the install +continues. `kirocrew service uninstall` unloads and removes it, so a host is +left as it was found rather than carrying an orphaned userns permission. The installer skips the profile silently, with a reason it can print, when AppArmor is not an active LSM, when the sysctl is not `1`, when @@ -809,8 +803,8 @@ launcher script runs confined too. A launch that does **not** go through that path — `python -m kiro_crew`, a different venv's entry point, a re-created venv the profile has not been re-pointed at — stays unconfined, and `kirocrew doctor` reports the attachment as stale in the re-created-venv case. Prefer running the -gateway as the service: it pins `ExecStart` to the attached path and restarts on -boot. +gateway as the service: it pins `ExecStart` to the attached path and restarts +after failure. ### The AppImage (desktop app) needs its own profile @@ -957,11 +951,11 @@ The `kiro-cli` backend did not answer in time. Five common causes: recover the slot. 5. **The host needs a proxy and the service does not have one.** On a corporate network, `kiro-cli` must reach its backend through your proxy. A - systemd service inherits none of your shell's `HTTPS_PROXY`/`HTTP_PROXY` + service does not reliably inherit your shell's `HTTPS_PROXY`/`HTTP_PROXY` exports, so a gateway that works when run from your terminal can still time out as a service. Set the proxy variables on the unit with a [systemd drop-in](#setting-other-environment-variables-systemd-drop-in), - then `sudo systemctl daemon-reload && sudo systemctl restart kirocrew`. + then restart it with `kirocrew restart`. Agent sessions inherit the service environment, so this fixes them. One known gap: the first-run setup gate's login probe currently filters proxy variables out even when the unit carries them, so it can stay stuck on diff --git a/docs/guides/remote-and-mobile.md b/docs/guides/remote-and-mobile.md index f7d93c680dfb..c581eb7e8042 100644 --- a/docs/guides/remote-and-mobile.md +++ b/docs/guides/remote-and-mobile.md @@ -761,10 +761,11 @@ open "$URL" kirocrew service install ``` -On Linux this writes a **system-level** systemd unit at -`/etc/systemd/system/kirocrew.service` and enables it, so the gateway survives -SSH disconnects, restarts on failure, and starts on boot -(`WantedBy=multi-user.target`). On macOS it writes a launchd LaunchAgent at +On Linux this prefers a per-user systemd unit at +`~/.config/systemd/user/kirocrew.service`, falling back to +`/etc/systemd/system/kirocrew.service` when the user manager is unavailable. +Enable lingering if the user unit must survive logout or run before login. On +macOS it writes a launchd LaunchAgent at `~/Library/LaunchAgents/dev.kirocrew.gateway.plist` with `RunAtLoad`, `KeepAlive=true`, and a finite `ExitTimeOut`, so it starts at login, relaunches after exit, and force-kills only after the graceful stop deadline. An explicit @@ -778,106 +779,11 @@ kirocrew restart # restart (service-aware) kirocrew service uninstall # remove the unit / plist ``` -**Sudo scope on Linux:** the install shells out to `sudo install` (to place the -unit as root-owned `0644`) and `sudo systemctl` (daemon-reload, enable, -restart). No kirocrew, MCP, or LLM code path runs under sudo. Once started the -gateway runs as `User=$USER Group=$(id -gn)`, not root. The unit also caps -crash-looping with `StartLimitBurst=3` / `StartLimitIntervalSec=300` and pins -`LimitNOFILE=65536`, because a stock 1024 FD limit fails the frontend -production build with `EMFILE`. - -**Why system-level rather than `systemctl --user`:** older distros (systemd 219 -era) have no working per-user manager, and `systemctl --user` there fails with -`Failed to get D-Bus connection`. A system unit behaves the same on every -systemd since 2015. - -### Hosts without a working `systemd --user` - -If you specifically want a **user** unit and `systemctl --user status` errors -out, the per-user manager is not running. Enable it once (needs sudo), then -install the user unit: - -```bash -sudo tee /etc/systemd/system/user@$(id -u).service << 'EOF' -[Unit] -Description=User Manager for UID %i -After=systemd-user-sessions.service -After=user-runtime-dir@%i.service -Wants=user-runtime-dir@%i.service - -[Service] -LimitNOFILE=infinity -LimitNPROC=infinity -User=%i -PAMName=systemd-user -Type=notify -PermissionsStartOnly=true -ExecStartPre=/bin/loginctl enable-linger %i -ExecStart=/usr/lib/systemd/systemd --user -Slice=user-%i.slice -KillMode=mixed -Delegate=yes -TasksMax=infinity -Restart=always -RestartSec=15 - -[Install] -WantedBy=default.target -EOF - -sudo systemctl daemon-reload -sudo systemctl enable user@$(id -u).service -sudo systemctl start user@$(id -u).service -``` - -`ExecStartPre=/bin/loginctl enable-linger` is the load-bearing line: without -lingering, the user manager (and everything under it) is torn down when your -last login session ends, which defeats the entire point of running 24/7. - -Verify with `systemctl --user status`, then install the user unit with the helper -script [`assets/setup.sh`](assets/setup.sh). It resolves the `kirocrew` binary -and the Node version, renders [`assets/kirocrew.service`](assets/kirocrew.service) -into `~/.config/systemd/user/`, and enables it. It reads the template from its -own directory, so run it from there, and it refuses to proceed if a gateway is -already running (that port conflict again): - -```bash -cd docs/guides/assets && ./setup.sh -``` - -Either way, read the rendered `Environment=PATH=` line before you start the -service and drop any entry that does not exist on your host, then add whatever -does: the unit gets exactly this `PATH` and nothing from your shell profile. - -Or do it by hand: - -```bash -mkdir -p ~/.config/systemd/user -cp docs/guides/assets/kirocrew.service ~/.config/systemd/user/ -sed -i "s|KIROCREW_BIN|$(command -v kirocrew)|g" ~/.config/systemd/user/kirocrew.service -sed -i "s/%u/$(whoami)/g" ~/.config/systemd/user/kirocrew.service -sed -i "s/NVM_NODE_VERSION/$(node --version)/g" ~/.config/systemd/user/kirocrew.service -systemctl --user daemon-reload -systemctl --user enable kirocrew -systemctl --user start kirocrew -``` - -`systemctl --user status kirocrew` should report `active (running)`. - -> **`Failed to get D-Bus connection` while running `systemctl --user`?** Your -> shell has no `XDG_RUNTIME_DIR`, which is how the client finds the per-user bus -> socket. This is normal in a non-login shell, in a `cron` job, and inside an -> agent-spawned subprocess. Export it and retry: -> `export XDG_RUNTIME_DIR=/run/user/$(id -u)`. - -Manage a user unit: - -| Action | Command | -|---|---| -| Status | `systemctl --user status kirocrew` | -| Restart | `systemctl --user restart kirocrew` | -| Logs | `journalctl --user -u kirocrew -f` | -| Uninstall | `systemctl --user disable --now kirocrew` | +**Linux scope:** user installs run `systemctl --user` without sudo. The system +fallback retains the root-owned unit and sudo-backed `systemctl` calls. The unit +also caps crash-looping with `StartLimitBurst=3` / +`StartLimitIntervalSec=300` and pins `LimitNOFILE=65536`, because a stock 1024 +FD limit fails the frontend production build with `EMFILE`. ### Hand-rolled system unit diff --git a/docs/system-specs/modules/cli.md b/docs/system-specs/modules/cli.md index 153ec6c2fc7d..f68fc71a2094 100644 --- a/docs/system-specs/modules/cli.md +++ b/docs/system-specs/modules/cli.md @@ -151,8 +151,8 @@ choice blob makes the usage line unreadable. `gateway`, `service`, `doctor`. - Its notes answer the two questions the flat list never did: how `gateway` (foreground, dies with the terminal) differs from `service install` (systemd - unit / launchd agent, detached, restarts on crash, starts at boot, only one at - a time), and that the dashboard on loopback `5476` is the **only** port opened + unit / launchd agent, detached, restarts on crash, only one at a time), and + that the dashboard on loopback `5476` is the **only** port opened — messaging channels connect outbound. - `cli.py` sets `help=argparse.SUPPRESS` on the subparsers action to hide argparse's listing, passes `cli_help.TOP_USAGE` as the top-level `usage=` @@ -207,7 +207,7 @@ choice blob makes the usage line unreadable. | `kirocrew status` | Show runtime stats from running gateway | | `kirocrew stop` | Stop a running gateway (service-aware: stops the systemd/launchd service if active, otherwise terminates the gateway found by a cross-platform port lookup — lsof on POSIX, netstat on Windows). Pass `--port N` to bypass the service short-circuit and target a specific gateway. | | `kirocrew restart` | Restart a running gateway (service-aware: restarts the systemd/launchd service if active, otherwise terminates the foreground gateway and respawns it detached). Pass `--port N` to bypass the service short-circuit and target a specific gateway. | -| `kirocrew service install` | Install gateway as a system-level systemd service (Linux, requires sudo for `tee` + `systemctl` only) or launchd LaunchAgent (macOS, no sudo). Auto-restarts on crash, auto-starts on boot. | +| `kirocrew service install` | Install the gateway with systemd (Linux, preferring `systemctl --user` and falling back to a system unit) or launchd (macOS). Auto-restarts on crash. | | `kirocrew service uninstall` | Stop and remove the systemd unit / launchd plist. | | `kirocrew service status` | Show service status (`systemctl status` or `launchctl list`). No sudo required. | | `kirocrew logs` | Tail gateway logs from the systemd journal, launchd stdout file, or `~/.kiro/crew/gateway.log`. Hosts without systemd/launchd, including Windows, read the UTF-8 fallback file in Python without requiring `tail`. Read failures exit with file-access/retry guidance instead of an exception traceback. | @@ -1190,8 +1190,9 @@ that must not change, because the SPA's per-origin `localStorage` is keyed on it `stop`'s service-aware structure: 1. If a systemd/launchd service is active **and** the caller did not - pass `--port` explicitly, ask the platform to restart it. On Linux: - `sudo systemctl restart kirocrew.service` (single + pass `--port` explicitly, ask the platform to restart it. On Linux this is + `systemctl --user restart kirocrew.service` for a user unit or + `sudo systemctl restart kirocrew.service` for the system fallback (a single atomic operation, smaller down-window than stop+start, and the supervisor stays in charge of the lifecycle the whole time). On macOS: `launchctl unload ` + `launchctl load ` (no @@ -1241,19 +1242,19 @@ that must not change, because the SPA's per-origin `localStorage` is keyed on it ## Service Management `kirocrew service {install,uninstall,status}` registers the gateway -with the OS service manager so it survives SSH disconnects, restarts -on crash, and starts on boot. Implemented in `src/kiro_crew/service/`. +with the OS service manager so it runs detached and restarts on crash. +Implemented in `src/kiro_crew/service/`. - **Linux** (`current_platform() == SYSTEMD`): - - Unit file: `/etc/systemd/system/kirocrew.service` (root-owned). - - Install: `sudo install` writes the unit, then `sudo systemctl - daemon-reload && sudo systemctl enable --now kirocrew.service`. - Privilege is resolved per call: already-root (euid 0) skips `sudo` - entirely — required on minimal container / `root`-login images that - ship no `sudo` binary — and a non-root caller with no `sudo` fails - with a clear `ServiceInstallError` rather than an uncaught - `FileNotFoundError`. - - The gateway runs as `User=$USER Group=$(id -gn)`. Every elevated + - A fresh install probes `systemctl --user show-environment`. Success selects + `~/.config/systemd/user/kirocrew.service`; failure selects the existing + system path at `/etc/systemd/system/kirocrew.service`. Re-running install + preserves an existing unit's scope. + - User scope writes the unit directly and runs `systemctl --user + daemon-reload`, `enable`, and `restart`. The system fallback retains the + existing sudo-backed write and control path. + - A user unit runs as its manager's account. The system fallback sets + `User=$USER Group=$(id -gn)`. Every elevated executable is a stock system program, not a kirocrew one; the module docstring in `service/linux.py` sits next to the call sites, names the current set, and records what escalating the AppArmor step's @@ -1263,17 +1264,18 @@ on crash, and starts on boot. Implemented in `src/kiro_crew/service/`. into the unit's `Environment=` lines at install time (`service_environment()` in `service/common.py`) — this is how `KIROCREW_PORT=5477 kirocrew service install` binds a non-default port. - The unit also reads `EnvironmentFile=-/etc/kirocrew/kirocrew.env`, an + The system fallback also reads + `EnvironmentFile=-/etc/kirocrew/kirocrew.env`, an operator-editable file the installer seeds create-if-absent (a reinstall never clobbers edits). systemd applies the file AFTER — and overriding — the baked `Environment=` lines, so editing it and running `sudo systemctl restart kirocrew` changes a value (e.g. the port) without reinstalling. Uninstall removes the file and its `/etc/kirocrew` directory. - - **Credentials are deliberately NOT captured.** Both baked locations are - world-readable — the unit lives in root-owned `/etc/systemd/system` and the - override file is installed `0644` — so a model credential placed there - would be readable by every local user on the host. `service_environment()` - therefore carries no credential — its only installer-derived values are + - **Credentials are deliberately NOT captured.** Unit files are service + definitions, not credential stores; in the system fallback both the unit + and its `0644` override file are readable by every local user. + `service_environment()` therefore carries no credential — its only + installer-derived values are `PATH`, `KIROCREW_KIRO_BIN` and `KIROCREW_PORT` (it also returns `HOME`, `LANG` and `LC_ALL`) — and a test pins the absence so a future "just propagate it" change fails. @@ -1299,11 +1301,12 @@ on crash, and starts on boot. Implemented in `src/kiro_crew/service/`. lacks a credential; a fall-back login store, or a stopped unit beside a foreground `kirocrew gateway`, both leave the host healthy while the check fires. - - Boot survival via `WantedBy=multi-user.target` (no linger needed — - that's a user-service concept; this is system-level). + - User units use `WantedBy=default.target`; administrators can enable linger + when the service must persist after logout or start before login. The + system fallback uses `WantedBy=multi-user.target`. - Crash-loop safety: `StartLimitBurst=3 StartLimitIntervalSec=300`. - - Logs are read from the journal: `sudo journalctl -u kirocrew -f`, - or unprivileged if the user is in `systemd-journal` / `adm`. + - Logs use `journalctl --user` for user scope. System scope first tries an + unprivileged journal read, then sudo when a TTY is available. - **macOS** (`current_platform() == LAUNCHD`): - Plist: `~/Library/LaunchAgents/dev.kirocrew.gateway.plist` - Install: `launchctl load -w `. `RunAtLoad=true` and diff --git a/docs/system-specs/modules/security.md b/docs/system-specs/modules/security.md index d5089fd6e7d6..a39ba8997676 100644 --- a/docs/system-specs/modules/security.md +++ b/docs/system-specs/modules/security.md @@ -373,7 +373,7 @@ Wired into `AcpClient._spawn()` — all kiro-cli processes are sandboxed. Parent - **The abi is detected from the policy files present** (`/etc/apparmor.d/abi/`, highest numeric wins, omitted when none exist), not from the parser version: Ubuntu 25.10 ships `apparmor_parser` 5.x but only `abi/3.0` and `abi/4.0` on disk, so pinning the abi to the parser major makes the profile fail to load with `Could not open 'abi/5.0'`. - **Validate before loading, verify enforcement after.** The generated profile is parsed with `apparmor_parser -Q --skip-cache` (`--skip-cache` because writing `/var/cache/apparmor` needs root and this runs before any privileged step) and is NOT installed if it fails to compile — loading a broken profile is how a service becomes unstartable. After `apparmor_parser -r`, enforcement is confirmed by transitioning into the profile with `aa-exec -p` and running a namespace probe, because the installing process is not itself confined by a profile systemd applies to the service, so probing in-process would report the unpatched host. Three constraints shape that check. It needs **privilege to enter** the profile — `aa_change_onexec()` into a named profile is not permitted for an unconfined user and `aa-exec` does not fail loudly when it cannot transition, it execs unconfined, so an unprivileged attempt returns a false negative. It must **not execute anything user-writable as root**: every tool (`apparmor_parser`, `aa-exec`, `setpriv`, `python3`) is resolved from a fixed list of trusted system directories and required to be root-owned and not group/world-writable — never through `$PATH`, and never `sys.executable`, since the venv interpreter is user-writable and running it under `sudo` would be a local privilege escalation — and the payload is a constant stdlib snippet that does not import `kiro_crew`, so user-writable site-packages never runs with privilege. And the probe itself must run **unprivileged**, or it proves nothing: root may be permitted to create namespaces regardless of the restriction, so `setpriv` drops back to the invoking uid/gid inside the profile before probing. A missing trusted tool is reported as inconclusive rather than as a failure, and a profile that loads but does not take effect is worse than none, so an unconfirmed verification says exactly that instead of claiming success. - **The profile is loaded BEFORE the unit is started.** A path attachment applies at the kernel's own `execve()` time, so it must already be loaded before the first exec of the launcher script or the first gateway process (and everything it forks) comes up unprofiled. `linux.install()` therefore writes the unit, loads the profile, and only then runs `daemon-reload`/`enable`/`restart`. -- **Fail-soft throughout, and symmetric on removal.** No step here can fail the service install; every path returns an outcome the CLI prints (`⚠️` on failure) and continues. `service uninstall` unloads (`apparmor_parser -R`) and deletes the profile, so a host is left as it was found rather than carrying an orphaned grant. Privilege reuses the existing `sudo install` / `sudo systemctl` path the unit write already needs — no new escalation, and no KiroCrew or LLM-influenced code runs under sudo. +- **Fail-soft throughout, and symmetric on removal.** No step here can fail the service install; every path returns an outcome the CLI prints (`⚠️` on failure) and continues. `service uninstall` unloads (`apparmor_parser -R`) and deletes the profile, so a host is left as it was found rather than carrying an orphaned grant. Privilege reuses the service module's existing sudo helpers; user-unit control itself remains unprivileged, and no KiroCrew or LLM-influenced code runs under sudo. - **Verified end to end on Ubuntu 26.04** with the sysctl at 1: inside the profile `detect_backend()` returns `namespace`; outside it, on the same host at the same moment, `none` with `unshare(CLONE_NEWNS) failed with errno 1 (EPERM)`; and `apparmor_restrict_unprivileged_userns` remains `1` — the grant is app-scoped and the kernel-wide protection is untouched. - Other ways unprivileged userns can be denied are **not** addressed by this profile and have different remedies (and different errnos): `user.max_user_namespaces=0` denies NEWUSER with ENOSPC/EUSERS; Debian's legacy `kernel.unprivileged_userns_clone=0`; a kernel without `CONFIG_USER_NS` (EINVAL/ENOSYS); and a container whose seccomp filter denies `unshare`, which is fixed with container flags, not host config. The probe's step-aware reason is what makes these distinguishable at diagnosis time. - **A DIRECT launch (AppImage / desktop app) needs a SECOND, separately-named profile** — `/etc/apparmor.d/kirocrew-launcher`, installed by `kirocrew sandbox install-profile`, kept distinct from the service profile above even though both are now path-attached. The reason is not attachment-vs-not (both attach); it is that the service profile's target is *automatically resolved and always known* (`kirocrew_bin()`, the same path `ExecStart` uses, loaded before the unit starts), while a direct launch has no unit to load anything before, no reliably-known target without user input (`$APPIMAGE` / `--path`), and cannot transition itself into a profile at all: entering a named profile needs `aa_change_onexec`, which an unprivileged unconfined process is not permitted to do, and `aa-exec` does not fail loudly when it cannot transition — it execs unconfined, so a re-exec would appear to work while changing nothing (`sudo aa-exec` does transition, but would run the gateway as root). An attachment is applied by the kernel at exec time with no cooperation from the process, and is inherited by the backend; it is the mechanism stock Ubuntu already uses for `chrome`, `brave`, `1password` and `Discord`. An AppImage is a single self-contained file used by nothing else, which is what makes it a safe attachment target. diff --git a/src/kiro_crew/builtin_skills/kirocrew-commands/SKILL.md b/src/kiro_crew/builtin_skills/kirocrew-commands/SKILL.md index baf71a57fb82..5fb707feae73 100644 --- a/src/kiro_crew/builtin_skills/kirocrew-commands/SKILL.md +++ b/src/kiro_crew/builtin_skills/kirocrew-commands/SKILL.md @@ -64,7 +64,7 @@ transcripts. | Command | Description | |---------|-------------| -| `kirocrew service install` | Install and start as system service (sudo on Linux) | +| `kirocrew service install` | Install and start as an OS service | | `kirocrew service uninstall` | Stop and remove system service | | `kirocrew service status` | Show service status (systemctl/launchctl) | | `kirocrew logs` | Show gateway logs (last 100 lines) | diff --git a/src/kiro_crew/cli.py b/src/kiro_crew/cli.py index ca90965038c1..57210057824e 100644 --- a/src/kiro_crew/cli.py +++ b/src/kiro_crew/cli.py @@ -2151,14 +2151,12 @@ def main() -> None: ), ) - # service — install/uninstall/status as a system-level systemd unit (Linux, - # /etc/systemd/system/, requires sudo) or launchd LaunchAgent (macOS, - # ~/Library/LaunchAgents/, no sudo) so the gateway survives SSH disconnect, - # auto-restarts on crash, and auto-starts on boot. + # service — install/uninstall/status through systemd (Linux, preferring the + # per-user manager) or a launchd LaunchAgent (macOS). svc_parser = cli_help.add_command(sub, "service") svc_sub = svc_parser.add_subparsers(dest="service_action") - svc_sub.add_parser("install", help="Install and start the gateway service (sudo on Linux)") - svc_sub.add_parser("uninstall", help="Stop and remove the gateway service (sudo on Linux)") + svc_sub.add_parser("install", help="Install and start the gateway service") + svc_sub.add_parser("uninstall", help="Stop and remove the gateway service") svc_sub.add_parser("status", help="Show service status (systemctl/launchctl)") # sandbox — the AppArmor grant a DIRECT launch needs. `service install` diff --git a/src/kiro_crew/cli_help.py b/src/kiro_crew/cli_help.py index 866e75099ab6..a6fa0c5f8637 100644 --- a/src/kiro_crew/cli_help.py +++ b/src/kiro_crew/cli_help.py @@ -31,7 +31,7 @@ "Start here", ( ("gateway", "Start Kiro Crew in this terminal (dashboard + messaging channels)"), - ("service", "Run the gateway as a background service that starts on boot"), + ("service", "Run the gateway as a background service"), ("doctor", "Verify this install and diagnose problems"), ), ), @@ -140,11 +140,11 @@ def _listing_rank(name: str) -> int: kirocrew gateway runs in the foreground and stops on Ctrl-C or when the terminal closes. Best for a first look and for development. - kirocrew service install registers a systemd unit (Linux, needs sudo) or a - launchd agent (macOS) that runs the SAME gateway - detached: it survives logout, restarts on crash and - starts at boot. Then use `kirocrew service status`, - `kirocrew restart`, `kirocrew logs`. + kirocrew service install registers a systemd unit (Linux, preferring your + user manager) or launchd agent (macOS) that runs the + SAME gateway detached and restarts it on crash. Then + use `kirocrew service status`, `kirocrew restart`, + `kirocrew logs`. Run only one of them at a time -- both bind the same port. Ports: the dashboard is the only port Kiro Crew opens, and it binds loopback @@ -152,7 +152,7 @@ def _listing_rank(name: str) -> int: connect outbound, so nothing else needs to be reachable. Override the port with `kirocrew gateway --port N`, KIROCREW_PORT=N, or the `dashboard.url` config value; for the service, set KIROCREW_PORT when you run - `service install` (later, edit /etc/kirocrew/kirocrew.env and restart).""" + `service install` (re-run it to update a user unit).""" def add_command( diff --git a/src/kiro_crew/cli_server.py b/src/kiro_crew/cli_server.py index 86038b5eb99c..b6db779cc18c 100644 --- a/src/kiro_crew/cli_server.py +++ b/src/kiro_crew/cli_server.py @@ -1133,10 +1133,9 @@ def _restart(cli_port: int | None = None) -> None: explicitly request a specific port, ask the platform to restart it (``systemctl restart`` / ``launchctl kickstart -k``). When the service manager REFUSES that restart while the unit is still active - (system-scope unit, unprivileged caller / polkit denial), fail loudly - naming the privileged command the operator must run — never fall - through to the listener path, which cannot see a service gateway - bound to a unix socket and would misreport the outcome. + fail loudly with the manager-specific command — never fall through to + the listener path, which cannot see a service gateway bound to a unix + socket and would misreport the outcome. 2. Otherwise, SIGTERM the foreground gateway via the existing lsof+SIGTERM path used by ``kirocrew stop``, then spawn a detached replacement and **verify it is serving** before reporting @@ -1164,16 +1163,14 @@ def _restart(cli_port: int | None = None) -> None: return if service_controller.is_service_active(): # The service manager refused the restart while the unit is active - # RIGHT NOW — the system-scope unit needs root/polkit privileges - # this process does not have ("Interactive authentication - # required"). Falling through to the listener path would be worse + # RIGHT NOW. Falling through to the listener path would be worse # than failing: on a unix-socket deployment nothing listens on TCP, # so the fallback finds nothing to stop, spawns a competitor the # KIROCREW_HOME lock refuses, and the original gateway keeps # running while the command's outcome reads like a restart. Name - # the privileged command the operator must run instead. The - # active-check runs AFTER the refused restart so a service that - # merely stopped in between still falls through below. + # the manager-specific command instead. The active-check runs AFTER + # the refused restart so a service that merely stopped in between + # still falls through below. hint = service_controller.manual_restart_hint() sel().log_api_access( caller="cli", @@ -2449,7 +2446,7 @@ def _logs_cmd(args: argparse.Namespace) -> None: """Tail gateway logs from the most appropriate source. Order of preference: - 1. systemd journal (if the system service is installed on Linux) + 1. systemd journal (if a user or system service is installed on Linux) 2. launchd stdout file (macOS) 3. ``~/.kiro/crew/gateway.log`` (foreground gateway) """ @@ -2468,14 +2465,29 @@ def _logs_cmd(args: argparse.Namespace) -> None: resources=f"follow={follow} lines={lines} platform={plat.value}", ) - if plat == Platform.SYSTEMD and svc_linux.UNIT_PATH.exists(): + installed_unit = svc_linux.installed_unit_path() if plat == Platform.SYSTEMD else None + if installed_unit is not None: + user_scope = installed_unit == svc_linux.user_unit_path() + base = [ + "journalctl", + *(["--user"] if user_scope else []), + "--no-pager", + "-u", + unit, + "-n", + str(lines), + ] + if user_scope: + if follow: + base.append("-f") + os.execvp("journalctl", base) + # Try journalctl unprivileged first — it works if the user is in # the `systemd-journal` or `adm` group. Only fall back to sudo # journalctl if the unprivileged probe returns no rows. Without # this fall-through, `kirocrew logs` would hang on hosts without # passwordless sudo, which is a surprising failure mode for a # read-only log-viewer. - base = ["journalctl", "--no-pager", "-u", unit, "-n", str(lines)] probe = subprocess.run( ["journalctl", "-u", unit, "-n", "1", "--no-pager"], capture_output=True, diff --git a/src/kiro_crew/docs/getting-started.md b/src/kiro_crew/docs/getting-started.md index 696b29a3f225..b7dd0e0a14cb 100644 --- a/src/kiro_crew/docs/getting-started.md +++ b/src/kiro_crew/docs/getting-started.md @@ -187,9 +187,10 @@ kirocrew service status kirocrew service uninstall ``` -The service survives an SSH disconnect, restarts on crash, and starts on boot. -On Linux the install prompts for `sudo` once to write the unit; the gateway -itself then runs as your own user. macOS needs no `sudo`. +The service runs detached and restarts on crash. Linux prefers a per-user +systemd unit and falls back to a system unit when the user manager is +unavailable; enable lingering if the user unit must survive logout. macOS uses +a launchd agent. Tail its output with `kirocrew logs -f`. diff --git a/src/kiro_crew/service/__init__.py b/src/kiro_crew/service/__init__.py index d034d50c53fe..16ebc59d6aa5 100644 --- a/src/kiro_crew/service/__init__.py +++ b/src/kiro_crew/service/__init__.py @@ -1,13 +1,11 @@ """Service management for the KiroCrew gateway. -Provides ``install``, ``uninstall``, ``status`` for systemd (Linux, -system-level unit at ``/etc/systemd/system/``) and launchd (macOS, -LaunchAgent under ``~/Library/LaunchAgents/``). +Provides ``install``, ``uninstall``, ``status`` for systemd (Linux, preferring +the per-user manager) and launchd (macOS, LaunchAgent under +``~/Library/LaunchAgents/``). The gateway always runs as the invoking user — never root. On Linux, -sudo is needed only to write the unit file and invoke ``systemctl``; -no kirocrew / MCP / LLM code is ever invoked under sudo. On macOS no -sudo is required at all because LaunchAgents live in the user's home. +sudo is only needed by the system-scope fallback and optional host hardening. Public entry points used by the CLI: install_service() diff --git a/src/kiro_crew/service/common.py b/src/kiro_crew/service/common.py index d0b068d2cd18..a2495f92f6a5 100644 --- a/src/kiro_crew/service/common.py +++ b/src/kiro_crew/service/common.py @@ -327,10 +327,7 @@ def service_path(home: str) -> str: class Platform(enum.Enum): """Supported service-management platforms.""" - # System-level systemd. Unit lives at /etc/systemd/system/, write - # and control commands require sudo. The name reflects the privilege - # model: a user-level (~/.config/systemd/user/) variant doesn't work - # on older systemd (e.g. 219), so we don't ship one. + # systemd on Linux; the Linux backend selects user or system scope. SYSTEMD = "systemd" LAUNCHD = "launchd" UNSUPPORTED = "unsupported" @@ -357,18 +354,16 @@ def restart_command_hint() -> str: scopes are not interchangeable — printing the wrong one sends the user down a dead end: - * ``SYSTEMD`` — the unit is **system-level** at - ``/etc/systemd/system/kirocrew.service`` (see - :mod:`kiro_crew.service.linux`). ``systemctl --user`` fails on AL2 - (no per-user systemd manager), so the working command needs sudo: - ``sudo systemctl restart kirocrew``. + * ``SYSTEMD`` — use the installed unit's user or system scope. * ``LAUNCHD`` / ``UNSUPPORTED`` — defer to the service-aware ``kirocrew restart`` CLI, which resolves the right mechanism itself. - Centralised so the update path and the Slack restart-failure hint share - one source of truth and can never drift back to the broken - ``systemctl --user`` string. + Centralised so the update path and Slack use the same scope. """ if current_platform() is Platform.SYSTEMD: + from kiro_crew.service import linux + + if linux.user_unit_path().is_file(): + return f"systemctl --user restart {SERVICE_NAME}" return f"sudo systemctl restart {SERVICE_NAME}" return "kirocrew restart" diff --git a/src/kiro_crew/service/controller.py b/src/kiro_crew/service/controller.py index 33c393a778c9..db962b621008 100644 --- a/src/kiro_crew/service/controller.py +++ b/src/kiro_crew/service/controller.py @@ -55,8 +55,8 @@ def installed_unit_path() -> "Path | None": and inherits the invoking shell instead. """ plat = current_platform() - if plat == Platform.SYSTEMD and linux.UNIT_PATH.is_file(): - return linux.UNIT_PATH + if plat == Platform.SYSTEMD: + return linux.installed_unit_path() if plat == Platform.LAUNCHD and macos.PLIST_PATH.is_file(): return macos.PLIST_PATH return None @@ -106,13 +106,9 @@ def _unsupported_message() -> None: def install_service() -> int: """Install and start the platform service. - Returns 0 on success, non-zero otherwise. On Linux the install - prompts for sudo on first use to write - ``/etc/systemd/system/kirocrew.service`` and to run - ``systemctl daemon-reload / enable / restart``. The gateway itself - runs as ``User=$USER`` once started — kirocrew code is never - invoked under sudo. On macOS no sudo is required. The CLI is - expected to surface the sudo prompt to a real terminal. + Returns 0 on success, non-zero otherwise. Linux prefers the invoking + account's per-user systemd manager and falls back to the existing + sudo-backed system install when that manager is unavailable. """ plat = current_platform() if plat == Platform.SYSTEMD: @@ -122,7 +118,7 @@ def install_service() -> int: print(f"❌ {exc}", file=sys.stderr) return 1 print("✅ kirocrew service installed and started.") - print(f" unit: {linux.UNIT_PATH}") + print(f" unit: {linux.installed_unit_path() or linux.UNIT_PATH}") # Reported here, but performed inside linux.install() before the unit is # started — the directive only applies at service start. Deliberately # non-fatal: a failure warns and leaves the service running. @@ -291,17 +287,14 @@ def restart_service() -> bool: def manual_restart_hint() -> str: """Command an operator can run BY HAND to restart the installed service. - Printed when :func:`restart_service` was refused by the service manager — - a system-scope unit needs root/polkit privileges the calling process may - not have. Unlike :func:`kiro_crew.service.common.restart_command_hint`, - this must never answer ``kirocrew restart``: that is the command that just - failed, so a circular hint would send the operator straight back into the - same refusal. + Printed when :func:`restart_service` was refused by the service manager. + Unlike :func:`kiro_crew.service.common.restart_command_hint`, this must + never answer ``kirocrew restart``: that is the command that just failed, so + a circular hint would send the operator straight back into the same refusal. """ plat = current_platform() if plat == Platform.SYSTEMD: - # "sudo systemctl restart kirocrew" — shared with the update path and - # the Slack restart-failure hint so the string cannot drift. + # Shared with the update path and Slack so the scope cannot drift. return restart_command_hint() if plat == Platform.LAUNCHD: # NOT `launchctl kickstart` — that is the exact call macos.restart() diff --git a/src/kiro_crew/service/linux.py b/src/kiro_crew/service/linux.py index d5cec6af893b..3a7e82b8c9fb 100644 --- a/src/kiro_crew/service/linux.py +++ b/src/kiro_crew/service/linux.py @@ -1,16 +1,9 @@ -"""systemd system-service generation and control for Linux. +"""systemd service generation and control for Linux. -The unit lives at ``/etc/systemd/system/kirocrew.service`` and is -enabled+started via ``sudo systemctl enable --now``. The service runs -as the invoking user (via ``User=`` in the unit) — only the install, -uninstall, and start/stop actions need sudo. - -Why system-level instead of user-level (``systemctl --user``): -some older distros (notably systemd 219) do not have a working -per-user systemd manager — ``systemctl --user`` fails with -``Failed to get D-Bus connection``. System-level units work -uniformly across any distro shipping systemd >= 219, which is -everything since 2015. +Fresh installs use ``systemctl --user`` when the invoking account has a +reachable per-user manager. Existing system units stay system-scoped, and hosts +without a usable user manager fall back to +``/etc/systemd/system/kirocrew.service``. One host class this choice does NOT work on, and cannot be made to work by anything the installer writes: an SELinux-enforcing host whose kirocrew lives @@ -18,11 +11,8 @@ atomic desktops). PID 1's domain is denied ``execute`` on a home-labelled file, so the unit fails every start with ``203/EXEC``. :mod:`kiro_crew.service .selinux` detects exactly that case by querying the loaded policy, and -:func:`install` refuses up front with a rendered user-scope unit as the remedy -rather than writing a unit that provably cannot start. A per-user install mode is -the real fix and is deliberately NOT implemented here — it is an install-model -change (scope-aware status/restart/uninstall, where the AppArmor profile and the -root-owned overrides file live) rather than a mechanical one. +:func:`install` refuses the system-scope fallback up front rather than writing a +unit that provably cannot start. Sudo scope: this file escalates ``systemctl``, ``install``, ``mkdir``, ``rm``, ``rmdir`` and ``test`` directly, and lends its privileged helpers @@ -63,7 +53,6 @@ import logging import os -import shlex import shutil import subprocess import sys @@ -83,12 +72,7 @@ UNIT_PATH = Path(f"/etc/systemd/system/{SERVICE_NAME}.service") -# Where a user-scope unit belongs, per systemd.unit(5) — RELATIVE to the service -# account's home, deliberately. Referenced only in the printed remedy; nothing in -# this module writes here. It is not spelled "~/.config/..." because "~" resolves -# against whoever pastes the command, and `service install` is documented to run -# under sudo — so a tilde would silently name root's home in the one shell the -# operator is most likely to be sitting in. +# Where a user-scope unit belongs, relative to the service account's home. USER_UNIT_SUBDIR = Path(".config/systemd/user") # Operator-editable environment overrides, read by the unit via @@ -189,6 +173,23 @@ def _home_for_user(user: str) -> str: return str(Path.home()) +def user_unit_path() -> Path: + """Return the standard per-user unit path for the invoking account.""" + user = _current_user() + home = _home_for_user(user) if user else str(Path.home()) + return Path(home) / USER_UNIT_SUBDIR / UNIT_PATH.name + + +def installed_unit_path() -> Path | None: + """Return the installed user or system unit, preferring user scope.""" + user_path = user_unit_path() + if user_path.is_file(): + return user_path + if UNIT_PATH.is_file(): + return UNIT_PATH + return None + + def render_unit(*, user_scope: bool = False) -> str: """Render the systemd unit file contents. @@ -207,14 +208,9 @@ def render_unit(*, user_scope: bool = False) -> str: systemd's ``change_onexec`` transition silently wins over the kernel's automatic path attachment, defeating it. - ``user_scope`` renders the ``systemctl --user`` variant this module only ever - PRINTS (see :func:`selinux_refusal`) — rendered here rather than hand-written - so the copy-pasteable remedy cannot drift from the unit we actually install. - Two directives differ, and both are hard requirements of the per-user manager - rather than style choices: ``User=``/``Group=`` are rejected outright in a - user unit (the manager already runs as that account), and the install target - is ``default.target`` because ``multi-user.target`` is a system target the - user manager does not have. + ``user_scope`` omits ``User=``/``Group=`` because the per-user manager + already runs as that account, and uses ``default.target`` because + ``multi-user.target`` is a system target. """ bin_path = kirocrew_bin() user = _current_user() @@ -258,6 +254,7 @@ def render_unit(*, user_scope: bool = False) -> str: ("DBUS_SESSION_BUS_ADDRESS", f"unix:path=/run/user/{uid}/bus"), ) ) + env_file_line = "" if user_scope else f"EnvironmentFile=-{ENV_FILE_PATH}\n" return ( "[Unit]\n" "Description=Kiro Crew gateway (dashboard + Slack + cron)\n" @@ -293,7 +290,7 @@ def render_unit(*, user_scope: bool = False) -> str: # KIROCREW_PORT) without a re-install. The leading "-" makes a missing # file non-fatal, so the unit still starts where install could not write # /etc/kirocrew (the baked Environment= values then apply). - f"EnvironmentFile=-{ENV_FILE_PATH}\n" + f"{env_file_line}" # Pin a high open-file limit rather than inheriting the host's # ambient DefaultLimitNOFILE. Stock systemd defaults to 1024 — and # the frontend production build (vite/rollup) opens ~1000 @@ -406,6 +403,49 @@ def _systemctl(*args: str, sudo: bool = True) -> subprocess.CompletedProcess[str ) +def _user_systemctl(*args: str) -> subprocess.CompletedProcess[str]: + return _systemctl("--user", *args, sudo=False) + + +def _installed_systemctl( + *args: str, sudo: bool = True +) -> subprocess.CompletedProcess[str]: + if user_unit_path().is_file(): + return _user_systemctl(*args) + return _systemctl(*args, sudo=sudo) + + +def _user_manager_available() -> bool: + """Whether this process can control its own per-user systemd manager.""" + geteuid = getattr(os, "geteuid", None) + if os.environ.get("SUDO_USER") or (geteuid is not None and geteuid() == 0): + return False + try: + return _user_systemctl("show-environment").returncode == 0 + except OSError: + return False + + +def _require_user_manager() -> None: + if not _user_manager_available(): + raise ServiceInstallError( + "The user unit is installed, but `systemctl --user` is not " + "available in this session. Re-run without sudo from the service " + "account's login session." + ) + + +def _write_user_unit(contents: str) -> Path: + """Write the unit to the invoking account's standard user-unit directory.""" + path = user_unit_path() + try: + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(contents, encoding="utf-8") + except OSError as exc: + raise ServiceInstallError(f"Failed to write user unit {path}: {exc}") from exc + return path + + def _write_unit_via_sudo(contents: str) -> subprocess.CompletedProcess[str]: """Write the unit file at ``UNIT_PATH`` atomically via ``sudo install``. @@ -526,101 +566,17 @@ def _env_file_is_untouched_seed() -> bool: return False -def _user_scope_remedy() -> str: - """The commands that stand up a working per-user unit on this host. - - Shared by :func:`selinux_refusal` (pre-flight proved the system unit cannot - start) and :func:`selinux_start_failure_hint` (it started nothing and SELinux - is enforcing), so the operator is handed the same verified sequence either - way and the two cannot drift. - - **Every path and account is spelled out, and none is taken from the pasting - shell.** A user unit has no ``User=`` — the account it runs as is whichever - manager loads it — so ``~`` and ``$USER`` would decide who runs the agent. - ``service install`` is documented to run under ``sudo``, so the shell reading - this is usually root's: a tilde would name ``/root``, ``$USER`` would expand to - ``root``, and the remedy would hand an operator a unit that runs untrusted - agent tools as root — defeating the same invariant :func:`install` enforces by - refusing a ``User=root`` unit. Hence the absolute home, the explicit account - name, and the warning. - - Both generated paths go through :func:`shlex.quote`, like the ``.env`` remedy - in :mod:`kiro_crew.service.common`: these lines are copy-pasted verbatim, and - an account home containing a space would word-split, so ``mkdir`` would create - the wrong directories and the redirect would put the unit somewhere systemd - never reads. Ordinary paths come back unquoted, so the common case is - unchanged. - """ - unit_body = render_unit(user_scope=True) - user = _current_user() - home = _home_for_user(user) if user else str(Path.home()) - account = user or "" - unit_dir = shlex.quote(str(Path(home) / USER_UNIT_SUBDIR)) - unit_file = shlex.quote(str(Path(home) / USER_UNIT_SUBDIR / UNIT_PATH.name)) - return ( - f" Run the next four commands AS {account} — a user unit carries no\n" - f" User=, so it runs as whichever account's manager loads it. Loading it\n" - f" from a root shell (the shell you are probably in, since `service\n" - f" install` needs sudo) would run the agent as ROOT, which this installer\n" - f" otherwise refuses outright. `sudo -u {account}` is NOT enough — it\n" - f" creates no session, so `systemctl --user` cannot reach that account's\n" - f" manager. Get a real session first, e.g. `machinectl shell {account}@`,\n" - f" or just log in as {account}.\n" - f"\n" - f" mkdir -p {unit_dir}\n" - f" cat > {unit_file} <<'KIROCREW_UNIT'\n" - f"{unit_body}" - f"KIROCREW_UNIT\n" - f" systemctl --user daemon-reload\n" - f" systemctl --user enable --now {SERVICE_NAME}.service\n" - f"\n" - f" Then, back in a root shell — this one step needs privilege, and takes\n" - f" the account name explicitly so it cannot land on the wrong user:\n" - f"\n" - f" loginctl enable-linger {shlex.quote(account)}\n" - f"\n" - f" Manage it with `systemctl --user status|restart {SERVICE_NAME}` and\n" - f" `journalctl --user -u {SERVICE_NAME} -f`. `kirocrew service " - f"status|uninstall`\n" - f" only looks at the system unit, so it will not see this one." - ) - - def selinux_refusal(reason: str) -> str: - """Operator-facing refusal for a system unit SELinux proves cannot start. - - A refusal rather than a warning because everything after this point is - destructive to no purpose: install would write the unit, ``enable`` it, fail - at the first ``systemctl restart``, and leave a unit enabled that crash-loops - at every boot until it exhausts ``StartLimitBurst``. Stopping before the - first write leaves the host exactly as it was found. - - The remedy embeds a ready-to-paste user unit rendered by :func:`render_unit`, - not prose describing one: the operator's working unit then carries the same - ``ExecStart`` and the same baked environment as the unit we would have - installed, and cannot drift from it as this module changes. - """ + """Explain why the system-scope fallback cannot be installed.""" return ( f"Refusing to install a system service that cannot start on this host.\n" f" {reason}.\n" f"\n" - f" This is SELinux type enforcement, not a broken file. The binary is\n" - f" perfectly ordinary — it exists, it is executable, and `test -x` on\n" - f" it succeeds; the policy's execute check is the only thing that\n" - f" fails, and nothing short of asking the policy reveals it. A unit at\n" - f" {UNIT_PATH} would fail every start with\n" - f" status=203/EXEC until it hit its restart limit.\n" + f" {UNIT_PATH} would fail with status=203/EXEC.\n" f"\n" - f" A per-user unit is not subject to this: the per-user systemd manager\n" - f" does not run in PID 1's domain, so it is allowed to execute a binary\n" - f" under $HOME.\n" - f"\n" - f"{_user_scope_remedy()}\n" - f"\n" - f" Installing kirocrew outside $HOME (onto a system-labelled path such\n" - f" as /usr/local/bin) also resolves it. Relocating only the LAUNCHER\n" - f" does not: whatever systemd execs still runs in PID 1's domain, so\n" - f" the next execve of the binary under $HOME is denied identically." + f" Re-run `kirocrew service install` from a login session where\n" + f" `systemctl --user` works, or install kirocrew outside $HOME onto a\n" + f" system-labelled path such as /usr/local/bin." ) @@ -637,13 +593,10 @@ def selinux_start_failure_hint() -> str: :mod:`kiro_crew.service.selinux`), name SELinux here, where the unit has actually failed, so the operator is never left with only "run journalctl". - Deliberately the HYPOTHESIS and the command that settles it — NOT the - user-scope remedy :func:`selinux_refusal` prints. This fires on every failed - restart on every enforcing host, which is all of RHEL/Fedora, including the - ones the pre-flight positively proved ALLOW for; a port conflict on a stock - RHEL box would otherwise be answered with a wall of SELinux text and a - pasteable unit for a denial nobody has observed. A remedy belongs behind a - proven denial, so this points at the documented one and stops. + Deliberately the HYPOTHESIS and the command that settles it. This fires on + every failed restart on every enforcing host, including ones the pre-flight + positively proved ALLOW, so a port conflict must not be answered as a proven + denial. Empty on any host that is not enforcing, so nothing changes on the overwhelming majority of installs. @@ -670,9 +623,8 @@ def selinux_start_failure_hint() -> str: def install() -> apparmor.ProfileOutcome: """Write the unit file and enable+start the service. Idempotent. - Calls ``sudo`` to write the unit and to invoke ``systemctl``. Sudo - will prompt for a password the first time (or when the cached - ticket has expired) — that prompt appears on the user's terminal. + Uses the invoking account's per-user manager when available. The existing + sudo-backed system install remains the fallback. No kirocrew / LLM / agent code runs under sudo deliberately — see the module docstring's sudo scope for the full set of escalated programs, including the ones the AppArmor step adds, and for what the escalated interpreter can @@ -687,11 +639,6 @@ def install() -> apparmor.ProfileOutcome: service start, so loading it afterwards would leave the first gateway process unprofiled and every agent spawn failing closed until the next restart. """ - # Fail early and cleanly if we cannot escalate: without this the first - # `sudo` call raises FileNotFoundError, which controller.install_service - # does not catch, so the CLI prints a traceback instead of the reason. - _require_privilege() - user = _current_user() if not user: raise ServiceInstallError( @@ -712,29 +659,39 @@ def install() -> apparmor.ProfileOutcome: "service install`), or set $USER to a non-root account." ) - # Last gate before anything is written: on an SELinux-enforcing host whose - # kirocrew lives under $HOME, PID 1's domain is denied execute on the binary - # this unit would name, so the unit can never start. Everything below - # would still "succeed" up to the first `systemctl restart`, leaving an - # enabled unit crash-looping at 203/EXEC on every boot. Fires only on a - # proven policy denial and fails open on every indeterminate answer, so a - # host without SELinux, or in permissive mode, is unaffected. - blocked, selinux_reason = selinux.blocks_system_unit(kirocrew_bin()) - if blocked: - raise ServiceInstallError(selinux_refusal(selinux_reason)) + user_path = user_unit_path() + if user_path.is_file(): + _require_user_manager() + user_scope = True + elif UNIT_PATH.is_file(): + user_scope = False + else: + user_scope = _user_manager_available() + + if not user_scope: + # Fail early and cleanly if the system fallback cannot escalate. + _require_privilege() + + # PID 1 cannot execute a home-labelled binary on some enforcing SELinux + # hosts. The user-scoped path does not have that restriction. + blocked, selinux_reason = selinux.blocks_system_unit(kirocrew_bin()) + if blocked: + raise ServiceInstallError(selinux_refusal(selinux_reason)) needs_profile, profile_reason = apparmor.should_install() - write_res = _write_unit_via_sudo(render_unit()) - if write_res.returncode != 0: - raise ServiceInstallError( - "Failed to write the unit file. The sudo step is required because " - f"{UNIT_PATH} is owned by root.\n" - f" sudo install said: {(write_res.stderr or write_res.stdout).strip()}" - ) + if user_scope: + _write_user_unit(render_unit(user_scope=True)) + else: + write_res = _write_unit_via_sudo(render_unit()) + if write_res.returncode != 0: + raise ServiceInstallError( + "Failed to write the unit file. The sudo step is required because " + f"{UNIT_PATH} is owned by root.\n" + f" sudo install said: {(write_res.stderr or write_res.stdout).strip()}" + ) - # Seed the operator-editable overrides file (create-if-absent), so a later - # `KIROCREW_PORT=...` edit + restart works without re-installing. - _seed_env_file() + # The root-owned overrides file belongs only to the system-scope fallback. + _seed_env_file() # Before daemon-reload/enable/restart: a path-attached profile applies at the # kernel's own execve() time, so it must already be loaded or the first @@ -745,33 +702,41 @@ def install() -> apparmor.ProfileOutcome: else apparmor.ProfileOutcome(False, f"AppArmor profile not needed: {profile_reason}") ) - reload_res = _systemctl("daemon-reload") + systemctl_name = "systemctl --user" if user_scope else "sudo systemctl" + ctl = _user_systemctl if user_scope else _systemctl + + reload_res = ctl("daemon-reload") if reload_res.returncode != 0: raise ServiceInstallError( - f"`sudo systemctl daemon-reload` failed: " + f"`{systemctl_name} daemon-reload` failed: " f"{(reload_res.stderr or reload_res.stdout).strip()}" ) - enable_res = _systemctl("enable", f"{SERVICE_NAME}.service") + enable_res = ctl("enable", f"{SERVICE_NAME}.service") if enable_res.returncode != 0: raise ServiceInstallError( - f"`sudo systemctl enable` failed: " + f"`{systemctl_name} enable` failed: " f"{(enable_res.stderr or enable_res.stdout).strip()}" ) # Use restart (not start) so re-running install picks up a unit-file # change without manual intervention. - restart_res = _systemctl("restart", f"{SERVICE_NAME}.service") + restart_res = ctl("restart", f"{SERVICE_NAME}.service") if restart_res.returncode != 0: + journal_command = ( + f"journalctl --user -u {SERVICE_NAME}.service -n 50" + if user_scope + else f"sudo journalctl -u {SERVICE_NAME}.service -n 50" + ) raise ServiceInstallError( - f"`sudo systemctl restart` failed: " + f"`{systemctl_name} restart` failed: " f"{(restart_res.stderr or restart_res.stdout).strip()}\n" - f"Run `sudo journalctl -u {SERVICE_NAME}.service -n 50` for details." + f"Run `{journal_command}` for details." # The pre-flight only proves denials for the file systemd itself # execs, so a wrapper's delegated binary can still be denied and land # here. Name SELinux where the unit has actually failed rather than # leave the operator with only a journalctl command. - + selinux_start_failure_hint() + + ("" if user_scope else selinux_start_failure_hint()) ) return profile_outcome @@ -863,6 +828,18 @@ def remove_launcher_profile() -> apparmor.ProfileOutcome: def uninstall() -> None: """Stop, disable, and remove the unit. Idempotent.""" + user_path = user_unit_path() + if user_path.is_file(): + _require_user_manager() + _user_systemctl("stop", f"{SERVICE_NAME}.service") + _user_systemctl("disable", f"{SERVICE_NAME}.service") + try: + user_path.unlink() + except OSError as exc: + raise ServiceInstallError(f"Failed to remove user unit {user_path}: {exc}") from exc + _user_systemctl("daemon-reload") + return + # Probe unprivileged so we don't prompt for a password when the unit isn't # even present: a stock `/etc/systemd/system` is traversable by every user, # so a plain stat answers this. Unlike `_seed_env_file`'s probe, this one @@ -888,18 +865,14 @@ def uninstall() -> None: def is_active() -> bool: - """Return True if the systemd service is currently active. - - ``is-active`` does not require sudo to query state, so we use the - non-sudo path. - """ - res = _systemctl("is-active", f"{SERVICE_NAME}.service", sudo=False) + """Return True if the installed systemd service is currently active.""" + res = _installed_systemctl("is-active", f"{SERVICE_NAME}.service", sudo=False) return res.returncode == 0 and res.stdout.strip() == "active" def stop() -> None: """Stop the running service without disabling it.""" - _systemctl("stop", f"{SERVICE_NAME}.service") + _installed_systemctl("stop", f"{SERVICE_NAME}.service") def restart() -> bool: @@ -911,22 +884,16 @@ def restart() -> bool: unit are unaffected: ``systemctl restart`` is an explicit operator action, so the manager honors it regardless of restart policy. - A system-scope restart requires root/polkit; an unprivileged caller - gets a non-zero exit ("Interactive authentication required"). We - return that outcome so callers do not report a restart that never - happened. + A user-scoped restart is unprivileged; the system fallback retains its + existing sudo requirement. """ - return _systemctl("restart", f"{SERVICE_NAME}.service").returncode == 0 + return _installed_systemctl("restart", f"{SERVICE_NAME}.service").returncode == 0 def status() -> str: """Return a human-readable status block from systemctl. - Status is queryable without sudo. We avoid sudo here so - ``kirocrew service status`` doesn't prompt for a password just to - show whether the service is up. + Status is queryable without sudo in either scope. """ - res = _systemctl( - "status", f"{SERVICE_NAME}.service", "--no-pager", sudo=False - ) + res = _installed_systemctl("status", f"{SERVICE_NAME}.service", "--no-pager", sudo=False) return res.stdout or res.stderr diff --git a/src/kiro_crew/service/live_target.py b/src/kiro_crew/service/live_target.py index fd986d3cec1f..5965c4b349c8 100644 --- a/src/kiro_crew/service/live_target.py +++ b/src/kiro_crew/service/live_target.py @@ -5,8 +5,8 @@ definition, because every service manager makes its own definition expensive to mutate in a different way: -* a systemd **system** unit (what ``kirocrew service install`` writes on Linux) - lives under ``/etc/systemd/system`` and needs root to change; +* a systemd unit may be user- or system-scoped, depending on which manager was + available when ``kirocrew service install`` ran; * a launchd plist only re-reads on ``bootout`` + ``bootstrap``, and the ``bootout`` half kills the very process that would have to run the second half; diff --git a/src/kiro_crew/service/selinux.py b/src/kiro_crew/service/selinux.py index c2c0f551cb2b..571aa91d5326 100644 --- a/src/kiro_crew/service/selinux.py +++ b/src/kiro_crew/service/selinux.py @@ -66,9 +66,8 @@ the other side. So the boundary is left where soundness puts it, and :func:`kiro_crew.service.linux.install` covers the residue at the point of failure instead: when the unit is written and the first ``systemctl restart`` fails on an -enforcing host, its error names SELinux as a candidate and prints the same -user-scope remedy. Nothing is left silently unexplained, and no install that would -have worked is refused. +enforcing host, its error names SELinux as a candidate and points to user scope. +No install that would have worked is refused. """ from __future__ import annotations diff --git a/test/test_cli_server_more_coverage.py b/test/test_cli_server_more_coverage.py index d133c826c60f..a6c6d7ee3b64 100644 --- a/test/test_cli_server_more_coverage.py +++ b/test/test_cli_server_more_coverage.py @@ -633,6 +633,29 @@ def _systemd(self, monkeypatch, tmp_path): unit.write_text("[Unit]\n", encoding="utf-8", newline="\n") monkeypatch.setattr(cli_server, "current_platform", lambda: Platform.SYSTEMD) monkeypatch.setattr(svc_linux, "UNIT_PATH", unit) + monkeypatch.setattr( + svc_linux, + "user_unit_path", + lambda: tmp_path / "missing-user.service", + ) + + def test_user_journal_is_execed_without_sudo( + self, monkeypatch, tmp_path, sel_rec, fake_execvp + ) -> None: + unit = tmp_path / "user" / "kirocrew.service" + unit.parent.mkdir() + unit.write_text("[Unit]\n", encoding="utf-8", newline="\n") + monkeypatch.setattr(svc_linux, "user_unit_path", lambda: unit) + + def unreachable(*_a, **_k): # pragma: no cover - proves no permission probe + raise AssertionError("user journal must not use the system-journal probe") + + monkeypatch.setattr(subprocess, "run", unreachable) + with pytest.raises(_ExecCalled) as exc: + cli_server._logs_cmd(argparse.Namespace(follow=True, lines=42)) + assert exc.value.file == "journalctl" + assert exc.value.argv[:2] == ["journalctl", "--user"] + assert "-f" in exc.value.argv def test_unprivileged_journal_is_execed_when_probe_returns_rows( self, monkeypatch, sel_rec, fake_execvp diff --git a/test/test_service.py b/test/test_service.py index d93e93f250be..0631eb1ea4fe 100644 --- a/test/test_service.py +++ b/test/test_service.py @@ -38,7 +38,7 @@ @pytest.fixture(autouse=True) -def _clear_sudo_user(monkeypatch): +def _clear_sudo_user(monkeypatch, tmp_path): """Keep ``User=`` resolution deterministic across hosts. ``_current_user()`` prefers ``SUDO_USER`` (so ``sudo … service install`` @@ -48,6 +48,16 @@ def _clear_sudo_user(monkeypatch): explicitly themselves. """ monkeypatch.delenv("SUDO_USER", raising=False) + # Never probe the developer's real user manager from a unit test. Tests + # exercising the new default opt in explicitly. + from kiro_crew.service import linux as svc_linux + + monkeypatch.setattr(svc_linux, "_user_manager_available", lambda: False) + monkeypatch.setattr( + svc_linux, + "user_unit_path", + lambda: tmp_path / "missing-user.service", + ) class TestPlatformDetection: @@ -281,7 +291,51 @@ def test_render_unit_falls_back_to_argv0_when_kirocrew_not_on_path(self, monkeyp # that ends in the (quoted) kirocrew executable followed by gateway. assert 'kirocrew" gateway' in unit - def test_install_writes_unit_via_sudo_install_and_invokes_systemctl( + def test_install_prefers_user_manager(self, tmp_path, monkeypatch): + from kiro_crew.service import linux as svc_linux + + user_unit = tmp_path / "user" / "kirocrew.service" + monkeypatch.setenv("USER", "tester") + monkeypatch.setattr(svc_linux, "UNIT_PATH", tmp_path / "system.service") + monkeypatch.setattr(svc_linux, "user_unit_path", lambda: user_unit) + monkeypatch.setattr(svc_linux, "_user_manager_available", lambda: True) + monkeypatch.setattr( + svc_linux.apparmor, + "should_install", + lambda: (False, "not needed"), + ) + + ok = MagicMock(returncode=0, stdout="", stderr="") + with patch( + "kiro_crew.service.common.shutil.which", + return_value="/usr/local/bin/kirocrew", + ), patch( + "kiro_crew.service.linux.subprocess.run", return_value=ok + ) as run: + svc_linux.install() + + unit = user_unit.read_text(encoding="utf-8") + assert "User=" not in unit + assert "Group=" not in unit + assert "EnvironmentFile=" not in unit + assert "WantedBy=default.target" in unit + called = [list(c.args[0]) for c in run.call_args_list] + assert ["systemctl", "--user", "daemon-reload"] in called + assert [ + "systemctl", + "--user", + "enable", + f"{SERVICE_NAME}.service", + ] in called + assert [ + "systemctl", + "--user", + "restart", + f"{SERVICE_NAME}.service", + ] in called + assert not any("sudo" in command for command in called) + + def test_install_falls_back_to_sudo_when_user_manager_is_unavailable( self, tmp_path, monkeypatch ): from kiro_crew.service import linux as svc_linux @@ -301,7 +355,7 @@ def test_install_writes_unit_via_sudo_install_and_invokes_systemctl( ) as run: svc_linux.install() - # Four things must happen: + # The existing system-scope path remains the fallback: # 1) `sudo install -m 0644 -o root -g root /etc/systemd/system/kirocrew.service` # 2) `sudo systemctl daemon-reload` # 3) `sudo systemctl enable kirocrew.service` @@ -1396,6 +1450,28 @@ def test_uninstall_runs_full_teardown_when_unit_exists(self, tmp_path, monkeypat assert ["sudo", "systemctl", "daemon-reload"] in called assert sentinel.read_text() == "user data" + def test_user_unit_lifecycle_uses_user_manager(self, tmp_path, monkeypatch): + from kiro_crew.service import linux as svc_linux + + unit_path = tmp_path / "kirocrew.service" + unit_path.write_text("[Unit]\n", encoding="utf-8") + monkeypatch.setattr(svc_linux, "user_unit_path", lambda: unit_path) + monkeypatch.setattr(svc_linux, "_user_manager_available", lambda: True) + result = MagicMock(returncode=0, stdout="active\n", stderr="") + with patch( + "kiro_crew.service.linux.subprocess.run", return_value=result + ) as run: + assert svc_linux.is_active() is True + svc_linux.stop() + assert svc_linux.restart() is True + assert svc_linux.status() == "active\n" + svc_linux.uninstall() + + called = [list(c.args[0]) for c in run.call_args_list] + assert called + assert all(command[:2] == ["systemctl", "--user"] for command in called) + assert not unit_path.exists() + def test_is_active_returns_true_when_systemctl_says_active(self): from kiro_crew.service import linux as svc_linux @@ -1817,18 +1893,36 @@ class TestRestartCommandHint: """`restart_command_hint` returns a command that matches how the service is actually installed. - The bug was the update path and the Slack restart-failure hint both - hardcoding ``systemctl --user restart kirocrew``, which fails on the - system-level systemd unit. The helper centralises the correct command - per platform. + The helper follows the installed systemd scope. """ - def test_systemd_returns_sudo_systemctl(self, monkeypatch): + def test_systemd_user_unit_returns_user_systemctl(self, monkeypatch, tmp_path): from kiro_crew.service import common as svc_common + from kiro_crew.service import linux as svc_linux + unit = tmp_path / "kirocrew.service" + unit.write_text("[Unit]\n", encoding="utf-8") monkeypatch.setattr( svc_common, "current_platform", lambda: Platform.SYSTEMD ) + monkeypatch.setattr(svc_linux, "user_unit_path", lambda: unit) + assert ( + svc_common.restart_command_hint() + == f"systemctl --user restart {SERVICE_NAME}" + ) + + def test_systemd_system_unit_returns_sudo_systemctl(self, monkeypatch, tmp_path): + from kiro_crew.service import common as svc_common + from kiro_crew.service import linux as svc_linux + + monkeypatch.setattr( + svc_common, "current_platform", lambda: Platform.SYSTEMD + ) + monkeypatch.setattr( + svc_linux, + "user_unit_path", + lambda: tmp_path / "missing.service", + ) assert svc_common.restart_command_hint() == f"sudo systemctl restart {SERVICE_NAME}" def test_launchd_returns_service_aware_cli(self, monkeypatch): @@ -1847,18 +1941,6 @@ def test_unsupported_returns_service_aware_cli(self, monkeypatch): ) assert svc_common.restart_command_hint() == "kirocrew restart" - def test_never_returns_broken_user_scope_command(self, monkeypatch): - """Regression: no platform may emit the broken `systemctl --user` - string that was filed against.""" - from kiro_crew.service import common as svc_common - - for platform in Platform: - monkeypatch.setattr( - svc_common, "current_platform", lambda p=platform: p - ) - assert "systemctl --user" not in svc_common.restart_command_hint() - - class TestKirocrewBinOverride: def test_service_bin_override_wins_over_which(self, monkeypatch): monkeypatch.setenv("KIROCREW_SERVICE_BIN", "/opt/wrapper/kirocrew") @@ -4235,6 +4317,23 @@ def test_systemd_reports_the_unit_when_present(self, monkeypatch, tmp_path): unit.write_text("[Unit]\n", encoding="utf-8") monkeypatch.setattr(controller, "current_platform", lambda: Platform.SYSTEMD) monkeypatch.setattr(controller.linux, "UNIT_PATH", unit) + monkeypatch.setattr( + controller.linux, + "user_unit_path", + lambda: tmp_path / "missing-user.service", + ) + assert controller.installed_unit_path() == unit + + def test_systemd_reports_the_user_unit_when_present(self, monkeypatch, tmp_path): + unit = tmp_path / "kirocrew.service" + unit.write_text("[Unit]\n", encoding="utf-8") + monkeypatch.setattr(controller, "current_platform", lambda: Platform.SYSTEMD) + monkeypatch.setattr(controller.linux, "user_unit_path", lambda: unit) + monkeypatch.setattr( + controller.linux, + "UNIT_PATH", + tmp_path / "missing-system.service", + ) assert controller.installed_unit_path() == unit def test_launchd_reports_the_plist_when_present(self, monkeypatch, tmp_path): @@ -4247,6 +4346,11 @@ def test_launchd_reports_the_plist_when_present(self, monkeypatch, tmp_path): def test_absent_definition_is_not_installed(self, monkeypatch, tmp_path): monkeypatch.setattr(controller, "current_platform", lambda: Platform.SYSTEMD) monkeypatch.setattr(controller.linux, "UNIT_PATH", tmp_path / "nope.service") + monkeypatch.setattr( + controller.linux, + "user_unit_path", + lambda: tmp_path / "nope-user.service", + ) assert controller.installed_unit_path() is None def test_unsupported_platform_is_not_installed(self, monkeypatch): diff --git a/test/test_service_selinux.py b/test/test_service_selinux.py index 822d5c5d9598..419a79a28fde 100644 --- a/test/test_service_selinux.py +++ b/test/test_service_selinux.py @@ -10,8 +10,6 @@ from __future__ import annotations import os -import shlex -from pathlib import Path from unittest.mock import MagicMock, patch import pytest @@ -431,6 +429,12 @@ class TestStartFailureCoversWhatThePreflightCannotProve: def _restart_fails(monkeypatch, *, enforcing): monkeypatch.setenv("USER", "tester") monkeypatch.setattr(svc_linux.os, "geteuid", lambda: 1000, raising=False) + monkeypatch.setattr(svc_linux, "_user_manager_available", lambda: False) + monkeypatch.setattr( + svc_linux, + "user_unit_path", + lambda: svc_linux.UNIT_PATH.parent / ".missing-user.service", + ) # The gate finds nothing: this is precisely the wrapper case. monkeypatch.setattr(svc_linux.selinux, "blocks_system_unit", lambda _p: (False, "allowed")) monkeypatch.setattr(svc_linux.selinux, "is_enforcing", lambda: enforcing) @@ -442,7 +446,7 @@ def run(argv, **_kw): return run - def test_enforcing_host_gets_the_selinux_hypothesis_and_remedy(self, monkeypatch): + def test_enforcing_host_gets_the_selinux_hypothesis(self, monkeypatch): run = self._restart_fails(monkeypatch, enforcing=True) with ( patch( @@ -478,25 +482,6 @@ def test_enforcing_host_gets_the_selinux_hypothesis_and_remedy(self, monkeypatch assert "systemctl --user enable --now" not in msg assert "loginctl enable-linger" not in msg - def test_the_hint_is_much_shorter_than_the_proven_refusal(self, monkeypatch): - """A hypothesis must not cost the operator as much text as a finding.""" - monkeypatch.setenv("USER", "tester") - monkeypatch.setattr(svc_linux.selinux, "is_enforcing", lambda: True) - with ( - patch( - "kiro_crew.service.common.shutil.which", - return_value="/home/tester/.local/bin/kirocrew", - ), - patch.object(svc_linux, "_home_for_user", return_value="/home/tester"), - ): - hint = svc_linux.selinux_start_failure_hint() - refusal = svc_linux.selinux_refusal("a proven denial") - - # Measured on this tree: 15 lines vs 68. The bound is what stops the - # remedy (or another wall of prose) drifting back onto the guess path. - assert len(hint.splitlines()) <= 20, "the hypothesis path must stay compact" - assert len(refusal.splitlines()) > len(hint.splitlines()) * 3 - def test_non_enforcing_host_gets_no_selinux_noise(self, monkeypatch): """A restart failure on a host without SELinux must read exactly as before.""" run = self._restart_fails(monkeypatch, enforcing=False) @@ -519,21 +504,6 @@ def test_hint_is_empty_off_the_enforcing_path(self, monkeypatch): monkeypatch.setattr(svc_linux.selinux, "is_enforcing", lambda: False) assert svc_linux.selinux_start_failure_hint() == "" - def test_only_the_proven_refusal_carries_the_remedy(self, monkeypatch): - """The remedy belongs behind a proven denial, not ahead of a guess.""" - monkeypatch.setenv("USER", "tester") - monkeypatch.setattr(svc_linux.selinux, "is_enforcing", lambda: True) - with ( - patch( - "kiro_crew.service.common.shutil.which", - return_value="/home/tester/.local/bin/kirocrew", - ), - patch.object(svc_linux, "_home_for_user", return_value="/home/tester"), - ): - remedy = svc_linux._user_scope_remedy() - assert remedy in svc_linux.selinux_refusal("some proven denial") - assert remedy not in svc_linux.selinux_start_failure_hint() - class TestInstallRefusesAnUnstartableSystemUnit: """install() must stop BEFORE the first write, not after enabling a @@ -543,6 +513,12 @@ class TestInstallRefusesAnUnstartableSystemUnit: def _blocked(monkeypatch, blocked=True): monkeypatch.setenv("USER", "tester") monkeypatch.setattr(svc_linux.os, "geteuid", lambda: 1000, raising=False) + monkeypatch.setattr(svc_linux, "_user_manager_available", lambda: False) + monkeypatch.setattr( + svc_linux, + "user_unit_path", + lambda: svc_linux.UNIT_PATH.parent / ".missing-user.service", + ) monkeypatch.setattr( svc_linux.selinux, "blocks_system_unit", @@ -571,7 +547,7 @@ def test_install_raises_before_touching_the_host(self, monkeypatch): assert "203/EXEC" in msg assert "policy denies init_t execute on user_home_t" in msg - def test_refusal_carries_a_pasteable_user_unit(self, monkeypatch): + def test_refusal_points_to_the_user_manager(self, monkeypatch): self._blocked(monkeypatch) with patch( "kiro_crew.service.common.shutil.which", @@ -581,135 +557,8 @@ def test_refusal_carries_a_pasteable_user_unit(self, monkeypatch): svc_linux.install() msg = str(exc.value) - # The remedy must be the user-scope unit, complete and self-contained. - assert "systemctl --user enable --now" in msg - assert "loginctl enable-linger" in msg - assert str(svc_linux.USER_UNIT_SUBDIR) in msg - assert "WantedBy=default.target" in msg - assert "ExecStart=" in msg - # Every command named must exist. `kirocrew service` has only - # install/uninstall/status, so the remedy may not invent a subcommand. - assert "kirocrew service print-unit" not in msg - - def test_refusal_names_only_real_service_subcommands(self, monkeypatch): - """Guards the class of bug where a remedy prints a command we do not - ship, which sends the operator into `invalid choice`.""" - self._blocked(monkeypatch) - with patch( - "kiro_crew.service.common.shutil.which", - return_value="/home/tester/.local/bin/kirocrew", - ): - with pytest.raises(svc_linux.ServiceInstallError) as exc: - svc_linux.install() - - real = {"install", "uninstall", "status"} - for token in str(exc.value).split("kirocrew service ")[1:]: - word = token.split()[0].strip("`.,\n") - # A pipe-joined hint like `status|uninstall` names several at once. - assert set(word.split("|")) <= real, f"unknown subcommand: {word}" - - def test_refusal_never_lets_the_pasting_shell_pick_the_account(self, monkeypatch): - """A user unit has no User=, so whoever's manager loads it runs the agent. - - `service install` runs under sudo, so the shell reading this refusal is - usually root's. If the remedy said `~` or `$USER` it would name /root and - root, and the operator would end up running untrusted agent tools as root - -- the exact thing install() refuses outright a few lines earlier. Nothing - in the remedy may be resolved by the shell that pastes it. - """ - self._blocked(monkeypatch) - with ( - patch( - "kiro_crew.service.common.shutil.which", - return_value="/home/tester/.local/bin/kirocrew", - ), - patch.object(svc_linux, "_home_for_user", return_value="/home/tester"), - ): - with pytest.raises(svc_linux.ServiceInstallError) as exc: - svc_linux.install() - - msg = str(exc.value) - assert "$USER" not in msg, "the pasting shell must not choose the account" - assert "~/" not in msg, "the pasting shell must not choose the home" - # Joined the same way the code joins it rather than hard-coded with - # forward slashes: this file is collected on Windows, where Path renders - # separators as backslashes, and a POSIX-spelled literal here fails there - # for a reason that has nothing to do with the property being tested. - expected_unit = ( - Path("/home/tester") / svc_linux.USER_UNIT_SUBDIR / (f"{SERVICE_NAME}.service") - ) - assert str(expected_unit) in msg - assert "loginctl enable-linger tester" in msg - - def test_refusal_warns_that_a_root_shell_would_run_the_agent_as_root(self, monkeypatch): - """The path names alone are not enough -- an operator pasting into the - wrong shell must be told what goes wrong, since a user unit gives no - error, it just silently runs as the wrong account.""" - self._blocked(monkeypatch) - with ( - patch( - "kiro_crew.service.common.shutil.which", - return_value="/home/tester/.local/bin/kirocrew", - ), - patch.object(svc_linux, "_home_for_user", return_value="/home/tester"), - ): - with pytest.raises(svc_linux.ServiceInstallError) as exc: - svc_linux.install() - - msg = str(exc.value) - assert "AS tester" in msg - assert "ROOT" in msg - # `sudo -u` looks like the obvious way to run as another account and - # cannot work here (no session, so no user manager to talk to). - assert "sudo -u tester` is NOT" in msg - assert "machinectl shell tester@" in msg - - def test_remedy_quotes_a_home_containing_a_space(self, monkeypatch): - """The remedy is copy-pasted verbatim, so an unquoted path word-splits. - - `mkdir -p /home/tester with space/.config/systemd/user` would create two - wrong directories and the redirect would land the unit where systemd never - looks -- an operator following the instructions exactly would end up with - no service and no error explaining why. - """ - self._blocked(monkeypatch) - spaced_home = "/home/tester with space" - with ( - patch( - "kiro_crew.service.common.shutil.which", - return_value="/home/tester/.local/bin/kirocrew", - ), - patch.object(svc_linux, "_home_for_user", return_value=spaced_home), - ): - with pytest.raises(svc_linux.ServiceInstallError) as exc: - svc_linux.install() - - msg = str(exc.value) - quoted = shlex.quote(str(Path(spaced_home) / svc_linux.USER_UNIT_SUBDIR)) - assert f"mkdir -p {quoted}" in msg - # The bare, splittable form must be gone entirely. - assert f"mkdir -p {spaced_home}" not in msg - - @pytest.mark.skipif( - os.name == "nt", - reason="shlex.quote is POSIX and quotes the backslashes in a Windows path, " - "so 'needs no quoting' is only meaningful on POSIX -- and what this renders " - "is a Linux shell snippet either way", - ) - def test_ordinary_paths_are_not_needlessly_quoted(self, monkeypatch): - """shlex.quote leaves simple paths alone; the common case must stay clean.""" - self._blocked(monkeypatch) - with ( - patch( - "kiro_crew.service.common.shutil.which", - return_value="/home/tester/.local/bin/kirocrew", - ), - patch.object(svc_linux, "_home_for_user", return_value="/home/tester"), - ): - with pytest.raises(svc_linux.ServiceInstallError) as exc: - svc_linux.install() - - assert "'" not in str(exc.value).split("mkdir -p ")[1].splitlines()[0] + assert "systemctl --user" in msg + assert "login session" in msg def test_install_proceeds_normally_when_not_blocked(self, monkeypatch): """The overwhelmingly common host must be completely unaffected.""" @@ -733,6 +582,12 @@ def test_gate_is_asked_about_the_unit_exec_path(self, monkeypatch): """It must judge the SAME binary render_unit puts in ExecStart.""" monkeypatch.setenv("USER", "tester") monkeypatch.setattr(svc_linux.os, "geteuid", lambda: 1000, raising=False) + monkeypatch.setattr(svc_linux, "_user_manager_available", lambda: False) + monkeypatch.setattr( + svc_linux, + "user_unit_path", + lambda: svc_linux.UNIT_PATH.parent / ".missing-user.service", + ) asked: list[str] = [] monkeypatch.setattr( svc_linux.selinux,