diff --git a/.gitattributes b/.gitattributes index 9135a01..77cddb2 100644 --- a/.gitattributes +++ b/.gitattributes @@ -5,3 +5,9 @@ # targets in LF-only files. *.cmd text eol=crlf *.bat text eol=crlf + +# Files packaged for Linux and FreeBSD: a CRLF would break the interpreter line +# of the init scripts and the service definitions. +packaging/linux/openrc/* text eol=lf +packaging/freebsd/* text eol=lf +*.service text eol=lf diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 6a69a41..20116f5 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -46,6 +46,11 @@ jobs: - name: Test the release tooling run: python3 scripts/release/release_tool_test.py + - name: Test the Linux and FreeBSD service setup + run: | + python3 scripts/release/service_setup_test.py + python3 scripts/release/freebsd_setup_test.py + - name: Read the version and build the Linux matrix id: meta run: | @@ -140,12 +145,17 @@ jobs: run: | mkdir -p release-out for component in server agent; do + # The maintainer scripts set the service up when the package is installed. + python3 scripts/release/release_tool.py package-scripts \ + --component "$component" --format "$FORMAT" \ + --out-dir "release-stage/scripts-$component" python3 scripts/release/release_tool.py nfpm-config \ --catalogue packaging/linux/distros.json \ --component "$component" --distro "$DISTRO" --arch "$ARCH" \ --version "$VERSION" --release "$RELEASE" \ --stage-dir release-stage --dashboard-dir dashboard/dist \ - --license-file LICENSE > "nfpm-$component.yaml" + --license-file LICENSE --packaging-dir packaging/linux \ + --scripts-dir "release-stage/scripts-$component" > "nfpm-$component.yaml" asset="$(python3 scripts/release/release_tool.py asset-name \ --component "$component" --platform "$DISTRO" --arch "$ARCH" --ext "$EXT")" nfpm package --config "nfpm-$component.yaml" --packager "$FORMAT" \ @@ -162,7 +172,8 @@ jobs: --volume "$PWD/release-out:/pkgs:ro" \ --volume "$PWD/scripts/release:/release:ro" \ --env INSTALL_CMD --env EXPECTED_VERSION="$VERSION" \ - "$IMAGE" sh /release/smoke-install.sh + --env THEWATCHER_SERVER=localhost --env ENROLLMENT_TOKEN=smoke-token \ + "$IMAGE" sh -c 'sh /release/smoke-install.sh && sh /release/smoke-service.sh' - uses: actions/upload-artifact@v4 with: @@ -207,12 +218,9 @@ jobs: Set-Content -Path $path -Value 'stand-in' } - # The runner image ships Inno Setup; install it if that ever changes. - $iscc = "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe" - if (-not (Test-Path $iscc)) { - choco install innosetup --no-progress -y - if ($LASTEXITCODE -ne 0) { throw 'choco install innosetup failed' } - } + # The runner image only ships the previous major version (6). The installers + # are built with 7, installed from a pinned, verified download (docs/adr/0006). + $iscc = & scripts/release/install-inno-setup.ps1 -Destination "$env:RUNNER_TEMP\InnoSetup" $env:THEWATCHER_VERSION = $env:VERSION foreach ($component in 'server', 'agent') { @@ -283,12 +291,9 @@ jobs: New-Item -ItemType Directory -Force release-stage/crt | Out-Null Copy-Item "$($crt.FullName)/*.dll" release-stage/crt - # The runner image may not ship Inno Setup. - $iscc = "${env:ProgramFiles(x86)}\Inno Setup 6\ISCC.exe" - if (-not (Test-Path $iscc)) { - choco install innosetup --no-progress -y - if ($LASTEXITCODE -ne 0) { throw 'choco install innosetup failed' } - } + # Inno Setup 7 from a pinned, verified download (the image ships only 6; + # docs/adr/0006). + $iscc = & scripts/release/install-inno-setup.ps1 -Destination "$env:RUNNER_TEMP\InnoSetup" # TheWatcher.iss reads the version and the component from these # variables; it refuses to compile without a component. @@ -304,6 +309,121 @@ jobs: } Get-ChildItem release-out + # The installers must leave working services behind. Install them for real + # on the runner (an administrator), check the result, upgrade, then + # uninstall. Nothing here publishes anything. + - name: Install, upgrade and uninstall the installers + shell: pwsh + run: | + $ErrorActionPreference = 'Stop' + $configDir = Join-Path $env:ProgramData 'TheWatcher' + $rule = 'TheWatcher server (agents)' + $uninstallKey = 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall' + $appIds = @{ server = '{B94E273C-BD27-4184-82A2-8F6726F6DE2E}'; agent = '{0EDA80FF-F84A-44C5-B376-F3017E8EE1E6}' } + + function Assert-That([bool]$condition, [string]$message) { + if (-not $condition) { throw "FAIL: $message" } + Write-Host "ok $message" + } + + # Runs one installer silently and fails with its setup log on a non-zero exit. + function Install-Product([string]$name, [string[]]$extra = @()) { + $log = Join-Path $env:RUNNER_TEMP "$name-setup.log" + $installer = (Resolve-Path "release-out/thewatcher-$name-windows-x86_64.exe").Path + $arguments = @('/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', "/LOG=$log") + $extra + $process = Start-Process -FilePath $installer -ArgumentList $arguments -Wait -PassThru + if ($process.ExitCode -ne 0) { + if (Test-Path $log) { Get-Content $log | Select-Object -Last 80 } + throw "FAIL: the $name installer exited with $($process.ExitCode)" + } + } + + function Uninstall-Product([string]$name) { + $entry = Get-ItemProperty (Join-Path $uninstallKey "$($appIds[$name])_is1") + $uninstaller = $entry.UninstallString.Trim('"') + $process = Start-Process -FilePath $uninstaller -ArgumentList '/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART' -Wait -PassThru + Assert-That ($process.ExitCode -eq 0) "the $name uninstaller exits 0" + } + + function Config-Lines([string]$file) { Get-Content (Join-Path $configDir $file) } + + # ── Server: first install ──────────────────────────────────────────── + Install-Product 'server' + Assert-That ((Get-Service TheWatcherServer).Status -eq 'Running') 'the server service is running after a first install' + $server = Config-Lines 'TheWatcherServer.conf' + Assert-That ($server -contains 'API_HOST=127.0.0.1') 'the server API listens on loopback only' + Assert-That (($server | Where-Object { $_ -match '^ENROLLMENT_TOKEN=[0-9a-f]{48}$' }).Count -eq 1) 'the server config has a generated enrollment token' + Assert-That (($server | Where-Object { $_ -match '^SERVER_SECRET_KEY=.{40}$' }).Count -eq 1) 'the server config has a CURVE secret key' + Assert-That ((sc.exe qfailure TheWatcherServer | Out-String) -match 'RESTART') 'the server service restarts on failure' + + $firewall = Get-NetFirewallRule -DisplayName $rule + Assert-That (@($firewall).Count -eq 1) 'there is one firewall rule for the agents' + Assert-That ("$($firewall.Profile)" -eq 'Domain, Private') 'the rule covers only the Domain and Private profiles' + Assert-That ("$($firewall.Direction)" -eq 'Inbound' -and "$($firewall.Action)" -eq 'Allow') 'the rule allows inbound traffic' + $ports = @(($firewall | Get-NetFirewallPortFilter).LocalPort) | Sort-Object + Assert-That (($ports -join ',') -eq '5555,5556') 'the rule opens TCP 5555 and 5556' + $program = ($firewall | Get-NetFirewallApplicationFilter).Program + Assert-That ($program -like '*\TheWatcherServer.exe') 'the rule is tied to the server executable' + + # ── Server: upgrade over itself ────────────────────────────────────── + $before = (Get-FileHash (Join-Path $configDir 'TheWatcherServer.conf')).Hash + Install-Product 'server' + Assert-That ((Get-Service TheWatcherServer).Status -eq 'Running') 'the server service is running again after an upgrade' + Assert-That ((Get-FileHash (Join-Path $configDir 'TheWatcherServer.conf')).Hash -eq $before) 'an upgrade leaves the server config unchanged' + Assert-That (@(Get-NetFirewallRule -DisplayName $rule).Count -eq 1) 'an upgrade does not add a second firewall rule' + + # ── Server: a replacement that stopped half way ───────────────────── + # RegisterService says to close services.msc and run the installer again when the old + # service is still marked for deletion. By then the service is gone, and the run must + # still count as an upgrade. Make that state: the marker the installer leaves, no + # service, the rule narrowed by the administrator, and the service stopped. + Stop-Service TheWatcherServer + sc.exe delete TheWatcherServer | Out-Null + Assert-That ($null -eq (Get-Service TheWatcherServer -ErrorAction SilentlyContinue)) 'the service is gone before the installer runs again' + Set-Content -Path (Join-Path $configDir 'TheWatcherServer.replacing') -Value 'replacing' + Set-NetFirewallRule -DisplayName $rule -RemoteAddress '10.0.0.0/8' + $narrowed = "$((Get-NetFirewallRule -DisplayName $rule | Get-NetFirewallAddressFilter).RemoteAddress)" + Assert-That ($narrowed -ne 'Any') 'the test narrowed the rule' + Install-Product 'server' + Assert-That ($null -ne (Get-Service TheWatcherServer -ErrorAction SilentlyContinue)) 'the service is registered again' + Assert-That ((Get-Service TheWatcherServer).Status -eq 'Stopped') 'an interrupted replacement does not start a service the administrator had stopped' + $after = "$((Get-NetFirewallRule -DisplayName $rule | Get-NetFirewallAddressFilter).RemoteAddress)" + Assert-That ($after -eq $narrowed) 'an interrupted replacement keeps the firewall rule the administrator narrowed' + Assert-That (-not (Test-Path (Join-Path $configDir 'TheWatcherServer.replacing'))) 'the marker is removed once the service is registered again' + Start-Service TheWatcherServer + + # ── Agent: no server address ───────────────────────────────────────── + Install-Product 'agent' + $agent = Get-Service TheWatcherAgent + Assert-That ($agent.Status -eq 'Stopped') 'an agent without a server address is not started' + Assert-That ($agent.StartType -eq 'Manual') 'an agent without a server address does not start at boot' + Assert-That (-not (Test-Path (Join-Path $configDir 'TheWatcherAgent.conf'))) 'no agent config is made up without an address' + + # ── Agent: finished later with /SERVER= ────────────────────────────── + # The token goes in the environment, not in a switch: Setup's /LOG= writes its + # whole command line to the log. It has spaces and a trailing backslash on + # purpose; the installer must hand it to the agent exactly as given. + $token = 'correct horse battery staple\' + $env:ENROLLMENT_TOKEN = $token + Install-Product 'agent' @('/SERVER=localhost') + Remove-Item Env:ENROLLMENT_TOKEN + $agent = Get-Service TheWatcherAgent + Assert-That ($agent.Status -eq 'Running') 'the agent runs once it is given a server address' + Assert-That ($agent.StartType -eq 'Automatic') 'the agent starts at boot once it is configured' + $agentConf = Config-Lines 'TheWatcherAgent.conf' + Assert-That ($agentConf -contains 'THEWATCHER_SERVER=localhost') 'the agent config has the server address' + Assert-That ($agentConf -contains "ENROLLMENT_TOKEN=$token") 'the agent config has the enrollment token exactly as given' + $setupLog = Get-Content (Join-Path $env:RUNNER_TEMP 'agent-setup.log') -Raw + Assert-That (-not $setupLog.Contains('horse battery')) 'the setup log does not contain the enrollment token' + + # ── Uninstall ──────────────────────────────────────────────────────── + Uninstall-Product 'agent' + Uninstall-Product 'server' + Assert-That ($null -eq (Get-Service TheWatcherServer -ErrorAction SilentlyContinue)) 'the server service is removed' + Assert-That ($null -eq (Get-Service TheWatcherAgent -ErrorAction SilentlyContinue)) 'the agent service is removed' + Assert-That ($null -eq (Get-NetFirewallRule -DisplayName $rule -ErrorAction SilentlyContinue)) 'the firewall rule is removed' + Assert-That (Test-Path (Join-Path $configDir 'TheWatcherServer.conf')) 'uninstalling keeps the server config and its keys' + - uses: actions/upload-artifact@v4 with: name: release-windows @@ -354,6 +474,8 @@ jobs: set -e sh ./meson-build-bsd.sh sh scripts/release/freebsd-package.sh + # Installs the packages and checks that the services come up. + sh scripts/release/freebsd-smoke.sh - uses: actions/upload-artifact@v4 with: diff --git a/CHANGELOG.md b/CHANGELOG.md index b57c8d2..511243a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,245 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ## [Unreleased] +## [0.10.3] - 2026-12-01 + +### Added + +- An architecture decision record (ADR) register in `docs/adr/` + ([index](docs/adr/index.md)): a template, the rules for when a record is + written, and records of the decisions made in this release (the service setup, + the secure first-install defaults, the agent restart policy, the unconfigured + agent, the installer compiler and when a FreeBSD package stops its service). + `scripts/check_adr.py` + (`meson test adr_register`) fails when a record lacks its status, date or + sections, when the numbering has a gap, or when the index and the records + disagree; `scripts/check_adr_test.py` (`meson test adr_checker`) tests the + checker itself. The index is parsed by splitting rows on `|`, not with one + regular expression over the whole row, whose backtracking grew quadratically + with the length of a row (SonarCloud `python:S8786`). A row that links a record + but does not have its four columns is reported, not skipped, so a stale extra + row beside the correct one cannot pass. +- Installing a package or installer now sets the service up, with no manual + steps (docs/installation.md, docs/releases.md): + - **Linux packages** (deb, rpm, Arch, Alpine) create the service user + (`thewatcher`, `thewatcher-agent`), a private config directory, the config + and, for the server, the data directory; install a systemd unit (OpenRC + script on Alpine); enable the service and start it when an init system is + running; and open TCP 5555 and 5556 in a running `ufw` or `firewalld` (server + first install only). Upgrades restart a running service, never change the + config, never enable a service the administrator disabled and never add a + removed firewall rule back. An install that stops part way leaves a marker + (`/var/lib/thewatcher-setup/.incomplete`, a directory only root + can write, because the service user owns its config directory and could aim a + symlink there at a file root would truncate), so the package manager's retry + (an upgrade) finishes it. Removal stops and disables the service, takes back + the ufw or firewalld rules the server install added, and keeps the config, data + and user. An install retried after a run that left the service group behind + uses that group instead of failing at the same step. + - **FreeBSD packages** install an rc.d script and create the user and config; + `pkg` post-install sets `thewatcher_server_enable` / `thewatcher_agent_enable` + in `rc.conf` when they were never set. They do not start the service: `pkg` + ends every process a package script leaves running, so a service started + there was dead before the install finished. Start it with + `service thewatcher_server start` afterwards (for a configured agent, + `service thewatcher_agent start`), or `onestart` instead of `start` when + `rc.conf` has the service set to `NO` or empty (rc.subr refuses a plain + `start` for a service that is not enabled). The `rc.conf` value is the + administrator's choice: `NO` is kept, and so is an empty value. + When `rc.conf` cannot be written (an image build, a restricted jail) the + helper says so and how to enable the service by hand, instead of reporting it + enabled and then disabled. A package stops its service only when it is removed, + from `post-deinstall` (pkg runs the old `pre-deinstall` during an upgrade, and + `post-install` cannot start the service again), so an upgrade leaves a running + service running and says how to restart it. The rc.d scripts start `daemon` + with `-f`, so `service ... start` over ssh returns instead of waiting for the + service to exit (this made the FreeBSD release job run until its timeout), and + send what the service prints to stderr to syslog. + - **Windows installers** create the config, register the service with + restart-on-failure recovery actions and start it on a first install. The + server installer adds an inbound firewall rule for TCP 5555 and 5556 on the + Domain and Private profiles for the server program (first install only; the + uninstaller removes it). The agent installer has a wizard page for the server + address and enrollment token, and `/SERVER=` plus the `ENROLLMENT_TOKEN` + environment variable for silent installs (not a switch: Setup's `/LOG=` + writes its whole command line to the log). An upgrade keeps the existing agent + config, and says so when `/SERVER=` was given and not applied. When setup stops + before the service is registered, the advice shown creates the config first. + A replacement of the registration that stops half way (the old service is + still marked for deletion) leaves a `.replacing` marker in + `C:\ProgramData\TheWatcher`, so the run that finishes it is still an upgrade: a + firewall rule you narrowed stays, and a service you had stopped stays stopped. + - The agent needs the server address: Linux and FreeBSD packages read + `THEWATCHER_SERVER` and `ENROLLMENT_TOKEN` from the environment or use an + existing config. Without an address the agent service is enabled but not + started (a manual start type on Windows), and the install says how to finish. + `/usr/lib/thewatcher/service-setup-agent agent install` (FreeBSD: + `/usr/local/libexec/thewatcher/service-setup-agent agent setup`) can be run + again at any time to finish it. Each package installs its own copy of the + helper, because the server and the agent are installed side by side and + `dpkg`, `pacman`, `apk` and `pkg` refuse a file two packages own. +- `TheWatcherServer --init-config` and `TheWatcherAgent --init-config` create + the config file when it does not exist and exit. An existing config is never + changed, so the command is safe to run on every package upgrade. The server + config it creates has a generated CURVE key pair, `API_HOST=127.0.0.1` and a + random `ENROLLMENT_TOKEN`; `--db-path` keeps the database outside the config + directory. The agent requires `--server-host` and takes `--enrollment-token`. + Nothing is written when a value is refused. See docs/configuration.md. +- `common/crypto.hpp` `generate_hex_token()` returns random bytes from libsodium + as lowercase hex, used for the enrollment token. +- Tests: `scripts/check_init_config.py` (`cli_init_config`) runs the built + binaries; `scripts/release/service_setup_test.py` and + `scripts/release/freebsd_setup_test.py` run the setup helpers against a fake + root with stand-in commands; `release_tool_test.py` covers the package + scripts and the nfpm and pkg manifests. CI installs the packages in clean + distro containers (`smoke-service.sh`), in the FreeBSD VM (`freebsd-smoke.sh`) + and on the Windows runner, and runs the services. + +### Changed + +- The Windows installers are built with **Inno Setup 7** (7.1.1), up from 6. The + release workflow installs it with `scripts/release/install-inno-setup.ps1`, which + downloads the pinned version from the vendor's GitHub release and refuses to run + it unless its SHA-256 and Authenticode signature match, because the runner + image only ships 6.7.1 and an unpinned compiler could change between runs. The + installer script compiles unchanged with both versions + ([ADR-0006](docs/adr/0006-build-the-windows-installers-with-inno-setup-7.md)). +- The Linux package metadata depends on the package that provides `useradd` + (`passwd`, `shadow-utils`, `shadow`) and, on Alpine, on `openrc`. +- `release_tool.py nfpm-config` needs `--packaging-dir` and `--scripts-dir`, and + the new `package-scripts` command writes the maintainer scripts the package + runs; the FreeBSD manifest carries `post-install` and `post-deinstall` scripts. +- `.gitattributes` keeps LF line endings for the packaged service files. + +### Fixed + +- The Python tooling and its tests (`release_tool.py`, `service_setup_test.py`, + `freebsd_setup_test.py`, `release_tool_test.py`, `check_adr_test.py`) no longer + pass `newline=` to `Path.write_text`, which needs Python 3.10: Rocky 9 has 3.9, + so four test files failed there. They write bytes instead, and a test rejects + `newline=` on `write_text` and `read_text` anywhere under `scripts/`. +- FreeBSD: the setup no longer starts the service from the `pkg` script (see + above), the smoke test starts it as an administrator would, and the helper + reads the service-scoped `rc.conf` value (`sysrc -s`), keeps an empty + `*_enable` value, and tells an agent's operator to add `ENROLLMENT_TOKEN` when + the server has one. +- Linux and FreeBSD: the config is checked and its mode set while root owns its + directory, and a config that is a symbolic link is left alone with a warning, + so a compromised service cannot aim a root `chmod` at another file. +- Linux: firewall changes no longer reload firewalld (which dropped runtime-only + rules), use the default zone and remember it, are written in both the running + and the permanent configuration, and removal deletes only what the install + recorded, in the recorded zone. Debian maintainer scripts start and restart the + service through `deb-systemd-invoke`, which honours `policy-rc.d`, and + `prerm deconfigure` no longer stops the service, which `postinst + abort-deconfigure` could not undo. +- Linux and FreeBSD: root takes the config directory before its mode is set (the + other way round, the service user could make it writable in the gap). Linux + firewalld: a permanent rule that is not loaded is opened in the running firewall + too, and a removal that fails while the port is still open is reported and keeps + the record, while one that fails because the port is gone is not an error. +- Linux: a firewall rule that could not be added at install is remembered in a file + of its own (`.firewall-pending`, one ` ` line per failed port, + scope `both`, `permanent` or `running`) and retried by the next upgrade for exactly + that port and configuration (a permanent rule an administrator removed since is not + added back, and the port is not opened because only the running add had failed), which changes nothing else about the + service, so a service the administrator stopped or disabled stays that way and a + rule they removed for a port that did open is not added back. An upgrade that finds + no firewall running keeps the list. The install only says a port is open from anywhere when + this run opened it. `ufw` outbound and routed rules (`ALLOW OUT`, `ALLOW FWD`) no + longer count as the inbound rule. A firewalld query that fails is "unknown", not + "absent": nothing is added for that port, which stays on the pending list and is + added, recorded and later removable once the query works, and a retry after a + permanent add that worked and a running add that failed now owns the running rule + too. +- Linux: a retry works only on the firewall that failed (`ufw` lines are ` ufw`), + so a ufw rule the administrator deleted is not added back because firewalld failed; + with firewalld down at removal, a running-only record is dropped (that rule is gone + with firewalld) and no permanent removal is advised for it, and only the permanent + rule stays recorded for the rest. +- Linux firewall retry state: each pending entry (` []`) is + cleared only by its own firewall, so a `ufw` entry waits while only firewalld runs; + the zone an attempt started in is stored and used by the retry; a failed + default-zone lookup keeps the original scope; a running retry waits when the owned + permanent rule cannot be queried; and a permanent retry whose running rule is gone + waits too (a firewalld reload drops running rules as well as a removal does), with a + warning, instead of opening the port or cancelling the retry. + Once the running rule is confirmed absent the install stops owning it (the record is + trimmed) and the pending entry carries a `runtime-gone` flag instead, so a rule the + administrator adds later is never removed with the package. +- Windows: a first install whose setup stopped after the service was registered + still owes the firewall rule; the recovery advice starts the service only once its + config exists and then removes the `.pending` reminder; the kept-config note names + `SERVER_ADDRESS` and `ENROLLMENT_ADDRESS` as well as `THEWATCHER_SERVER`; and the + agent address and token are only checked when a config is being created, so an + upgrade is not stopped by an environment variable it does not use. +- FreeBSD: the rc scripts check the configured config path in `start_precmd` and pass it + as one quoted argument, so a path with a space works (rc.subr splits `required_files` + and the evaluated command line on spaces). The path is also escaped for the evaluation (a dollar sign, + backtick, quote or backslash in it stays literal). The package removal hook stops a service + only when the pid file's process is a `daemon(8)` whose retitled process name + (`daemon: /usr/local/bin/TheWatcher[] (daemon)`) names that component's + binary (another service's supervisor is left alone; the `-P` argument is not in what + `ps` shows for a supervisor), and says how to stop it when + it is still running after 30 seconds. The install notes give `onerestart` for a service + started with `onestart`. Linux firewall retries remember which firewall ran during the + run (one that starts or stops in between neither drops nor restores entries), and the + firewalld message names each port's zone. The Windows installer stops a replacement + before anything is removed if the replacement marker cannot be written, and a setup that + fails after recording a start restarts the services and clears those records. + A service that was running is recorded as owed a start (its `.pending` file) before the old + registration is removed, not only when its start fails, so a setup cut off in between does + not leave it mistaken for one the administrator stopped; a cancelled install clears it + once the service is positively reported RUNNING again (and keeps it if the restart failed + or the state cannot be told). +- The nfpm and wrap downloads retry six times with curl's doubling wait (about a minute) + instead of five times 2 seconds apart, which a GitHub release download answering HTTP 500 for + longer than ten seconds failed the whole fedora-43 release job. +- The smoke tests give the agent 20 seconds and the server 50, and the FreeBSD one + starts and checks the agent after the reinstall too. +- Linux firewall removal rewrites the record so it names only what could not be + taken back (a port, and only the configuration that failed or whose state is + unknown), instead of keeping every entry after a partial failure. +- Linux firewalld: the running and the permanent rule are recorded separately + (`firewalld`, `firewalld-permanent`, `firewalld-runtime`), so removal takes back + only what the install added, and a removal whose result cannot be told because + firewalld stopped answering is reported and keeps the record. +- Linux firewalld: a port that was open only in the running firewall before the + install is not closed again on removal (only the permanent rule the install added + is recorded and removed). The Linux and Windows guides say that an agent + installed without a server address has no config and is not started. +- Windows installers: a firewall rule or a start that failed after the service was + registered is remembered in a `*.pending` file in the config directory and + finished by the next run, the recovery message no longer advises registering a + service that exists, and an enrollment token with a character outside ASCII is + refused, because the agent's command line would change it. +- `server --init-config` refuses a database path that starts or ends with + whitespace (the loader would trim it and open another file); the smoke test + compares the saved host and token literally and gives the server 40 seconds; + the helper path check uses `fullmatch`; tests read fixtures as bytes and check + that an install finished before checking its cleanup. The FreeBSD agent hint + uses `service onestart` (rc.subr refuses a plain start while the service + is not enabled), the Windows kept-config note says to delete the pinned server + key lines when changing the server, and the OpenRC agent message says the + config is missing or not readable. +- `scripts/release/freebsd-smoke.sh` prints the process list, service status, + directory modes, service logs and a five-second foreground run of the server + when a check fails, so a service that is "not running" on the FreeBSD runner + can be told apart from a server that crashes at start. + +### Known limits + +- The agent is restarted after a failure by systemd and by the Windows service + recovery actions. Alpine (OpenRC) and FreeBSD do not supervise it at all: a + supervisor that restarts it however it exits would also restart it after a + `DISCONNECT` command, which ends it on purpose (issue #85), so a crashed agent + stays down there. +- On Debian and Ubuntu, installing a package again after `apt remove` counts as + an upgrade (dpkg remembers the removed version), so the service stays disabled: + run `systemctl enable --now thewatcher-server.service` (or + `thewatcher-agent.service` for the agent package). RPM, Arch and Alpine + packages and FreeBSD set the service up again by themselves, as a new install. + ## [0.10.2] - 2026-12-01 ### Added diff --git a/README.md b/README.md index afc9b1d..e48f639 100644 --- a/README.md +++ b/README.md @@ -68,7 +68,8 @@ the agent writes back to `TheWatcherAgent.conf`. - [Installation](docs/installation.md): build outputs, install locations, Windows service installation, non-Windows supervision. - [Rolling Release](docs/releases.md): prebuilt Linux, FreeBSD, and Windows - packages published from `main`, how to install and verify them. + packages published from `main`, how to install and verify them. Installing + one sets the service up (an agent only needs to be told where its server is). - [Configuration](docs/configuration.md): every server and agent config option, default config paths, generated files, and command-line overrides. - [Running](docs/running.md): foreground start/stop, service start/stop, @@ -94,6 +95,9 @@ the agent writes back to `TheWatcherAgent.conf`. - [Logging](docs/logging.md): log file locations and startup diagnostics. - [Service Installation](docs/service-installation.md): focused Windows service command reference. +- [Architecture decisions](docs/adr/index.md): the decisions that would + otherwise be easy to undo by accident, with the alternatives that were + rejected and why. ## Main Targets diff --git a/agent/config.cpp b/agent/config.cpp index e112e4c..f6460a8 100644 --- a/agent/config.cpp +++ b/agent/config.cpp @@ -46,6 +46,16 @@ namespace return buf; } + // Gives a new agent its own id and CURVE keypair. libsodium must already be + // initialised (thewatcher::crypto::init()). + void assign_new_identity(AgentConfig& cfg) + { + const auto kp = thewatcher::crypto::generate_curve_keypair(); + cfg.agent_id = generate_uuid(); + cfg.agent_public_key = kp.public_key_z85; + cfg.agent_secret_key = kp.secret_key_z85; + } + std::string trim(std::string value) { while (!value.empty() && std::isspace(static_cast(value.front()))) @@ -88,9 +98,10 @@ namespace // Extracts the host from "host", "host:port", "tcp://host:port" or the // IPv6 forms "[addr]" / "[addr]:port". The result keeps the brackets so it // can be put straight back into an endpoint. An unbracketed IPv6 address - // is ambiguous with host:port and is rejected (issue #98). Throws + // is ambiguous with host:port and is rejected (issue #98). The result is + // empty when the value names no host (":5555", "tcp://"). Throws // std::invalid_argument. - std::string host_from_server_value(const std::string& value) + std::string parse_server_host(const std::string& value) { auto host = trim(value); constexpr std::string_view tcp_prefix = "tcp://"; @@ -115,6 +126,16 @@ namespace throw std::invalid_argument("IPv6 server addresses must be written in brackets, e.g. [::1]:5555: " + value); if (colons == 1) host = host.substr(0, host.find(':')); + return host; + } + + // parse_server_host with the long-standing THEWATCHER_SERVER rule: a value + // that names no host means this machine. The installer does not use it, + // because an agent pointed at 127.0.0.1 by accident looks configured and + // monitors nothing (create_installed). + std::string host_from_server_value(const std::string& value) + { + const auto host = parse_server_host(value); return host.empty() ? "127.0.0.1" : host; } @@ -247,10 +268,7 @@ AgentConfig AgentConfig::load_or_create(const std::filesystem::path& path) LOG_INFO("Agent config does not exist; creating a new config with generated identity"); AgentConfig cfg; cfg.config_path = path.string(); - cfg.agent_id = generate_uuid(); - auto kp = thewatcher::crypto::generate_curve_keypair(); - cfg.agent_public_key = kp.public_key_z85; - cfg.agent_secret_key = kp.secret_key_z85; + assign_new_identity(cfg); if (path.has_parent_path()) std::filesystem::create_directories(path.parent_path()); @@ -259,6 +277,59 @@ AgentConfig AgentConfig::load_or_create(const std::filesystem::path& path) return cfg; } +// Package and installer entry point (--init-config). Package scripts run it on +// every install and upgrade, so an existing file is never read or written: it +// may hold the server key the agent learned at enrollment. The server address +// is required because an agent that silently defaults to 127.0.0.1 looks +// configured and monitors nothing. Everything is validated before the file is +// written. +bool AgentConfig::create_installed(const std::filesystem::path& path, const std::string& server_host, + const std::string& enrollment_token) +{ + LOG_FUNCTION_TRACE + std::error_code ec; + const auto existing = std::filesystem::status(path, ec); + // "Not found" is the answer we want; any other error means we cannot tell + // whether a config is there, and overwriting one would lose the identity. + if (ec && existing.type() != std::filesystem::file_type::not_found) + throw std::runtime_error("Cannot inspect " + path.string() + ": " + ec.message()); + if (std::filesystem::exists(existing)) + { + LOGF_INFO("Agent config %s already exists; leaving it unchanged", path.string().c_str()); + return false; + } + + const auto host = trim(server_host); + if (host.empty()) + throw std::invalid_argument("The server host must not be empty"); + // A line break would start a new KEY=VALUE line; a space or control + // character would make an endpoint ZeroMQ cannot connect to. + if (std::any_of(host.begin(), host.end(), [](unsigned char c) { + return std::isspace(c) != 0 || std::iscntrl(c) != 0; + })) + throw std::invalid_argument("The server host must not contain spaces or control characters"); + require_single_line("ENROLLMENT_TOKEN", enrollment_token); + + // Throws std::invalid_argument for an unbracketed IPv6 address (issue #98). + // A value with only a port or a scheme names no host; THEWATCHER_SERVER would + // read that as 127.0.0.1, but an installer must not guess. + const auto parsed_host = parse_server_host(host); + if (parsed_host.empty()) + throw std::invalid_argument("The server host names no host (only a port or a scheme was given)"); + + thewatcher::crypto::init(); + AgentConfig cfg; + cfg.config_path = path.string(); + cfg.server_address = endpoint_for_host(parsed_host, 5555); + cfg.enrollment_address = endpoint_for_host(parsed_host, 5556); + cfg.enrollment_token = enrollment_token; + assign_new_identity(cfg); + + LOGF_INFO("Creating agent config %s for a new installation", path.string().c_str()); + cfg.save(path); + return true; +} + // Applies the non-empty command-line overrides for this process and keeps the // file values they replace, so save() does not persist them (issue #150). void AgentConfig::apply_cli_overrides(const std::string& server, const std::string& enrollment, diff --git a/agent/config.hpp b/agent/config.hpp index c61fe8e..db749a3 100644 --- a/agent/config.hpp +++ b/agent/config.hpp @@ -54,6 +54,20 @@ struct AgentConfig void apply_cli_overrides(const std::string& server, const std::string& enrollment, const std::string& server_key); static AgentConfig load_or_create(const std::filesystem::path& path); + // For package and installer scripts (--init-config): creates the config at + // path for an agent that reports to server_host and returns true. The file + // has a new agent id and CURVE keypair, THEWATCHER_SERVER, and + // ENROLLMENT_TOKEN when enrollment_token is non-empty. An existing file is + // neither read nor written and the function returns false, so it is safe on + // every upgrade. server_host is a host name, an IPv4 address or a bracketed + // IPv6 address; a port or tcp:// prefix is accepted and ignored, as for + // THEWATCHER_SERVER. Throws std::invalid_argument for an empty host or one + // with whitespace or control characters, a value that names no host (only a + // port or a scheme) or an unbracketed IPv6 address, and + // std::runtime_error for a token with a line break or a path that cannot be + // inspected or written. Nothing is written when it throws. + static bool create_installed(const std::filesystem::path& path, const std::string& server_host, + const std::string& enrollment_token); // Writes the config as KEY=VALUE lines, atomically: an owner-only temp file // in the same directory is flushed and renamed over the target (it holds // the CURVE secret key). Throws std::runtime_error if any value contains diff --git a/agent/main.cpp b/agent/main.cpp index f21596d..13cb03b 100644 --- a/agent/main.cpp +++ b/agent/main.cpp @@ -40,6 +40,11 @@ static void print_usage(const char* prog) << " --log-level Log file level: trace, debug, info, notice, warning, error,\n" << " critical or off (overrides LOG_LEVEL in the config)\n" << " --genkey Generate a CURVE keypair and print it, then exit\n" + << " --init-config Create the config if it does not exist, then exit. Needs\n" + << " --server-host. An existing config is never changed.\n" + << " --server-host With --init-config: host name or IP address of the server\n" + << " (the agent uses ports 5555 and 5556 on it)\n" + << " --enrollment-token With --init-config: the server's ENROLLMENT_TOKEN\n" << " --service Run under Windows Service Control Manager\n" << " --service-name Service name (default: TheWatcherAgent)\n" << " --install-service Install the Windows service and exit\n" @@ -67,7 +72,10 @@ int main(int argc, char* argv[]) std::string override_server_key; std::string cli_log_level; std::string service_name = "TheWatcherAgent"; + std::string init_server_host; + std::string init_enrollment_token; bool do_genkey = false; + bool init_config = false; bool allow_insecure = false; bool service_mode = false; bool install_service = false; @@ -90,6 +98,18 @@ int main(int argc, char* argv[]) { do_genkey = true; } + else if (arg == "--init-config") + { + init_config = true; + } + else if (arg == "--server-host" && i + 1 < argc) + { + init_server_host = argv[++i]; + } + else if (arg == "--enrollment-token" && i + 1 < argc) + { + init_enrollment_token = argv[++i]; + } else if (arg == "--service") { service_mode = true; @@ -147,7 +167,40 @@ int main(int argc, char* argv[]) return 0; } + // The host and token only mean something to --init-config; ignoring them + // would leave an administrator believing the agent was pointed somewhere. + if (!init_config && (!init_server_host.empty() || !init_enrollment_token.empty())) + { + std::cerr << "--server-host and --enrollment-token can only be used with --init-config\n"; + return 1; + } + fs::path cfg_path = config_path.empty() ? AgentConfig::default_path() : fs::path(config_path); + + // Package scripts and installers run this on every install and upgrade. It + // comes before the log file is opened so that a script running as root + // leaves nothing behind that the service user cannot write. + if (init_config) + { + if (init_server_host.empty()) + { + std::cerr << "--init-config needs --server-host \n"; + return 1; + } + try + { + const bool created = AgentConfig::create_installed(cfg_path, init_server_host, init_enrollment_token); + std::cout << (created ? "Created " : "Config already exists, left unchanged: ") << cfg_path.string() + << "\n"; + return 0; + } + catch (const std::exception& e) + { + std::cerr << "Cannot create the config: " << e.what() << "\n"; + return 1; + } + } + auto log_path = log_path_for_config(cfg_path, "TheWatcherAgent.log"); auto& logger = thewatcher::logging::SingleLog::GetInstance(); logger.SetConsoleLogLevel(thewatcher::logging::LogLevel::L_INFO); diff --git a/agent_tests/config_test.cpp b/agent_tests/config_test.cpp index 606fd56..c05d498 100644 --- a/agent_tests/config_test.cpp +++ b/agent_tests/config_test.cpp @@ -780,3 +780,290 @@ SCENARIO("Agent config LOG_* keys control the log level and rotation (issue #99) fs::remove(path); } } + +// ── Package and installer config creation (--init-config) ──────────────────── + +namespace +{ +fs::path installed_config_dir(const char* name) +{ + auto dir = thewatcher::test::process_temp_dir().path() / name; + fs::remove_all(dir); + fs::create_directories(dir); + return dir; +} + +std::string slurp(const fs::path& path) +{ + std::ifstream f(path, std::ios::binary); + return {std::istreambuf_iterator(f), std::istreambuf_iterator()}; +} +} // namespace + +SCENARIO("A package creates the agent config from the server address it was given") +{ + GIVEN("a clean directory, a server host name and an enrollment token") + { + auto path = installed_config_dir("agent-installed-config") / "TheWatcherAgent.conf"; + + WHEN("the installer creates the config") + { + const bool created = AgentConfig::create_installed(path, "monitor.example.internal", "0123456789abcdef"); + + THEN("a file is created") + { + REQUIRE(created); + REQUIRE(fs::exists(path)); + } + + AND_THEN("the agent derives the data and enrollment endpoints from the host") + { + auto cfg = AgentConfig::load_or_create(path); + REQUIRE(cfg.server_address == "tcp://monitor.example.internal:5555"); + REQUIRE(cfg.enrollment_address == "tcp://monitor.example.internal:5556"); + } + + AND_THEN("the enrollment token is stored") + { + REQUIRE(AgentConfig::load_or_create(path).enrollment_token == "0123456789abcdef"); + } + + AND_THEN("the agent has its own identity and CURVE keypair already") + { + auto cfg = AgentConfig::load_or_create(path); + REQUIRE_FALSE(cfg.agent_id.empty()); + REQUIRE(cfg.agent_public_key.size() == 40); + REQUIRE(cfg.agent_secret_key.size() == 40); + } + } + } +} + +SCENARIO("A package may create an agent config without an enrollment token") +{ + GIVEN("a clean directory and a server host but no token") + { + auto path = installed_config_dir("agent-installed-no-token") / "TheWatcherAgent.conf"; + + WHEN("the installer creates the config") + { + const bool created = AgentConfig::create_installed(path, "monitor.example.internal", ""); + + THEN("no ENROLLMENT_TOKEN line is written, so a server without a token still accepts it") + { + // An empty read would also lack the token, so require the file first. + REQUIRE(created); + REQUIRE(fs::is_regular_file(path)); + const auto text = slurp(path); + REQUIRE_FALSE(text.empty()); + REQUIRE(text.find("ENROLLMENT_TOKEN") == std::string::npos); + } + } + } +} + +SCENARIO("A package upgrade never changes an existing agent config") +{ + GIVEN("an enrolled agent whose config holds the server key it learned") + { + auto path = installed_config_dir("agent-installed-existing") / "TheWatcherAgent.conf"; + const std::string enrolled = "THEWATCHER_SERVER=old.example.internal\nSERVER_PUBLIC_KEY=pinned\n"; + { + std::ofstream f(path, std::ios::binary); + f << enrolled; + } + + WHEN("the installer asks for the config to be created with another host") + { + const bool created = AgentConfig::create_installed(path, "other.example.internal", "token"); + + THEN("nothing is created") + { + REQUIRE_FALSE(created); + } + + AND_THEN("the file is byte for byte what the agent left") + { + REQUIRE(slurp(path) == enrolled); + } + } + } +} + +SCENARIO("A package accepts a bracketed IPv6 server address") +{ + GIVEN("a clean directory and an IPv6 literal host") + { + auto path = installed_config_dir("agent-installed-ipv6") / "TheWatcherAgent.conf"; + + WHEN("the installer creates the config") + { + AgentConfig::create_installed(path, "[2001:db8::10]", ""); + + THEN("both endpoints keep the brackets") + { + auto cfg = AgentConfig::load_or_create(path); + REQUIRE(cfg.server_address == "tcp://[2001:db8::10]:5555"); + REQUIRE(cfg.enrollment_address == "tcp://[2001:db8::10]:5556"); + } + } + } +} + +SCENARIO("A package refuses to guess when it cannot tell whether an agent config exists") +{ + GIVEN("a config path that cannot be inspected, because it is a symbolic link to itself") + { + auto path = installed_config_dir("agent-installed-uninspectable") / "TheWatcherAgent.conf"; + // Following the link never ends, so stat fails with a loop error rather than "no such + // file". That is the case where creating a config could overwrite one that is there, + // and the config holds the agent's identity and the server key it pinned. + std::error_code link_error; + fs::create_symlink(path.filename(), path, link_error); + if (link_error) + SKIP("this host cannot create symbolic links: " << link_error.message()); + + WHEN("the installer asks for the config to be created") + { + THEN("it is refused, and the message says the path could not be inspected") + { + REQUIRE_THROWS_WITH(AgentConfig::create_installed(path, "monitor.example.internal", ""), + Catch::Matchers::ContainsSubstring("Cannot inspect")); + } + + AND_THEN("the link is still there: nothing was created over it") + { + REQUIRE_THROWS(AgentConfig::create_installed(path, "monitor.example.internal", "")); + REQUIRE(fs::is_symlink(path)); + } + } + } +} + +// Kept apart from the scenario above, whose symbolic link may be impossible to make (Windows +// without the privilege): a skip there must not hide this one. +SCENARIO("A config path with no file is an ordinary first install, not a failure to inspect") +{ + GIVEN("a config path whose file simply does not exist yet") + { + auto path = installed_config_dir("agent-installed-not-yet-there") / "TheWatcherAgent.conf"; + + WHEN("the installer asks for the config to be created") + { + THEN("the config is created") + { + REQUIRE(AgentConfig::create_installed(path, "monitor.example.internal", "")); + REQUIRE(fs::exists(path)); + } + } + } +} + +SCENARIO("A package refuses a server address or token that would corrupt the config") +{ + GIVEN("a clean directory") + { + auto path = installed_config_dir("agent-installed-invalid") / "TheWatcherAgent.conf"; + + WHEN("the host is empty") + { + THEN("it is refused and no file is written") + { + REQUIRE_THROWS(AgentConfig::create_installed(path, "", "token")); + REQUIRE_FALSE(fs::exists(path)); + } + } + + WHEN("the host contains a line break that would start a new KEY=VALUE line") + { + THEN("it is refused and no file is written") + { + REQUIRE_THROWS(AgentConfig::create_installed(path, "evil.example\nALLOW_INSECURE=1", "")); + REQUIRE_FALSE(fs::exists(path)); + } + } + + WHEN("the host contains a space") + { + THEN("it is refused, because it would make an unusable endpoint") + { + REQUIRE_THROWS(AgentConfig::create_installed(path, "monitor example", "")); + REQUIRE_FALSE(fs::exists(path)); + } + } + + WHEN("the host is an unbracketed IPv6 address") + { + THEN("it is refused as ambiguous with host:port (issue #98)") + { + REQUIRE_THROWS(AgentConfig::create_installed(path, "2001:db8::10", "")); + REQUIRE_FALSE(fs::exists(path)); + } + } + + WHEN("the token contains a line break") + { + THEN("it is refused and no file is written") + { + REQUIRE_THROWS(AgentConfig::create_installed(path, "monitor.example.internal", "a\nALLOW_INSECURE=1")); + REQUIRE_FALSE(fs::exists(path)); + } + } + } +} + +SCENARIO("A package refuses a server address that names no host") +{ + GIVEN("a clean directory") + { + auto path = installed_config_dir("agent-installed-no-host") / "TheWatcherAgent.conf"; + + WHEN("the address is only a port, only a scheme, or a scheme and a port") + { + THEN("it is refused instead of becoming the default 127.0.0.1, and no file is written") + { + for (const auto* address : {":5555", "tcp://", "tcp://:5555", " :5555 "}) + { + INFO("address: '" << address << "'"); + REQUIRE_THROWS_AS(AgentConfig::create_installed(path, address, ""), std::invalid_argument); + REQUIRE_FALSE(fs::exists(path)); + } + } + } + } +} + +SCENARIO("A package still accepts the supported forms of a server address") +{ + GIVEN("a clean directory") + { + auto path = installed_config_dir("agent-installed-forms") / "TheWatcherAgent.conf"; + + WHEN("the address is a tcp:// URL with a port") + { + AgentConfig::create_installed(path, "tcp://monitor.example.internal:6000", ""); + + THEN("the host is used and the agent's own ports apply") + { + auto cfg = AgentConfig::load_or_create(path); + REQUIRE(cfg.server_address == "tcp://monitor.example.internal:5555"); + REQUIRE(cfg.enrollment_address == "tcp://monitor.example.internal:5556"); + } + } + } + + GIVEN("another clean directory") + { + auto path = installed_config_dir("agent-installed-forms-ipv4") / "TheWatcherAgent.conf"; + + WHEN("the address is an IPv4 address with a port") + { + AgentConfig::create_installed(path, "192.0.2.10:5555", ""); + + THEN("the address is used as the host") + { + REQUIRE(AgentConfig::load_or_create(path).server_address == "tcp://192.0.2.10:5555"); + } + } + } +} diff --git a/common/crypto.hpp b/common/crypto.hpp index 0267d39..891b51d 100644 --- a/common/crypto.hpp +++ b/common/crypto.hpp @@ -125,4 +125,25 @@ inline std::string server_public_key_fingerprint(const std::string& public_key_z return out.str(); } +// Returns `byte_count` bytes from libsodium's CSPRNG as 2 * byte_count lowercase +// hex characters. Used for secrets that are typed or pasted (the enrollment +// token), where Z85 punctuation would be awkward. Throws std::invalid_argument +// for 0 bytes (an empty token would switch the check off) or more than 1024. +inline std::string generate_hex_token(std::size_t byte_count) +{ + constexpr std::size_t max_token_bytes = 1024; + if (byte_count == 0 || byte_count > max_token_bytes) + throw std::invalid_argument("Token length must be between 1 and 1024 bytes"); + + init(); + std::string raw(byte_count, '\0'); + randombytes_buf(raw.data(), raw.size()); + + std::ostringstream out; + out << std::hex << std::setfill('0'); + for (const auto byte : raw) + out << std::setw(2) << static_cast(static_cast(byte)); + return out.str(); +} + } // namespace thewatcher::crypto diff --git a/common_tests/crypto_test.cpp b/common_tests/crypto_test.cpp index 4069128..b7c5d3a 100644 --- a/common_tests/crypto_test.cpp +++ b/common_tests/crypto_test.cpp @@ -59,3 +59,41 @@ SCENARIO("CURVE Z85 decoding rejects invalid key material") } } } + +SCENARIO("Random hex tokens are generated for enrollment") +{ + GIVEN("libsodium is initialised") + { + init(); + + WHEN("a token of 24 random bytes is generated") + { + const auto token = generate_hex_token(24); + + THEN("it is 48 lowercase hexadecimal characters") + { + REQUIRE(token.size() == 48); + REQUIRE(token.find_first_not_of("0123456789abcdef") == std::string::npos); + } + } + + WHEN("two tokens are generated") + { + const auto first = generate_hex_token(24); + const auto second = generate_hex_token(24); + + THEN("they differ") + { + REQUIRE(first != second); + } + } + + WHEN("a token of zero bytes is requested") + { + THEN("the request is rejected, because an empty token would disable the check") + { + REQUIRE_THROWS_AS(generate_hex_token(0), std::invalid_argument); + } + } + } +} diff --git a/dashboard/package-lock.json b/dashboard/package-lock.json index fe17129..0234b6c 100644 --- a/dashboard/package-lock.json +++ b/dashboard/package-lock.json @@ -1,12 +1,12 @@ { "name": "thewatcher-dashboard", - "version": "0.10.2", + "version": "0.10.3", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "thewatcher-dashboard", - "version": "0.10.2", + "version": "0.10.3", "dependencies": { "@vitejs/plugin-react": "^5.1.1", "lucide-react": "^0.562.0", diff --git a/dashboard/package.json b/dashboard/package.json index a6cb709..1cb0331 100644 --- a/dashboard/package.json +++ b/dashboard/package.json @@ -1,6 +1,6 @@ { "name": "thewatcher-dashboard", - "version": "0.10.2", + "version": "0.10.3", "private": true, "type": "module", "engines": { diff --git a/docs/01-progress-tracker.md b/docs/01-progress-tracker.md index 16af8e6..99da48e 100644 --- a/docs/01-progress-tracker.md +++ b/docs/01-progress-tracker.md @@ -46,14 +46,24 @@ Status: in progress. packages for the major Linux distros (x86_64 and aarch64), FreeBSD `.pkg` files, and separate Windows server and agent installers, so every platform has one server package and one agent package (see [Rolling Release](releases.md)). +- An architecture decision record register (`docs/adr/`) holds the decisions + that would otherwise be easy to undo by accident; see [the index](adr/index.md). +- Installing a package or installer sets the service up with no manual steps: + service user, config (`--init-config`: CURVE keys, loopback API, generated + enrollment token), systemd unit, OpenRC script, rc.d script or Windows + service, enabled and started, with the agent ports opened in a running Linux + firewall or the Windows firewall (see [Installation](installation.md)). ### TODO - Confirm the first runs of the rolling release workflow on GitHub (container builds, nfpm packaging, FreeBSD `pkg create`, publish) and fix what they turn up; the container and VM steps cannot run on a developer workstation. -- Ship service units (systemd, OpenRC, rc.d) and a service user in the release - packages, and sign the packages and `SHA256SUMS`. +- Confirm the first CI runs of the service setup (the distro container smoke + tests, the FreeBSD VM smoke test and the Windows install step). The Windows + installer script compiles with Inno Setup 6.7.4 and 7.1.1, but what the + installers do when run is only exercised in CI. +- Sign the packages and `SHA256SUMS`. - Add a repeatable alpha smoke-test checklist that covers server startup, agent enrollment, metrics submission, dashboard login, alert creation, and command dispatch. diff --git a/docs/adr/0000-record-architecture-decisions.md b/docs/adr/0000-record-architecture-decisions.md new file mode 100644 index 0000000..41ad3ea --- /dev/null +++ b/docs/adr/0000-record-architecture-decisions.md @@ -0,0 +1,63 @@ +# ADR-0000: Record architecture decisions + +Status: Accepted +Date: 2026-12-01 + +## Context + +Some decisions in this project cannot be seen in the code that follows from them. +A server that listens on loopback only, an agent that is not restarted by its +supervisor, and an installer that is pinned to one compiler version all look like +oversights to someone who does not know that the alternative was tried or +considered and rejected. The usual outcome is that the choice is "fixed" later by +a person who had no way to know why it was made. + +The records that exist do not carry that reason. `CHANGELOG.md` says what changed +in each version, not what was rejected or why. Commit messages and pull request +descriptions say it once, for the people reviewing it, and are hard to find from +the code afterwards. `docs/architecture.md` describes how the system works, not +why it is not built another way. + +## Decision + +A decision is recorded in `docs/adr/` when a future reader would otherwise be +likely to undo it by accident: + +- a constraint the code depends on but does not state locally; +- a rejected alternative that looks better in isolation; +- a rule about how future code must be written. + +A choice with no rejected alternative is a fact, not a decision, and does not get +a record. Neither does something an external specification dictates. + +Each record is made when the decision is made, in the same commit as the change, +and says what was not checked as plainly as what was. + +## Alternatives considered + +- **Rely on commit messages and `CHANGELOG.md`.** Both already exist and are + required. They are the right place for what changed, and they are poor at + answering "why not the obvious alternative" from the code, because nothing + links the code to them. +- **Explain the reasons in code comments.** Comments are the right place for a + reason that applies to one line, and the project uses them for that. A decision + that spans an installer, a service definition and a config default has no one + place to carry its comment, and a comment next to one of them does not stop + someone changing the other. +- **Add the rationale to `docs/architecture.md`.** That document describes the + system as it is. Mixing the history of rejected options into it makes it longer + and harder to keep correct, and its sections are rewritten as the system + changes, which would lose the record. + +## Consequences + +- There is one place to look before changing a default or a rule that looks + arbitrary: [the index](index.md). +- A change that overturns a recorded decision has to supersede its record, so the + reversal is deliberate and the reasons for both choices stay readable. +- Writing a record costs a few minutes at the time of the decision. `scripts/check_adr.py` + (`meson test adr_register`) fails when the register is inconsistent, so the + index cannot quietly drift from the records. +- Decisions made before this register existed are not recorded. They are added + when someone has to work out why one of them is the way it is, with the reason + as far as it can be established. diff --git a/docs/adr/0001-use-markdown-architectural-decision-records.md b/docs/adr/0001-use-markdown-architectural-decision-records.md new file mode 100644 index 0000000..59cf2f4 --- /dev/null +++ b/docs/adr/0001-use-markdown-architectural-decision-records.md @@ -0,0 +1,54 @@ +# ADR-0001: Use Markdown architectural decision records + +Status: Accepted +Date: 2026-12-01 + +## Context + +[ADR-0000](0000-record-architecture-decisions.md) decides that decisions are +recorded. This decides how, so that the records are easy to write, easy to find +from the repository, and cannot silently disagree with their index. + +## Decision + +- Each record is one Markdown file in `docs/adr/`, named `NNNN-short-title.md`: + a four-digit number in order of creation, then lowercase words joined by + hyphens. Numbers start at `0000` and have no gaps. +- It starts with the heading `# ADR-NNNN: Title`, then a `Status:` line and a + `Date:` line (both mandatory), then the sections **Context**, **Decision**, + **Alternatives considered** and **Consequences**, as in [template.md](template.md). +- Status is one of Proposed, Accepted, Rejected, Deprecated, or + `Superseded by ADR-NNNN`. Date is the day the decision was made, `YYYY-MM-DD`. +- A record is never renumbered or deleted. A decision that is replaced keeps its + record, which is marked superseded and points at the record that replaces it. +- [index.md](index.md) has one row per record with its number, title, status and + date, and is changed in the same commit as the record. +- `scripts/check_adr.py` checks all of this and runs as `meson test adr_register`. + +## Alternatives considered + +- **A wiki or the issue tracker.** Easy to write in, but away from the code: it is + not reviewed in the same pull request as the change, not versioned with it, and + not found by someone reading the repository. Nothing would link a change to its + reason. +- **A single `DECISIONS.md` file.** Simpler to start, but it grows without bound, + every change touches the same file (and conflicts), and a record cannot be linked + to from code or another record without an anchor that moves when sections are + edited. +- **A heavier template (for example one with fields for deciders, drivers and a + scored option matrix).** Those fields help in a large organisation. Here they are + extra work at the moment of the decision, which is when the record is least + likely to be written. The four sections above carry what a later reader needs. +- **No automated check.** Cheapest, but an index kept by hand is the part of a + register that goes stale first, and a stale index is worse than none because it + is trusted. + +## Consequences + +- Records are reviewed with the change that makes the decision, and + `git log -- docs/adr` is the history of the decisions. +- The format is plain enough to write by hand and to read in a terminal. +- Adding a record means two edits (the file and the index row), enforced by the + check, so forgetting one fails the test run instead of going unnoticed. +- The rules live in the check as well as in this record. If they change, change + both, and supersede this record if the change is more than a detail. diff --git a/docs/adr/0002-packages-and-installers-set-the-service-up-with-init-config.md b/docs/adr/0002-packages-and-installers-set-the-service-up-with-init-config.md new file mode 100644 index 0000000..34d8b81 --- /dev/null +++ b/docs/adr/0002-packages-and-installers-set-the-service-up-with-init-config.md @@ -0,0 +1,83 @@ +# ADR-0002: Packages and installers set the service up, using `--init-config` + +Status: Accepted +Date: 2026-12-01 + +## Context + +Until 0.10.3 the Linux and FreeBSD packages installed only the binaries and the +dashboard bundle, and the Windows installers registered a service they did not +start and created no agent config. The installation guides filled the gap with +manual steps: create a service user and directories, start the server for a few +seconds so that it writes its own config, edit that config, write a service unit, +enable it, open the firewall. That defeats the point of shipping installers. + +Two facts about the server constrain how a config can be created: + +- A server config with no CURVE key pair makes the server run **without + encryption** on the agent data port. A config written by hand or by a script + that forgets the keys is therefore not a harmless mistake. +- The server refuses a config directory that another user could replace. It + accepts one owned by root or by the user it runs as (`common/secure_file.cpp`), + so root cannot run it against a directory the service user already owns. + +## Decision + +- `TheWatcherServer --init-config` and `TheWatcherAgent --init-config` create the + first config and exit. They never read or change a config that exists, and + succeed either way, so a package can run them on every upgrade. Nothing is + written when a value is refused. The server's config has a generated key pair, + the secure defaults of [ADR-0003](0003-a-fresh-install-is-closed-by-default.md) + and, with `--db-path`, a database outside the config directory. The agent's + needs `--server-host` ([ADR-0005](0005-an-agent-without-a-server-address-is-installed-but-not-started.md)). +- Package scripts and installers only call that, then give the files to the + service user and enable and start the service. They write no config themselves. +- Each Linux package carries a setup helper, and so does each FreeBSD package, that + the package-manager scripts call. The manager's own arguments (dpkg's + `configure `, rpm's instance count, apk's and pacman's separate + upgrade hook) are translated into three actions: install, upgrade and remove. + The FreeBSD helper decides from state instead of from which `pkg` script called + it. Both can be run again by hand to finish a setup. +- The Linux helper tells an interrupted install from a finished one by a marker, not + by what exists. An install writes `/var/lib/thewatcher-setup/.incomplete` + first and removes it last, and an upgrade that finds the marker (or no service user) + runs as an install. The package manager retries a failed install as an upgrade, and + neither the user nor the config says whether the last one finished: an install can + stop with both in place, and an agent installed without a server address legitimately + has no config. Without the marker the helper would either leave an unenabled service + or re-enable one an administrator disabled. +- The marker is kept in a directory only root can write, not in the config directory. + That directory is handed to the service user, which could replace the marker with a + symlink to a file root owns, and the next upgrade, running as root, would truncate + it. Removing the package removes the marker. +- The helper runs `--init-config` as root in a root-owned directory and hands the + directory to the service user afterwards. + +## Alternatives considered + +- **Package scripts write the config.** Needs no new binary option and looks + simplest. Rejected: it must be written again for `sh`, for busybox `sh` and for + Inno Setup's Pascal, none of it can use the server's own config code, and a + missed key line silently turns encryption off. +- **Start the service once and let it generate the config** (what the guides said + to do). Needs a running init system, a sleep and a stop, so it cannot work in a + container or an image build and is racy everywhere. +- **Run `--init-config` as the service user** with `su` or `runuser`, which would + avoid the directory ownership dance. Rejected because those differ between + busybox and util-linux, depend on PAM, and have no Windows equivalent. The + `chown` afterwards works the same everywhere. +- **Keep the manual guides.** The status quo. + +## Consequences + +- Every upgrade script relies on `--init-config` never altering an existing + config. Changing that is a break for every platform and needs a new record. +- Config creation is unit-tested in C++ (`server_tests/config_test.cpp`, + `agent_tests/config_test.cpp`), the binaries by `scripts/check_init_config.py`, + and the helpers against a fake root with stand-in commands + (`scripts/release/service_setup_test.py`, `freebsd_setup_test.py`). +- The server's database moves out of the config directory for packaged installs. + A config made by hand with the default `DB_PATH` keeps it beside the config. +- The helpers and the generated maintainer scripts are part of the release + pipeline, which can only be exercised on GitHub for the container, FreeBSD and + Windows steps. diff --git a/docs/adr/0003-a-fresh-install-is-closed-by-default.md b/docs/adr/0003-a-fresh-install-is-closed-by-default.md new file mode 100644 index 0000000..461f8fc --- /dev/null +++ b/docs/adr/0003-a-fresh-install-is-closed-by-default.md @@ -0,0 +1,62 @@ +# ADR-0003: A fresh install is closed by default + +Status: Accepted +Date: 2026-12-01 + +## Context + +The server's built-in defaults are made for a developer on one machine: the HTTP +API listens on every interface (`API_HOST=0.0.0.0`), it is plain HTTP, the +dashboard has a default account (`thewatcher` / `look_at_me`), and agents may +enroll without a token (enrollment is trust-on-first-use, so any host that can +reach port 5556 creates a pending enrollment). An installer that starts the +service with those defaults puts all of that on the network the moment it +finishes. + +The project owner chose, on 2026-12-01, to have the packages apply safer defaults +and to open the agent ports in the firewall, so that a fresh install both works +and is not exposed. + +## Decision + +- **The API listens on loopback.** A new server config has `API_HOST=127.0.0.1`. + The dashboard is published through a TLS reverse proxy, or `API_HOST` is changed + on purpose. +- **Enrollment needs a token.** A new server config has a random 192-bit + `ENROLLMENT_TOKEN`, written as 48 hexadecimal characters and never printed. The + agent installers take the same value. +- **Only the agent ports are opened, and only on first install.** TCP 5555 and + 5556, never 8080. On Windows the rule is for the server executable on the Domain + and Private profiles only. On Linux it is added when `ufw` or `firewalld` is + running. FreeBSD and other firewalls are left alone. An upgrade never adds a rule + back, so an administrator who removed or narrowed it keeps that. + +## Alternatives considered + +- **Keep the server defaults.** The dashboard answers at once on every interface + with no extra step, which is attractive for a demo. Rejected: it exposes a + default login over plain HTTP and lets any reachable host create pending + enrollments on every host that installs the package. +- **No token.** Fewer things to carry from the server to each agent. Rejected for + the same reason: the token is what keeps arbitrary hosts from creating + pending-agent records. The cost is that an administrator must copy it. +- **Change no firewall.** The safest for the host. Rejected: on a host with an + active firewall the install would report success and the agents could not + connect, which is the failure the project is trying to remove. +- **Open the Windows rule on every profile, or without tying it to the program.** + Simpler. Rejected: it would open the monitoring ports on a Public network, and + for any program that happens to listen on them. +- **Restrict the Linux rule to a network** (the guides used `10.0.0.0/8` as an + example). A package cannot know the administrator's network, so a fixed range + would silently fail for everyone else. + +## Consequences + +- The Linux rule allows every source. That is the minimum for agents to connect and + wider than most networks need; the documentation tells the administrator to + narrow it. Narrowing it is a decision that belongs to the administrator and is + never undone by an upgrade. +- A fresh server cannot be reached from another machine's browser until a reverse + proxy or an `API_HOST` change is in place. +- Moving back to the old defaults, or dropping the token, changes the exposure of + every new install. That needs a new record that supersedes this one. diff --git a/docs/adr/0004-the-agent-is-restarted-only-after-a-failure.md b/docs/adr/0004-the-agent-is-restarted-only-after-a-failure.md new file mode 100644 index 0000000..0406ffc --- /dev/null +++ b/docs/adr/0004-the-agent-is-restarted-only-after-a-failure.md @@ -0,0 +1,52 @@ +# ADR-0004: The agent is restarted only after a failure + +Status: Accepted +Date: 2026-12-01 + +## Context + +The server can send an agent a `DISCONNECT` command. The agent then ends its own +process on purpose and exits with status 0, which also ends a Windows service +(issue #85). It is how an operator takes an agent out of service remotely. + +A service supervisor that restarts the process however it exits would start it +again, and the agent would reconnect (or enroll again) and undo the command. +systemd can tell the two cases apart with `Restart=on-failure`, which restarts +only after a non-zero exit. The other service managers the packages target have no +such setting: OpenRC's `supervise-daemon` and FreeBSD's `daemon -r` restart a +supervised process whenever it exits, by their documentation as I read it. I did +not run either of them in this session. + +## Decision + +- Under systemd, both the server and the agent use `Restart=on-failure`. +- The server is supervised on every platform. It exits non-zero on a failure and 0 + only after SIGTERM, so a supervisor that restarts it however it exits does no + harm: `supervise-daemon` on Alpine, `daemon -R 5` on FreeBSD. +- The agent is **not** supervised on Alpine or FreeBSD. It is started in the + background and stays down after a crash until someone starts it again. + +## Alternatives considered + +- **Supervise the agent everywhere with the same tool as the server.** Looks better + in isolation: a crashed agent comes back by itself, which is what an operator + expects of a monitoring agent. Rejected because a `DISCONNECT` would then be + undone five seconds later. +- **`Restart=always` under systemd.** The same problem, and the same reason for + rejecting it. +- **Change the agent so that `DISCONNECT` exits with a status of its own, and + restart on every status but that one.** This would give every platform crash + recovery without the problem. Not done: it changes the agent and what a service + manager sees, and is a change to make deliberately, not as part of an installer. + +## Consequences + +- On Alpine and FreeBSD a crashed agent leaves its host unmonitored until it is + started again. The installation guide says so. +- If the agent ever exits with a distinct status for `DISCONNECT`, supervise it + everywhere and supersede this record. Until then, do not add a restart-always + setting to an agent service definition: a test pins the OpenRC script to being + unsupervised. +- The Windows service recovery actions are set by the installer + (`sc.exe failure ... restart`, with the failure flag), and Windows applies them + to a non-zero exit. That already matches this decision. diff --git a/docs/adr/0005-an-agent-without-a-server-address-is-installed-but-not-started.md b/docs/adr/0005-an-agent-without-a-server-address-is-installed-but-not-started.md new file mode 100644 index 0000000..1942dff --- /dev/null +++ b/docs/adr/0005-an-agent-without-a-server-address-is-installed-but-not-started.md @@ -0,0 +1,63 @@ +# ADR-0005: An agent without a server address is installed but not started + +Status: Accepted +Date: 2026-12-01 + +## Context + +An agent has to know where its server is, and an installer cannot know that. The +agent's built-in default is `127.0.0.1`: if there is no config file when it starts, +it creates one that points at the local machine, generates its identity, and runs. +That agent looks configured, reports to nothing useful, and enrolls as a pending +agent with whatever happens to listen on port 5556 locally. + +The Linux package managers differ in what an install script can ask or receive: +`apt` could prompt through debconf, `dnf`, `apk` and `pacman` cannot, a package may +be installed inside an image build with nobody to ask, and some managers do not pass +the environment on to the scripts. `pkg` on FreeBSD may not either. The Windows +installer is interactive unless run silent. + +## Decision + +- The agent's server address and enrollment token come from, in this order, an + existing config; the environment (`THEWATCHER_SERVER`, `ENROLLMENT_TOKEN`) on + Linux and FreeBSD; the wizard page, or `/SERVER=` and the `ENROLLMENT_TOKEN` + environment variable, on Windows. The token is never a Windows switch: Setup's + `/LOG=` writes its whole command line to the log, which would put the token in a + file (checked: the switch's value appears in the log's `Setup command line`). +- With none of them, the agent is **installed and enabled but not started**, and + the install says in one message how to finish. Running the setup again with the + address finishes it. It is safe to repeat. +- A config that is missing keeps the service from starting at all: a systemd + `ConditionPathExists`, an OpenRC `start_pre`, an rc.d `required_files`, and on + Windows a manual start type until a config exists. Without that, the next boot + would start the agent and create the default config this record is avoiding. + OpenRC uses `start_pre` and not `required_files` because openrc-run checks + `required_files` for every command, so `rc-service stop` would fail on an agent + whose config was removed; rc.subr on FreeBSD checks it for `start` only. +- `TheWatcherAgent --init-config` requires `--server-host` and refuses to guess. + +## Alternatives considered + +- **Let the agent default to `127.0.0.1`.** Nothing to ask and nothing to fail, + and the service is always running. Rejected: it produces an agent that looks + fine and monitors nothing, and nothing reports the mistake. +- **Fail the install without an address.** The mistake cannot be made. Rejected: + it breaks image builds and unattended installs, and for the package managers that + do not hand the environment on it would fail even when the address was given. +- **Prompt during the install on every platform.** Only `apt` and the Windows + wizard can, so the behaviour would differ per platform and an unattended install + would still need the other path. +- **Require the config to exist before installing.** Supported (an existing config + is used as it is), but it cannot be the only way: it asks the administrator to + know the file format before the first install. + +## Consequences + +- An unconfigured agent needs one more command, and the message printed by the + install, and the installation guide, show it. +- A Windows agent that was installed without an address and is later configured by + running the installer again with `/SERVER=` is switched back to automatic start + and started, because that run creates the config. +- The agent's `--init-config` is stricter than the server's. That is deliberate. + The server can create a useful config from nothing and the agent cannot. diff --git a/docs/adr/0006-build-the-windows-installers-with-inno-setup-7.md b/docs/adr/0006-build-the-windows-installers-with-inno-setup-7.md new file mode 100644 index 0000000..a5b02d0 --- /dev/null +++ b/docs/adr/0006-build-the-windows-installers-with-inno-setup-7.md @@ -0,0 +1,67 @@ +# ADR-0006: Build the Windows installers with Inno Setup 7 + +Status: Accepted +Date: 2026-12-01 + +## Context + +The project ships its Windows installers, built from `packaging/windows/TheWatcher.iss`, +so the compiler that builds them is part of what ships. Until now the documentation +said "Install Inno Setup 6" (since 2026-05-01) and the release workflow looked for +`Inno Setup 6\ISCC.exe` and fell back to `choco install innosetup`. No record gives a +reason for choosing version 6 over version 7; it reads as a default that was never +revisited. + +What was checked on 2026-12-01: + +- The `windows-latest` runner image (Windows Server 2025, image 20261124) ships + Inno Setup **6.7.1** and nothing newer. +- The vendor recommends Inno Setup 7 (7.1.1, released 2026-10-28). Version 7 can be + installed beside version 6. +- The installer script compiles **unchanged** with 6.7.4 and with 7.1.1, with the + same warnings. The choice is not forced by anything in the script. +- The 7.1.1 installer is 13.7 MB, Authenticode-signed by "Pyrsys B.V." and has a + GitHub release attestation, which `gh release verify-asset` confirmed. + +The project owner decided to ship with version 7. + +## Decision + +- The release workflow builds the installers with Inno Setup 7. Because the runner + image does not ship it, `scripts/release/install-inno-setup.ps1` installs it. +- That script installs **one pinned version** (`$Version`) and refuses to run the + installer unless the download matches the pinned SHA-256 (`$Sha256`) and has a + valid Authenticode signature from the expected publisher. It is the same + approach as `scripts/release/install-nfpm.sh`. +- Changing the version means changing `$Version` and `$Sha256` together, as + described in [Rolling Release](../releases.md). + +## Alternatives considered + +- **Use the runner's Inno Setup 6.7.1.** No download and no install step, which is + attractive. Rejected: it is the previous major version, and which version the + workflow builds with would follow whatever the runner image contains on the day, + not what the project chose. +- **`choco install innosetup`**, which the workflow used as its fallback. Rejected + because it is not pinned: the version is whatever the package repository serves, a + later run could build with a different compiler, and the step looked for the + compiler at a path that names version 6. I did not check which version the package + serves. +- **Install version 7 without checking the download.** One line shorter. Rejected: a + compiler that runs in the pipeline that produces the shipped installers should be + the exact file that was reviewed. +- **Move to `x64compatible` while upgrading.** The compiler suggests it in place of + the deprecated `x64`. Not done: the two are not the same (it would also allow + installation on Windows on Arm through emulation), so it is a separate decision + about supported platforms, not part of a compiler change. + +## Consequences + +- Both Windows jobs download about 14 MB per run. +- The script fails if the vendor changes the signing publisher. That has happened: + before 6.4.2 the publisher was "Open Source Developer, Martijn Laan". Check the + new publisher with the vendor's verification page, then update `$Publisher`. +- Developers get the same compiler with the same script (`-CurrentUser` needs no + administrator rights). +- The `x64` deprecation warning remains in the compiler output until the + architecture decision above is made. diff --git a/docs/adr/0007-a-freebsd-package-stops-its-service-only-when-it-is-removed.md b/docs/adr/0007-a-freebsd-package-stops-its-service-only-when-it-is-removed.md new file mode 100644 index 0000000..a7e01b3 --- /dev/null +++ b/docs/adr/0007-a-freebsd-package-stops-its-service-only-when-it-is-removed.md @@ -0,0 +1,65 @@ +# ADR-0007: A FreeBSD package stops its service only when it is removed + +Status: Accepted +Date: 2026-12-01 + +## Context + +- `pkg` ends every process a package script leaves running, however the script + detached it. The first smoke test of the packages found a service that was dead + before the install had finished. So `post-install` cannot start the service, and + the package scripts pass `THEWATCHER_NO_START=1` so that the helper only enables it. +- pkg-script(5) for FreeBSD 14.2 gives the order of an **upgrade**: the new + `pre-install`, the old `pre-deinstall`, replace the files, the new `post-install`. + The old package's `post-deinstall` is not in the list. +- The package used to stop its service from `pre-deinstall`. An upgrade ran that + stop, and nothing could start the service again: every upgraded service stayed + down until an administrator noticed. `HANDLE_RC_SCRIPTS`, with which pkg restarts + services itself, defaults to `NO`. An automated review found this. +- Removal does need a stop. A service left running after `pkg delete` has no rc + script to stop it and a binary that no longer exists. +- Not checked: the ordering in pkg versions other than the one of FreeBSD 14.2, which + is the only release the packages are built for. The smoke test installs the + packages over themselves (`pkg add -f`) and fails if a running service is not still + running, which checks the ordering on 14.2 in the FreeBSD VM. + +## Decision + +- The package has no `pre-deinstall` script. Its `post-deinstall` script stops the + service, which only a removal runs. +- By then the rc script and the helper are gone, so the script sends SIGTERM to the + supervisor named in `/var/run/thewatcher_.pid` (the one `daemon -P` + writes; it forwards the signal to the service, as `service ... stop` does) and + waits for it to exit. It signals the process only when it is called `daemon`, because + a pid file left by a crash can name an unrelated process that has the number now. +- An upgrade therefore leaves a running service running, on the binary it was started + from. The `post-install` message says how to restart it onto the new one. + +## Alternatives considered + +- **Keep stopping in `pre-deinstall` and start again in `post-install`.** Impossible: + `pkg` ends what `post-install` starts. +- **Mark the upgrade in the new `pre-install` and let the old `pre-deinstall` skip + the stop.** `pre-install` also runs on a first install, so the marker has to be + cleared by `post-install`; one left by a failed install would make a later removal + skip the stop, so it needs an expiry too. It is state kept to learn what the + documented ordering already says. +- **Start the service after pkg has finished, from a detached job.** The job is a + descendant of the script and is ended with it, and `at` and `cron` are not part of + a default install. +- **Stop in `pre-deinstall` unless the environment says it is an upgrade.** + pkg-script(5) lists no such variable. + +## Consequences + +- An upgrade does not put a new binary to work until the service is restarted, by the + administrator or by pkg with `HANDLE_RC_SCRIPTS=YES`. `docs/installation.md` says so. +- The decision depends on pkg not running the old `post-deinstall` during an upgrade. If + a pkg version did, an upgrade would stop the service as it did before this record: no + worse than that. +- The rc.d scripts start `daemon` with `-f`. Without it a started service keeps its + caller's output open, and `service ... start` over ssh does not return; the first + complete run of the FreeBSD release job waited on it until the job timed out. +- Covered by `scripts/release/release_tool_test.py` (the generated scripts, and + `post-deinstall` run against a real process), `freebsd_setup_test.py` (the rc.d + scripts) and `freebsd-smoke.sh`. diff --git a/docs/adr/index.md b/docs/adr/index.md new file mode 100644 index 0000000..6c57613 --- /dev/null +++ b/docs/adr/index.md @@ -0,0 +1,22 @@ +# Architecture decision records + +A record is made when a decision would otherwise be likely to be undone by +accident; see [ADR-0000](0000-record-architecture-decisions.md) and +[ADR-0001](0001-use-markdown-architectural-decision-records.md) for what qualifies and +how a record is written, and [template.md](template.md) to start one. Add a row +here in the same commit as the record. Records are never renumbered or deleted: a +decision that is replaced is marked `Superseded by ADR-NNNN`. + +`scripts/check_adr.py` (`meson test adr_register`) fails when this table and the +records disagree. + +| ADR | Title | Status | Date | +| --- | --- | --- | --- | +| [0000](0000-record-architecture-decisions.md) | Record architecture decisions | Accepted | 2026-12-01 | +| [0001](0001-use-markdown-architectural-decision-records.md) | Use Markdown architectural decision records | Accepted | 2026-12-01 | +| [0002](0002-packages-and-installers-set-the-service-up-with-init-config.md) | Packages and installers set the service up, using `--init-config` | Accepted | 2026-12-01 | +| [0003](0003-a-fresh-install-is-closed-by-default.md) | A fresh install is closed by default | Accepted | 2026-12-01 | +| [0004](0004-the-agent-is-restarted-only-after-a-failure.md) | The agent is restarted only after a failure | Accepted | 2026-12-01 | +| [0005](0005-an-agent-without-a-server-address-is-installed-but-not-started.md) | An agent without a server address is installed but not started | Accepted | 2026-12-01 | +| [0006](0006-build-the-windows-installers-with-inno-setup-7.md) | Build the Windows installers with Inno Setup 7 | Accepted | 2026-12-01 | +| [0007](0007-a-freebsd-package-stops-its-service-only-when-it-is-removed.md) | A FreeBSD package stops its service only when it is removed | Accepted | 2026-12-01 | diff --git a/docs/adr/template.md b/docs/adr/template.md new file mode 100644 index 0000000..2857b60 --- /dev/null +++ b/docs/adr/template.md @@ -0,0 +1,40 @@ +# ADR-NNNN: Short title of the decision + +Status: Proposed +Date: YYYY-MM-DD + + + +## Context + +What forces the decision: the problem, the constraints, and what was true at the +time. Enough that someone who was not there can follow it. + +## Decision + +What was decided, in the present tense ("The server creates ..."). One decision +per record. + +## Alternatives considered + +Each alternative that was rejected, and why. Say what looked attractive about it, +because that is what a future reader will be tempted by. + +## Consequences + +What follows: what becomes easier, what becomes harder, what the code now relies +on, and when to revisit the decision. diff --git a/docs/architecture.md b/docs/architecture.md index f246d53..7c59e26 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -3,6 +3,10 @@ TheWatcher has four primary runtime pieces: server, agent, common protocol, and dashboard. +This document describes how the system works. Why it is not built another way, +where that would otherwise be easy to undo by accident, is in the +[architecture decision records](adr/index.md). + ## Server Files: diff --git a/docs/configuration.md b/docs/configuration.md index 55955dc..0540133 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -424,12 +424,19 @@ Agent command-line options override loaded config values for that process: --install-service --uninstall-service --genkey +--init-config +--server-host +--enrollment-token --version --help ``` `--version` prints the agent version and exits. +`--init-config` creates the config and exits; see +[Creating the first config](#creating-the-first-config). `--server-host` and +`--enrollment-token` belong to it and are refused without it. + `--server`, `--enrollment` and `--server-key` are not written to the config file: when the agent saves its config after enrollment, it keeps the file's own values for those settings. @@ -466,6 +473,8 @@ fails enrollment unless the agent runs with `--insecure` / `ALLOW_INSECURE=1`. --install-service --uninstall-service --genkey +--init-config +--db-path --version --help ``` @@ -473,6 +482,46 @@ fails enrollment unless the agent runs with `--insecure` / `ALLOW_INSECURE=1`. `--genkey` prints a new CURVE keypair and exits. `--version` prints the server version and whether PostgreSQL support was compiled in, then exits. `--log-level` sets the log file level for this process and wins over `LOG_LEVEL` in the config. +`--init-config` creates the config and exits; see +[Creating the first config](#creating-the-first-config). `--db-path` belongs to +it and is refused without it. + +### Creating the first config + +`--init-config` is what the packages and the Windows installers run to create +the first config. It does only that: it needs no database and opens no +sockets, writes no log file, and prints the path it created. + +```bash +TheWatcherServer --init-config --config /etc/thewatcher/TheWatcherServer.conf --db-path /var/lib/thewatcher/thewatcher.db +TheWatcherAgent --init-config --config /etc/thewatcher-agent/TheWatcherAgent.conf --server-host monitor.example.internal --enrollment-token 'paste-the-server-token-here' +``` + +- **An existing config is never read or changed.** The command prints that the + config exists and exits `0`, so it is safe to run on every upgrade. Delete the + file first to have a new one made (that also makes a new key pair). +- **Server.** The new config has a generated CURVE key pair, `API_HOST=127.0.0.1` + (the HTTP API is plain HTTP, so it stays off the network until a TLS reverse + proxy is in front) and a random 48-character hexadecimal `ENROLLMENT_TOKEN` + (192 bits), so agents cannot create pending enrollments without it. The token + is not printed; read it from the config as its owner. `--db-path` puts the + SQLite database somewhere other than beside the config, which the packages use + so the config directory holds only config and keys. It must be an absolute + path on one line. +- **Agent.** `--server-host` is required: a host name, an IPv4 address or a + bracketed IPv6 address (`[2001:db8::10]`), without spaces. A port or a `tcp://` + prefix is accepted and ignored, as for `THEWATCHER_SERVER`: the agent always + uses ports 5555 and 5556. The new config has the agent's id and CURVE key pair + as well. Without `--server-host` the command fails and writes nothing, because + an agent that defaults to `127.0.0.1` looks configured and monitors nothing. + `--enrollment-token` is optional, for a server that sets `ENROLLMENT_TOKEN`. +- **Nothing is written on a bad value.** A line break in any value, a relative + `--db-path` or an unbracketed IPv6 address is refused with exit status `1`. +- **Run it as the account the service runs as, or hand the directory over.** The + server accepts a config directory owned by root or by the user it runs as. + Run as root against a directory the service user already owns and it refuses, + as it does at startup; the packages create the config as root in a root-owned + directory and then hand the directory to the service user. ### Exit status diff --git a/docs/installation.md b/docs/installation.md index 921e335..dacaf02 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -114,9 +114,12 @@ are available for your deployment process. Every push to `main` publishes server and agent packages for Windows, FreeBSD and the major Linux distros to the rolling `latest` release on GitHub. Use them -instead of building from source. [Rolling Release](releases.md) lists the -assets, the install command for each package manager, and what the packages do -not include yet (service units, signatures). +instead of building from source. Installing one sets the service up: the +service user, the config, the service definition and (when it can) the running +service, with no manual steps. [Rolling Release](releases.md) lists the assets, +the install command for each package manager and what each package does; +[Windows EXE Installers](#windows-exe-installers) and +[Linux And BSD](#linux-and-bsd) below cover the details and the options. ## Dashboard Publishing @@ -293,7 +296,11 @@ The steps are: finished page repeats them, and the setup process exits with code 10 (so silent installs can detect it; `/LOG` records the message). Close `services.msc` and run the installer again if the old service is still marked - for deletion. The services that were running before the upgrade are then + for deletion. That run is still an upgrade: before it removes the old + registration the installer leaves `.replacing` in + `C:\ProgramData\TheWatcher` (deleted once the new one is in place), so a firewall + rule you narrowed stays and a service you had stopped stays stopped, although + the service is gone by then. The services that were running before the upgrade are then started; one that does not start is reported the same way (message, finished page, exit code 10), so check its log and the Windows event log and start it with `sc.exe start `. @@ -392,7 +399,18 @@ Prerequisites: builddir-release TheWatcherServer TheWatcherAgent`). - Build the dashboard with `npm.cmd run build` if the server installer should include static dashboard files. -- Install Inno Setup 6 on the packaging machine. +- Install Inno Setup 7 on the packaging machine. The release workflow uses + `scripts\release\install-inno-setup.ps1`, which downloads the pinned version + from the vendor's GitHub release, checks its SHA-256 and signature, and + installs it; run it yourself to get the same compiler (add `-CurrentUser` to + install without administrator rights): + + ```powershell + $iscc = .\scripts\release\install-inno-setup.ps1 -Destination "$env:LOCALAPPDATA\InnoSetup7" -CurrentUser + ``` + + Use the path it prints in place of `iscc.exe` below. The script also compiles + unchanged with version 6.7, but 7 is what ships. Build both installers from the repository root (the path below is relative to it; if you built the dashboard, `cd ..` out of `dashboard` first): @@ -406,49 +424,209 @@ foreach ($component in 'server', 'agent') { Each is written to `packaging\windows\dist\TheWatcher---windows.exe`. +### What installing does + +Run an installer as Administrator. It sets its service up completely: + +| | Server installer | Agent installer | +| --- | --- | --- | +| Files | `C:\Program Files\TheWatcher\server` and `\dashboard` | `C:\Program Files\TheWatcher\agent` | +| Config | `C:\ProgramData\TheWatcher\TheWatcherServer.conf`, created with a CURVE key pair, `API_HOST=127.0.0.1` and a random `ENROLLMENT_TOKEN` | `C:\ProgramData\TheWatcher\TheWatcherAgent.conf`, created from the server address and token you give it | +| Service | `TheWatcherServer`, starts at boot, restarts after a failure | `TheWatcherAgent`, starts at boot, restarts after a failure | +| Firewall | Inbound TCP 5555 and 5556 for the server program, on the Domain and Private profiles only | None (the agent only connects out) | +| Started | Yes | Yes, once it has a server address | + +`C:\ProgramData\TheWatcher` is limited to SYSTEM and Administrators, because +it holds the CURVE secret keys. The server config keeps the HTTP API on +loopback: publish the dashboard through a TLS reverse proxy, +or change `API_HOST` if you must. Read the `ENROLLMENT_TOKEN` line from the +server config as an administrator and give it to every agent. + +**The agent asks where the server is.** The agent installer shows a page for the +server host name or IP address and the enrollment token. For a silent install +pass the address as `/SERVER=` and the token in the `ENROLLMENT_TOKEN` +environment variable: + +```powershell +$env:ENROLLMENT_TOKEN = 'paste-the-server-token-here' +.\thewatcher-agent-windows-x86_64.exe /VERYSILENT /SUPPRESSMSGBOXES /NORESTART /SERVER=monitor.example.internal +``` + +The token is optional, for a server that sets no `ENROLLMENT_TOKEN`. It is an +environment variable and not a switch because Setup's `/LOG=` writes its whole +command line to the log: a `/TOKEN=` switch would put the token in a file, while +the environment is not logged. The server address may not contain spaces or +quotation marks. The token may hold spaces and quotation marks (any single line +the server accepts) and reaches the agent exactly as typed. With no server +address the agent service is installed with a manual start type and left +stopped, because an agent started with no config would create one that points at +`127.0.0.1`. Run the installer again with `/SERVER=` (and the environment +variable) to finish: it creates the config, switches the service to automatic and +starts it. + +**Upgrades.** Run a newer installer over the old one. It stops its own service, +replaces the files, registers the service again and starts it again only if it +was running. An existing config is never changed (`/SERVER=` and the token are +ignored, and the agent page is not shown), and an existing firewall rule is +left as you set it: it is added on a first install only. A service you stopped +yourself stays stopped. + +**Failures.** Setup exits with code `10` when the files were installed but the +service could not be set up or started (the config could not be created, the +service could not be registered, a firewall rule or recovery setting failed, or +the service did not start). The finished page and the setup log name the +problem; silent installs show nothing, so check the exit code. + +**Uninstall.** Settings, Apps, Installed apps. The service and the firewall rule +are removed. `C:\ProgramData\TheWatcher` stays, so reinstalling keeps the same +keys and agents do not have to enroll again. Delete it to start from nothing. + **Upgrading from the old combined installer.** Earlier versions had one installer for both. Neither new installer reuses its identity, and both refuse to run while that installation is present, so uninstall it first (Settings, Apps, Installed apps). That removes both services and keeps the configuration -in `C:\ProgramData\TheWatcher`. Then install the server and agent installers you -need. A fresh install starts nothing, so afterwards start each service you -installed, once its configuration is in place: +in `C:\ProgramData\TheWatcher`. Then run the installers you need; they find the +existing config, so the services start as soon as they are installed. -```powershell -sc.exe start TheWatcherServer -sc.exe start TheWatcherAgent -``` +Since 0.8.0 the installers reset the config directory ACL to SYSTEM and +Administrators only. Earlier installers granted `Users:modify`, so upgrades +should re-run an installer of 0.8.0 or later to pick up the restricted ACL. +The agent writes `SERVER_PUBLIC_KEY` and `SERVER_PUBLIC_KEY_FINGERPRINT` into its +config after the first approved enrollment. + +## Linux And BSD -The installers write application files under: +Linux and BSD builds use the same Meson targets. The binaries run in foreground +mode under a host supervisor. The Windows service flags intentionally return an +explanatory error outside Windows. -```text -C:\Program Files\TheWatcher +### Installing a package + +The [rolling-release packages](releases.md) set the service up when you install +them. Install the server package on the server host and the agent package on +every monitored host; the packages are separate and independent. + +| | Server package | Agent package | +| --- | --- | --- | +| Service user | `thewatcher` | `thewatcher-agent` | +| Config | `TheWatcherServer.conf`, created with a CURVE key pair, `API_HOST=127.0.0.1` and a random `ENROLLMENT_TOKEN`; `DB_PATH` in the data directory | `TheWatcherAgent.conf`, created from the server address and token you give it | +| Config directory (mode 0700) | Linux `/etc/thewatcher`, FreeBSD `/usr/local/etc/thewatcher` | Linux `/etc/thewatcher-agent`, FreeBSD `/usr/local/etc/thewatcher-agent` | +| Database | Linux `/var/lib/thewatcher`, FreeBSD `/var/db/thewatcher` | none | +| Service | systemd unit `thewatcher-server` (deb, rpm, Arch), OpenRC `thewatcher-server` (Alpine), rc.d `thewatcher_server` (FreeBSD) | the same, named `thewatcher-agent` (rc.d `thewatcher_agent`) | +| Firewall (Linux) | Opens TCP 5555 and 5556 when `ufw` or `firewalld` is running | none | + +On Linux the service is enabled for boot and started now, unless the host has no +running init system (a container, a chroot, an image build). Then it is enabled and +starts at the next boot. On Debian and Ubuntu the start goes through +`deb-systemd-invoke` inside the package scripts, so a `policy-rc.d` that denies +starting services (a container, an image build) is honoured. **FreeBSD is +different:** `pkg` ends every process a package script leaves running, so the +package enables the service in `rc.conf` but cannot leave it running; start it +once the install has finished with `service thewatcher_server start` +(`service thewatcher_server onestart` if `rc.conf` has it set to `NO` or empty, +which rc.subr otherwise refuses) +(`thewatcher_agent` for the agent). + +**Tell the agent where the server is.** An installer cannot know the server's +address, so the agent package takes it from the environment, or from a config you +wrote before installing: + +```bash +# Linux (an assignment on the command line passes the variable on). Replace the +# quoted text with the server's token; the quotes keep the shell from reading it. +sudo THEWATCHER_SERVER=monitor.example.internal ENROLLMENT_TOKEN='paste-the-server-token-here' apt install ./thewatcher-agent-debian-12-x86_64.deb ``` -Both create `C:\ProgramData\TheWatcher`; the server installer installs -`TheWatcherServer` as a Windows service and the agent installer installs -`TheWatcherAgent`, each using its existing service install flags and removing -its own service on uninstall. Since 0.8.0 the installers -reset the config directory ACL to SYSTEM and Administrators only — earlier -installers granted `Users:modify`, so upgrades should re-run the 0.8.0 -installer to pick up the restricted ACL. Edit -`C:\ProgramData\TheWatcher\TheWatcherAgent.conf` after installation so -`THEWATCHER_SERVER` points at the correct server before starting the agent -service. The agent writes `SERVER_PUBLIC_KEY` and -`SERVER_PUBLIC_KEY_FINGERPRINT` after the first approved enrollment. +`THEWATCHER_SERVER` is a host name or IP address; `ENROLLMENT_TOKEN` is the +server's, if it sets one (read it from `TheWatcherServer.conf` as root). Without +an address the service is enabled but not started, and the install prints how to +finish. Some package managers do not pass the environment to install scripts. The +setup is safe to repeat, so finish it by running the helper the packages +install, with the same variables: -## Linux And BSD +```bash +sudo THEWATCHER_SERVER=monitor.example.internal ENROLLMENT_TOKEN='paste-the-server-token-here' /usr/lib/thewatcher/service-setup-agent agent install +# FreeBSD (omit ENROLLMENT_TOKEN only if the server sets none): +sudo env THEWATCHER_SERVER=monitor.example.internal ENROLLMENT_TOKEN='paste-the-server-token-here' /usr/local/libexec/thewatcher/service-setup-agent agent setup +``` -Linux and BSD builds use the same Meson targets. Run the binaries in -foreground mode under a host supervisor such as systemd, rc.d, or another -service manager. The Windows service flags intentionally return an -explanatory error outside Windows. +The token is visible to other users on the host for the moment the command runs, +as any command-line argument is, and enrollment still needs an administrator's +approval in the dashboard. + +**Firewall.** The Linux server package opens TCP 5555 and 5556 for every source +in `ufw` or `firewalld` when one is running (in firewalld, the default zone, in the +running and the permanent configuration, with no reload, so runtime-only rules for +other services are kept). A port the firewall already allowed is left as it is. The +package records what it added, and removing it takes back exactly that, in the zone +it used. That is the minimum for agents to connect, but it is wider than most +networks need: narrow the rule to the network your agents are on. The HTTP API port (8080) is never opened; the API listens on +loopback and is published through a reverse proxy. FreeBSD +packages and hosts with another firewall are left alone: open the ports yourself. + +**Upgrades.** Install the newer package. An existing config is never changed +and a firewall rule you removed or narrowed is not added back. What happens to +the running service depends on the platform: + +- **Linux.** The service restarts only if it was running. A service you stopped + or disabled stays that way. +- **FreeBSD.** `pkg` ends any process a package script leaves running, so the + upgrade cannot start the service again, and the package does not stop it either + (it stops the service only when the package is removed). A running service keeps + running on the binary it was started from, and the install says how to restart it + onto the new one: `service thewatcher_server restart` (`thewatcher_agent` for the + agent; `onerestart` for a service you started with `onestart` while `rc.conf` has it + set to `NO`, which rc.subr refuses a plain `restart` for). `pkg` does that itself with `HANDLE_RC_SCRIPTS=YES` in `pkg.conf`; the + default is `NO`. A service that was stopped stays stopped: start it with + `service thewatcher_server start` (`onestart` for a service `rc.conf` has set to + `NO`). The setup reads `rc.conf` (and + `rc.conf.d/`): a value that is already set, even an empty one, is kept, + and a service you set to `NO` stays down. Run by hand, the helper starts or + restarts an enabled service. + +A package from before 0.10.3 never set the service up, and an install can stop +part way (a full disk, a failed `chown`). On Linux an install writes a marker, +`/var/lib/thewatcher-setup/server.incomplete` (`agent.incomplete` for the agent), +first and removes it last, and the package manager retries a failed install as an +upgrade, so an upgrade that finds no service user, or that marker, sets the service +up as for a first install and keeps whatever it finds. A service user and a config +without the marker (a finished install, or a setup you made by hand) are left alone, +including an agent that has no config because it was installed without a server +address. The marker is in a directory only root can write, not in the config +directory: the service user owns that one, and a file it could replace with a symlink +would make the upgrade, which runs as root, truncate the file the link names. If you +see the marker, an install did not finish: run the package's setup helper again (see +above). + +**Removing a package** stops and disables the service and, for the server, takes +back the ufw or firewalld rules for TCP 5555 and 5556 that the install added (a +rule you narrowed or replaced is a different rule and stays, and a rule already +gone is not an error). The config, the database and the service user stay, +because they hold the CURVE keys and your data. Installing the package again sets the service up again on RPM, Arch and Alpine +(the package manager reports a new install, so the install steps run) and on +FreeBSD (its `rc.conf` choice is kept). On Debian and Ubuntu, `apt remove` leaves +dpkg's record of the removed version, so the next install counts as an upgrade and +the service stays disabled: enable it with +`sudo systemctl enable --now thewatcher-server` (`thewatcher-agent` for the agent +package). + +**Restarts.** The server is restarted after a failure on every platform. The +agent is restarted after a failure by systemd and by the Windows service recovery +actions. A `DISCONNECT` command from the server ends the agent on purpose, and +OpenRC's `supervise-daemon` and FreeBSD's `daemon -r` restart a process however it +exits, which would undo it, so Alpine and FreeBSD do not supervise the agent at +all: a crashed agent stays down there until started again. + +**Other distros.** Packages exist only for the distros in the +[release list](releases.md). Elsewhere, build from source and write the service +definition yourself. + +### Building and running by hand + +The [Linux Installation Guide](linux-installation.md) and the +[Windows Installation Guide](windows-installation.md) walk through the same setup +step by step, including doing it by hand for a build from source. -The [rolling-release packages](releases.md) install the binaries and the -dashboard bundle but no service unit. For Linux, the -[Linux Installation Guide](linux-installation.md) has the service users, config -and systemd units for the server and the agent. On the BSDs the supervisor -definition (rc.d) is yours to write. Typical config paths: @@ -458,7 +636,10 @@ Typical config paths: ``` For daemon deployments, prefer explicit config paths owned by the service user -and pass `--config ` in the service definition. +and pass `--config ` in the service definition. To create the first config +the way the packages do, run `TheWatcherServer --init-config --config ` or +`TheWatcherAgent --init-config --config --server-host `; see +[Configuration](configuration.md#creating-the-first-config). ## Network Ports diff --git a/docs/linux-installation.md b/docs/linux-installation.md index f03b772..094de7e 100644 --- a/docs/linux-installation.md +++ b/docs/linux-installation.md @@ -14,6 +14,26 @@ The unit files below use systemd. On Alpine (OpenRC) or another supervisor, run the same command lines as the same users under that supervisor. FreeBSD is covered in [Installation](installation.md#linux-and-bsd). +> **Packages set the service up (0.10.3 and later).** Installing a server package +> creates the service user, the private config directory and the config, installs +> the systemd unit (OpenRC on Alpine), enables and starts the service and opens +> ports 5555 and 5556 in a running `ufw` or `firewalld`; see +> [Installing a package](installation.md#installing-a-package). An agent package +> does the same **when it is told the server's address** (`THEWATCHER_SERVER`, and +> `ENROLLMENT_TOKEN` if the server sets one, in the environment of the install). +> Without an address it creates the user and the unit and enables the service, but +> writes no config and does not start it: do step 3.2 to write the config, then +> start it. After a package install, skip the rest of the manual steps (2.1 to 2.4, +> 3.1 and 3.3) and use this guide to check the result, edit the config, approve +> agents and troubleshoot. The manual steps are for a build from source, or to finish +> a reinstall after `apt remove` on Debian or Ubuntu, which needs +> `systemctl enable --now thewatcher-server` (see "Removing a package" in +> [Installation](installation.md#installing-a-package)). On a host +> without a running init system (a container, a chroot, an image build) the package +> has already done them, and they would fail there (the user exists, `systemctl` +> has nothing to talk to): the service is enabled and starts at the next boot, or +> start it by hand once an init system runs. + ## What talks to what | Port | Where | Who connects | Purpose | @@ -48,8 +68,10 @@ The packages install: | Agent binary | `/usr/bin/TheWatcherAgent` | | Dashboard bundle (server package) | `/usr/share/thewatcher/dashboard` | -They install no service unit, no service user and no configuration, so the -remaining steps create those. If you built from source instead, copy the +From 0.10.3 the packages also create the service user, the private config +directory and the config, install the systemd unit (OpenRC script on Alpine) and +enable the service, as the note above says. The manual steps below (2.1 to 2.4 +and 3.1 to 3.3) are for a source build. If you built from source, copy the binaries to `/usr/local/bin` and replace `/usr/bin` with `/usr/local/bin` in the unit files below. @@ -170,15 +192,31 @@ Allow the agent ports from your monitored network only, not from everywhere. Do not open `8080` when a reverse proxy on the same host reaches it over loopback. +A package install already allows `5555/tcp` and `5556/tcp` from any source in a +running ufw or firewalld (the default zone). Add the restricted rules, then remove +those broad ones, or the restriction does nothing. Removing the package takes back +only the rules it added, so a rule you changed is left alone. + ```bash # ufw (Debian, Ubuntu) -sudo ufw allow from 10.0.0.0/8 to any port 5555 proto tcp -sudo ufw allow from 10.0.0.0/8 to any port 5556 proto tcp - -# firewalld (Fedora, Rocky, openSUSE) -sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.0.0.0/8" port port="5555" protocol="tcp" accept' -sudo firewall-cmd --permanent --add-rich-rule='rule family="ipv4" source address="10.0.0.0/8" port port="5556" protocol="tcp" accept' -sudo firewall-cmd --reload +# Each broad rule is deleted only after its restricted replacement was added. +for port in 5555 5556; do + sudo ufw allow from 10.0.0.0/8 to any port "$port" proto tcp && + sudo ufw delete allow "$port/tcp" || + echo "port $port: not changed, check the rule" >&2 +done + +# firewalld (Fedora, Rocky, openSUSE): each rule goes into the running firewall and the +# permanent configuration, so no reload is needed (a reload would also drop runtime-only +# rules you added for other services). Removing a port that is not there only warns. +for port in 5555 5556; do + for scope in "" "--permanent"; do + # The broad port is removed only if the restricted rule was added. + sudo firewall-cmd $scope --add-rich-rule="rule family=\"ipv4\" source address=\"10.0.0.0/8\" port port=\"$port\" protocol=\"tcp\" accept" && + sudo firewall-cmd $scope --remove-port="$port/tcp" || + echo "port $port ($scope): not changed, check the rules" >&2 + done +done ``` On SELinux hosts (Fedora, Rocky) a denial shows up as an AVC message. Read it diff --git a/docs/releases.md b/docs/releases.md index 8ef6fea..13a7b7c 100644 --- a/docs/releases.md +++ b/docs/releases.md @@ -78,12 +78,33 @@ sudo pkg add ./thewatcher-agent-freebsd-14-amd64.pkg ``` Package managers install the dependencies listed in the package (the C++ -runtime and, for the server on Linux, `libpq`). +runtime, the package that provides `useradd` (or `openrc` on Alpine) and, for +the server on Linux, `libpq`). + +**Installing sets the service up.** The package creates the service user and the +config, installs a service definition, enables it, starts it, and, for the +server on Linux, opens the agent ports in a running `ufw` or `firewalld`. There +is nothing to configure first, except that an **agent** needs the address of its +server, which an installer cannot guess. Give it in the environment, as in +[Installation](installation.md#installing-a-package): + +```bash +sudo THEWATCHER_SERVER=monitor.example.internal ENROLLMENT_TOKEN='paste-the-server-token-here' apt install ./thewatcher-agent-debian-12-x86_64.deb +``` + +Replace the quoted text with the server's token (the quotes stop the shell reading +it as something else). Leave `ENROLLMENT_TOKEN` out if the server sets none. + +Without `THEWATCHER_SERVER` the agent service is enabled but not started, and +the install prints the command that finishes it. On Windows, run `thewatcher-agent-windows-x86_64.exe` or -`thewatcher-server-windows-x86_64.exe` as Administrator. Each installs and -registers only its own service and uninstalls independently; see -[Installation](installation.md#windows-exe-installers). +`thewatcher-server-windows-x86_64.exe` as Administrator. Each creates its +config, registers and starts only its own service and uninstalls independently. +The agent installer asks for the server address and token (or takes `/SERVER=` +and the `ENROLLMENT_TOKEN` environment variable); the server installer also opens +its ports in the Windows firewall. +See [Installation](installation.md#windows-exe-installers). ## What is in the packages @@ -92,19 +113,18 @@ registers only its own service and uninstalls independently; see | Server binary | `/usr/bin/TheWatcherServer` | `/usr/local/bin/TheWatcherServer` | | Agent binary | `/usr/bin/TheWatcherAgent` | `/usr/local/bin/TheWatcherAgent` | | Dashboard bundle (server package) | `/usr/share/thewatcher/dashboard` | `/usr/local/share/thewatcher/dashboard` | +| Service definition | systemd unit `/usr/lib/systemd/system/thewatcher-.service` (deb, rpm, Arch) or OpenRC script `/etc/init.d/thewatcher-` (Alpine) | rc.d script `/usr/local/etc/rc.d/thewatcher_` | +| Setup helper (one copy per package, so both can be installed together) | `/usr/lib/thewatcher/service-setup-` | `/usr/local/libexec/thewatcher/service-setup-` | | Licence | `/usr/share/doc/thewatcher-/` | `/usr/local/share/doc/thewatcher-/` | +The helper is what the packages' install scripts run (it creates the user and +config and enables and starts the service) and what you run to finish an agent +setup; see [Installation](installation.md#linux-and-bsd). The config, the +database and the service user are created at install time, not shipped in the +package, so removing a package keeps them. + Not included yet: -- **Service units.** There are no systemd, OpenRC or rc.d files and no service - user. Run the binaries under your own supervisor; the - [Linux Installation Guide](linux-installation.md) has systemd units, and - [Installation](installation.md#linux-and-bsd) covers the rest. Windows has - `--install-service`, and its installers register the services. -- **Configuration.** Create the config files yourself; see - [Linux](linux-installation.md), [Windows](windows-installation.md) and - [Configuration](configuration.md). To publish the dashboard, see - [Reverse Proxy](reverse-proxy.md). - **Signatures.** Packages and `SHA256SUMS` are unsigned. Database support differs by platform. The Linux server is built with @@ -117,22 +137,39 @@ source for PostgreSQL there. `.github/workflows/release.yml` runs on pushes to `main`, on manual dispatch, and on pull requests that touch the release machinery. Only `main` publishes. -1. **prepare** runs the tooling tests, reads the version from `meson.build`, - and expands `packaging/linux/distros.json` into the build matrix. +1. **prepare** runs the tooling tests (`release_tool_test.py`, and the tests of + the service setup helpers, `service_setup_test.py` and + `freebsd_setup_test.py`, which run them against a fake root with stand-in + commands), reads the version from `meson.build`, and expands + `packaging/linux/distros.json` into the build matrix. 2. **dashboard** builds `dashboard/dist` once. 3. **linux** (one job per distro and architecture) builds and runs the full `meson test` inside that distro's container with `scripts/release/linux-build.sh`, packages with a pinned, checksum-verified - [nfpm](https://nfpm.goreleaser.com), then installs the packages into a clean - container of the same distro and checks that both binaries report the - project version. `aarch64` jobs run natively on Arm runners. + [nfpm](https://nfpm.goreleaser.com) (`release_tool.py package-scripts` + writes the maintainer scripts, `nfpm-config` the package definition), then + installs the packages into a clean container of the same distro. There + `smoke-install.sh` checks that both binaries report the project version, and + `smoke-service.sh` checks that the install created the service user, the + config and its permissions and the enabled service, then runs the server and + the agent as their service users and checks that the server receives the + agent's enrollment request (with the server's own token) and the agent sees + it pending, and finally runs an upgrade. `aarch64` jobs run + natively on Arm runners. 4. **installers** compiles both installer scripts against stand-in files in about a minute, so a script error fails fast. **windows** waits for it, then builds and tests with `meson-build.cmd`, stages the MSVC runtime DLLs and builds one Inno Setup installer per component from `packaging/windows/TheWatcher.iss` (selected with `THEWATCHER_COMPONENT`). + The compiler is Inno Setup 7, installed by + `scripts/release/install-inno-setup.ps1` from a pinned, checksum- and + signature-verified download, because the runner image only ships version 6. + It then installs both installers on the runner, checks the running services, + configs and firewall rule, upgrades the server over itself, and uninstalls. 5. **freebsd** builds and tests in a FreeBSD 14 VM with `meson-build-bsd.sh` - and creates the `.pkg` files with `pkg create`. + and creates the `.pkg` files with `pkg create`, then installs them in the VM + and checks the running services, a removal and a reinstall + (`scripts/release/freebsd-smoke.sh`). 6. **publish** needs every job above. It writes `SHA256SUMS`, uploads the assets, and only then moves the `latest` tag and rewrites the release notes, so a failed upload never advertises a build whose assets did not arrive. @@ -183,6 +220,13 @@ To change the nfpm version, update `NFPM_VERSION` and both tarball checksums in `scripts/release/install-nfpm.sh` together; the values are in the release's `checksums.txt`. +To change the Inno Setup version, update `$Version` and `$Sha256` in +`scripts/release/install-inno-setup.ps1` together. The hash is the installer's +digest on the release page at ; +check the file with `gh release verify-asset is-__ +innosetup--x64.exe --repo jrsoftware/issrc` first. Then compile both +installers (`docs/installation.md#windows-exe-installers`) before pushing. + Third-party actions (`ilammy/msvc-dev-cmd`, `vmactions/freebsd-vm`) are pinned to a full commit SHA with the release tag in a trailing comment, so their owners cannot change what runs with the workflow's token. To update one, diff --git a/docs/service-installation.md b/docs/service-installation.md index 5d803cc..d104b1e 100644 --- a/docs/service-installation.md +++ b/docs/service-installation.md @@ -5,8 +5,11 @@ operator setup is in [Installation](installation.md), [Configuration](configurat and [Running](running.md). For packaged Windows installs, use `packaging\windows\TheWatcher.iss` with -Inno Setup. The installer runs the same service install/uninstall commands -shown below and installs files under `C:\Program Files\TheWatcher`. +Inno Setup. The installers run the same service install/uninstall commands +shown below, and they also create the config, set the service to restart after +a failure and start it, so after running one nothing is left to do by hand; see +[Installation](installation.md#windows-exe-installers). Use the commands below +only for a zip of the binaries or a build from source. The server and agent run in foreground mode by default. Use the service flags only when installing or running under Windows Service Control Manager. @@ -101,5 +104,16 @@ C:\ProgramData\TheWatcher\TheWatcherAgent.log The service flags return an explanatory error outside Windows. Linux and BSD service management should be handled by the host init system, such as systemd, rc.d, or another supervisor, using normal foreground mode and explicit -`--config` paths. The [Linux Installation Guide](linux-installation.md) has -ready-made systemd units for the server and the agent. +`--config` paths. + +The [rolling-release packages](releases.md) do this for you: they install a +systemd unit, OpenRC script or rc.d script, create the service user and the +config, and enable and start the service; see +[Installation](installation.md#installing-a-package). For a build from source, +create the first config with `--init-config` +([Creating the first config](configuration.md#creating-the-first-config)) and +use the files under `packaging/linux/systemd`, `packaging/linux/openrc` and +`packaging/freebsd` as the service definitions. +The [Linux Installation Guide](linux-installation.md) walks through doing the same +by hand. + diff --git a/docs/windows-installation.md b/docs/windows-installation.md index d1c86ec..e7c6d5e 100644 --- a/docs/windows-installation.md +++ b/docs/windows-installation.md @@ -11,6 +11,20 @@ installers, ACL details) in [Installation](installation.md). All commands run in an **elevated** PowerShell (Run as administrator). +> **The installers set the service up (0.10.3 and later).** The server installer +> creates the config (a CURVE key pair, the API on loopback and an enrollment +> token), registers the service with restart-on-failure, opens ports 5555 and +> 5556 on the Domain and Private firewall profiles (first install only) and +> starts it. The agent installer asks for the server address and enrollment +> token (or takes `/SERVER=` and the `ENROLLMENT_TOKEN` environment +> variable for a silent install). Given an address it creates the config, +> registers the service and starts it; **without one** it registers the service +> with a manual start type and does not start it, and step 3 below finishes it. +> See [Installation](installation.md#windows-exe-installers). After an installer +> run, skip the first-run steps below (2.1 and the service registration) and use +> this guide to check the result, edit the config, approve agents and +> troubleshoot. Those steps are for a manual install from the binaries. + ## What talks to what | Port | Where | Who connects | Purpose | @@ -56,9 +70,11 @@ the exact command to run. Details are in | Config and logs | `C:\ProgramData\TheWatcher` (SYSTEM and Administrators only) | | Services | `TheWatcherServer`, `TheWatcherAgent` | -A fresh install registers the service but does **not** start it. Step 2.1 starts -it once, briefly, to generate its config; do not leave it running until the -config below is in place. +From 0.10.3 the server installer creates the config and starts the service, as +the note above says, so step 2.1 is only for a manual install from the binaries +(it starts the service once, briefly, to generate the config). An agent installed +without a server address is registered but not started until you give it one; +step 3 below does that. Not using the installers (a zip of the binaries, or a build from source)? Copy the binaries anywhere, then follow diff --git a/meson.build b/meson.build index 356f519..685fb1f 100644 --- a/meson.build +++ b/meson.build @@ -1,7 +1,7 @@ project( 'thewatcher', ['c', 'cpp'], - version: '0.10.2', + version: '0.10.3', default_options: [ 'cpp_std=c++20', 'default_library=static', @@ -205,6 +205,17 @@ test('release_tool', lint_python, args: [files('scripts/release/release_tool_test.py')], suite: 'release', ) +# The helper every Linux package runs to set the service up (docs/releases.md), +# tested against a fake root with stand-in commands. +test('service_setup', lint_python, + args: [files('scripts/release/service_setup_test.py')], + suite: 'release', +) +# Its FreeBSD counterpart: the pkg-script helper and the rc.d scripts. +test('freebsd_setup', lint_python, + args: [files('scripts/release/freebsd_setup_test.py')], + suite: 'release', +) # Repository-level checks. Both run under `meson test --suite thewatcher`. python_exe = find_program('python3', 'python', required: false) @@ -222,4 +233,27 @@ if python_exe.found() workdir: meson.project_build_root(), depends: [server_exe, agent_exe], ) + # The ADR register (docs/adr) is true: numbering, status, date, sections, and an + # index that matches the records. + test( + 'adr_register', + python_exe, + args: [files('scripts/check_adr.py'), meson.project_source_root()], + ) + # The checker itself: each way a register can be wrong is rejected, and a very + # long index row does not slow it down. + test( + 'adr_checker', + python_exe, + args: [files('scripts/check_adr_test.py')], + ) + # Package scripts and the Windows installers create the first config with + # --init-config and rerun it on every upgrade (docs/releases.md). + test( + 'cli_init_config', + python_exe, + args: [files('scripts/check_init_config.py')], + workdir: meson.project_build_root(), + depends: [server_exe, agent_exe], + ) endif diff --git a/packaging/freebsd/service-setup.sh b/packaging/freebsd/service-setup.sh new file mode 100755 index 0000000..fd1d76b --- /dev/null +++ b/packaging/freebsd/service-setup.sh @@ -0,0 +1,263 @@ +#!/bin/sh +# Set the installed TheWatcher component up as an rc.d service on FreeBSD. +# +# Installed by each package as /usr/local/libexec/thewatcher/service-setup- +# (a copy per package: the two are installed side by side, and pkg refuses a file +# that two packages own) and called by the pkg scripts of the server and agent +# packages (see scripts/release/release_tool.py): +# +# service-setup- server|agent setup post-install: user, +# directories, config, rc.conf, start +# service-setup- server|agent stop stop the service, by hand +# +# The package's own post-deinstall script stops the service when the package is +# removed: the files, this helper among them, are gone by then, so it signals the +# supervisor in the pid file instead (see release_tool.py). Nothing stops the +# service during an upgrade. pkg-script(5): an upgrade runs the new pre-install, the +# old pre-deinstall, replaces the files and runs the new post-install, never the old +# post-deinstall; and a service stopped before post-install cannot be started again +# from it (see below). +# +# pkg runs its old and new scripts in an order that differs between versions. So +# `setup` decides from state and not from which script called it: +# +# * The service user is created if it is missing, the directories and config if +# they are missing; nothing that exists is changed. +# * thewatcher__enable in rc.conf is the administrator's choice. It +# is set to YES only when it has never been set (a first install, or an +# upgrade from a package that never set the service up). YES or NO that is +# already there is kept, so a service the administrator disabled stays down. +# * When it is YES the service is started, or restarted if it is running so it +# picks up the new binary. The package scripts set THEWATCHER_NO_START=1 +# (see below), so only a run by hand does this. +# `stop` leaves rc.conf, the config and the user in place, so installing the +# package again and starting the service brings it back. +# +# pkg runs a package script as the reaper of every process the script leaves behind +# and kills them all when the script returns, whatever daemon(8) or nohup did. A +# service started from post-install is therefore dead before the install ends. The +# package scripts set THEWATCHER_NO_START=1, which makes `setup` enable the service +# and say how to start it, and leave a running service alone; the administrator (or +# the smoke test) starts it with `service start` once pkg has finished. An +# upgrade therefore leaves a running service running, on the binary it was started +# from, and says how to restart it onto the new one (pkg does that itself when +# HANDLE_RC_SCRIPTS is YES; the default is NO). +# +# The agent needs the address of the server, which only the administrator knows: +# THEWATCHER_SERVER= host name or IP address of the TheWatcher server +# ENROLLMENT_TOKEN= the server's ENROLLMENT_TOKEN, if it sets one +# are read from the environment, or an existing config is used. Without either, +# the agent is enabled but not started, and the message printed says how to +# finish. pkg may not pass the environment to its scripts, so run +# THEWATCHER_SERVER=YOUR_SERVER /usr/local/libexec/thewatcher/service-setup-agent agent setup +# after the install, or write the config first. +# +# Failing to create the user, directories or config is fatal. Failing to start the +# service only warns, so a jail or an image build can still install the package. +# +# Plain POSIX sh. THEWATCHER_ROOT prefixes every absolute path so the tests can +# run it against a scratch directory. + +set -eu + +usage() { + echo "usage: $0 server|agent setup|stop" >&2 + exit 2 +} + +[ $# -eq 2 ] || usage +component=$1 +action=$2 + +case "${component}" in + server) + service=thewatcher_server + user=thewatcher + binary_name=TheWatcherServer + config_dir=/usr/local/etc/thewatcher + config_name=TheWatcherServer.conf + data_dir=/var/db/thewatcher + comment="TheWatcher server" + ;; + agent) + service=thewatcher_agent + user=thewatcher-agent + binary_name=TheWatcherAgent + config_dir=/usr/local/etc/thewatcher-agent + config_name=TheWatcherAgent.conf + data_dir= + comment="TheWatcher agent" + ;; + *) usage ;; +esac +case "${action}" in + setup | stop) ;; + *) usage ;; +esac + +# The copy of this helper that this component's package installs. +helper_path="/usr/local/libexec/thewatcher/service-setup-${component}" +root="${THEWATCHER_ROOT:-}" +binary="${root}/usr/local/bin/${binary_name}" +conf_dir="${root}${config_dir}" +conf="${conf_dir}/${config_name}" +rcvar="${service}_enable" + +say() { echo "${service}: $*"; } +warn() { echo "${service}: warning: $*" >&2; } +die() { + echo "${service}: $*" >&2 + exit 1 +} + +service_running() { + service "${service}" onestatus >/dev/null 2>&1 +} + +# The administrator's rc.conf value, empty when the variable is unset or empty. The +# lookup is scoped to the service so that rc.conf.d/ counts, as it does for +# rc.d itself. sysrc fails (and complains) for an unknown variable. +rc_value() { + sysrc -s "${service}" -n "${rcvar}" 2>/dev/null || true +} + +# True when the variable has any value, an empty one included: an administrator who +# wrote ${rcvar}="" made a choice that is not the same as never having set it. +rc_defined() { + sysrc -s "${service}" -n "${rcvar}" >/dev/null 2>&1 +} + +rc_enabled() { + case "$(rc_value)" in + [Yy][Ee][Ss] | [Tt][Rr][Uu][Ee] | [Oo][Nn] | 1) return 0 ;; + *) return 1 ;; + esac +} + +ensure_user() { + if id "${user}" >/dev/null 2>&1; then + return 0 + fi + say "creating the system user ${user}" + # A group that already exists is fine; a real failure shows up in useradd. + pw groupadd -n "${user}" >/dev/null 2>&1 || true + pw useradd -n "${user}" -g "${user}" -c "${comment}" -d /nonexistent -s /usr/sbin/nologin || + die "could not create the user ${user}" +} + +# Creates the config with the binary's own --init-config, which writes the CURVE +# key pair and the secure defaults and never overwrites an existing file. The +# server always gets one. The agent needs the server's address, so without +# THEWATCHER_SERVER (and without a config already in place) it gets none. +create_config() { + if [ "${component}" = server ]; then + # The real path, not the THEWATCHER_ROOT-prefixed one: it is written into the config. + "${binary}" --init-config --config "${conf}" --db-path "${data_dir}/thewatcher.db" || + die "could not create ${config_dir}/${config_name}" + return 0 + fi + if [ -z "${THEWATCHER_SERVER:-}" ]; then + return 0 + fi + if [ -n "${ENROLLMENT_TOKEN:-}" ]; then + "${binary}" --init-config --config "${conf}" --server-host "${THEWATCHER_SERVER}" \ + --enrollment-token "${ENROLLMENT_TOKEN}" || die "could not create ${config_dir}/${config_name}" + else + "${binary}" --init-config --config "${conf}" --server-host "${THEWATCHER_SERVER}" || + die "could not create ${config_dir}/${config_name}" + fi +} + +# The server accepts a config directory owned by root or by the user it runs as, +# so while --init-config runs as root the directory is root's; it is handed over +# afterwards. +prepare_files() { + mkdir -p "${conf_dir}" + if [ -n "${data_dir}" ]; then + mkdir -p "${root}${data_dir}" + chmod 0750 "${root}${data_dir}" + fi + # The service user owns this directory from an earlier run, so it could swap the + # config for a symbolic link between the check and the chmod below, and root would + # then change the mode of whatever the link names. Taking the directory back first + # makes the check hold. Its mode is set only after that: set first, the owner could + # still make it writable (0777) in the gap, and the new owner would keep that mode. + chown root:wheel "${conf_dir}" + chmod 0700 "${conf_dir}" + if [ -L "${conf}" ]; then + warn "${config_dir}/${config_name} is a symbolic link; its mode was not changed. Replace it with a regular file" + else + if [ ! -e "${conf}" ]; then + create_config + fi + if [ -e "${conf}" ]; then + chmod 0600 "${conf}" + fi + fi + chown -R "${user}:${user}" "${conf_dir}" + if [ -n "${data_dir}" ]; then + chown -R "${user}:${user}" "${root}${data_dir}" + fi +} + +# $1 is how far the service got: "enabled, but not started" unless something else is said. +tell_agent_how_to_finish() { + say "${1:-enabled, but not started}: no server address is set." + echo " To finish, run this with your server's address (and its enrollment token, if it has one):" + echo " THEWATCHER_SERVER=YOUR_SERVER ENROLLMENT_TOKEN=YOUR_TOKEN ${helper_path} ${component} setup" + echo " or create ${config_dir}/${config_name} with a line THEWATCHER_SERVER=YOUR_SERVER (and a line" + echo " ENROLLMENT_TOKEN=YOUR_TOKEN if the server has an enrollment token) and run:" + echo " service ${service} onestart" +} + +do_setup() { + ensure_user + prepare_files + + enable_failed= + if ! rc_defined; then + if sysrc "${rcvar}=YES" >/dev/null; then + say "enabled in rc.conf (${rcvar}=YES)" + else + enable_failed=1 + warn "could not set ${rcvar}=YES in rc.conf; enable it with: sysrc ${rcvar}=YES" + fi + fi + + if [ -n "${enable_failed}" ]; then + # A read-only rc.conf (an image build, a restricted jail): nothing was recorded. It is + # neither enabled nor something an administrator chose to disable, and a service that + # is not enabled is not started. An agent still has to be told how to finish. + if [ ! -e "${conf}" ]; then + tell_agent_how_to_finish "not started" + fi + elif ! rc_enabled; then + say "disabled in rc.conf (${rcvar}); start it with: service ${service} onestart" + elif [ ! -e "${conf}" ]; then + tell_agent_how_to_finish + elif [ -n "${THEWATCHER_NO_START:-}" ]; then + # Under pkg: a service started here would be killed when the script returns. + if service_running; then + say "running; restart it onto the new version with: service ${service} restart" + else + say "enabled, not started (pkg ends processes a package script leaves running); start it with: service ${service} start" + fi + elif service_running; then + service "${service}" restart || warn "could not restart ${service}" + else + service "${service}" start || warn "could not start ${service}; see: service ${service} start" + fi +} + +do_stop() { + if service_running; then + service "${service}" onestop >/dev/null 2>&1 || warn "could not stop ${service}" + fi + # rc.conf, the config and the user stay: they hold the CURVE keys and the database. +} + +case "${action}" in + setup) do_setup ;; + stop) do_stop ;; +esac +exit 0 diff --git a/packaging/freebsd/thewatcher_agent b/packaging/freebsd/thewatcher_agent new file mode 100755 index 0000000..ef8d323 --- /dev/null +++ b/packaging/freebsd/thewatcher_agent @@ -0,0 +1,62 @@ +#!/bin/sh +# +# PROVIDE: thewatcher_agent +# REQUIRE: LOGIN NETWORKING +# KEYWORD: shutdown +# +# Add these to /etc/rc.conf (or use sysrc) to control the TheWatcher agent: +# +# thewatcher_agent_enable (bool): Set to NO by default. Set it to YES to run the agent. +# thewatcher_agent_account (str): Account the agent runs as. Default: thewatcher-agent +# thewatcher_agent_config (str): Config file. Default: /usr/local/etc/thewatcher-agent/TheWatcherAgent.conf + +. /etc/rc.subr + +name="thewatcher_agent" +rcvar="thewatcher_agent_enable" +desc="TheWatcher monitoring agent" + +load_rc_config ${name} + +: ${thewatcher_agent_enable:="NO"} +# The account is deliberately not called thewatcher_agent_user: rc.subr runs the whole +# command through su(1) for ${name}_user, so daemon would run as that account and +# could not create its pid file in /var/run. daemon -u drops privileges for the +# child only. +: ${thewatcher_agent_account:="thewatcher-agent"} +: ${thewatcher_agent_config:="/usr/local/etc/thewatcher-agent/TheWatcherAgent.conf"} + +# daemon(8) runs the agent in the background; -P is the supervisor's pid file +# that rc.subr tracks. There is deliberately no restart flag: the server can end +# the agent with a DISCONNECT command (issue #85), and a supervisor that always +# restarts it would undo that. The agent writes its own log beside its config. +# +# -f closes the agent's standard descriptors. Without it they stay on the +# starter's, and `service thewatcher_agent start` over ssh (or in a CI step) does +# not return until the agent exits. What the agent prints to stderr (a config it +# refuses, an argument it does not know) would be lost with them, so -S -m 2 -s err +# sends stderr alone to syslog; everything else it prints is in its own log. +# +# An agent installed without a server address has no config yet. rc.subr refuses +# to start it until one exists, instead of the agent creating a config that +# points at 127.0.0.1. +pidfile="/var/run/${name}.pid" +# The config is checked in start_precmd, not in required_files, and passed to the binary as one +# quoted argument: rc.subr splits required_files and the evaluated command line on spaces, so a +# configured path with a space in it would otherwise be refused or cut in two. A config that is +# not readable still stops the start. +start_precmd="thewatcher_agent_prestart" +thewatcher_agent_prestart() +{ + if [ ! -r "${thewatcher_agent_config}" ]; then + warn "${thewatcher_agent_config} is not readable" + return 1 + fi +} +command="/usr/sbin/daemon" +# rc.subr evaluates command_args, so the path is escaped for the double quotes below: a backslash, +# a double quote, a dollar sign or a backtick in it stays literal and is not expanded. +thewatcher_agent_config_escaped=$(printf '%s' "${thewatcher_agent_config}" | sed 's/[\\"$`]/\\&/g') +command_args="-f -S -m 2 -s err -T ${name} -P ${pidfile} -u ${thewatcher_agent_account} /usr/local/bin/TheWatcherAgent --config \"${thewatcher_agent_config_escaped}\"" + +run_rc_command "$1" diff --git a/packaging/freebsd/thewatcher_server b/packaging/freebsd/thewatcher_server new file mode 100755 index 0000000..915e5ce --- /dev/null +++ b/packaging/freebsd/thewatcher_server @@ -0,0 +1,58 @@ +#!/bin/sh +# +# PROVIDE: thewatcher_server +# REQUIRE: LOGIN NETWORKING +# KEYWORD: shutdown +# +# Add these to /etc/rc.conf (or use sysrc) to control the TheWatcher server: +# +# thewatcher_server_enable (bool): Set to NO by default. Set it to YES to run the server. +# thewatcher_server_account (str): Account the server runs as. Default: thewatcher +# thewatcher_server_config (str): Config file. Default: /usr/local/etc/thewatcher/TheWatcherServer.conf + +. /etc/rc.subr + +name="thewatcher_server" +rcvar="thewatcher_server_enable" +desc="TheWatcher monitoring server" + +load_rc_config ${name} + +: ${thewatcher_server_enable:="NO"} +# The account is deliberately not called thewatcher_server_user: rc.subr runs the whole +# command through su(1) for ${name}_user, so daemon would run as that account and +# could not create its pid file in /var/run. daemon -u drops privileges for the +# child only. +: ${thewatcher_server_account:="thewatcher"} +: ${thewatcher_server_config:="/usr/local/etc/thewatcher/TheWatcherServer.conf"} + +# daemon(8) supervises the server: -R 5 starts it again five seconds after it +# exits (the server exits 1 on a fatal error and 0 only on SIGTERM, which +# daemon forwards when the service is stopped), and -P is the supervisor's pid +# file that rc.subr tracks. The server writes its own log beside its config. +# +# -f closes the server's standard descriptors. Without it they stay on the +# starter's, and `service thewatcher_server start` over ssh (or in a CI step) does +# not return until the server exits. What the server prints to stderr (a config +# it refuses, an argument it does not know) would be lost with them, so -S -m 2 -s err +# sends stderr alone to syslog; everything else it prints is in its own log. +pidfile="/var/run/${name}.pid" +# The config is checked in start_precmd, not in required_files, and passed to the binary as one +# quoted argument: rc.subr splits required_files and the evaluated command line on spaces, so a +# configured path with a space in it would otherwise be refused or cut in two. A config that is +# not readable still stops the start. +start_precmd="thewatcher_server_prestart" +thewatcher_server_prestart() +{ + if [ ! -r "${thewatcher_server_config}" ]; then + warn "${thewatcher_server_config} is not readable" + return 1 + fi +} +command="/usr/sbin/daemon" +# rc.subr evaluates command_args, so the path is escaped for the double quotes below: a backslash, +# a double quote, a dollar sign or a backtick in it stays literal and is not expanded. +thewatcher_server_config_escaped=$(printf '%s' "${thewatcher_server_config}" | sed 's/[\\"$`]/\\&/g') +command_args="-f -S -m 2 -s err -T ${name} -R 5 -P ${pidfile} -u ${thewatcher_server_account} /usr/local/bin/TheWatcherServer --config \"${thewatcher_server_config_escaped}\"" + +run_rc_command "$1" diff --git a/packaging/linux/distros.json b/packaging/linux/distros.json index 37ec65a..19e4052 100644 --- a/packaging/linux/distros.json +++ b/packaging/linux/distros.json @@ -6,7 +6,7 @@ "image": "docker.io/library/debian:12", "format": "deb", "arches": ["x86_64", "aarch64"], - "depends": ["libc6", "libstdc++6", "libgcc-s1"], + "depends": ["libc6", "libstdc++6", "libgcc-s1", "passwd"], "server_depends": ["libpq5"], "install_cmd": "apt-get update && apt-get install -y /pkgs/*.deb" }, @@ -15,7 +15,7 @@ "image": "docker.io/library/ubuntu:22.04", "format": "deb", "arches": ["x86_64", "aarch64"], - "depends": ["libc6", "libstdc++6", "libgcc-s1"], + "depends": ["libc6", "libstdc++6", "libgcc-s1", "passwd"], "server_depends": ["libpq5"], "install_cmd": "apt-get update && apt-get install -y /pkgs/*.deb" }, @@ -24,7 +24,7 @@ "image": "docker.io/library/ubuntu:24.04", "format": "deb", "arches": ["x86_64", "aarch64"], - "depends": ["libc6", "libstdc++6", "libgcc-s1"], + "depends": ["libc6", "libstdc++6", "libgcc-s1", "passwd"], "server_depends": ["libpq5"], "install_cmd": "apt-get update && apt-get install -y /pkgs/*.deb" }, @@ -33,7 +33,7 @@ "image": "registry.fedoraproject.org/fedora:43", "format": "rpm", "arches": ["x86_64", "aarch64"], - "depends": ["libstdc++", "libgcc"], + "depends": ["libstdc++", "libgcc", "shadow-utils"], "server_depends": ["libpq"], "install_cmd": "dnf install -y /pkgs/*.rpm" }, @@ -42,7 +42,7 @@ "image": "quay.io/rockylinux/rockylinux:9", "format": "rpm", "arches": ["x86_64", "aarch64"], - "depends": ["libstdc++", "libgcc"], + "depends": ["libstdc++", "libgcc", "shadow-utils"], "server_depends": ["libpq"], "install_cmd": "dnf install -y /pkgs/*.rpm" }, @@ -51,7 +51,7 @@ "image": "registry.opensuse.org/opensuse/tumbleweed:latest", "format": "rpm", "arches": ["x86_64", "aarch64"], - "depends": ["libstdc++6", "libgcc_s1"], + "depends": ["libstdc++6", "libgcc_s1", "shadow"], "server_depends": ["libpq5"], "install_cmd": "zypper --non-interactive install --allow-unsigned-rpm /pkgs/*.rpm" }, @@ -60,7 +60,7 @@ "image": "docker.io/library/alpine:3.22", "format": "apk", "arches": ["x86_64", "aarch64"], - "depends": ["libstdc++", "libgcc"], + "depends": ["libstdc++", "libgcc", "openrc"], "server_depends": ["libpq"], "install_cmd": "apk add --no-cache --allow-untrusted /pkgs/*.apk" }, @@ -69,7 +69,7 @@ "image": "docker.io/library/archlinux:latest", "format": "archlinux", "arches": ["x86_64"], - "depends": ["gcc-libs"], + "depends": ["gcc-libs", "shadow"], "server_depends": ["postgresql-libs"], "install_cmd": "pacman -Sy --noconfirm && pacman -U --noconfirm /pkgs/*.pkg.tar.zst" } diff --git a/packaging/linux/openrc/thewatcher-agent b/packaging/linux/openrc/thewatcher-agent new file mode 100755 index 0000000..085dfea --- /dev/null +++ b/packaging/linux/openrc/thewatcher-agent @@ -0,0 +1,35 @@ +#!/sbin/openrc-run +# TheWatcher agent on OpenRC (Alpine). Installed as /etc/init.d/thewatcher-agent. + +description="TheWatcher agent" +command="/usr/bin/TheWatcherAgent" +command_args="--config /etc/thewatcher-agent/TheWatcherAgent.conf" +command_user="thewatcher-agent:thewatcher-agent" + +# An agent installed without a server address has no config yet. start_pre +# refuses to start it until one exists, instead of the agent creating a config +# that points at 127.0.0.1. It is not required_files: openrc-run checks that for +# every command, stop and status included, so a missing config would make +# `rc-service thewatcher-agent stop` fail before it signalled anything. + +# Deliberately not supervised. supervise-daemon starts a process again however it +# exits, which would undo the server's DISCONNECT command: that ends the agent on +# purpose (issue #85). systemd's Restart=on-failure has no OpenRC equivalent, so +# on Alpine a crashed agent stays down until it is started again. +command_background=true +pidfile="/run/${RC_SVCNAME}.pid" + +# The agent writes its own log file beside its config, so nothing is captured +# from stdout. + +start_pre() { + if [ ! -r "/etc/thewatcher-agent/TheWatcherAgent.conf" ]; then + eerror "/etc/thewatcher-agent/TheWatcherAgent.conf is missing or not readable: set the server address first" + return 1 + fi +} + +depend() { + need net + after firewall +} diff --git a/packaging/linux/openrc/thewatcher-server b/packaging/linux/openrc/thewatcher-server new file mode 100755 index 0000000..8bc932f --- /dev/null +++ b/packaging/linux/openrc/thewatcher-server @@ -0,0 +1,21 @@ +#!/sbin/openrc-run +# TheWatcher server on OpenRC (Alpine). Installed as /etc/init.d/thewatcher-server. + +description="TheWatcher server" +command="/usr/bin/TheWatcherServer" +command_args="--config /etc/thewatcher/TheWatcherServer.conf" +command_user="thewatcher:thewatcher" + +# supervise-daemon runs the server in the foreground itself and starts it again +# when it dies. respawn_max=0 means no limit on restarts. +supervisor="supervise-daemon" +respawn_delay=5 +respawn_max=0 + +# The server writes its own log file beside its config, so nothing is captured +# from stdout. + +depend() { + need net + after firewall +} diff --git a/packaging/linux/service-setup.sh b/packaging/linux/service-setup.sh new file mode 100755 index 0000000..ea510a7 --- /dev/null +++ b/packaging/linux/service-setup.sh @@ -0,0 +1,866 @@ +#!/bin/sh +# Set the installed TheWatcher component up as a service. +# +# Installed by each package as /usr/lib/thewatcher/service-setup- (a +# copy per package: the two are installed side by side, and dpkg, pacman and apk +# refuse a file that two packages own) and called by the maintainer scripts of +# every Linux package (see scripts/release/release_tool.py): +# +# service-setup- server|agent install|upgrade|remove +# +# install First install: create the service user and directories, create the +# config, enable the service, start it, and (server) open the agent +# ports in an active firewall. +# upgrade A newer package over an older one: restart the service only if it +# is running. Never enables a service the administrator disabled, +# never re-adds a firewall rule they removed, never touches the +# config. An upgrade is run as an install when there is no service +# user (the package never set the service up) or when an install +# began and did not finish (see "The install marker" below): the +# package manager retries a failed install as an upgrade. +# remove Stop and disable the service. Config, data and the user are kept. +# +# The agent needs the address of the server, which only the administrator knows: +# THEWATCHER_SERVER= host name or IP address of the TheWatcher server +# ENROLLMENT_TOKEN= the server's ENROLLMENT_TOKEN, if it sets one +# are read from the environment, or an existing config is used. Without either, +# the agent service is enabled but not started, and the message printed says how +# to finish. Running `install` again with the variables set completes the setup. +# +# Every step is idempotent: package managers run these scripts on every upgrade. +# Failing to create the user, directories or config is fatal (the package is +# half installed otherwise). Failing to enable or start the service, or to open +# the firewall, only prints a warning, so a host without a working init system +# can still install the package. +# +# Plain POSIX sh: Alpine runs it with busybox. THEWATCHER_ROOT prefixes every +# absolute path so the tests can run it against a scratch directory. + +set -eu + +DATA_PORT=5555 +ENROLLMENT_PORT=5556 + +usage() { + echo "usage: $0 server|agent install|upgrade|remove" >&2 + exit 2 +} + +[ $# -eq 2 ] || usage +component=$1 +action=$2 + +case "${component}" in + server) + service=thewatcher-server + user=thewatcher + binary_name=TheWatcherServer + config_dir=/etc/thewatcher + config_name=TheWatcherServer.conf + data_dir=/var/lib/thewatcher + ;; + agent) + service=thewatcher-agent + user=thewatcher-agent + binary_name=TheWatcherAgent + config_dir=/etc/thewatcher-agent + config_name=TheWatcherAgent.conf + data_dir= + ;; + *) usage ;; +esac +case "${action}" in + install | upgrade | remove) ;; + *) usage ;; +esac + +# The copy of this helper that this component's package installs. +helper_path="/usr/lib/thewatcher/service-setup-${component}" +root="${THEWATCHER_ROOT:-}" +binary="${root}/usr/bin/${binary_name}" +conf_dir="${root}${config_dir}" +conf="${conf_dir}/${config_name}" +# The install marker: a file that exists only while an install is in progress. It is +# written before the first thing an install does and removed after the last step that +# can stop it, so its presence means the last install did not finish. It is what tells +# an interrupted install (finish it) from a completed one that left no config (an agent +# installed without a server address) and from a setup made by hand (leave it alone): +# the user and the config alone cannot, because an install can stop with both in place, +# for example when handing the directories to the service user fails. +# +# It is kept in a directory only root can write, never in the config or data directory: +# those are handed to the service user, which could plant a symlink named like the marker, +# and the next upgrade (running as root) would then truncate whatever the link names. +state_dir="${root}/var/lib/thewatcher-setup" +marker="${state_dir}/${component}.incomplete" + +say() { echo "${service}: $*"; } +warn() { echo "${service}: warning: $*" >&2; } +die() { + echo "${service}: $*" >&2 + exit 1 +} + +# The package ships one service definition, chosen by its format: a systemd unit +# (deb, rpm, Arch) or an OpenRC script (Alpine). That, not which tools happen to +# be installed, decides how the service is managed. +if [ -f "${root}/usr/lib/systemd/system/${service}.service" ]; then + flavour=systemd +elif [ -f "${root}/etc/init.d/${service}" ]; then + flavour=openrc +else + flavour=none +fi + +# True when the init system is running, so a service can be started now. It is +# not in a container, a chroot or an image build, where units can still be +# enabled for the next boot. +init_running() { + case "${flavour}" in + systemd) [ -d "${root}/run/systemd/system" ] ;; + openrc) [ -d "${root}/run/openrc" ] ;; + *) return 1 ;; + esac +} + +service_active() { + case "${flavour}" in + systemd) systemctl is-active --quiet "${service}" ;; + openrc) rc-service "${service}" status >/dev/null 2>&1 ;; + *) return 1 ;; + esac +} + +service_enable() { + case "${flavour}" in + systemd) systemctl enable "${service}" >/dev/null 2>&1 ;; + openrc) rc-update add "${service}" default >/dev/null 2>&1 ;; + *) return 1 ;; + esac +} + +# dpkg sets DPKG_MAINTSCRIPT_NAME for a maintainer script. There, starting or restarting +# goes through deb-systemd-invoke, which honours policy-rc.d (a container or an image build +# denies services starting at install time). An administrator running the helper by hand, +# and every other distribution, calls systemctl directly. +systemctl_invoke() { + if [ -n "${DPKG_MAINTSCRIPT_NAME:-}" ] && command -v deb-systemd-invoke >/dev/null 2>&1; then + deb-systemd-invoke "$1" "${service}" + else + systemctl "$1" "${service}" + fi +} + +service_start() { + case "${flavour}" in + systemd) systemctl_invoke start ;; + openrc) rc-service "${service}" start ;; + *) return 1 ;; + esac +} + +service_restart() { + case "${flavour}" in + systemd) systemctl_invoke restart ;; + openrc) rc-service "${service}" restart ;; + *) return 1 ;; + esac +} + +# The command that starts the service by hand, for the messages below. +start_hint() { + case "${flavour}" in + openrc) echo "rc-service ${service} start" ;; + *) echo "systemctl start ${service}" ;; + esac +} + +reload_units() { + if [ "${flavour}" = systemd ] && init_running; then + systemctl daemon-reload || warn "systemctl daemon-reload failed" + fi +} + +service_user_exists() { + id "${user}" >/dev/null 2>&1 +} + +# True when the service's group exists. An earlier run that stopped between making the +# group and the user leaves the group behind, and neither addgroup nor useradd +# --user-group accepts one that exists, so a retry would fail at the same step for good. +group_exists() { + getent group "${user}" >/dev/null 2>&1 +} + +# Creates the system user the service runs as: no login, no home directory. +ensure_user() { + if service_user_exists; then + return 0 + fi + shell=$(command -v nologin 2>/dev/null || echo /bin/false) + say "creating the system user ${user}" + if [ "${flavour}" = openrc ]; then + if ! group_exists; then + addgroup -S "${user}" || die "could not create the group ${user}" + fi + adduser -S -D -H -h /nonexistent -s "${shell}" -G "${user}" "${user}" || + die "could not create the user ${user}" + elif group_exists; then + useradd --system --gid "${user}" --no-create-home --home-dir /nonexistent --shell "${shell}" "${user}" || + die "could not create the user ${user}" + else + useradd --system --user-group --no-create-home --home-dir /nonexistent --shell "${shell}" "${user}" || + die "could not create the user ${user}" + fi +} + +# Creates the config with the binary's own --init-config, which writes the +# CURVE key pair and the secure defaults and never overwrites an existing file. +# The server always gets one. The agent needs the server's address, so without +# THEWATCHER_SERVER (and without a config already in place) it gets none. +create_config() { + if [ "${component}" = server ]; then + # The database goes in the data directory, not beside the config: the + # config directory is for config and keys. The real path, not the + # THEWATCHER_ROOT-prefixed one, because it is written into the config. + "${binary}" --init-config --config "${conf}" --db-path "${data_dir}/thewatcher.db" || + die "could not create ${config_dir}/${config_name}" + return 0 + fi + if [ -z "${THEWATCHER_SERVER:-}" ]; then + return 0 + fi + if [ -n "${ENROLLMENT_TOKEN:-}" ]; then + "${binary}" --init-config --config "${conf}" --server-host "${THEWATCHER_SERVER}" \ + --enrollment-token "${ENROLLMENT_TOKEN}" || die "could not create ${config_dir}/${config_name}" + else + "${binary}" --init-config --config "${conf}" --server-host "${THEWATCHER_SERVER}" || + die "could not create ${config_dir}/${config_name}" + fi +} + +# Directories and config, owned by the service user. The server accepts a config +# directory owned by root or by the user it runs as, so while --init-config +# runs as root the directory is root's; it is handed over afterwards. +prepare_files() { + mkdir -p "${conf_dir}" + if [ -n "${data_dir}" ]; then + mkdir -p "${root}${data_dir}" + chmod 0750 "${root}${data_dir}" + fi + # The service user owns this directory from an earlier run, so it could swap the config + # for a symbolic link between the check and the chmod below, and root would then change + # the mode of whatever the link names. Take the directory back first, and only then set + # its mode: the other way round, the owner could still make it writable (0777) in the + # gap, and ownership would keep that mode. + chown root:root "${conf_dir}" + chmod 0700 "${conf_dir}" + if [ -L "${conf}" ]; then + warn "${config_dir}/${config_name} is a symbolic link; its mode was not changed. Replace it with a regular file" + else + if [ ! -e "${conf}" ]; then + create_config + fi + if [ -e "${conf}" ]; then + chmod 0600 "${conf}" + fi + fi + chown -R "${user}:${user}" "${conf_dir}" + if [ -n "${data_dir}" ]; then + chown -R "${user}:${user}" "${root}${data_dir}" + fi +} + +ufw_active() { + command -v ufw >/dev/null 2>&1 && ufw status 2>/dev/null | grep -q '^Status: active' +} + +firewalld_running() { + command -v firewall-cmd >/dev/null 2>&1 && firewall-cmd --state >/dev/null 2>&1 +} + +# What an install added to the firewall, one line per entry ("ufw 5555/tcp" or +# "firewalld public 5555/tcp"), in the root-only state directory. Removal deletes exactly +# these: a rule that was already there, or one the administrator added since, is not ours. +fw_record="${state_dir}/${component}.firewall" + +record_rule() { + echo "$*" >>"${fw_record}" +} + +# What could not be opened is remembered in a file of its own, one " []" +# line per piece of work (scope: ufw, both, permanent or running): the next upgrade retries exactly that, without +# enabling or starting a service the administrator has since stopped or disabled and without +# adding back a rule they removed for a port or a configuration that did work. The Windows +# installer keeps a pending firewall rule too. The install marker is for failures that stop +# the service setup itself. +fw_pending="${state_dir}/${component}.firewall-pending" +fw_ports= +fw_failed_lines= +fw_retry_lines= +# Set while the upgrade retries: a run that finds no firewall running must keep the list. +fw_retry= +NL=' +' + +# True when ufw already has an allow rule for the port, from any source. +ufw_has_rule() { + # An outbound or routed rule ("ALLOW OUT", "ALLOW FWD") does not let an agent connect. + ufw status 2>/dev/null | grep -E "^$1 +ALLOW" | grep -Evq "^$1 +ALLOW +(OUT|FWD)" +} + +# The pending file has one " [ []]" line per piece of firewall work +# that could not be done. The scope is "ufw" or, for firewalld, "both", "permanent" or "running"; +# the zone is the firewalld zone the work was started in, once it is known; the flag +# "runtime-gone" says a permanent retry found the running rule this install added absent. That +# is kept here and not in the ownership record, which must stop naming a rule that is gone: +# an administrator may add the same rule later, and removal must not take it away. +pending_has() { + printf '%s\n' "${fw_retry_lines}" | grep -Eq "^$1 $2( |\$)" +} + +pending_has_flag() { + printf '%s\n' "${fw_retry_lines}" | grep -Eq "^$1 [^ ]+ [^ ]+ $2\$" +} + +# The firewalld zone an earlier attempt for the port used, empty when none was known. +pending_zone() { + printf '%s\n' "${fw_retry_lines}" | awk -v port="$1" '$1 == port && $2 != "ufw" && $3 != "" { print $3; exit }' +} + +# Whether a retry works on ufw for a port. A first run always does; a retry only when ufw is what +# failed: a ufw rule that was added, and that the administrator has since deleted, is not added +# back because firewalld failed. +ufw_wanted() { + [ -z "${fw_retry_lines}" ] || pending_has "$1" ufw +} + +# Which configuration of a pending port a retry works on in firewalld: "both", "permanent", +# "running", or "none" when firewalld is not what failed. A first run works on both. A port +# that failed in one configuration only is retried there only: the other configuration was +# done, and the administrator may have changed it since. +scope_wanted() { + if [ -z "${fw_retry_lines}" ]; then + echo both + elif pending_has "$1" both || { pending_has "$1" permanent && pending_has "$1" running; }; then + echo both + elif pending_has "$1" permanent; then + echo permanent + elif pending_has "$1" running; then + echo running + else + echo none + fi +} + +# Opens the agent ports in a firewall that is running. Only on a first install and for a retry +# of what failed: an administrator who closed or narrowed the rule keeps their choice on +# upgrade. The HTTP API port is never opened: the server config binds it to loopback. +# What is said matches what happened: a refused rule is not reported as allowed, and a +# port the firewall already allowed is left as it is and not recorded. +open_firewall() { + mkdir -p "${state_dir}" + # A retry reads what failed from the pending file. + fw_retry_lines= + if [ -n "${fw_retry}" ] && [ -f "${fw_pending}" ]; then + fw_retry_lines=$(cat "${fw_pending}") + fi + fw_ports= + for port in "${DATA_PORT}" "${ENROLLMENT_PORT}"; do + if [ -z "${fw_retry_lines}" ] || printf '%s\n' "${fw_retry_lines}" | grep -q "^${port} "; then + fw_ports="${fw_ports} ${port}" + fi + done + if [ -z "${fw_ports}" ]; then + fw_ports="${DATA_PORT} ${ENROLLMENT_PORT}" + fi + fw_failed_lines= + ufw_ran= + fwd_ran= + if ufw_active; then + ufw_ran=1 + ufw_failed= + ufw_opened= + for port in ${fw_ports}; do + if ! ufw_wanted "${port}"; then + continue + fi + if ufw_has_rule "${port}/tcp"; then + say "ufw already has a rule for ${port}/tcp; left as it is" + elif ufw allow "${port}/tcp" comment "TheWatcher agents" >/dev/null; then + record_rule "ufw ${port}/tcp" + ufw_opened="${ufw_opened} ${port}/tcp" + else + warn "could not allow ${port}/tcp in ufw" + ufw_failed=1 + fw_failed_lines="${fw_failed_lines}${port} ufw${NL}" + fi + done + # Only what this run opened is called open from anywhere: a rule that was already there + # may be narrowed, and saying otherwise would be false. + if [ -z "${ufw_failed}" ] && [ -n "${ufw_opened}" ]; then + say "ufw allows${ufw_opened} from anywhere; narrow them to your monitored network" + fi + fi + if firewalld_running; then + fwd_ran=1 + open_firewalld + fi + # What could not be tried because its firewall did not run is carried over as it was: each + # entry is cleared only by its own firewall. Whether a firewall ran is what was recorded above, + # not asked again here: one that starts or stops in between must not drop or restore work. + fw_carried= + if [ -n "${fw_retry_lines}" ]; then + while read -r carried_port carried_scope carried_zone carried_flag; do + if [ -z "${carried_port}" ]; then + continue + fi + if [ "${carried_scope}" = ufw ]; then + if [ -z "${ufw_ran}" ]; then + fw_carried="${fw_carried}${carried_port} ufw${NL}" + fi + elif [ -z "${fwd_ran}" ]; then + fw_carried="${fw_carried}${carried_port} ${carried_scope}${carried_zone:+ ${carried_zone}}${carried_flag:+ ${carried_flag}}${NL}" + fi + done <"${fw_pending}" + warn "the firewall was not fully set up; the next upgrade of this package tries again for what failed" + elif [ -n "${fw_carried}" ]; then + printf '%s' "${fw_carried}" >"${fw_pending}" + warn "a firewall that still has ports to open is not running; they are kept for the next upgrade of this package" + else + rm -f "${fw_pending}" + fi +} + +# Whether a port is open in one firewalld configuration, "running" or "permanent": +# 0 when it is, 1 when it is not, 2 when that cannot be told (firewalld stopped answering). +# An answer that cannot be told is never taken as "not open", and nothing is added there: +# a rule added blindly might be the administrator's own, or never be recorded as ours. +fw_query() { + scope=$1 + zone_name=$2 + port_spec=$3 + permanent_flag= + if [ "${scope}" = permanent ]; then + permanent_flag=--permanent + fi + query_rc=0 + firewall-cmd ${permanent_flag} --zone="${zone_name}" --query-port="${port_spec}" >/dev/null 2>&1 || query_rc=$? + case "${query_rc}" in + 0) return 0 ;; + 1) return 1 ;; + *) return 2 ;; + esac +} + +# True when the record already has a line of this kind for the zone and port. +record_has() { + [ -f "${fw_record}" ] && grep -Eqx "$1 $2 $3" "${fw_record}" +} + +# Drops every record line for a zone and port, so they can be written again as one. +forget_port() { + if [ -f "${fw_record}" ]; then + grep -Evx "firewalld(-permanent|-runtime)? $1 $2" "${fw_record}" >"${fw_record}.new" || true + mv -f "${fw_record}.new" "${fw_record}" + fi +} + +# The running rule this install added is confirmed absent, so the install no longer owns it: +# the record keeps only what is still ours (the permanent rule, if it was recorded). +drop_running_ownership() { + if record_has "firewalld-runtime" "$1" "$2"; then + forget_port "$1" "$2" + elif record_has "firewalld" "$1" "$2"; then + forget_port "$1" "$2" + record_rule "firewalld-permanent $1 $2" + fi +} + +# firewalld: the zone is the one an earlier attempt for the port used, or else the default zone at +# this moment, and is stored with what fails so a retry works in the same zone even if the +# default has changed. Rules are written to the running rules and to the permanent +# configuration separately. A reload would also throw away every runtime-only change the +# administrator made for other services, so none is run. Ownership is recorded for each +# configuration on its own, and only for a port that was confirmed absent there. A failure is +# remembered per port and configuration, so a retry does not redo, or add back after the +# administrator removed it, the configuration that worked. +open_firewalld() { + default_zone=$(firewall-cmd --get-default-zone 2>/dev/null) || default_zone= + fw_failed= + fw_opened= + for port in ${fw_ports}; do + spec="${port}/tcp" + want=$(scope_wanted "${port}") + if [ "${want}" = none ]; then + continue + fi + zone=$(pending_zone "${port}") + if [ -z "${zone}" ]; then + zone=${default_zone} + fi + if [ -z "${zone}" ]; then + # Nothing was started for this port, so its scopes are kept as they were. + warn "could not read the default zone of firewalld; ${spec} was not opened" + fw_failed=1 + fw_failed_lines="${fw_failed_lines}${port} ${want}${NL}" + continue + fi + perm_rc=0 + run_rc=0 + fw_query permanent "${zone}" "${spec}" || perm_rc=$? + fw_query running "${zone}" "${spec}" || run_rc=$? + if [ "${perm_rc}" -eq 0 ] && [ "${run_rc}" -eq 0 ]; then + say "firewalld zone ${zone} already allows ${spec}; left as it is" + continue + fi + # What an earlier run of this install already added for the port. + own_permanent= + own_running= + if record_has "firewalld(-permanent)?" "${zone}" "${spec}"; then + own_permanent=1 + fi + if record_has "firewalld(-runtime)?" "${zone}" "${spec}"; then + own_running=1 + fi + # A retry for one configuration depends on the state of the other one this install added. + if [ "${want}" = running ] && [ -n "${own_permanent}" ]; then + if [ "${perm_rc}" -eq 1 ]; then + # The permanent rule is in the configuration file: it does not vanish by itself, so + # its absence is the administrator's removal and the port is left closed. + say "firewalld zone ${zone}: the permanent rule for ${spec} was removed since the install; ${spec} is left closed" + forget_port "${zone}" "${spec}" + continue + elif [ "${perm_rc}" -ge 2 ]; then + warn "could not tell whether the permanent rule for ${spec} in firewalld zone ${zone} is still there; the running rule stays pending" + fw_failed=1 + fw_failed_lines="${fw_failed_lines}${port} running ${zone}${NL}" + continue + fi + fi + if [ "${want}" = permanent ] && [ "${run_rc}" -ne 0 ] && { [ -n "${own_running}" ] || pending_has_flag "${port}" runtime-gone; }; then + # A running rule is lost at a firewalld reload as well as by an administrator removing + # it, and the two cannot be told apart. Opening the port could undo a removal and + # cancelling would leave it closed after a reload, so nothing is done and the permanent + # rule stays pending. + fw_failed=1 + if [ "${run_rc}" -eq 1 ]; then + # Its absence is confirmed, so the install stops owning it: if the administrator adds + # the same rule later, removal must not delete it. That the rule was ours stays in the + # pending entry, apart from the ownership record. + drop_running_ownership "${zone}" "${spec}" + warn "the running rule for ${spec} in firewalld zone ${zone} is gone (a reload or a removal); the permanent rule stays pending and ${spec} is not opened" + fw_failed_lines="${fw_failed_lines}${port} permanent ${zone} runtime-gone${NL}" + else + warn "could not tell whether the running rule for ${spec} in firewalld zone ${zone} is still there; the permanent rule stays pending" + if pending_has_flag "${port}" runtime-gone; then + fw_failed_lines="${fw_failed_lines}${port} permanent ${zone} runtime-gone${NL}" + else + fw_failed_lines="${fw_failed_lines}${port} permanent ${zone}${NL}" + fi + fi + continue + fi + do_permanent= + do_running= + if [ "${want}" != running ]; then + do_permanent=1 + fi + if [ "${want}" != permanent ]; then + do_running=1 + fi + perm_failed= + run_failed= + added= + if [ -n "${do_permanent}" ]; then + if [ "${perm_rc}" -ge 2 ]; then + warn "could not tell whether ${spec} is already open in the permanent configuration of firewalld zone ${zone}; it is left alone for now and tried again at the next upgrade of this package" + perm_failed=1 + elif [ "${perm_rc}" -eq 1 ]; then + if firewall-cmd --permanent --zone="${zone}" --add-port="${spec}" >/dev/null; then + own_permanent=1 + added=1 + else + warn "could not add ${spec} to the permanent configuration of firewalld zone ${zone}" + perm_failed=1 + fi + fi + fi + if [ -n "${do_running}" ]; then + if [ "${run_rc}" -ge 2 ]; then + warn "could not tell whether ${spec} is already open in the running firewalld zone ${zone}; it is left alone for now and tried again at the next upgrade of this package" + run_failed=1 + elif [ "${run_rc}" -eq 1 ]; then + if firewall-cmd --zone="${zone}" --add-port="${spec}" >/dev/null; then + # A running rule confirmed absent is ours unless the permanent rule is the + # administrator's (loading their rule is not ours to take back). The permanent + # rule is ours when this install added it, now or in an earlier run; one whose + # state could not be told does not make the running rule any less ours. + if [ "${perm_rc}" -ne 0 ] || [ -n "${own_permanent}" ]; then + own_running=1 + added=1 + fi + else + warn "could not open ${spec} in the running firewalld zone ${zone}" + run_failed=1 + fi + fi + fi + if [ -n "${added}" ]; then + forget_port "${zone}" "${spec}" + if [ -n "${own_permanent}" ] && [ -n "${own_running}" ]; then + record_rule "firewalld ${zone} ${spec}" + elif [ -n "${own_permanent}" ]; then + record_rule "firewalld-permanent ${zone} ${spec}" + else + record_rule "firewalld-runtime ${zone} ${spec}" + fi + fw_opened="${fw_opened} ${spec} (zone ${zone})" + fi + if [ -n "${perm_failed}" ] && [ -n "${run_failed}" ]; then + fw_failed=1 + fw_failed_lines="${fw_failed_lines}${port} both ${zone}${NL}" + elif [ -n "${perm_failed}" ]; then + fw_failed=1 + fw_failed_lines="${fw_failed_lines}${port} permanent ${zone}${NL}" + elif [ -n "${run_failed}" ]; then + fw_failed=1 + fw_failed_lines="${fw_failed_lines}${port} running ${zone}${NL}" + fi + done + if [ -z "${fw_failed}" ] && [ -n "${fw_opened}" ]; then + say "firewalld allows${fw_opened} from anywhere; narrow them to your monitored network" + fi +} + +# Takes one port out of one firewalld configuration, "running" or "permanent". Returns 0 when +# the port is gone afterwards, 1 when it is still open and 2 when that cannot be told (firewalld +# stopped answering). A failed removal is harmless only if a query then says the port is absent; +# a failed query is not that answer. +fw_remove_port() { + scope=$1 + zone_name=$2 + port_spec=$3 + permanent_flag= + if [ "${scope}" = permanent ]; then + permanent_flag=--permanent + fi + if firewall-cmd ${permanent_flag} --zone="${zone_name}" --remove-port="${port_spec}" >/dev/null 2>&1; then + return 0 + fi + query_status=0 + firewall-cmd ${permanent_flag} --zone="${zone_name}" --query-port="${port_spec}" >/dev/null 2>&1 || query_status=$? + case "${query_status}" in + 0) return 1 ;; + 1) return 0 ;; + *) return 2 ;; + esac +} + +# Takes back what open_firewall recorded, so removing the server leaves no inbound rule for +# software that is gone (the Windows uninstaller does the same with its own rule). A rule +# that was already there before the install, one the administrator narrowed or replaced, +# and one that is already gone are not touched or reported. +close_firewall() { + if [ ! -f "${fw_record}" ]; then + return 0 + fi + # What could not be taken back is written to a new record, so a later removal still knows it + # is ours, and what was taken back is not claimed any more: a rule an administrator adds + # afterwards must not be deleted because an old record still names it. + fw_remaining="${fw_record}.remaining" + : >"${fw_remaining}" + while read -r kind first second; do + case "${kind}" in + ufw) + if ! ufw_active; then + warn "ufw is not running; remove the rule for ${first} by hand: ufw delete allow ${first}" + echo "ufw ${first}" >>"${fw_remaining}" + # --force: without it ufw asks for a confirmation that no package script can answer. + elif ! ufw --force delete allow "${first}" >/dev/null 2>&1; then + warn "could not remove the ufw rule for ${first}" + echo "ufw ${first}" >>"${fw_remaining}" + else + say "removed the ufw rule for ${first}" + fi + ;; + firewalld | firewalld-permanent | firewalld-runtime) + if ! firewalld_running; then + if [ "${kind}" = firewalld-runtime ]; then + # A running rule lives in firewalld's memory: with firewalld down it is gone, + # and the permanent configuration was never this install's to touch. + say "firewalld is not running, so the running rule for ${second} in zone ${first} is already gone" + else + warn "firewalld is not running; remove ${second} from the permanent configuration of zone ${first} by hand: firewall-cmd --permanent --zone=${first} --remove-port=${second}" + # Only the permanent rule is left to take back. + echo "firewalld-permanent ${first} ${second}" >>"${fw_remaining}" + fi + continue + fi + # The zone recorded at install, not today's default zone. A removal that fails + # because the port is already gone is not a failure; one that fails while the + # port is still there, or whose result cannot be told, is said and kept. + left_running= + left_permanent= + # The kind says which configuration this install added the port to: "firewalld- + # permanent" was already open in the running firewall, "firewalld-runtime" had no + # permanent rule added. Only what was added is taken back. + if [ "${kind}" != firewalld-permanent ]; then + status=0 + fw_remove_port running "${first}" "${second}" || status=$? + case "${status}" in + 0) ;; + 1) + warn "could not close ${second} in the running firewalld zone ${first}: firewall-cmd --zone=${first} --remove-port=${second}" + left_running=1 + ;; + *) + warn "could not tell whether ${second} is still open in the running firewalld zone ${first}: firewall-cmd --zone=${first} --query-port=${second}" + left_running=1 + ;; + esac + fi + if [ "${kind}" != firewalld-runtime ]; then + status=0 + fw_remove_port permanent "${first}" "${second}" || status=$? + case "${status}" in + 0) ;; + 1) + warn "could not remove ${second} from the permanent configuration of firewalld zone ${first}: firewall-cmd --permanent --zone=${first} --remove-port=${second}" + left_permanent=1 + ;; + *) + warn "could not tell whether ${second} is still in the permanent configuration of firewalld zone ${first}: firewall-cmd --permanent --zone=${first} --query-port=${second}" + left_permanent=1 + ;; + esac + fi + if [ -n "${left_running}" ] && [ -n "${left_permanent}" ]; then + echo "firewalld ${first} ${second}" >>"${fw_remaining}" + elif [ -n "${left_running}" ]; then + echo "firewalld-runtime ${first} ${second}" >>"${fw_remaining}" + elif [ -n "${left_permanent}" ]; then + echo "firewalld-permanent ${first} ${second}" >>"${fw_remaining}" + else + say "removed ${second} from firewalld zone ${first}" + fi + ;; + esac + done <"${fw_record}" + if [ -s "${fw_remaining}" ]; then + mv -f "${fw_remaining}" "${fw_record}" + else + rm -f "${fw_remaining}" "${fw_record}" + fi +} + +tell_agent_how_to_finish() { + say "enabled, but not started: no server address is set." + echo " To finish, run this with your server's address (and its enrollment token, if it has one):" + echo " sudo THEWATCHER_SERVER=YOUR_SERVER ENROLLMENT_TOKEN=YOUR_TOKEN ${helper_path} agent install" + echo " or create ${config_dir}/${config_name} with a line THEWATCHER_SERVER=YOUR_SERVER (and a line" + echo " ENROLLMENT_TOKEN=YOUR_TOKEN if the server has an enrollment token) and run:" + echo " $(start_hint)" +} + +begin_install() { + # chmod because the caller's umask is not ours to trust: this directory must not be + # writable by anyone but root. + mkdir -p "${state_dir}" + chmod 0755 "${state_dir}" + : >"${marker}" +} + +# Reached only when every step before it succeeded: a failure above exits the script +# (set -e, die) with the marker still in place. Enabling, starting and the firewall only +# warn, because a host without a working init system must still be able to install. +finish_install() { + rm -f "${marker}" +} + +install_steps() { + ensure_user + prepare_files + reload_units + + if [ "${flavour}" = none ]; then + warn "this package has no service definition; the config was created but nothing is enabled or started" + return 0 + fi + service_enable || warn "could not enable ${service}" + if [ "${component}" = server ]; then + open_firewall + fi + + if [ ! -e "${conf}" ]; then + tell_agent_how_to_finish + elif init_running; then + service_start || warn "could not start ${service}; see: $(start_hint)" + else + say "enabled; it starts at the next boot, or now with: $(start_hint)" + fi +} + +do_install() { + begin_install + install_steps + finish_install +} + +do_upgrade() { + # Keep ownership and directory modes right for a service that predates this + # package version, and create nothing that exists. + prepare_files + reload_units + # A firewall rule refused at install is retried here, only for the ports that failed; + # nothing else about the service changes. + if [ "${component}" = server ] && [ -e "${fw_pending}" ]; then + fw_retry=1 + open_firewall + fi + if service_active; then + service_restart || warn "could not restart ${service} onto the new version; see: $(start_hint)" + fi +} + +do_remove() { + case "${flavour}" in + systemd) systemctl disable --now "${service}" >/dev/null 2>&1 || true ;; + openrc) + rc-service "${service}" stop >/dev/null 2>&1 || true + rc-update del "${service}" default >/dev/null 2>&1 || true + ;; + esac + # The agent ports were opened for the server only, so only its removal closes them. + if [ "${component}" = server ]; then + close_firewall + fi + # Config, data and the user stay: they hold the CURVE keys and the database. The + # marker of an install that never finished does not: nothing else would remove it. + rm -f "${marker}" "${fw_pending}" + rmdir "${state_dir}" 2>/dev/null || true +} + +# An upgrade has nothing to keep when the package never set the service up (no +# service user) or an earlier install began and did not finish (the marker). Set it up +# as a new install. A user and a config with no marker were made by a finished install +# or by an administrator by hand, and that is left alone, including an agent that has +# no config because it was installed without a server address. +if [ "${action}" = upgrade ]; then + if ! service_user_exists || [ -e "${marker}" ]; then + say "the service has not been fully set up yet; setting it up" + action=install + fi +fi + +case "${action}" in + install) do_install ;; + upgrade) do_upgrade ;; + remove) do_remove ;; +esac +exit 0 diff --git a/packaging/linux/systemd/thewatcher-agent.service b/packaging/linux/systemd/thewatcher-agent.service new file mode 100644 index 0000000..52b7e22 --- /dev/null +++ b/packaging/linux/systemd/thewatcher-agent.service @@ -0,0 +1,33 @@ +[Unit] +Description=TheWatcher agent +Documentation=https://github.com/OMG-Software/TheWatcher +Wants=network-online.target +After=network-online.target +# An agent installed without a server address has no config yet. Skip the unit +# quietly until one exists instead of failing on every boot (the agent would +# otherwise create a config that points at 127.0.0.1). +ConditionPathExists=/etc/thewatcher-agent/TheWatcherAgent.conf + +[Service] +Type=simple +User=thewatcher-agent +Group=thewatcher-agent +ExecStart=/usr/bin/TheWatcherAgent --config /etc/thewatcher-agent/TheWatcherAgent.conf +Restart=on-failure +RestartSec=5 + +# Optional: let the log monitor read these directories. The user also needs read +# access to the files themselves (for example SupplementaryGroups=adm). Put +# overrides in `systemctl edit thewatcher-agent`, not in this file. +#Environment=LOG_ALLOWED_DIRS=/var/log +#SupplementaryGroups=adm + +# Hardening: the agent writes only its own config directory (its log file is +# beside the config; it rewrites the config after enrollment). +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ReadWritePaths=/etc/thewatcher-agent + +[Install] +WantedBy=multi-user.target diff --git a/packaging/linux/systemd/thewatcher-server.service b/packaging/linux/systemd/thewatcher-server.service new file mode 100644 index 0000000..fcd4af7 --- /dev/null +++ b/packaging/linux/systemd/thewatcher-server.service @@ -0,0 +1,25 @@ +[Unit] +Description=TheWatcher server +Documentation=https://github.com/OMG-Software/TheWatcher +Wants=network-online.target +After=network-online.target + +[Service] +Type=simple +User=thewatcher +Group=thewatcher +ExecStart=/usr/bin/TheWatcherServer --config /etc/thewatcher/TheWatcherServer.conf +# The server exits 1 on a startup or fatal runtime failure and 0 on SIGTERM. +Restart=on-failure +RestartSec=5 + +# Hardening: the server writes only its config directory (its log file is +# beside the config) and its database. +NoNewPrivileges=true +PrivateTmp=true +ProtectSystem=strict +ProtectHome=true +ReadWritePaths=/etc/thewatcher /var/lib/thewatcher + +[Install] +WantedBy=multi-user.target diff --git a/packaging/windows/TheWatcher.iss b/packaging/windows/TheWatcher.iss index e807018..116b654 100644 --- a/packaging/windows/TheWatcher.iss +++ b/packaging/windows/TheWatcher.iss @@ -5,10 +5,26 @@ ; Each has its own AppId and name, so they install, upgrade and uninstall ; independently, and each manages only its own service. They share the {app} ; root and the configuration directory under {commonappdata}\TheWatcher. +; +; Installing sets the service up, so there are no manual steps afterwards: +; server creates its config (CURVE key pair, API on loopback, enrollment +; token), registers the service with restart-on-failure, opens +; TCP 5555 and 5556 for the agents on the Domain and Private firewall +; profiles (first install only), and starts it. +; agent asks for the server address and enrollment token on a wizard page, or +; takes /SERVER= and the ENROLLMENT_TOKEN environment variable for +; a silent install (never a /TOKEN= switch: Setup's /LOG= writes its whole +; command line to the log), creates +; its config, registers the service and starts it. Without an address +; the service is registered with a manual start type and not started. +; An upgrade keeps every existing config and firewall rule and restarts only the +; services that were running. See docs/installation.md. #define AppName "TheWatcher" +; The inbound rule the server installer adds and its uninstaller removes. +#define FirewallRuleName "TheWatcher server (agents)" #define AppVersion GetEnv("THEWATCHER_VERSION") #if AppVersion == "" -#define AppVersion "0.10.2" +#define AppVersion "0.10.3" #endif #define Component GetEnv("THEWATCHER_COMPONENT") #if (Component != "server") && (Component != "agent") @@ -60,10 +76,19 @@ Name: "{commonappdata}\TheWatcher" [UninstallRun] #if Component == "server" Filename: "{app}\server\TheWatcherServer.exe"; Parameters: "--uninstall-service"; Flags: runhidden waituntilterminated +Filename: "{sys}\netsh.exe"; Parameters: "advfirewall firewall delete rule name=""{#FirewallRuleName}"""; Flags: runhidden waituntilterminated; RunOnceId: "RemoveFirewallRule" #else Filename: "{app}\agent\TheWatcherAgent.exe"; Parameters: "--uninstall-service"; Flags: runhidden waituntilterminated #endif +[UninstallDelete] +; A replacement that never finished must not make a later install look like an upgrade. +#if Component == "server" +Type: files; Name: "{commonappdata}\TheWatcher\TheWatcherServer.replacing" +#else +Type: files; Name: "{commonappdata}\TheWatcher\TheWatcherAgent.replacing" +#endif + [Icons] #if Component == "server" Name: "{group}\TheWatcher Dashboard"; Filename: "{app}\dashboard\index.html"; Check: DashboardExists @@ -94,6 +119,21 @@ var // Set by PrepareToInstall for each service it stopped, so the service is // started again after the upgrade, or when the install is aborted. AgentWasRunning, ServerWasRunning: Boolean; + // Set by PrepareToInstall: the service was registered before this install, so + // this is an upgrade and not a first install. + AgentExisted, ServerExisted: Boolean; + // --init-config created the config during this install (it did not exist). + AgentConfigCreatedNow, ServerConfigCreatedNow: Boolean; + // The agent has no config and no server address was given: the service is + // registered with a manual start type and left stopped. + AgentNeedsConfig: Boolean; + // The server address and enrollment token the agent is set up with: the wizard + // page, or /SERVER= and the ENROLLMENT_TOKEN environment variable for a silent + // install. + AgentHost, AgentToken: String; + AgentPage: TInputQueryWizardPage; + // Text for the finished page that is not an error (shown, and logged). + PostInstallNote: String; // True once the files are installed (ssPostInstall). DeinitializeSetup uses // it to tell an aborted install from a finished one. PostInstallReached: Boolean; @@ -107,6 +147,16 @@ begin ewWaitUntilTerminated, ResultCode) and (ResultCode = 0); end; +// True when sc query reports the service as RUNNING. A query that fails, or reports any other state +// (starting, stopping), is not a yes: it is for deciding that a start worked, and that needs a positive answer. +function ServiceIsRunning(const Name: String): Boolean; +var + ResultCode: Integer; +begin + Result := Exec(ExpandConstant('{sys}\cmd.exe'), '/C sc query ' + Name + ' | find "RUNNING" >nul', '', SW_HIDE, + ewWaitUntilTerminated, ResultCode) and (ResultCode = 0); +end; + // Upgrades: stop the running services before any file is replaced, so the // executables are not locked and the service registration can be deleted and // recreated immediately afterwards. @@ -265,6 +315,24 @@ begin ewWaitUntilTerminated, ResultCode) and (ResultCode = 0); end; +// Exists only while a registration is being replaced: written before the old one is removed +// and deleted once the new one is in place. If the replacement stops half way (the old service +// is still marked for deletion, and the message says to close services.msc and run the installer +// again), the service is gone by the next run, which without this file would take itself for a +// first install: it would put back a firewall rule the administrator narrowed and start a +// service they had stopped. In the config directory, which only administrators can write to. +function ReplacingFile(const Name: String): String; +begin + Result := ExpandConstant('{commonappdata}\TheWatcher\') + Name + '.replacing'; +end; + +// True when this machine had the service before this run: it is registered, or a replacement +// of its registration was begun and not finished. +function WasInstalled(const Name: String): Boolean; +begin + Result := ServiceExists(Name) or FileExists(ReplacingFile(Name)); +end; + // (Re)registers a service so its command line points at ConfPath. Service // registration lives here instead of [Run] because [Run] cannot check exit // codes. Any failure aborts the install with a message. @@ -283,6 +351,10 @@ var begin if ServiceExists(Name) then begin + // Before the old registration goes, so a replacement that stops half way is still an upgrade next time. + // Checked: without the marker a replacement that stops half way would look like a first install. + if not SaveStringToFile(ReplacingFile(Name), 'replacing', False) then + RaiseException('Could not record that the ' + Name + ' service is being replaced (' + ReplacingFile(Name) + '), so the existing service was left as it is.'); if not Exec(Exe, '--uninstall-service', '', SW_HIDE, ewWaitUntilTerminated, ResultCode) or (ResultCode <> 0) then RaiseException('Could not remove the existing ' + Name + ' service (exit code ' + IntToStr(ResultCode) + ').'); @@ -309,6 +381,221 @@ begin end; if not Registered then RaiseException('Could not register the ' + Name + ' service (exit code ' + IntToStr(ResultCode) + ').'); + // The replacement is complete. A failure above leaves the marker for the run that finishes it. + DeleteFile(ReplacingFile(Name)); +end; + +// Appends a failure to the text shown at the end and returned as exit code 10. +procedure AddProblem(const Text: String); +begin + if RegistrationError <> '' then + RegistrationError := RegistrationError + #13#10; + RegistrationError := RegistrationError + Text; +end; + +// Runs a program and raises an exception naming What when it cannot start or +// exits non-zero. The command line is deliberately not in the message: it can +// hold the enrollment token. +procedure RunChecked(const Exe, Params, What: String); +var + ResultCode: Integer; +begin + if not Exec(Exe, Params, '', SW_HIDE, ewWaitUntilTerminated, ResultCode) then + RaiseException('Could not ' + What + ': ' + Exe + ' did not start (' + SysErrorMessage(ResultCode) + ').'); + if ResultCode <> 0 then + RaiseException('Could not ' + What + ' (exit code ' + IntToStr(ResultCode) + ').'); +end; + +// The config file the service of this installer reads. +function ConfigPath(): String; +begin + if InstallsServer then + Result := ExpandConstant('{commonappdata}\TheWatcher\TheWatcherServer.conf') + else + Result := ExpandConstant('{commonappdata}\TheWatcher\TheWatcherAgent.conf'); +end; + +// Windows restarts the service when it exits with a failure: the server and +// agent exit non-zero on a startup or fatal runtime error. Registration creates +// the service afresh, so this is applied on every install and upgrade. +// failureflag makes a non-zero exit code count as a failure. +procedure SetRestartOnFailure(const Name: String); +begin + RunChecked(ExpandConstant('{sys}\sc.exe'), + 'failure ' + Name + ' reset= 86400 actions= restart/5000/restart/5000/restart/30000', + 'set the recovery actions of the ' + Name + ' service'); + RunChecked(ExpandConstant('{sys}\sc.exe'), 'failureflag ' + Name + ' 1', + 'set the failure flag of the ' + Name + ' service'); +end; + +// Opens the agent ports for the server program on the Domain and Private +// profiles only: a Public network (an airport, a cafe) is never trusted with +// the monitoring ports. The rule is tied to the executable so it opens nothing +// for any other program. Any rule of that name is removed first, so repeating +// this never leaves two. netsh is language independent. +procedure OpenFirewall(const Exe: String); +var + ResultCode: Integer; + Netsh: String; +begin + Netsh := ExpandConstant('{sys}\netsh.exe'); + Exec(Netsh, 'advfirewall firewall delete rule name="{#FirewallRuleName}"', '', SW_HIDE, + ewWaitUntilTerminated, ResultCode); + try + RunChecked(Netsh, + 'advfirewall firewall add rule name="{#FirewallRuleName}" dir=in action=allow protocol=TCP ' + + 'localport=5555,5556 profile=domain,private program="' + Exe + '"', + 'open TCP 5555 and 5556 in the Windows firewall'); + except + RaiseException(GetExceptionMessage() + ' Add an inbound rule for ' + Exe + ' on TCP 5555 and 5556 yourself.'); + end; +end; + +// Quotes one command-line argument so the program receives exactly Value: +// wrapped in double quotes, a double quote written as \", and the backslashes in +// front of a double quote (or of the closing quote) doubled. That is what +// CommandLineToArgvW and the MSVC runtime read back. Without it a token that ends +// in a backslash would swallow the closing quote and arrive changed. +function QuoteArgument(const Value: String): String; +var + I, Backslashes: Integer; + C: Char; +begin + Result := '"'; + Backslashes := 0; + for I := 1 to Length(Value) do + begin + C := Value[I]; + if C = '\' then + Backslashes := Backslashes + 1 + else + begin + if C = '"' then + Result := Result + StringOfChar('\', Backslashes * 2 + 1) + else + Result := Result + StringOfChar('\', Backslashes); + Result := Result + C; + Backslashes := 0; + end; + end; + Result := Result + StringOfChar('\', Backslashes * 2) + '"'; +end; + +// Why a server address cannot be used, or ''. A host name or address never holds +// a space, a control character or a quotation mark, and the agent refuses them. +function HostProblem(const Value: String): String; +var + I: Integer; +begin + Result := ''; + for I := 1 to Length(Value) do + if (Ord(Value[I]) <= 32) or (Value[I] = '"') then + begin + Result := 'The server address must not contain spaces, control characters or quotation marks.'; + Exit; + end; +end; + +// Why an enrollment token cannot be used, or ''. The server accepts any single +// line, spaces and quotation marks included, and QuoteArgument passes them on, so +// a line break (which would start a new KEY=VALUE line in the config) or another +// control character is refused. So is any character outside ASCII: the agent reads +// its command line through the process code page, which replaces a character it +// cannot represent (with '?', for example), and the agent would then store a token +// that is not the one the server holds. +function TokenProblem(const Value: String): String; +var + I: Integer; +begin + Result := ''; + for I := 1 to Length(Value) do + begin + if (Ord(Value[I]) < 32) or (Ord(Value[I]) = 127) then + begin + Result := 'The enrollment token must not contain line breaks or other control characters.'; + Exit; + end; + if Ord(Value[I]) > 127 then + begin + Result := 'The enrollment token may contain only ASCII characters: other characters can change on the way to the agent.'; + Exit; + end; + end; +end; + +function AgentSettingsProblem(): String; +begin + Result := HostProblem(AgentHost); + if Result = '' then + Result := TokenProblem(AgentToken); +end; + +// Server: create the config, register the service with its recovery actions. +// The config comes first, so the service never starts on a missing one and +// generates a config without a token or with the API on every interface. +// --init-config never changes an existing config, so an upgrade keeps it. +procedure SetUpServer(); +var + Exe, Conf: String; +begin + Exe := ExpandConstant('{app}\server\TheWatcherServer.exe'); + Conf := ConfigPath(); + ServerConfigCreatedNow := not FileExists(Conf); + RunChecked(Exe, '--init-config --config ' + QuoteArgument(Conf), 'create the server config'); + RegisterService('TheWatcherServer', Exe, Conf); + SetRestartOnFailure('TheWatcherServer'); +end; + +// Agent: create the config from the address and token, register the service +// with its recovery actions. Without an address, and without a config from an +// earlier install, there is nothing to connect to: the service is registered +// with a manual start type. Left automatic, the next boot would start an agent +// that creates a default config pointing at 127.0.0.1. +procedure SetUpAgent(); +var + Exe, Conf, Args, Problem: String; +begin + Exe := ExpandConstant('{app}\agent\TheWatcherAgent.exe'); + Conf := ConfigPath(); + + AgentConfigCreatedNow := False; + if FileExists(Conf) then + begin + // An upgrade keeps the config: it holds the agent's identity and the server key it pinned. + // Say so when an address was given, or a silent /SERVER= that changed nothing looks like it worked. + if AgentHost <> '' then + PostInstallNote := 'The existing agent config was kept, so /SERVER= and the enrollment token were not applied.' + #13#10 + + 'To change the server, edit THEWATCHER_SERVER, SERVER_ADDRESS and ENROLLMENT_ADDRESS in ' + Conf + ' (the last two win over THEWATCHER_SERVER) and delete its SERVER_PUBLIC_KEY and SERVER_PUBLIC_KEY_FINGERPRINT lines (the agent pinned the old server''s key and would refuse the new one), or delete that file and run the installer again (the agent then enrolls as a new agent).'; + end + else if AgentHost <> '' then + begin + // Only a config that is being created uses the address and the token, so an upgrade of an + // agent that already has one is not stopped by an environment variable it does not use. + Problem := AgentSettingsProblem(); + if Problem <> '' then + RaiseException(Problem); + Args := '--init-config --config ' + QuoteArgument(Conf) + ' --server-host ' + QuoteArgument(AgentHost); + if AgentToken <> '' then + Args := Args + ' --enrollment-token ' + QuoteArgument(AgentToken); + RunChecked(Exe, Args, 'create the agent config'); + AgentConfigCreatedNow := True; + end; + + RegisterService('TheWatcherAgent', Exe, Conf); + SetRestartOnFailure('TheWatcherAgent'); + + AgentNeedsConfig := not FileExists(Conf); + if AgentNeedsConfig then + begin + RunChecked(ExpandConstant('{sys}\sc.exe'), 'config TheWatcherAgent start= demand', + 'set the agent service to start manually'); + PostInstallNote := 'The agent service is installed but not started, because no server address was given.' + #13#10 + + 'To finish, run the installer again with /SERVER=YOUR_SERVER (and the ENROLLMENT_TOKEN environment variable set to the server''s token, if it has one), or run as Administrator:' + #13#10 + + '"' + Exe + '" --init-config --config "' + Conf + '" --server-host YOUR_SERVER' + #13#10 + + '(if the server has an enrollment token, add --enrollment-token YOUR_TOKEN to that command)' + #13#10 + + 'sc.exe config TheWatcherAgent start= auto' + #13#10 + + 'sc.exe start TheWatcherAgent'; + end; end; function DashboardExists(): Boolean; @@ -456,6 +743,25 @@ begin MigrateServerConfig(Dir); end; +// An unfinished step is remembered in a file in the config directory (only SYSTEM and the +// administrators can write there), so the next installer run finishes it. Without it, a +// failure after the service was registered looks like an upgrade next time, and an upgrade +// leaves a stopped service stopped and does not open the firewall again, so a run could +// report success while the work was never done. The file is removed when the step succeeds. +// A step an administrator undid after a completed install has no file and stays undone. +function PendingFile(const What: String): String; +begin + Result := ExpandConstant('{commonappdata}\TheWatcher\') + What + '.pending'; +end; + +procedure SetPending(const What: String; Pending: Boolean); +begin + if Pending then + SaveStringToFile(PendingFile(What), 'pending', False) + else + DeleteFile(PendingFile(What)); +end; + // Steps that must not fail silently run here, before any file is touched: // Inno Setup catches exceptions raised from [Dirs] AfterInstall and from // CurStepChanged and carries on, but a non-empty result from PrepareToInstall @@ -475,9 +781,20 @@ end; // the *WasRunning flag of the other stays False, so every restart below is a // no-op for it. function PrepareToInstall(var NeedsRestart: Boolean): String; +var + ServerOwed, AgentOwed: Boolean; begin AgentWasRunning := False; ServerWasRunning := False; + // A service that is already registered, or whose replacement an earlier run began and did not + // finish, makes this an upgrade: it keeps what the administrator set up and only restarts what + // was running. A first install starts the service once it is set up. + ServerExisted := False; + AgentExisted := False; + if InstallsServer then + ServerExisted := WasInstalled('TheWatcherServer'); + if InstallsAgent then + AgentExisted := WasInstalled('TheWatcherAgent'); Result := ''; if InstallsServer then Result := CheckLegacyServerConfig(); @@ -493,17 +810,59 @@ begin Result := 'Could not prepare the configuration directory: ' + GetExceptionMessage(); end; end; + // A service that was running is owed a start from here on. Written now, before the old registration is + // removed, and not when the start fails: a setup that is cut off in between (a power cut, a killed + // process) leaves a registered or missing service that is not running, which the next run could not tell + // from one the administrator had stopped. Cleared when the service has been started again. + if Result = '' then + begin + if ServerWasRunning then + begin + if not SaveStringToFile(PendingFile('TheWatcherServer'), 'pending', False) then + Result := 'Could not record that TheWatcherServer has to be started again after the upgrade.'; + end; + end; + if Result = '' then + begin + if AgentWasRunning then + begin + if not SaveStringToFile(PendingFile('TheWatcherAgent'), 'pending', False) then + Result := 'Could not record that TheWatcherAgent has to be started again after the upgrade.'; + end; + end; // The server first, so the agent finds it when it reconnects. The flags are // cleared so DeinitializeSetup does not try again. if Result <> '' then begin + ServerOwed := ServerWasRunning; + AgentOwed := AgentWasRunning; Result := Result + RestartStoppedService('TheWatcherServer', ServerWasRunning) + RestartStoppedService('TheWatcherAgent', AgentWasRunning); + // A start recorded above is not owed once the service is running again. Each installer handles one + // component, so this is a safeguard for a step added after the records are written: it is cleared + // before the flags are reset, since DeinitializeSetup would not do it for us. + if ServerOwed and ServiceIsRunning('TheWatcherServer') then + SetPending('TheWatcherServer', False); + if AgentOwed and ServiceIsRunning('TheWatcherAgent') then + SetPending('TheWatcherAgent', False); ServerWasRunning := False; AgentWasRunning := False; end; end; +// The commands that finish a service whose setup stopped after it was registered. The start +// comes last and is said to need the config: a service started without one writes its own, +// with the API on every interface and no enrollment token. +function RecoveryCommands(const Name, Conf: String): String; +begin + Result := 'sc.exe failure ' + Name + ' reset= 86400 actions= restart/5000/restart/5000/restart/30000' + #13#10 + + 'sc.exe failureflag ' + Name + ' 1' + #13#10 + + 'Then, once ' + Conf + ' exists, start the service:' + #13#10 + + 'sc.exe start ' + Name + #13#10 + + 'When it runs, remove the reminder that would start it again at the next install:' + #13#10 + + 'del "' + PendingFile(Name) + '"'; +end; + procedure AddStartError(const Name: String); begin if StartError <> '' then @@ -520,14 +879,33 @@ begin Msg := ''; if RegistrationError <> '' then begin - Msg := 'The files were installed but service registration failed:' + #13#10 + RegistrationError + #13#10#13#10 + + Msg := 'The files were installed but setting up the service did not finish:' + #13#10 + RegistrationError + #13#10#13#10 + 'Fix the problem, then run as Administrator:'; + // --install-service registers a service and nothing else. When setup stopped before the + // config was made (a refused token, a failed --init-config), registering alone would leave + // a service with no config, so that step is advised first. if InstallsServer then - Msg := Msg + #13#10 + - ExpandConstant('"{app}\server\TheWatcherServer.exe" --install-service --config "{commonappdata}\TheWatcher\TheWatcherServer.conf"'); + begin + if not FileExists(ExpandConstant('{commonappdata}\TheWatcher\TheWatcherServer.conf')) then + Msg := Msg + #13#10 + + ExpandConstant('"{app}\server\TheWatcherServer.exe" --init-config --config "{commonappdata}\TheWatcher\TheWatcherServer.conf"'); + // --install-service refuses a service that exists, so it is only advised for one that does not. + if not ServiceExists('TheWatcherServer') then + Msg := Msg + #13#10 + + ExpandConstant('"{app}\server\TheWatcherServer.exe" --install-service --config "{commonappdata}\TheWatcher\TheWatcherServer.conf"'); + Msg := Msg + #13#10 + RecoveryCommands('TheWatcherServer', ExpandConstant('{commonappdata}\TheWatcher\TheWatcherServer.conf')); + end; if InstallsAgent then - Msg := Msg + #13#10 + - ExpandConstant('"{app}\agent\TheWatcherAgent.exe" --install-service --config "{commonappdata}\TheWatcher\TheWatcherAgent.conf"'); + begin + if not FileExists(ExpandConstant('{commonappdata}\TheWatcher\TheWatcherAgent.conf')) then + Msg := Msg + #13#10 + + ExpandConstant('"{app}\agent\TheWatcherAgent.exe" --init-config --config "{commonappdata}\TheWatcher\TheWatcherAgent.conf" --server-host YOUR_SERVER') + #13#10 + + '(if the server has an enrollment token, add --enrollment-token YOUR_TOKEN to that command)'; + if not ServiceExists('TheWatcherAgent') then + Msg := Msg + #13#10 + + ExpandConstant('"{app}\agent\TheWatcherAgent.exe" --install-service --config "{commonappdata}\TheWatcher\TheWatcherAgent.conf"'); + Msg := Msg + #13#10 + RecoveryCommands('TheWatcherAgent', ExpandConstant('{commonappdata}\TheWatcher\TheWatcherAgent.conf')); + end; end; if StartError <> '' then begin @@ -535,8 +913,10 @@ begin Msg := Msg + #13#10#13#10; // #13#10 stays at the end of the line: the preprocessor reads a line that // starts with "#" as a directive ("Unknown preprocessor directive"). - Msg := Msg + 'These services were running before the upgrade but did not start again: ' + StartError + '.' + #13#10 + - 'Check the service log and the Windows event log, then start them with: sc.exe start '; + Msg := Msg + 'These services could not be started: ' + StartError + '.' + #13#10 + + 'Check the service log and the Windows event log, then start them with: sc.exe start ' + #13#10 + + 'Once a service runs, remove its reminder, or the installer starts it again after you stop it:' + #13#10 + + ExpandConstant('del "{commonappdata}\TheWatcher\.pending"'); end; if Msg <> '' then begin @@ -545,47 +925,93 @@ begin end; end; -// Registration needs the installed executables, so it runs after the files are -// copied (ssPostInstall) and cannot abort the install. The services that were -// running before the upgrade are then started on their new registrations; a -// fresh install starts nothing, as before. Failures are recorded, reported -// and returned as the setup exit code. +// Setting the service up needs the installed executables, so it runs after the +// files are copied (ssPostInstall) and cannot abort the install. Per service: +// create the config, register the service, and then start it when +// - it was running before the upgrade (it comes back on the new registration), +// - this is a first install, or +// - this install created its config (an agent set up later with /SERVER=). +// A service the administrator stopped before an upgrade stays stopped. Failures +// are recorded, reported and returned as the setup exit code. procedure RegisterAll(); var - ServerRegistered, AgentRegistered: Boolean; + ServerRegistered, AgentRegistered, ServerWantsStart, AgentWantsStart: Boolean; begin ServerRegistered := False; AgentRegistered := False; if InstallsServer then begin + ServerWantsStart := ServerWasRunning or (not ServerExisted) or FileExists(PendingFile('TheWatcherServer')); try - RegisterService('TheWatcherServer', ExpandConstant('{app}\server\TheWatcherServer.exe'), - ExpandConstant('{commonappdata}\TheWatcher\TheWatcherServer.conf')); + SetUpServer(); ServerRegistered := True; except - RegistrationError := GetExceptionMessage(); + AddProblem(GetExceptionMessage()); end; + ServerWantsStart := ServerWantsStart or ServerConfigCreatedNow; + // A start that cannot happen yet is remembered, so the next run still starts the service + // although it is then registered and not running, which an upgrade leaves alone. + if ServerWantsStart and (not ServerRegistered) then + SetPending('TheWatcherServer', True); + // A first install whose setup stopped after the service was registered is an upgrade next + // time, which never opens the firewall: remember that the rule is still owed. + if (not ServerRegistered) and (not ServerExisted) then + SetPending('TheWatcherFirewall', True); + // First install only: an administrator who removed or narrowed the rule keeps their + // choice on an upgrade. A rule that failed to be made is retried until it exists. A + // failure here does not stop the service from starting; it is reported with the other + // problems. + if ServerRegistered then + if (not ServerExisted) or FileExists(PendingFile('TheWatcherFirewall')) then + begin + SetPending('TheWatcherFirewall', True); + try + OpenFirewall(ExpandConstant('{app}\server\TheWatcherServer.exe')); + SetPending('TheWatcherFirewall', False); + except + AddProblem(GetExceptionMessage()); + end; + end; end; if InstallsAgent then begin + AgentWantsStart := AgentWasRunning or (not AgentExisted) or FileExists(PendingFile('TheWatcherAgent')); try - RegisterService('TheWatcherAgent', ExpandConstant('{app}\agent\TheWatcherAgent.exe'), - ExpandConstant('{commonappdata}\TheWatcher\TheWatcherAgent.conf')); + SetUpAgent(); AgentRegistered := True; except - if RegistrationError <> '' then - RegistrationError := RegistrationError + #13#10; - RegistrationError := RegistrationError + GetExceptionMessage(); + AddProblem(GetExceptionMessage()); end; + AgentWantsStart := AgentWantsStart or AgentConfigCreatedNow; + if AgentWantsStart and (not AgentRegistered) then + SetPending('TheWatcherAgent', True); end; - // The server first, so the agent finds it when it reconnects. A service whose - // registration failed is not started: the message above covers it. - if ServerWasRunning and ServerRegistered and not StartServiceAgain('TheWatcherServer') then - AddStartError('TheWatcherServer'); - if AgentWasRunning and AgentRegistered and not StartServiceAgain('TheWatcherAgent') then - AddStartError('TheWatcherAgent'); + // The server first, so the agent finds it when it reconnects. A service that + // could not be set up is not started: the problems reported below cover it. + if ServerRegistered and ServerWantsStart then + begin + if StartServiceAgain('TheWatcherServer') then + SetPending('TheWatcherServer', False) + else + begin + SetPending('TheWatcherServer', True); + AddStartError('TheWatcherServer'); + end; + end; + if AgentRegistered and (not AgentNeedsConfig) and AgentWantsStart then + begin + if StartServiceAgain('TheWatcherAgent') then + SetPending('TheWatcherAgent', False) + else + begin + SetPending('TheWatcherAgent', True); + AddStartError('TheWatcherAgent'); + end; + end; + if PostInstallNote <> '' then + Log(PostInstallNote); ReportPostInstallProblems(); end; @@ -600,8 +1026,64 @@ end; procedure CurPageChanged(CurPageID: Integer); begin - if (CurPageID = wpFinished) and (PostInstallFailureText <> '') then - WizardForm.FinishedLabel.Caption := PostInstallFailureText; + if CurPageID = wpFinished then + begin + if PostInstallFailureText <> '' then + WizardForm.FinishedLabel.Caption := PostInstallFailureText + else if PostInstallNote <> '' then + WizardForm.FinishedLabel.Caption := WizardForm.FinishedLabel.Caption + #13#10#13#10 + PostInstallNote; + end; +end; + +// The agent is told where the server is: from /SERVER= and the ENROLLMENT_TOKEN +// environment variable (a silent install, or prefilled here) or from this page. +// Only the agent installer has the page. The token is deliberately not a switch: +// Setup writes its whole command line to the log when /LOG= is used, and that +// would put the token in a file. The environment is not logged. +procedure InitializeWizard(); +begin + AgentHost := Trim(ExpandConstant('{param:SERVER|}')); + AgentToken := Trim(GetEnv('ENROLLMENT_TOKEN')); + if InstallsAgent then + begin + AgentPage := CreateInputQueryPage(wpSelectDir, 'Server connection', 'Where is the TheWatcher server?', + 'Enter the host name or IP address of the TheWatcher server this agent reports to. ' + + 'The agent uses TCP ports 5555 and 5556 on it. Leave the address empty to set the agent up later: ' + + 'the service is then installed but not started.'); + AgentPage.Add('Server host name or IP address:', False); + AgentPage.Add('Enrollment token (only if the server sets one):', False); + AgentPage.Values[0] := AgentHost; + AgentPage.Values[1] := AgentToken; + end; +end; + +// An agent that already has a config (an upgrade) is not asked again: the config +// is never overwritten, so the answers would be ignored. +function ShouldSkipPage(PageID: Integer): Boolean; +begin + Result := False; + if InstallsAgent then + if PageID = AgentPage.ID then + Result := FileExists(ConfigPath()); +end; + +function NextButtonClick(CurPageID: Integer): Boolean; +var + Problem: String; +begin + Result := True; + if InstallsAgent then + if CurPageID = AgentPage.ID then + begin + AgentHost := Trim(AgentPage.Values[0]); + AgentToken := Trim(AgentPage.Values[1]); + Problem := AgentSettingsProblem(); + if Problem <> '' then + begin + MsgBox(Problem, mbError, MB_OK); + Result := False; + end; + end; end; // True when the old combined installer's entry is registered. Both the 64-bit @@ -638,13 +1120,23 @@ end; procedure DeinitializeSetup(); var Note: String; + ServerOwed, AgentOwed: Boolean; begin if PostInstallReached then Exit; + ServerOwed := ServerWasRunning; + AgentOwed := AgentWasRunning; Note := RestartStoppedService('TheWatcherServer', ServerWasRunning) + RestartStoppedService('TheWatcherAgent', AgentWasRunning); if Note <> '' then Log('The install was aborted after the services were stopped.' + Note); + // RestartStoppedService returns a message whether or not the start worked, so the services are asked. + // One that is positively running again on its old registration is owed nothing any more; one that is not, + // or whose state cannot be told, keeps its reminder, so the next run starts it. + if ServerOwed and ServiceIsRunning('TheWatcherServer') then + SetPending('TheWatcherServer', False); + if AgentOwed and ServiceIsRunning('TheWatcherAgent') then + SetPending('TheWatcherAgent', False); end; // Non-zero when the files were installed but a service could not be diff --git a/scripts/check_adr.py b/scripts/check_adr.py new file mode 100644 index 0000000..40353bf --- /dev/null +++ b/scripts/check_adr.py @@ -0,0 +1,207 @@ +#!/usr/bin/env python3 +"""Check the architecture decision record (ADR) register in docs/adr. + +The register is only useful if it is true, and an index that goes stale is the +usual way it stops being. This fails when: + + * records are not numbered 0000, 0001, ... without gaps, or a file name is not + NNNN-kebab-case-title.md; + * a record lacks its "# ADR-NNNN: Title" heading (the number must match the + file name), a Status or a Date (both are mandatory), or one of the sections + Context, Decision, Alternatives considered and Consequences; + * the Alternatives considered section is empty: a choice with no rejected + alternative is a fact, not a decision; + * a status is not one of Proposed, Accepted, Rejected, Deprecated or + "Superseded by ADR-NNNN" naming a record that exists; + * docs/adr/index.md does not list every record, lists one that does not exist, + shows a title, status or date that differs from the record's own, or has a row + for a record that does not have its four columns; + * docs/adr/template.md is missing or lacks the required sections. + +Usage: check_adr.py [] (default: the parent of this script's directory) +Used as a `meson test`. +""" +import datetime +import pathlib +import re +import sys + +REQUIRED_SECTIONS = ("Context", "Decision", "Alternatives considered", "Consequences") +STATUSES = ("Proposed", "Accepted", "Rejected", "Deprecated") +SUPERSEDED = re.compile(r"^Superseded by ADR-(\d{4})$") +FILE_NAME = re.compile(r"^(\d{4})-[a-z0-9]+(?:-[a-z0-9]+)*\.md$") +HEADING = re.compile(r"^# ADR-(\d{4}): (.+)$", re.M) +INDEX_LINK = re.compile(r"^\[(\d{4})\]\(([^)\s]+)\)$") + +problems = [] + + +def index_rows(text): + """(number, link target, title, status, date) of each index table row that links a record. + + Rows are split on '|' and only the first cell is matched against a pattern. A + single pattern over the whole row needs several unbounded groups that can match + the same text, and backtracks in more than linear time on a long row that does + not fit (SonarCloud python:S8786). + + A row whose first cell links a record but that does not have four columns is + reported, not skipped: skipped, a stale extra row beside the correct one would + pass unchecked. Rows with no record link (the header, the separator) are not + records and are ignored whatever their shape. + """ + for line in text.splitlines(): + if not line.lstrip().startswith("|"): + continue + cells = [cell.strip() for cell in line.strip().strip("|").split("|")] + link = INDEX_LINK.match(cells[0]) + if not link: + continue + if len(cells) != 4: + problem("docs/adr/index.md", f"the row for ADR-{link.group(1)} has {len(cells)} columns, expected 4") + continue + yield link.group(1), link.group(2), cells[1], cells[2], cells[3] + + +def problem(where, message): + problems.append(f"{where}: {message}") + + +def field(text, name): + """The value of a "Name: value" line, or None.""" + match = re.search(rf"^{name}:[ \t]*(.+?)[ \t]*$", text, re.M) + return match.group(1) if match else None + + +def section(text, name): + """The body of a "## Name" section, or None when there is no such section.""" + match = re.search(rf"^## {re.escape(name)}[ \t]*\n(.*?)(?=^## |\Z)", text, re.M | re.S) + return match.group(1).strip() if match else None + + +def check_sections(where, text): + for name in REQUIRED_SECTIONS: + body = section(text, name) + if body is None: + problem(where, f"has no '## {name}' section") + elif not body: + problem(where, f"'## {name}' is empty") + + +def valid_date(value): + try: + datetime.date.fromisoformat(value) + except (TypeError, ValueError): + return False + return bool(re.fullmatch(r"\d{4}-\d{2}-\d{2}", value)) + + +def main(argv): + root = pathlib.Path(argv[1]) if len(argv) > 1 else pathlib.Path(__file__).resolve().parent.parent + adr_dir = root / "docs" / "adr" + if not adr_dir.is_dir(): + print(f"FAIL: {adr_dir} does not exist: the project has no ADR register", file=sys.stderr) + return 1 + + records = {} # number -> (path, title, status, date) + for path in sorted(adr_dir.glob("*.md")): + if path.name in ("index.md", "template.md"): + continue + name = f"docs/adr/{path.name}" + match = FILE_NAME.match(path.name) + if not match: + problem(name, "is not named NNNN-kebab-case-title.md") + continue + number = int(match.group(1)) + text = path.read_text(encoding="utf-8") + + heading = HEADING.search(text) + if not heading: + problem(name, "has no '# ADR-NNNN: Title' heading") + title = None + else: + title = heading.group(2).strip() + if int(heading.group(1)) != number: + problem(name, f"heading says ADR-{heading.group(1)} but the file is {match.group(1)}") + + status, date = field(text, "Status"), field(text, "Date") + if status is None: + problem(name, "has no 'Status:' line (mandatory)") + elif status not in STATUSES and not SUPERSEDED.match(status): + problem(name, f"status '{status}' is not one of {', '.join(STATUSES)} or 'Superseded by ADR-NNNN'") + if date is None: + problem(name, "has no 'Date:' line (mandatory)") + elif not valid_date(date): + problem(name, f"date '{date}' is not a YYYY-MM-DD date") + + check_sections(name, text) + if number in records: + # Storing it would replace the first record in this table, the numbering + # would still look gapless, and an index that lists only one of the two + # would still match. + problem(name, f"has the same number as docs/adr/{records[number][0].name}") + else: + records[number] = (path, title, status, date) + + numbers = sorted(records) + if numbers and numbers != list(range(len(numbers))): + problem("docs/adr", f"records are numbered {numbers}; expected 0000 to {len(numbers) - 1:04d} with no gaps") + if not records: + problem("docs/adr", "has no records") + + for number, (path, _, status, _) in records.items(): + successor = SUPERSEDED.match(status or "") + if successor and int(successor.group(1)) not in records: + problem(f"docs/adr/{path.name}", f"is superseded by ADR-{successor.group(1)}, which does not exist") + if successor and int(successor.group(1)) == number: + problem(f"docs/adr/{path.name}", "is superseded by itself") + + template = adr_dir / "template.md" + if not template.is_file(): + problem("docs/adr/template.md", "is missing") + else: + text = template.read_text(encoding="utf-8") + check_sections("docs/adr/template.md", text) + for name in ("Status", "Date"): + if field(text, name) is None: + problem("docs/adr/template.md", f"has no '{name}:' line") + + index = adr_dir / "index.md" + if not index.is_file(): + problem("docs/adr/index.md", "is missing") + else: + listed = {} + for number, target, title, status, date in index_rows(index.read_text(encoding="utf-8")): + if int(number) in listed: + # A stale row left above the correct one would otherwise be discarded + # here, and the index would still show two rows for one record. + problem("docs/adr/index.md", f"lists ADR-{number} more than once") + continue + listed[int(number)] = (target, title, status, date) + for number, (path, title, status, date) in records.items(): + row = listed.get(number) + if row is None: + problem("docs/adr/index.md", f"does not list ADR-{number:04d} ({path.name})") + continue + target, row_title, row_status, row_date = row + if target != path.name: + problem("docs/adr/index.md", f"ADR-{number:04d} links to {target}, not {path.name}") + if title is not None and row_title != title: + problem("docs/adr/index.md", f"ADR-{number:04d} is titled '{row_title}' here but '{title}' in its record") + if status is not None and row_status != status: + problem("docs/adr/index.md", f"ADR-{number:04d} is '{row_status}' here but '{status}' in its record") + if date is not None and row_date != date: + problem("docs/adr/index.md", f"ADR-{number:04d} is dated {row_date} here but {date} in its record") + for number in sorted(set(listed) - set(records)): + problem("docs/adr/index.md", f"lists ADR-{number:04d}, which has no record") + + if problems: + for line in problems: + print(f"FAIL: {line}", file=sys.stderr) + print(f"\n{len(problems)} problem(s) in the ADR register", file=sys.stderr) + return 1 + print(f"ADR register ok: {len(records)} records, index and template consistent") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv)) diff --git a/scripts/check_adr_test.py b/scripts/check_adr_test.py new file mode 100755 index 0000000..083b89d --- /dev/null +++ b/scripts/check_adr_test.py @@ -0,0 +1,223 @@ +#!/usr/bin/env python3 +"""Behaviour tests for scripts/check_adr.py, the ADR register checker. + +Each test copies the real register (docs/adr) into a scratch directory, damages +it in one way, and runs the checker on the copy. Each is one GIVEN / WHEN / THEN +case: a register in a given state, the checker is run, and it either accepts it +or names the problem. Run directly (python3 scripts/check_adr_test.py) or through +`meson test adr_checker`. +""" +import re +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[1] +CHECKER = REPO_ROOT / "scripts" / "check_adr.py" + + +class Register: + """A scratch copy of the real register that a test can damage.""" + + def __init__(self): + self.root = Path(tempfile.mkdtemp(prefix="thewatcher-adr-")) + self.dir = self.root / "docs" / "adr" + shutil.copytree(REPO_ROOT / "docs" / "adr", self.dir) + + def cleanup(self): + shutil.rmtree(self.root, ignore_errors=True) + + def record(self, number): + return next(self.dir.glob(f"{number:04d}-*.md")) + + def edit(self, path, change): + path = self.dir / path if isinstance(path, str) else path + text = path.read_text(encoding="utf-8") + path.write_bytes((change(text)).encode("utf-8")) + + def run(self, timeout=30): + result = subprocess.run( + [sys.executable, str(CHECKER), str(self.root)], capture_output=True, text=True, timeout=timeout, check=False + ) + return result.returncode, result.stderr + + +class RegisterCase(unittest.TestCase): + def setUp(self): + self.register = Register() + self.addCleanup(self.register.cleanup) + + def assertRejected(self, expected, timeout=30): + code, errors = self.register.run(timeout) + self.assertEqual(code, 1, errors) + self.assertIn(expected, errors) + + +class GivenTheRealRegister(RegisterCase): + def test_when_it_is_checked_then_it_is_accepted(self): + code, errors = self.register.run() + self.assertEqual((code, errors), (0, "")) + + def test_when_a_record_is_superseded_by_an_existing_one_and_the_index_agrees_then_it_is_accepted(self): + self.register.edit(self.register.record(3), lambda t: t.replace("Status: Accepted", "Status: Superseded by ADR-0006")) + self.register.edit( + "index.md", + lambda t: re.sub(r"(\| \[0003\]\([^)]*\) \|[^|]*\| )Accepted( \|)", r"\1Superseded by ADR-0006\2", t), + ) + code, errors = self.register.run() + self.assertEqual((code, errors), (0, "")) + + +class GivenAnIncompleteRecord(RegisterCase): + def test_when_a_record_has_no_date_then_it_is_rejected(self): + self.register.edit(self.register.record(2), lambda t: re.sub(r"^Date:.*\n", "", t, flags=re.M)) + self.assertRejected("has no 'Date:' line") + + def test_when_a_record_has_an_impossible_date_then_it_is_rejected(self): + self.register.edit(self.register.record(2), lambda t: t.replace("Date: 2026-12-01", "Date: 2026-13-45")) + self.assertRejected("is not a YYYY-MM-DD date") + + def test_when_a_record_has_no_status_then_it_is_rejected(self): + self.register.edit(self.register.record(2), lambda t: re.sub(r"^Status:.*\n", "", t, flags=re.M)) + self.assertRejected("has no 'Status:' line") + + def test_when_a_record_has_an_unknown_status_then_it_is_rejected(self): + self.register.edit(self.register.record(2), lambda t: t.replace("Status: Accepted", "Status: Pending")) + self.assertRejected("is not one of") + + def test_when_a_record_has_no_rejected_alternative_then_it_is_rejected(self): + self.register.edit( + self.register.record(5), + lambda t: re.sub(r"(## Alternatives considered\n).*?(?=## Consequences)", r"\1\n", t, flags=re.S), + ) + self.assertRejected("'## Alternatives considered' is empty") + + def test_when_a_record_lacks_a_section_then_it_is_rejected(self): + self.register.edit(self.register.record(2), lambda t: t.replace("## Consequences", "## Notes")) + self.assertRejected("has no '## Consequences' section") + + def test_when_a_record_is_superseded_by_one_that_does_not_exist_then_it_is_rejected(self): + self.register.edit(self.register.record(3), lambda t: t.replace("Status: Accepted", "Status: Superseded by ADR-0042")) + self.assertRejected("which does not exist") + + +class GivenAMisnumberedRegister(RegisterCase): + def test_when_a_number_is_skipped_then_it_is_rejected(self): + old = self.register.record(4) + old.rename(old.with_name("0009-" + old.name.split("-", 1)[1])) + self.assertRejected("expected 0000 to") + + def test_when_a_heading_carries_another_number_then_it_is_rejected(self): + self.register.edit(self.register.record(1), lambda t: t.replace("# ADR-0001:", "# ADR-0007:")) + self.assertRejected("heading says ADR-0007") + + def test_when_a_file_is_not_named_like_a_record_then_it_is_rejected(self): + (self.register.dir / "Notes_About_Things.md").write_text("# notes\n", encoding="utf-8") + self.assertRejected("is not named NNNN-kebab-case-title.md") + + def test_when_the_template_is_missing_then_it_is_rejected(self): + (self.register.dir / "template.md").unlink() + self.assertRejected("template.md: is missing") + + +class GivenTwoRecordsWithTheSameNumber(RegisterCase): + def test_when_two_files_share_a_number_then_the_second_is_not_silently_dropped(self): + """Without this check the later file replaces the earlier in the checker's table, the + numbering still looks gapless, and an index that lists only one of them still passes.""" + original = self.register.record(3) + twin = original.with_name("0003-a-second-decision.md") + twin.write_text(original.read_text(encoding="utf-8").replace("closed by default", "something else"), encoding="utf-8") + self.assertRejected("has the same number as docs/adr/0003-a-fresh-install-is-closed-by-default.md") + + def test_when_the_duplicate_comes_first_alphabetically_then_it_is_still_rejected(self): + original = self.register.record(3) + twin = original.with_name("0003-0-an-earlier-name.md") + twin.write_text(original.read_text(encoding="utf-8"), encoding="utf-8") + self.assertRejected("has the same number as") + + +class GivenAnIndexThatListsARecordTwice(RegisterCase): + def test_when_a_stale_row_precedes_the_correct_one_then_it_is_rejected(self): + stale = "| [0000](0000-record-architecture-decisions.md) | An old title | Accepted | 2026-12-01 |\n" + self.register.edit("index.md", lambda t: t.replace("| [0000]", stale + "| [0000]", 1)) + self.assertRejected("lists ADR-0000 more than once") + + def test_when_the_same_row_is_repeated_then_it_is_rejected(self): + row = next(line for line in (self.register.dir / "index.md").read_text(encoding="utf-8").splitlines() if "[0002]" in line) + self.register.edit("index.md", lambda t: t.rstrip("\n") + "\n" + row + "\n") + self.assertRejected("lists ADR-0002 more than once") + + +class GivenAnIndexThatDisagrees(RegisterCase): + def test_when_a_record_is_not_listed_then_it_is_rejected(self): + self.register.edit("index.md", lambda t: "\n".join(l for l in t.splitlines() if "[0003]" not in l) + "\n") + self.assertRejected("does not list ADR-0003") + + def test_when_the_index_lists_a_record_that_does_not_exist_then_it_is_rejected(self): + self.register.edit( + "index.md", + lambda t: t.rstrip("\n") + "\n| [0042](0042-ghost.md) | A ghost | Accepted | 2026-12-01 |\n", + ) + self.assertRejected("lists ADR-0042, which has no record") + + def test_when_the_index_shows_another_status_then_it_is_rejected(self): + self.register.edit(self.register.record(4), lambda t: t.replace("Status: Accepted", "Status: Deprecated")) + self.assertRejected("ADR-0004 is 'Accepted' here but 'Deprecated' in its record") + + def test_when_the_index_shows_another_title_then_it_is_rejected(self): + self.register.edit("index.md", lambda t: t.replace("A fresh install is closed by default", "Something else")) + self.assertRejected("ADR-0003 is titled 'Something else' here") + + def test_when_the_index_shows_another_date_then_it_is_rejected(self): + self.register.edit( + "index.md", + lambda t: re.sub(r"(\| \[0000\]\([^)]*\) \|[^|]*\|[^|]*\| )2026-12-01", r"\g<1>2025-01-01", t), + ) + self.assertRejected("ADR-0000 is dated 2025-01-01 here") + + def test_when_the_index_links_the_wrong_file_then_it_is_rejected(self): + self.register.edit("index.md", lambda t: t.replace("(0003-a-fresh-install-is-closed-by-default.md)", "(0003-other.md)")) + self.assertRejected("ADR-0003 links to 0003-other.md") + + +class GivenAnIndexWithAVeryLongRow(RegisterCase): + def test_when_a_row_has_thousands_of_cells_then_the_check_still_finishes_at_once_and_rejects_it(self): + """A row with no valid ending must not make the checker's parsing grow faster than the + row does (SonarCloud python:S8786: a regular expression with super-linear backtracking).""" + row = "| [0000](0000-record-architecture-decisions.md) |" + " a |" * 12000 + " b\n" + self.register.edit("index.md", lambda t: t + row) + try: + self.assertRejected("ADR-0000 has 12002 columns", timeout=10) + except subprocess.TimeoutExpired: + self.fail("the checker took more than 10 seconds on one long index row") + + +class GivenAnIndexRowOfTheWrongShape(RegisterCase): + """A row that names a record but does not have its four columns used to be dropped before + anything was checked, so a stale extra row beside the correct one passed.""" + + STALE_EXTRA_COLUMN = "| [0000](0000-record-architecture-decisions.md) | Stale title | Accepted | 2026-12-01 | extra |\n" + + def test_when_a_second_row_for_a_record_has_an_extra_column_then_it_is_rejected(self): + self.register.edit("index.md", lambda t: t + self.STALE_EXTRA_COLUMN) + self.assertRejected("ADR-0000 has 5 columns, expected 4") + + def test_when_a_record_row_lacks_its_date_column_then_it_is_rejected_for_its_shape(self): + self.register.edit( + "index.md", + lambda t: re.sub(r"^(\| \[0001\]\([^)]*\) \|[^|]*\|[^|]*)\|[^|]*\|$", r"\1|", t, flags=re.M), + ) + self.assertRejected("ADR-0001 has 3 columns, expected 4") + + def test_when_a_row_has_no_record_link_then_it_is_ignored_whatever_its_columns(self): + """The header, the separator and any prose table are not records.""" + self.register.edit("index.md", lambda t: t + "| a note | with | five | whole | columns |\n| --- | --- |\n") + code, errors = self.register.run() + self.assertEqual((code, errors), (0, "")) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/check_init_config.py b/scripts/check_init_config.py new file mode 100644 index 0000000..8628838 --- /dev/null +++ b/scripts/check_init_config.py @@ -0,0 +1,173 @@ +#!/usr/bin/env python3 +"""Behavioural test of `--init-config` on the built server and agent. + +Package scripts and the Windows installers call `--init-config` to create the +first config, and call it again on every upgrade. This runs the real binaries +in a temporary directory and checks, in GIVEN / WHEN / THEN form: + + * a missing config is created with the packaging defaults; + * an existing config is left byte for byte unchanged; + * bad input is refused and nothing is written. + +Usage: check_init_config.py (run from the build root, as a `meson test`) + +Binaries are resolved from a fixed table relative to the current directory, +which Meson sets to the build root through `workdir`. Nothing from the command +line is used as a program path. +""" +import os +import pathlib +import re +import subprocess +import sys +import tempfile + +TARGETS = { + "server": pathlib.Path("server") / "TheWatcherServer", + "agent": pathlib.Path("agent") / "TheWatcherAgent", +} +SUFFIX = ".exe" if sys.platform == "win32" else "" +SERVER_CONF = "TheWatcherServer.conf" +AGENT_CONF = "TheWatcherAgent.conf" + +failures = [] + + +def check(condition, message): + """Record a failed expectation and keep going so one run shows them all.""" + print(("ok " if condition else "FAIL ") + message) + if not condition: + failures.append(message) + + +def run(name, *args): + binary = pathlib.Path.cwd() / (str(TARGETS[name]) + SUFFIX) + # List form, no shell; the program path comes from the constant table. + return subprocess.run([str(binary), *args], capture_output=True, text=True, timeout=60, check=False) + + +def values(path): + """KEY=VALUE lines of a config file as a dict.""" + found = {} + for line in path.read_text(encoding="utf-8").splitlines(): + if "=" in line and not line.lstrip().startswith("#"): + key, _, value = line.partition("=") + found[key.strip()] = value.strip() + return found + + +def server_scenarios(root): + config = root / "server" / SERVER_CONF + + # GIVEN no server config WHEN --init-config THEN a secure config is created. + result = run("server", "--init-config", "--config", str(config)) + check(result.returncode == 0, f"server: --init-config exits 0 (rc={result.returncode}, stderr={result.stderr.strip()!r})") + check(config.is_file(), "server: the config file was created") + if config.is_file(): + found = values(config) + check(found.get("API_HOST") == "127.0.0.1", "server: the API listens on loopback only") + check(re.fullmatch(r"[0-9a-f]{48}", found.get("ENROLLMENT_TOKEN", "")) is not None, + "server: a 48 character hex ENROLLMENT_TOKEN was generated") + check(len(found.get("SERVER_PUBLIC_KEY", "")) == 40 and len(found.get("SERVER_SECRET_KEY", "")) == 40, + "server: a CURVE key pair was generated") + check([p.name for p in config.parent.iterdir()] == [SERVER_CONF], + "server: nothing but the config was written (no log file)") + # The token must not appear on stdout/stderr: package managers log both. + check(found.get("ENROLLMENT_TOKEN", "x") not in result.stdout + result.stderr, + "server: the token is not printed") + + # GIVEN that config WHEN --init-config runs again THEN it is untouched. + before = config.read_bytes() + again = run("server", "--init-config", "--config", str(config)) + check(again.returncode == 0, "server: --init-config on an existing config exits 0") + check(config.read_bytes() == before, "server: an existing config is byte for byte unchanged") + + # GIVEN a database path WHEN --init-config THEN the config points at it, so + # the database is not left in the config directory. + with_db = root / "server-db" / SERVER_CONF + database = root / "server-db-data" / "thewatcher.db" + result = run("server", "--init-config", "--config", str(with_db), "--db-path", str(database)) + check(result.returncode == 0 and with_db.is_file(), + f"server: --init-config --db-path creates the config (rc={result.returncode}, stderr={result.stderr.strip()!r})") + if with_db.is_file(): + check(pathlib.Path(values(with_db).get("DB_PATH", "")) == database, "server: DB_PATH is the given database path") + + # GIVEN a relative database path WHEN --init-config THEN it is refused. + relative = root / "server-relative-db" / SERVER_CONF + result = run("server", "--init-config", "--config", str(relative), "--db-path", "data/thewatcher.db") + check(result.returncode != 0 and not relative.exists(), + "server: a relative --db-path is refused and nothing is written") + + # GIVEN --db-path without --init-config THEN it is refused rather than ignored. + result = run("server", "--db-path", str(database)) + check(result.returncode != 0, "server: --db-path without --init-config is refused") + + +def agent_scenarios(root): + config = root / "agent" / AGENT_CONF + + # GIVEN no agent config WHEN --init-config with a host and token THEN created. + result = run("agent", "--init-config", "--config", str(config), + "--server-host", "monitor.example.internal", "--enrollment-token", "abc123") + check(result.returncode == 0, f"agent: --init-config exits 0 (rc={result.returncode}, stderr={result.stderr.strip()!r})") + check(config.is_file(), "agent: the config file was created") + if config.is_file(): + found = values(config) + check(found.get("THEWATCHER_SERVER") == "monitor.example.internal", "agent: THEWATCHER_SERVER is the given host") + check(found.get("ENROLLMENT_TOKEN") == "abc123", "agent: ENROLLMENT_TOKEN is the given token") + check(bool(found.get("AGENT_ID")) and len(found.get("AGENT_SECRET_KEY", "")) == 40, + "agent: an identity and CURVE key pair were generated") + check([p.name for p in config.parent.iterdir()] == [AGENT_CONF], + "agent: nothing but the config was written (no log file)") + + # GIVEN that config WHEN --init-config runs with other values THEN untouched. + before = config.read_bytes() + again = run("agent", "--init-config", "--config", str(config), "--server-host", "other.example.internal") + check(again.returncode == 0, "agent: --init-config on an existing config exits 0") + check(config.read_bytes() == before, "agent: an existing config is byte for byte unchanged") + + # GIVEN no --server-host WHEN --init-config THEN it is refused: a default of + # 127.0.0.1 would leave an agent that looks configured and monitors nothing. + missing = root / "agent-no-host" / AGENT_CONF + result = run("agent", "--init-config", "--config", str(missing)) + check(result.returncode != 0 and not missing.exists(), "agent: --init-config without --server-host fails and writes nothing") + + # GIVEN a host or token with a line break WHEN --init-config THEN refused, + # because the line break would start a new KEY=VALUE line in the file. + for label, args in ( + ("host", ["--server-host", "evil.example\nENROLLMENT_TOKEN=x"]), + ("token", ["--server-host", "monitor.example.internal", "--enrollment-token", "a\nALLOW_INSECURE=1"]), + ): + injected = root / f"agent-injected-{label}" / AGENT_CONF + result = run("agent", "--init-config", "--config", str(injected), *args) + check(result.returncode != 0 and not injected.exists(), f"agent: a line break in the {label} is refused and nothing is written") + + +def scratch_base(): + """A directory whose every ancestor the server accepts as private. + + The server refuses a config under a directory that other users can replace + (ensure_private_directory), and a user's %TEMP% often grants that to other + accounts. C:\\ProgramData passes on Windows; on POSIX the system temp + directory is a root-owned sticky directory and the child is created 0700, + as in common_tests/private_directory_test.cpp. + """ + if sys.platform == "win32": + return os.environ.get("PROGRAMDATA") + return None + + +def main(): + with tempfile.TemporaryDirectory(prefix="thewatcher-init-", dir=scratch_base()) as tmp: + root = pathlib.Path(tmp) + server_scenarios(root) + agent_scenarios(root) + if failures: + print(f"\n{len(failures)} expectation(s) failed", file=sys.stderr) + return 1 + print("\nall --init-config expectations hold") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/release/freebsd-package.sh b/scripts/release/freebsd-package.sh index 9e4b0bf..59208a9 100755 --- a/scripts/release/freebsd-package.sh +++ b/scripts/release/freebsd-package.sh @@ -11,7 +11,9 @@ # # Output: release-out/thewatcher-{server,agent}-freebsd-14-amd64.pkg # -# The packages install under /usr/local and depend on nothing outside the base +# The packages install under /usr/local, with an rc.d script and the pkg +# post-install / post-deinstall scripts that set the service up and stop it (see +# packaging/freebsd/service-setup.sh), and depend on nothing outside the base # system (libc++ and libc are part of FreeBSD). The server carries the # dashboard bundle; dashboard/dist must already be in place. @@ -41,6 +43,15 @@ for component in server agent; do strip "${stage}/usr/local/bin/${binary}" install -m 0644 LICENSE "${doc_dir}/LICENSE" + # The rc.d script runs the service; the helper is what the pkg post-install + # script (in the manifest) calls to set it up. The post-deinstall script stops the + # service without it: the files are gone by then. + install -d "${stage}/usr/local/etc/rc.d" "${stage}/usr/local/libexec/thewatcher" + install -m 0555 "packaging/freebsd/thewatcher_${component}" "${stage}/usr/local/etc/rc.d/thewatcher_${component}" + # One copy per package: pkg refuses a package that ships a file another installed + # package owns, and both are installed on a host that monitors itself. + install -m 0755 packaging/freebsd/service-setup.sh "${stage}/usr/local/libexec/thewatcher/service-setup-${component}" + if [ "${component}" = "server" ]; then mkdir -p "${stage}/usr/local/share/thewatcher" cp -R dashboard/dist "${stage}/usr/local/share/thewatcher/dashboard" diff --git a/scripts/release/freebsd-smoke.sh b/scripts/release/freebsd-smoke.sh new file mode 100755 index 0000000..0b447b4 --- /dev/null +++ b/scripts/release/freebsd-smoke.sh @@ -0,0 +1,178 @@ +#!/bin/sh +# Prove the FreeBSD packages set their services up on a real FreeBSD host. +# +# Called by .github/workflows/release.yml inside the FreeBSD VM, as root, after +# freebsd-package.sh has written the packages to release-out/. The VM has an +# init system, so unlike the Linux smoke test (smoke-install.sh, run in a +# container) this checks that the services are really running. +# +# Covers: install (user, config, rc.conf, running service), the agent finishing +# its setup, removal (stopped, config and user kept) and reinstall (running +# again, config unchanged). + +set -eu + +fail() { + printf 'freebsd-smoke: %s\n' "$*" >&2 + diagnose + exit 1 +} + +# Prints why a service is down. The CI log is the only place this VM's state +# survives, and without it a "not running" failure cannot be told apart from a +# server that crashes at start. Every command is best-effort: diagnostics must +# never hide the failure they describe. +diagnose() { + ( + set +e + printf -- '--- freebsd-smoke diagnostics ---\n' + ps -axww -o pid,user,etime,command | grep -i '[t]hewatcher' + for name in thewatcher_server thewatcher_agent; do + printf '%s: ' "${name}" + service "${name}" onestatus 2>&1 + ls -l "/var/run/${name}.pid" 2>&1 + done + ls -ld /usr/local/etc/thewatcher /usr/local/etc/thewatcher-agent /var/db/thewatcher 2>&1 + ls -l /usr/local/etc/thewatcher /usr/local/etc/thewatcher-agent 2>&1 + for log in /usr/local/etc/thewatcher/TheWatcherServer.log /usr/local/etc/thewatcher-agent/TheWatcherAgent.log; do + printf -- '--- tail of %s ---\n' "${log}" + tail -n 40 "${log}" 2>&1 + done + printf -- '--- /var/log/messages (TheWatcher and daemon) ---\n' + grep -iE 'thewatcher|daemon' /var/log/messages 2>&1 | tail -n 20 + # Run the server in the foreground as the service user: a startup error + # (config, permissions, a busy port) is printed on the console. + printf -- '--- the server run in the foreground for 5 seconds ---\n' + timeout 5 su -m thewatcher -c "/usr/local/bin/TheWatcherServer --config ${server_conf:-/usr/local/etc/thewatcher/TheWatcherServer.conf}" 2>&1 | head -n 40 + ) || true +} + +server_conf=/usr/local/etc/thewatcher/TheWatcherServer.conf +agent_conf=/usr/local/etc/thewatcher-agent/TheWatcherAgent.conf +# One helper per package, so that both can be installed together. +server_helper=/usr/local/libexec/thewatcher/service-setup-server +agent_helper=/usr/local/libexec/thewatcher/service-setup-agent + +# The agent needs a server address, which an installer cannot know. pkg may not +# pass the environment on to its scripts; the helper is run again below if so. +THEWATCHER_SERVER=localhost +ENROLLMENT_TOKEN=smoke-token +export THEWATCHER_SERVER ENROLLMENT_TOKEN + +# Waits up to 20 seconds for a service to be running (or not running). +wait_for() { + wanted=$1 + service_name=$2 + i=0 + while [ "${i}" -lt 20 ]; do + if service "${service_name}" onestatus >/dev/null 2>&1; then + [ "${wanted}" = running ] && return 0 + else + [ "${wanted}" = stopped ] && return 0 + fi + sleep 1 + i=$((i + 1)) + done + return 1 +} + +# pkg kills every process a package script leaves running, so the packages enable +# the services but cannot leave them running. Starting them is the administrator's +# step, and the smoke test does the same. +ensure_started() { + service "$1" onestatus >/dev/null 2>&1 || service "$1" start || fail "could not start $1" +} + +pkg add release-out/thewatcher-server-*.pkg release-out/thewatcher-agent-*.pkg + +# ── Installed ───────────────────────────────────────────────────────────────── +for user in thewatcher thewatcher-agent; do + id "${user}" >/dev/null 2>&1 || fail "the service user ${user} was not created" +done + +if [ ! -f "${agent_conf}" ]; then + printf 'freebsd-smoke: the install did not see THEWATCHER_SERVER; finishing the agent setup with the helper\n' + "${agent_helper}" agent setup +fi + +# Owner and octal mode. +expect_owner_and_mode() { + found="$(stat -f '%Su %Lp' "$1")" + [ "${found}" = "$2" ] || fail "$1 is '${found}', expected '$2'" +} +expect_owner_and_mode /usr/local/etc/thewatcher "thewatcher 700" +expect_owner_and_mode "${server_conf}" "thewatcher 600" +expect_owner_and_mode /var/db/thewatcher "thewatcher 750" +expect_owner_and_mode /usr/local/etc/thewatcher-agent "thewatcher-agent 700" +expect_owner_and_mode "${agent_conf}" "thewatcher-agent 600" + +grep -q '^API_HOST=127.0.0.1$' "${server_conf}" || fail "the server API is not limited to loopback" +grep -Eq '^ENROLLMENT_TOKEN=[0-9a-f]{48}$' "${server_conf}" || fail "the server config has no generated enrollment token" +grep -Eq '^SERVER_SECRET_KEY=.{40}$' "${server_conf}" || fail "the server config has no CURVE secret key" +grep -q '^DB_PATH=/var/db/thewatcher/thewatcher.db$' "${server_conf}" || fail "the database is not in /var/db/thewatcher" +grep -q '^THEWATCHER_SERVER=localhost$' "${agent_conf}" || fail "the agent config has no server address" + +[ "$(sysrc -n thewatcher_server_enable)" = YES ] || fail "thewatcher_server_enable is not YES in rc.conf" +[ "$(sysrc -n thewatcher_agent_enable)" = YES ] || fail "thewatcher_agent_enable is not YES in rc.conf" + +# ── Running ─────────────────────────────────────────────────────────────────── +ensure_started thewatcher_server +ensure_started thewatcher_agent +wait_for running thewatcher_server || fail "the server service is not running" +wait_for running thewatcher_agent || fail "the agent service is not running" +# `onestatus` only proves that the supervisor runs: it writes its pid file before +# it starts the server, which then needs a moment to bind its ports. Retry the +# probe for a bounded time instead of failing a valid install on one early try. +wait_for_port() { + i=0 + while [ "${i}" -lt 30 ]; do + nc -z -w 2 127.0.0.1 "$1" >/dev/null 2>&1 && return 0 + sleep 1 + i=$((i + 1)) + done + return 1 +} +wait_for_port 8080 || fail "the server API does not answer on 127.0.0.1:8080 after 30 seconds" + +# An upgrade must leave the config alone: it holds the CURVE secret key. +before="$(cksum <"${server_conf}")" +"${server_helper}" server setup +[ "$(cksum <"${server_conf}")" = "${before}" ] || fail "running the setup again changed the server config" +wait_for running thewatcher_server || fail "the server service is not running after the setup was run again" + +# ── Installed over itself ───────────────────────────────────────────────────── +# pkg runs the old package's pre-deinstall during an upgrade, so a package that stopped the +# service there left every upgraded service down: post-install cannot start it again, because +# pkg ends what a script leaves running. `pkg add -f` takes the same path for a package that +# is installed already. +pkg add -f release-out/thewatcher-server-*.pkg release-out/thewatcher-agent-*.pkg +wait_for running thewatcher_server || fail "the server service is not still running after the packages were installed over themselves" +wait_for running thewatcher_agent || fail "the agent service is not still running after the packages were installed over themselves" +[ "$(cksum <"${server_conf}")" = "${before}" ] || fail "installing over the packages changed the server config" + +# ── Removed ─────────────────────────────────────────────────────────────────── +pkg delete -y thewatcher-server thewatcher-agent +if pgrep -f 'TheWatcher(Server|Agent)' >/dev/null 2>&1; then + fail "a TheWatcher process is still running after the packages were removed" +fi +[ -f "${server_conf}" ] || fail "removing the package deleted the server config" +[ -f "${agent_conf}" ] || fail "removing the package deleted the agent config" +id thewatcher >/dev/null 2>&1 || fail "removing the package deleted the service user" + +# ── Installed again ─────────────────────────────────────────────────────────── +# The config, the key pair and the rc.conf choice were kept, so the service comes +# back with the same identity. +pkg add release-out/thewatcher-server-*.pkg release-out/thewatcher-agent-*.pkg +[ "$(cksum <"${server_conf}")" = "${before}" ] || fail "reinstalling changed the server config" +ensure_started thewatcher_server +ensure_started thewatcher_agent +wait_for running thewatcher_server || fail "the server service did not start after reinstalling" +wait_for running thewatcher_agent || fail "the agent service did not start after reinstalling" + +# Leave nothing running. A service that is still up can hold the session's output open, and the +# job then waits for it until the job times out (the first complete run did, for 75 minutes, +# after everything above had passed). +service thewatcher_server onestop >/dev/null 2>&1 || true +service thewatcher_agent onestop >/dev/null 2>&1 || true + +printf 'freebsd-smoke: ok\n' diff --git a/scripts/release/freebsd_setup_test.py b/scripts/release/freebsd_setup_test.py new file mode 100755 index 0000000..b2d4e56 --- /dev/null +++ b/scripts/release/freebsd_setup_test.py @@ -0,0 +1,628 @@ +#!/usr/bin/env python3 +"""Behaviour tests for packaging/freebsd/service-setup.sh and the rc.d scripts. + +The helper runs from the pkg scripts of the FreeBSD packages (post-install and +pre-deinstall). Like service_setup_test.py, these run it against a fake root +with stand-in pw, sysrc and service commands, so nothing on the machine is +touched. FreeBSD's pkg runs its old and new scripts in an order that differs +between versions, so the helper decides from state (is the user there? what does +rc.conf say?) and the tests check exactly that. Each test is one +GIVEN / WHEN / THEN case. + +Run directly (python3 scripts/release/freebsd_setup_test.py) or through +`meson test --suite release`. +""" + +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent)) + +import service_setup_test as common # noqa: E402 (path set up above; module, so its tests are not collected here) + +HELPER = common.REPO_ROOT / "packaging" / "freebsd" / "service-setup.sh" +RCD_DIR = common.REPO_ROOT / "packaging" / "freebsd" +needs_posix_shell = common.needs_posix_shell + +# Variables live in $STATE/rc/; an unset variable makes sysrc fail, as on a real host. +STUBS = { + "id": '[ -e "$STATE/users/$1" ]', + "pw": """ +if [ "$1" = useradd ]; then + shift + while [ $# -gt 0 ]; do + [ "$1" = -n ] && { mkdir -p "$STATE/users"; : > "$STATE/users/$2"; } + shift + done +fi +exit 0 +""", + # FAIL_HANDOVER makes only the recursive hand-over to the service user fail. + "chown": """ +case "$*" in -R*) [ -z "${FAIL_HANDOVER:-}" ] || exit 1 ;; esac +exit 0 +""", + "sysrc": """ +# -s scopes the lookup to rc.conf.d/; the fake keeps one value per variable. +[ "$1" = -s ] && shift 2 +if [ "$1" = -n ]; then + [ -e "$STATE/rc/$2" ] && cat "$STATE/rc/$2" && exit 0 + echo "sysrc: unknown variable '$2'" >&2 + exit 1 +fi +name="${1%%=*}" +value="${1#*=}" +# FAIL_SYSRC_WRITE: a read-only rc.conf, as in an image build or a restricted jail. +[ -z "${FAIL_SYSRC_WRITE:-}" ] || { echo "sysrc: cannot write /etc/rc.conf" >&2; exit 1; } +mkdir -p "$STATE/rc" +echo "$value" > "$STATE/rc/$name" +""", + "service": """ +svc="$1" +case "$2" in + onestatus) [ -e "$STATE/running/$svc" ] ;; + start|restart|onestart|onerestart) + [ -z "${FAIL_START:-}" ] || exit 1 + mkdir -p "$STATE/running"; : > "$STATE/running/$svc" ;; + onestop|stop) rm -f "$STATE/running/$svc" ;; + *) exit 0 ;; +esac +""", +} + + +class FakeBSDHost: + def __init__(self): + self.dir = Path(tempfile.mkdtemp(prefix="thewatcher-bsd-setup-")) + self.root = self.dir / "root" + self.state = self.dir / "state" + self.stubs = self.dir / "stubs" + self.call_log = self.dir / "calls.log" + self.call_log.write_text("", encoding="utf-8") + for component, name in (("server", "TheWatcherServer"), ("agent", "TheWatcherAgent")): + common.write_script(self.root / "usr/local/bin" / name, common.FAKE_BINARY) + common.write_script(self.root / "usr/local/etc/rc.d" / f"thewatcher_{component}", "exit 0") + for name, body in STUBS.items(): + common.write_script(self.stubs / name, f'echo "{name} $*" >> "$CALL_LOG"\n{body}') + + def cleanup(self): + shutil.rmtree(self.dir, ignore_errors=True) + + def add_user(self, name): + (self.state / "users").mkdir(parents=True, exist_ok=True) + (self.state / "users" / name).write_text("", encoding="utf-8") + + def set_rc(self, name, value): + (self.state / "rc").mkdir(parents=True, exist_ok=True) + # newline="\n": on Windows a CR written here would stay in the value the shell reads back. + (self.state / "rc" / name).write_bytes((value + "\n").encode("utf-8")) + + def mark_running(self, service): + (self.state / "running").mkdir(parents=True, exist_ok=True) + (self.state / "running" / service).write_text("", encoding="utf-8") + + def add_config(self, directory, name, text="edited by the administrator\n"): + path = self.root / directory / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + return path + + def run(self, component, action, **env): + environment = dict(os.environ) + for name in ("THEWATCHER_SERVER", "ENROLLMENT_TOKEN"): + environment.pop(name, None) + environment.update( + { + "PATH": str(self.stubs) + os.pathsep + environment["PATH"], + "THEWATCHER_ROOT": str(self.root), + "STATE": str(self.state), + "CALL_LOG": str(self.call_log), + } + ) + environment.update(env) + return subprocess.run( + ["sh", str(HELPER), component, action], + capture_output=True, text=True, env=environment, timeout=60, check=False, + ) + + def calls(self): + return self.call_log.read_text(encoding="utf-8").replace(chr(92), "/").splitlines() + + def called(self, prefix): + prefix = prefix.replace(chr(92), "/") + return any(line == prefix or line.startswith(prefix + " ") for line in self.calls()) + + def calls_to(self, command): + return [line for line in self.calls() if line.split(" ", 1)[0] == command] + + def rc(self, name): + path = self.state / "rc" / name + return path.read_text(encoding="utf-8").strip() if path.exists() else None + + +class HostCase(unittest.TestCase): + def setUp(self): + self.host = FakeBSDHost() + self.addCleanup(self.host.cleanup) + + +@needs_posix_shell +class GivenAServerPackageJustInstalledOnFreeBSD(HostCase): + def test_when_it_is_installed_then_the_service_user_and_group_are_created(self): + result = self.host.run("server", "setup") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue(self.host.called("pw groupadd -n thewatcher"), self.host.calls()) + user = self.host.calls_to("pw")[-1] + self.assertIn("useradd", user) + self.assertIn("-n thewatcher", user) + self.assertIn("/usr/sbin/nologin", user) + + def test_when_it_is_installed_then_the_binary_creates_the_config_with_the_database_in_var_db(self): + self.host.run("server", "setup") + conf = self.host.root / "usr/local/etc/thewatcher/TheWatcherServer.conf" + self.assertTrue(conf.is_file()) + self.assertTrue( + self.host.called(f"TheWatcherServer --init-config --config {conf} --db-path /var/db/thewatcher/thewatcher.db"), + self.host.calls(), + ) + + def test_when_it_is_installed_then_the_directories_belong_to_the_service_user(self): + self.host.run("server", "setup") + chowns = self.host.calls_to("chown") + self.assertTrue(any("thewatcher:thewatcher" in c and "usr/local/etc/thewatcher" in c for c in chowns), chowns) + self.assertTrue(any("thewatcher:thewatcher" in c and "var/db/thewatcher" in c for c in chowns), chowns) + + def test_when_it_is_installed_for_the_first_time_then_it_is_enabled_in_rc_conf_and_started(self): + result = self.host.run("server", "setup") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.host.rc("thewatcher_server_enable"), "YES") + self.assertTrue(self.host.called("service thewatcher_server start"), self.host.calls()) + + def test_when_the_package_script_runs_it_then_the_service_is_enabled_but_not_started(self): + """pkg kills every process a package script leaves running, so starting here would be undone.""" + result = self.host.run("server", "setup", THEWATCHER_NO_START="1") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.host.rc("thewatcher_server_enable"), "YES") + self.assertFalse(self.host.called("service thewatcher_server start"), self.host.calls()) + self.assertIn("service thewatcher_server start", result.stdout) + + def test_when_the_rc_setting_is_read_then_it_is_the_one_for_this_service(self): + """rc.conf.d/ counts for rc.d, so the helper must read it too.""" + self.host.run("server", "setup") + self.assertTrue(self.host.called("sysrc -s thewatcher_server -n thewatcher_server_enable"), self.host.calls()) + + def test_when_it_is_set_up_twice_then_the_user_and_config_are_created_once(self): + self.host.run("server", "setup") + self.host.run("server", "setup") + self.assertEqual(len(self.host.calls_to("pw")), 2, "one groupadd and one useradd, from the first run only") + self.assertEqual(len([c for c in self.host.calls() if "--init-config" in c]), 1) + + +@needs_posix_shell +class GivenAServerPackageUpgradedOnFreeBSD(HostCase): + def setUp(self): + super().setUp() + self.host.add_user("thewatcher") + self.conf = self.host.add_config("usr/local/etc/thewatcher", "TheWatcherServer.conf") + + def test_when_the_service_is_enabled_and_running_then_it_is_restarted_onto_the_new_binary(self): + self.host.set_rc("thewatcher_server_enable", "YES") + self.host.mark_running("thewatcher_server") + self.host.run("server", "setup") + self.assertTrue(self.host.called("service thewatcher_server restart"), self.host.calls()) + + def test_when_pkg_stopped_the_enabled_service_for_the_upgrade_then_it_is_started_again(self): + self.host.set_rc("thewatcher_server_enable", "YES") + self.host.run("server", "setup") + self.assertTrue(self.host.called("service thewatcher_server start"), self.host.calls()) + + def test_when_the_package_script_upgrades_a_running_service_then_it_is_left_running(self): + self.host.set_rc("thewatcher_server_enable", "YES") + self.host.mark_running("thewatcher_server") + result = self.host.run("server", "setup", THEWATCHER_NO_START="1") + self.assertFalse(self.host.called("service thewatcher_server restart"), self.host.calls()) + self.assertIn("service thewatcher_server restart", result.stdout) + + def test_when_the_enable_setting_is_empty_then_it_is_kept_and_the_service_is_not_started(self): + """An empty value is the administrator's choice, not a variable that was never set.""" + self.host.set_rc("thewatcher_server_enable", "") + self.host.run("server", "setup") + self.assertEqual(self.host.rc("thewatcher_server_enable"), "") + self.assertFalse(self.host.called("service thewatcher_server start"), self.host.calls()) + + def test_when_the_config_exists_then_the_directory_is_taken_back_before_the_config_is_touched(self): + """The service user owns the directory, so it must not be able to swap the file under root.""" + self.host.run("server", "setup") + conf_dir = str(self.host.root / "usr/local/etc/thewatcher").replace(chr(92), "/") + chowns = [c for c in self.host.calls_to("chown") if conf_dir in c] + self.assertTrue(chowns and chowns[0].startswith("chown root:wheel"), chowns) + + @unittest.skipIf(os.name != "posix", "symbolic links need POSIX") + def test_when_the_config_is_a_symbolic_link_then_its_target_is_not_changed(self): + target = self.host.root / "elsewhere" + target.write_text("not ours\n", encoding="utf-8") + target.chmod(0o644) + self.conf.unlink() + self.conf.symlink_to(target) + result = self.host.run("server", "setup") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(target.stat().st_mode & 0o777, 0o644) + self.assertIn("symbolic link", result.stderr) + + def test_when_the_config_directory_is_prepared_then_root_takes_it_before_its_mode_is_set(self): + """Mode first would let the service user, still the owner, make the directory writable + (0777) in the gap, and the chown would keep that mode.""" + text = HELPER.read_text(encoding="utf-8") + prepare = text[text.index("prepare_files() {"):] + self.assertLess(prepare.index('chown root:wheel "${conf_dir}"'), prepare.index('chmod 0700 "${conf_dir}"')) + + def test_when_the_service_is_started_again_then_a_stopped_one_is_not_asked_to_restart(self): + self.host.set_rc("thewatcher_server_enable", "YES") + self.host.run("server", "setup") + self.assertFalse(self.host.called("service thewatcher_server restart")) + + def test_when_the_administrator_disabled_the_service_then_it_stays_disabled_and_stopped(self): + self.host.set_rc("thewatcher_server_enable", "NO") + result = self.host.run("server", "setup") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.host.rc("thewatcher_server_enable"), "NO") + self.assertFalse(self.host.called("service thewatcher_server start")) + self.assertFalse(self.host.called("service thewatcher_server restart")) + + def test_when_the_service_was_never_enabled_then_this_is_treated_as_a_first_setup(self): + """Packages before 0.10.3 shipped only binaries, so rc.conf has no entry.""" + self.host.run("server", "setup") + self.assertEqual(self.host.rc("thewatcher_server_enable"), "YES") + self.assertTrue(self.host.called("service thewatcher_server start"), self.host.calls()) + + def test_when_upgraded_then_the_existing_config_is_left_alone(self): + self.host.run("server", "setup") + self.assertEqual(self.conf.read_text(encoding="utf-8"), "edited by the administrator\n") + self.assertFalse(any("--init-config" in c for c in self.host.calls())) + + def test_when_the_user_is_missing_but_a_config_exists_then_the_user_is_created_and_the_config_adopted(self): + shutil.rmtree(self.host.state / "users") + self.host.run("server", "setup") + self.assertTrue(self.host.called("pw groupadd -n thewatcher")) + self.assertTrue(any("thewatcher:thewatcher" in c and "usr/local/etc/thewatcher" in c for c in self.host.calls_to("chown"))) + self.assertEqual(self.conf.read_text(encoding="utf-8"), "edited by the administrator\n") + + def test_when_the_service_cannot_start_then_the_package_still_installs_with_a_warning(self): + self.host.set_rc("thewatcher_server_enable", "YES") + result = self.host.run("server", "setup", FAIL_START="1") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("warning", (result.stdout + result.stderr).lower()) + + +@needs_posix_shell +class GivenAServerPackageThatCannotCreateItsConfigOnFreeBSD(HostCase): + def test_when_init_config_fails_then_setup_fails_and_nothing_is_started(self): + result = self.host.run("server", "setup", FAIL_INIT="1") + self.assertNotEqual(result.returncode, 0) + self.assertFalse(self.host.called("service thewatcher_server start")) + self.assertEqual(self.host.rc("thewatcher_server_enable"), None) + + +@needs_posix_shell +class GivenASetupThatStoppedPartWayOnFreeBSD(HostCase): + """The rc.conf variable is written only after every step that can stop the setup, and an + administrator's NO is kept, so no separate marker is needed here (the Linux helper needs + one because nothing it can read records the administrator's choice).""" + + def test_when_the_handover_fails_after_the_config_was_created_then_a_retry_completes_the_setup(self): + first = self.host.run("server", "setup", FAIL_HANDOVER="1") + self.assertNotEqual(first.returncode, 0) + self.assertTrue((self.host.root / "usr/local/etc/thewatcher/TheWatcherServer.conf").is_file()) + self.assertIsNone(self.host.rc("thewatcher_server_enable")) + self.assertFalse(self.host.called("service thewatcher_server start")) + + retry = self.host.run("server", "setup") + self.assertEqual(retry.returncode, 0, retry.stderr) + self.assertEqual(self.host.rc("thewatcher_server_enable"), "YES") + self.assertTrue(self.host.called("service thewatcher_server start"), self.host.calls()) + + def test_when_an_agent_without_a_server_address_is_disabled_then_a_later_setup_keeps_it_disabled(self): + self.host.run("agent", "setup") + self.assertEqual(self.host.rc("thewatcher_agent_enable"), "YES") + self.host.set_rc("thewatcher_agent_enable", "NO") # the administrator's choice + self.host.run("agent", "setup") + self.assertEqual(self.host.rc("thewatcher_agent_enable"), "NO") + self.assertFalse(self.host.called("service thewatcher_agent start")) + + +@needs_posix_shell +class GivenAnRcConfThatCannotBeWrittenOnFreeBSD(HostCase): + """A read-only rc.conf (an image build, a restricted jail) makes sysrc fail. Nothing was recorded, so + the helper must not say it enabled the service, and must not say an administrator disabled it either: + that would be a choice nobody made.""" + + def run_setup(self, component="server", **env): + return self.host.run(component, "setup", FAIL_SYSRC_WRITE="1", **env) + + def test_when_the_write_fails_then_the_service_is_not_reported_as_enabled(self): + result = self.run_setup() + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotIn("enabled in rc.conf", result.stdout + result.stderr) + self.assertIsNone(self.host.rc("thewatcher_server_enable")) + + def test_when_the_write_fails_then_it_is_not_reported_as_an_administrators_choice(self): + result = self.run_setup() + self.assertNotIn("disabled in rc.conf", result.stdout + result.stderr) + + def test_when_the_write_fails_then_it_says_how_to_enable_the_service_by_hand(self): + result = self.run_setup() + self.assertIn("could not set thewatcher_server_enable=YES in rc.conf", result.stderr) + self.assertIn("sysrc thewatcher_server_enable=YES", result.stderr) + + def test_when_the_write_fails_then_the_service_is_not_started(self): + self.run_setup() + self.assertFalse(self.host.called("service thewatcher_server start")) + self.assertFalse(self.host.called("service thewatcher_server restart")) + + def test_when_the_write_fails_then_the_user_and_the_config_are_still_set_up(self): + self.run_setup() + self.assertTrue(self.host.called("pw useradd"), self.host.calls()) + self.assertTrue((self.host.root / "usr/local/etc/thewatcher/TheWatcherServer.conf").is_file()) + + def test_when_the_write_fails_for_an_agent_without_a_server_address_then_the_message_still_says_how_to_finish(self): + result = self.run_setup("agent") + self.assertIn("sysrc thewatcher_agent_enable=YES", result.stderr) + self.assertIn("THEWATCHER_SERVER=YOUR_SERVER", result.stdout) + + +@needs_posix_shell +class GivenAServerPackageRemovedOnFreeBSD(HostCase): + def setUp(self): + super().setUp() + self.host.add_user("thewatcher") + self.conf = self.host.add_config("usr/local/etc/thewatcher", "TheWatcherServer.conf") + self.host.set_rc("thewatcher_server_enable", "YES") + + def test_when_the_service_is_running_then_it_is_stopped(self): + self.host.mark_running("thewatcher_server") + result = self.host.run("server", "stop") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue(self.host.called("service thewatcher_server onestop"), self.host.calls()) + + def test_when_the_service_is_not_running_then_nothing_is_stopped(self): + result = self.host.run("server", "stop") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse(self.host.called("service thewatcher_server onestop")) + + def test_when_stopped_then_the_rc_conf_choice_the_config_and_the_user_are_kept(self): + self.host.mark_running("thewatcher_server") + self.host.run("server", "stop") + self.assertEqual(self.host.rc("thewatcher_server_enable"), "YES") + self.assertTrue(self.conf.is_file()) + self.assertFalse(self.host.called("pw userdel")) + + def test_when_the_package_is_installed_again_then_the_kept_rc_conf_choice_starts_it(self): + self.host.mark_running("thewatcher_server") + self.host.run("server", "stop") + self.host.run("server", "setup") + self.assertTrue(self.host.called("service thewatcher_server start"), self.host.calls()) + + +@needs_posix_shell +class GivenAnAgentPackageOnFreeBSD(HostCase): + def test_when_the_server_address_is_in_the_environment_then_the_config_is_created_and_the_agent_starts(self): + result = self.host.run("agent", "setup", THEWATCHER_SERVER="monitor.example.internal", ENROLLMENT_TOKEN="abc123") + self.assertEqual(result.returncode, 0, result.stderr) + conf = self.host.root / "usr/local/etc/thewatcher-agent/TheWatcherAgent.conf" + self.assertTrue( + self.host.called( + f"TheWatcherAgent --init-config --config {conf} --server-host monitor.example.internal " + "--enrollment-token abc123" + ), + self.host.calls(), + ) + self.assertEqual(self.host.rc("thewatcher_agent_enable"), "YES") + self.assertTrue(self.host.called("service thewatcher_agent start"), self.host.calls()) + + def test_when_the_agent_runs_then_it_has_its_own_user(self): + self.host.run("agent", "setup", THEWATCHER_SERVER="monitor.example.internal") + self.assertTrue(self.host.called("pw groupadd -n thewatcher-agent"), self.host.calls()) + self.assertTrue(any("thewatcher-agent:thewatcher-agent" in c for c in self.host.calls_to("chown"))) + + def test_when_the_administrator_already_wrote_a_config_then_it_is_kept_and_used(self): + conf = self.host.add_config("usr/local/etc/thewatcher-agent", "TheWatcherAgent.conf", "THEWATCHER_SERVER=chosen.example\n") + self.host.run("agent", "setup") + self.assertEqual(conf.read_text(encoding="utf-8"), "THEWATCHER_SERVER=chosen.example\n") + self.assertFalse(any("--init-config" in c for c in self.host.calls())) + self.assertTrue(self.host.called("service thewatcher_agent start"), self.host.calls()) + + def test_when_the_server_address_is_unknown_then_it_is_enabled_but_not_started_and_the_message_says_how_to_finish(self): + result = self.host.run("agent", "setup") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.host.rc("thewatcher_agent_enable"), "YES") + self.assertFalse(self.host.called("service thewatcher_agent start")) + output = result.stdout + result.stderr + self.assertIn("THEWATCHER_SERVER=", output) + self.assertIn("/usr/local/libexec/thewatcher/service-setup-agent agent setup", output) + # onestart: a plain start is refused by rc.subr while the service is not enabled. + self.assertIn("service thewatcher_agent onestart", output) + self.assertRegex(output, r"or create [^\n]*\n[^\n]*ENROLLMENT_TOKEN=YOUR_TOKEN if the server has an enrollment token") + + def test_when_the_agent_has_no_server_address_then_the_command_it_prints_is_safe_to_paste(self): + result = self.host.run("agent", "setup") + commands = [line for line in (result.stdout + result.stderr).splitlines() if "service-setup-agent" in line] + self.assertTrue(commands) + for line in commands: + self.assertNotIn("<", line) + self.assertNotIn(">", line) + + def test_when_the_setup_is_finished_later_with_the_server_address_then_the_agent_starts(self): + self.host.run("agent", "setup") + result = self.host.run("agent", "setup", THEWATCHER_SERVER="monitor.example.internal") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue(self.host.called("service thewatcher_agent start"), self.host.calls()) + + +@needs_posix_shell +class GivenBadArgumentsOnFreeBSD(HostCase): + def test_when_the_component_or_action_is_unknown_then_it_is_refused_before_anything_changes(self): + for component, action in (("proxy", "setup"), ("server", "install")): + result = self.host.run(component, action) + self.assertEqual(result.returncode, 2, f"{component} {action}") + self.assertEqual(self.host.calls(), []) + + +@needs_posix_shell +class GivenTheFreeBSDFiles(unittest.TestCase): + def files(self): + return [HELPER] + [RCD_DIR / f"thewatcher_{component}" for component in ("server", "agent")] + + def test_when_they_are_parsed_by_a_posix_shell_then_they_have_no_syntax_errors(self): + for path in self.files(): + result = subprocess.run(["sh", "-n", str(path)], capture_output=True, text=True, check=False) + self.assertEqual(result.returncode, 0, f"{path.name}: {result.stderr}") + + def test_when_they_are_read_then_they_keep_unix_line_endings(self): + for path in self.files(): + self.assertNotIn(bytes([13]), path.read_bytes(), path.name) + + def test_when_the_helper_is_read_then_it_uses_no_bashisms(self): + text = HELPER.read_text(encoding="utf-8") + for bashism in ("[[", "function ", "local ", "source ", "<<<", "${!", "=~"): + self.assertNotIn(bashism, text) + + +class GivenTheRcdScripts(unittest.TestCase): + def script(self, component): + return (RCD_DIR / f"thewatcher_{component}").read_text(encoding="utf-8") + + def helper_setting(self, component, name): + text = HELPER.read_text(encoding="utf-8") + block = text.split(f" {component})", 1)[1].split(";;", 1)[0] + for line in block.splitlines(): + line = line.strip() + if line.startswith(name + "="): + return line.split("=", 1)[1].strip('"') + raise AssertionError(f"{name} not set for {component}") + + def default(self, component, variable): + """The value of `: ${variable:="value"}` in an rc.d script.""" + prefix = ': ${' + variable + ':="' + for line in self.script(component).splitlines(): + if line.startswith(prefix): + return line[len(prefix):].split('"', 1)[0] + raise AssertionError(f"{variable} has no default in thewatcher_{component}") + + def test_when_a_script_is_read_then_it_is_an_rc_subr_script_named_after_its_service(self): + for component in ("server", "agent"): + text = self.script(component) + self.assertTrue(text.startswith("#!/bin/sh\n")) + self.assertIn(f"# PROVIDE: thewatcher_{component}\n", text) + self.assertIn(f'name="thewatcher_{component}"\n', text) + self.assertIn(f'rcvar="thewatcher_{component}_enable"\n', text) + self.assertIn("run_rc_command", text) + + def test_when_a_script_is_read_then_it_is_disabled_until_rc_conf_enables_it(self): + for component in ("server", "agent"): + self.assertEqual(self.default(component, f"thewatcher_{component}_enable"), "NO") + + def test_when_a_script_is_read_then_it_runs_as_the_user_the_helper_creates(self): + for component in ("server", "agent"): + self.assertEqual(self.default(component, f"thewatcher_{component}_account"), self.helper_setting(component, "user")) + + def test_when_a_script_is_read_then_it_uses_the_config_the_helper_creates(self): + for component in ("server", "agent"): + expected = "{}/{}".format(self.helper_setting(component, "config_dir"), self.helper_setting(component, "config_name")) + self.assertEqual(self.default(component, f"thewatcher_{component}_config"), expected) + + def test_when_a_script_is_read_then_it_starts_the_installed_binary_under_daemon(self): + for component in ("server", "agent"): + text = self.script(component) + self.assertIn('command="/usr/sbin/daemon"', text) + self.assertIn("/usr/local/bin/" + self.helper_setting(component, "binary_name"), text) + self.assertIn("-u ${thewatcher_" + component + "_account}", text) + + def test_when_a_script_is_read_then_it_defines_no_name_user_variable(self): + """rc.subr treats ${name}_user specially: it runs the whole command through su(1) + (FreeBSD 14.2, libexec/rc/rc.subr, run_rc_command). daemon would then run as the service + user and could not create its pid file in /var/run, so the service would never start. + The account for daemon -u has a different name.""" + for component in ("server", "agent"): + # Comments may name it (the one next to the account variable says why it is not + # called that); the code must not define or use it. + code = "\n".join(line for line in self.script(component).splitlines() if not line.lstrip().startswith("#")) + self.assertFalse(f"thewatcher_{component}_user" in code, f"thewatcher_{component}_user is used in the code") + + def test_when_the_agent_has_no_config_yet_then_rc_refuses_to_start_it(self): + text = self.script("agent") + self.assertIn('start_precmd="thewatcher_agent_prestart"', text) + self.assertIn('[ ! -r "${thewatcher_agent_config}" ]', text) + + def test_when_a_config_path_has_a_space_then_it_is_checked_and_passed_as_one_word(self): + """rc.subr splits required_files and the evaluated command line on spaces, so a path under + /usr/local/etc/site config/ would be refused or cut in two. The path is read quoted and given to + the binary as one quoted --config argument.""" + for component in ("server", "agent"): + with self.subTest(component=component): + text = self.script(component) + self.assertNotIn("required_files=", "\n".join(line for line in text.splitlines() if not line.lstrip().startswith("#"))) + self.assertIn(f'[ ! -r "${{thewatcher_{component}_config}}" ]', text) + line = next(line for line in text.splitlines() if line.startswith("command_args=")) + self.assertIn(f'--config \\"${{thewatcher_{component}_config_escaped}}\\"', line) + + def test_when_a_config_path_has_shell_characters_then_the_evaluated_command_line_keeps_it_literal(self): + """rc.subr evaluates command_args, so a path with a dollar sign, a quote, a backtick or a backslash + would be expanded inside the double quotes unless it is escaped first. This runs the escaping line + from each script and evaluates the quoted argument the way rc.subr does.""" + sh = shutil.which("sh") + for component in ("server", "agent"): + with self.subTest(component=component): + variable = f"thewatcher_{component}_config" + escaping = next(line for line in self.script(component).splitlines() if line.startswith(f"{variable}_escaped=")) + for path in ("/usr/local/etc/site config/a.conf", "/usr/local/etc/site $prod/a.conf", "/etc/q\"x/`id`/a\\b.conf"): + program = ( + f"{variable}=$WATCHER_CONFIG_PATH\n{escaping}\n" + f'eval "set -- --config \\"${{{variable}_escaped}}\\""\n' + 'printf "%s|%s" "$1" "$2"\n' + ) + # From a file, not "sh -c": on Windows the command line of a spawned MSYS shell loses doubled + # backslashes, which are exactly what the escaping adds. + with tempfile.TemporaryDirectory() as tmp: + program_file = Path(tmp) / "escape.sh" + program_file.write_bytes(program.encode("utf-8")) + result = subprocess.run( + [sh, str(program_file)], capture_output=True, text=True, timeout=30, check=False, + # In the environment, not argv: Windows rewrites a double quote in an argument. + env=dict(os.environ, WATCHER_CONFIG_PATH=path), + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, f"--config|{path}") + + def test_when_the_agent_is_stopped_by_the_server_then_it_is_not_restarted(self): + """A DISCONNECT command ends the agent on purpose (issue #85); daemon -r would bring it back.""" + text = self.script("agent") + for flag in (" -r ", " -R "): + self.assertNotIn(flag, text.split("command_args=", 1)[1].split("\n", 1)[0]) + + def command_args(self, component): + line = next(line for line in self.script(component).splitlines() if line.startswith("command_args=")) + return line.split("=", 1)[1].strip('"').split() + + def test_when_a_service_is_started_then_it_does_not_keep_its_callers_output_open(self): + """Without -f, daemon leaves the service's stdout and stderr on the starter's. `service ... start` + run over ssh, or in a CI step, then does not return until the service exits: the first complete + run of the FreeBSD job hung for 75 minutes after its smoke test had passed.""" + for component in ("server", "agent"): + self.assertIn("-f", self.command_args(component), f"thewatcher_{component} starts daemon without -f") + + def test_when_a_service_cannot_start_then_what_it_printed_to_stderr_still_reaches_syslog(self): + """-f sends the output to /dev/null. The binaries report a bad config or argument on stderr, and + write everything else to their own log, so stderr alone is routed to syslog (-S, -m 2).""" + for component in ("server", "agent"): + args = self.command_args(component) + self.assertIn("-S", args) + self.assertEqual(args[args.index("-m") + 1], "2") + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/release/install-inno-setup.ps1 b/scripts/release/install-inno-setup.ps1 new file mode 100644 index 0000000..8ae5a1a --- /dev/null +++ b/scripts/release/install-inno-setup.ps1 @@ -0,0 +1,97 @@ +<# +.SYNOPSIS +Installs the pinned Inno Setup 7 compiler and prints the path of its ISCC.exe. + +.DESCRIPTION +The release workflow compiles the Windows installers (packaging/windows/TheWatcher.iss) +with Inno Setup 7. The Windows runner image only ships Inno Setup 6, and an +unpinned download (a package manager's "latest") could change what ships between +two runs, so this installs one version, checks it, and runs it. See +docs/adr/0006-build-the-windows-installers-with-inno-setup-7.md. + +Before anything is run the download must match the pinned SHA-256 and carry a valid +Authenticode signature from the vendor's publisher. To move to another version, +change $Version and $Sha256 together: the hash is the asset's "digest" on the +release page (https://github.com/jrsoftware/issrc/releases), and +`gh release verify-asset is- --repo jrsoftware/issrc` +confirms that the file is the release's. + +.PARAMETER Destination +Directory to install into. It is created if needed. + +.PARAMETER CurrentUser +Install for the current user only, so no administrator rights are needed (for a +developer machine). The release workflow runs as an administrator and omits it. + +.OUTPUTS +The full path of ISCC.exe, as the only output. + +.EXAMPLE +$iscc = & scripts/release/install-inno-setup.ps1 -Destination "$env:RUNNER_TEMP\InnoSetup" +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)][string]$Destination, + [switch]$CurrentUser +) + +$ErrorActionPreference = 'Stop' + +# Windows PowerShell 5.1 does not offer TLS 1.2 by default on older systems. +[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12 + +# Bump both together (see above). +$Version = '7.1.1' +$Sha256 = '8A5A6711C3766A6E5FB74F280BA0E3551E719CE94538D901FDBD1F8F9920B3F0' +$Publisher = 'Pyrsys B.V.' + +# The x64 edition: the runners and the installers' target are x64. +$url = "https://github.com/jrsoftware/issrc/releases/download/is-$($Version -replace '\.', '_')/innosetup-$Version-x64.exe" + +$work = Join-Path ([IO.Path]::GetTempPath()) ('inno-setup-' + [Guid]::NewGuid().ToString('N')) +New-Item -ItemType Directory -Path $work | Out-Null +try { + $installer = Join-Path $work "innosetup-$Version-x64.exe" + + # GitHub's download CDN sometimes answers with an error that the next try gets past. + $downloaded = $false + for ($attempt = 1; $attempt -le 5; $attempt++) { + try { + Invoke-WebRequest -Uri $url -OutFile $installer -UseBasicParsing + $downloaded = $true + break + } catch { + Write-Host "Download attempt $attempt of 5 failed: $($_.Exception.Message)" + Start-Sleep -Seconds 2 + } + } + if (-not $downloaded) { throw "Could not download $url" } + + # Verify before running anything from the download. + $actual = (Get-FileHash -Path $installer -Algorithm SHA256).Hash + if ($actual -ne $Sha256) { + throw "innosetup-$Version-x64.exe has SHA-256 $actual but $Sha256 is pinned; refusing to run it." + } + $signature = Get-AuthenticodeSignature -FilePath $installer + if ($signature.Status -ne 'Valid' -or $signature.SignerCertificate.Subject -notlike "CN=$Publisher,*") { + throw "innosetup-$Version-x64.exe is not validly signed by ${Publisher}: $($signature.Status), $($signature.SignerCertificate.Subject)" + } + + # /MERGETASKS=!associatefileextension: do not take over .iss files on this machine. + $log = Join-Path $work 'setup.log' + $arguments = @('/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART', '/NOICONS', + '/MERGETASKS=!associatefileextension', "/DIR=`"$Destination`"", "/LOG=`"$log`"") + if ($CurrentUser) { $arguments += '/CURRENTUSER' } + $process = Start-Process -FilePath $installer -ArgumentList $arguments -Wait -PassThru + if ($process.ExitCode -ne 0) { + if (Test-Path $log) { Get-Content $log | Select-Object -Last 40 | ForEach-Object { Write-Host $_ } } + throw "The Inno Setup installer exited with code $($process.ExitCode)." + } + + $iscc = Join-Path $Destination 'ISCC.exe' + if (-not (Test-Path $iscc)) { throw "$iscc was not installed." } + Write-Host "Installed Inno Setup $Version at $Destination" + Write-Output $iscc +} finally { + Remove-Item -Recurse -Force $work -ErrorAction SilentlyContinue +} diff --git a/scripts/release/install-nfpm.sh b/scripts/release/install-nfpm.sh index 7bfaa64..023a72f 100755 --- a/scripts/release/install-nfpm.sh +++ b/scripts/release/install-nfpm.sh @@ -37,7 +37,9 @@ url="https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}/nfpm_ # HTTPS only, including after redirects (GitHub redirects downloads to its CDN). # --retry-all-errors: the CDN sometimes answers with a non-standard status # (618, "jwt:expired") that plain --retry does not retry; the next try works. -curl --proto '=https' --proto-redir '=https' --tlsv1.2 -fsSL --retry 5 --retry-all-errors --retry-delay 2 \ +# No --retry-delay: curl then doubles the wait (1, 2, 4, 8, 16, 32 s), so six retries cover about +# a minute. A fixed 2 s delay gave up after 10 s, which a GitHub outage that answers 500 outlasts. +curl --proto '=https' --proto-redir '=https' --tlsv1.2 -fsSL --retry 6 --retry-all-errors \ --output "${work}/nfpm.tar.gz" "${url}" # Verify before extracting anything from the archive. diff --git a/scripts/release/prefetch-wraps.sh b/scripts/release/prefetch-wraps.sh index e09859a..2a2765d 100755 --- a/scripts/release/prefetch-wraps.sh +++ b/scripts/release/prefetch-wraps.sh @@ -31,7 +31,7 @@ fetch() { # Every wrap URL is HTTPS; refuse to follow a redirect to anything else. # --retry-all-errors: GitHub's CDN sometimes answers with a non-standard # status (618, "jwt:expired") that plain --retry does not retry. - curl --proto '=https' --proto-redir '=https' --tlsv1.2 -fL --retry 5 --retry-all-errors --retry-delay 2 \ + curl --proto '=https' --proto-redir '=https' --tlsv1.2 -fL --retry 6 --retry-all-errors \ --output "${dest}" "${url}" fi if [[ -n "${hash}" ]]; then diff --git a/scripts/release/release_tool.py b/scripts/release/release_tool.py index e7c82ae..21d7e1a 100755 --- a/scripts/release/release_tool.py +++ b/scripts/release/release_tool.py @@ -7,6 +7,7 @@ version print the project version from meson.build matrix print the Linux build matrix as {"include": [...]} JSON nfpm-config print the nfpm package configuration for one package + package-scripts write the maintainer scripts that set the service up asset-name print a release asset's file name checksums print SHA256SUMS lines for every file in a directory stale-assets print release assets the new build no longer produces @@ -40,6 +41,23 @@ BINARY_NAMES = {"server": "TheWatcherServer", "agent": "TheWatcherAgent"} CHECKSUM_FILE = "SHA256SUMS" +# Where the packages install packaging/linux/service-setup.sh. Every maintainer +# script calls it, and it does the actual service setup (user, config, enable, +# start, firewall); see the header of that file. Each package installs its own +# copy under its own name: the server and the agent are installed side by side +# on a host that monitors itself, and dpkg, pacman, apk and pkg refuse to install +# a package that ships a file another installed package owns. +SERVICE_HELPER_DIR = "/usr/lib/thewatcher" +# The same for FreeBSD (packaging/freebsd/service-setup.sh), called from the pkg +# scripts in the package manifest. +FREEBSD_SERVICE_HELPER_DIR = "/usr/local/libexec/thewatcher" +# Package format -> the init system its service definition is written for. The +# service-setup helper manages whichever of the two the package ships. +INIT_SYSTEMS = {"deb": "systemd", "rpm": "systemd", "archlinux": "systemd", "apk": "openrc"} +# These formats run a different script when a package is upgraded; deb and rpm +# call the one postinstall script for both and say which through its arguments. +SEPARATE_UPGRADE_SCRIPT_FORMATS = ("apk", "archlinux") + HOMEPAGE = "https://github.com/OMG-Software/TheWatcher" VENDOR = "OMG-Software" # Placeholder until a real contact exists (tracked in the plan's follow-ups). @@ -52,6 +70,8 @@ # Anything that ends up in a file name must match this: no slashes, spaces or "..". _SAFE_PART = re.compile(r"^[a-z0-9][a-z0-9._-]*$") +# An absolute path that is safe to put, unquoted, in a shell script. +_SAFE_SHELL_PATH = re.compile(r"^/[A-Za-z0-9._/-]+$") _DISTRO_FIELDS = ("id", "image", "format", "arches", "depends", "server_depends", "install_cmd") # Same pattern scripts/check_version_consistency.py uses: meson.build is the # single source of truth for the version. @@ -155,16 +175,167 @@ def _join(directory, name): return f"{str(directory).rstrip('/' + chr(92))}/{name}" -def render_nfpm_config(component, distro, arch, version, release, stage_dir, dashboard_dir, license_file): +def service_helper_path(component): + """Where the Linux package of a component installs its setup helper.""" + if component not in COMPONENTS: + raise ValueError(f"unknown component {component!r}; choose from {list(COMPONENTS)}") + return f"{SERVICE_HELPER_DIR}/service-setup-{component}" + + +def freebsd_service_helper_path(component): + """Where the FreeBSD package of a component installs its setup helper.""" + if component not in COMPONENTS: + raise ValueError(f"unknown component {component!r}; choose from {list(COMPONENTS)}") + return f"{FREEBSD_SERVICE_HELPER_DIR}/service-setup-{component}" + + +def render_package_scripts(component, package_format, helper_path=None): + """Maintainer scripts for one package: {nfpm script name: script text}. + + Every package manager calls its scripts differently, so each script only + translates that into the three actions service-setup understands: install, + upgrade and remove. They always run the helper and return its status, so a + failure to create the user or the config is seen by the package manager. + + deb and rpm run one postinstall script for both a first install and an + upgrade and say which through arguments ("configure " and + the instance count). apk and Arch run a separate script on upgrade. + """ + if component not in COMPONENTS: + raise ValueError(f"unknown component {component!r}; choose from {list(COMPONENTS)}") + if package_format not in INIT_SYSTEMS: + raise ValueError(f"unknown package format {package_format!r}; choose from {sorted(INIT_SYSTEMS)}") + if helper_path is None: + helper_path = service_helper_path(component) + if not _SAFE_SHELL_PATH.fullmatch(helper_path): + raise ValueError(f"helper path {helper_path!r} is not an absolute path that is safe in a shell script") + + call = f"{helper_path} {component}" + if package_format == "deb": + return { + "postinstall": ( + "#!/bin/sh\n" + "set -e\n" + '# dpkg calls "postinst configure "; the version is empty\n' + "# on a first install.\n" + 'case "$1" in\n' + " configure)\n" + ' if [ -z "${2:-}" ]; then\n' + f" {call} install\n" + " else\n" + f" {call} upgrade\n" + " fi\n" + " ;;\n" + "esac\n" + "exit 0\n" + ), + "preremove": ( + "#!/bin/sh\n" + "set -e\n" + '# "prerm upgrade" runs on the old version during an upgrade: leave the service\n' + "# alone, the new package's postinst restarts it. \"prerm deconfigure\" is left\n" + "# alone too: dpkg undoes it with \"postinst abort-deconfigure\", which does\n" + "# nothing, so stopping the service here could leave it off for good.\n" + 'case "$1" in\n' + " remove)\n" + f" {call} remove\n" + " ;;\n" + "esac\n" + "exit 0\n" + ), + } + if package_format == "rpm": + return { + "postinstall": ( + "#!/bin/sh\n" + "# $1 is the number of copies of the package installed once this one is in\n" + "# place: 1 for a first install, 2 or more for an upgrade.\n" + 'if [ "${1:-1}" -ge 2 ]; then\n' + f" {call} upgrade\n" + "else\n" + f" {call} install\n" + "fi\n" + ), + "preremove": ( + "#!/bin/sh\n" + "# $1 is the number of copies left: 0 when the last one is erased, 1 while an\n" + "# upgrade removes the old one (the new package's script restarts the service).\n" + 'if [ "${1:-}" = 0 ]; then\n' + f" {call} remove\n" + "fi\n" + ), + } + # apk and Arch: one script per event; the upgrade and removal hooks never + # run together with a first install. + return { + "postinstall": f"#!/bin/sh\n{call} install\n", + "postupgrade": f"#!/bin/sh\n{call} upgrade\n", + "preremove": f"#!/bin/sh\n{call} remove\n", + } + + +def write_package_scripts(component, package_format, out_dir): + """Write render_package_scripts' output into out_dir as executable files.""" + scripts = render_package_scripts(component, package_format) + directory = Path(out_dir) + directory.mkdir(parents=True, exist_ok=True) + for name, text in scripts.items(): + path = directory / name + # Written as bytes so a Windows host cannot turn the line endings into + # CRLF, which breaks the interpreter line (Path.write_text(newline=) + # needs Python 3.10, and Rocky 9 has 3.9). + path.write_bytes(text.encode("utf-8")) + path.chmod(0o755) + return sorted(scripts) + + +def _service_contents(component, package_format, packaging_dir): + """Files that make the package's service work: the setup helper and the + unit (systemd) or init script (OpenRC) the format's distros use.""" + service = f"thewatcher-{component}" + contents = [ + { + "src": _join(packaging_dir, "service-setup.sh"), + "dst": service_helper_path(component), + "file_info": {"mode": 0o755}, + }, + ] + if INIT_SYSTEMS[package_format] == "systemd": + contents.append( + { + "src": _join(packaging_dir, f"systemd/{service}.service"), + "dst": f"/usr/lib/systemd/system/{service}.service", + "file_info": {"mode": 0o644}, + } + ) + else: + contents.append( + { + "src": _join(packaging_dir, f"openrc/{service}"), + "dst": f"/etc/init.d/{service}", + "file_info": {"mode": 0o755}, + } + ) + return contents + + +def render_nfpm_config( + component, distro, arch, version, release, stage_dir, dashboard_dir, license_file, packaging_dir, scripts_dir +): """nfpm configuration for one package, as JSON (valid YAML nfpm reads with -f). JSON rather than hand-written YAML so quoting is never ambiguous and tests - can parse the result with the standard library. + can parse the result with the standard library. packaging_dir is + packaging/linux (the helper, units and OpenRC scripts); scripts_dir holds the + files write_package_scripts wrote for this component and format. """ if component not in COMPONENTS: raise ValueError(f"unknown component {component!r}; choose from {list(COMPONENTS)}") if arch not in ARCHES: raise ValueError(f"unknown arch {arch!r}; choose from {sorted(ARCHES)}") + package_format = distro["format"] + if package_format not in INIT_SYSTEMS: + raise ValueError(f"unknown package format {package_format!r}; choose from {sorted(INIT_SYSTEMS)}") binary = BINARY_NAMES[component] depends = list(distro["depends"]) @@ -172,6 +343,7 @@ def render_nfpm_config(component, distro, arch, version, release, stage_dir, das {"src": _join(stage_dir, binary), "dst": f"/usr/bin/{binary}"}, {"src": str(license_file), "dst": f"/usr/share/doc/thewatcher-{component}/copyright"}, ] + contents += _service_contents(component, package_format, packaging_dir) if component == "server": # PostgreSQL support is linked dynamically on Linux (see scripts/release/linux-build.sh). depends += distro["server_depends"] @@ -192,7 +364,11 @@ def render_nfpm_config(component, distro, arch, version, release, stage_dir, das "description": DESCRIPTIONS[component], "depends": depends, "contents": contents, + "scripts": {"postinstall": _join(scripts_dir, "postinstall"), "preremove": _join(scripts_dir, "preremove")}, } + if package_format in SEPARATE_UPGRADE_SCRIPT_FORMATS: + # apk and pacman run this on upgrade instead of postinstall. + config[package_format] = {"scripts": {"postupgrade": _join(scripts_dir, "postupgrade")}} return json.dumps(config, indent=2) + "\n" @@ -212,6 +388,66 @@ def render_release_notes(version, sha, run_url, assets): ) +def render_freebsd_scripts(component): + """pkg scripts of a FreeBSD package: {script name: text}. + + post-install sets the service up and post-deinstall stops it. The helper + decides from state (user, rc.conf) and not from which script called it, + because pkg's order of old and new scripts during an upgrade differs between + versions; see packaging/freebsd/service-setup.sh. + + The stop is in post-deinstall, not pre-deinstall, on purpose. pkg-script(5): + an upgrade runs the new pre-install, the OLD pre-deinstall, replaces the files + and runs the new post-install, and never the old post-deinstall. post-install + cannot start the service again (pkg ends what a script leaves running), so a + stop in pre-deinstall left every upgraded service down. A removal runs both. + """ + if component not in COMPONENTS: + raise ValueError(f"unknown component {component!r}; choose from {list(COMPONENTS)}") + call = f"{freebsd_service_helper_path(component)} {component}" + return { + # pkg ends every process a script leaves running, so the service cannot be + # started from here: the helper only enables it and says how to start it. + "post-install": f"#!/bin/sh\nTHEWATCHER_NO_START=1 {call} setup\n", + "post-deinstall": _FREEBSD_STOP_SCRIPT.replace("@COMPONENT@", component).replace("@NAME@", component.capitalize()), + } + + +# The files are gone by the time post-deinstall runs, so it can use neither the rc script nor +# the helper. It signals the supervisor that daemon(8) recorded in the pid file, which forwards +# SIGTERM to the service: what `service ... stop` sends. THEWATCHER_ROOT and +# THEWATCHER_STOP_WAIT (seconds, default 30) are for the tests. +_FREEBSD_STOP_SCRIPT = """#!/bin/sh +pidfile="${THEWATCHER_ROOT:-}/var/run/thewatcher_@COMPONENT@.pid" +[ -r "${pidfile}" ] || exit 0 +pid=$(cat "${pidfile}") +case "${pid}" in '' | *[!0-9]*) exit 0 ;; esac +# A pid file left by a crash or a power cut can name an unrelated process that has the number now, +# even another service's daemon(8). daemon(8) retitles its own process (setproctitle) to +# "daemon: [] (daemon)", so the supervisor of this service is the one +# whose title names this service's binary, which another service's supervisor does not. Its original +# argument list, with the -P file, is not what ps shows for it. +[ "$(ps -o comm= -p "${pid}" 2>/dev/null)" = daemon ] || exit 0 +case "$(ps -ww -o command= -p "${pid}" 2>/dev/null)" in + "daemon: /usr/local/bin/TheWatcher@NAME@["*) ;; + *) exit 0 ;; +esac +kill -TERM "${pid}" 2>/dev/null || exit 0 +limit="${THEWATCHER_STOP_WAIT:-30}" +i=0 +while kill -0 "${pid}" 2>/dev/null && [ "${i}" -lt "${limit}" ]; do + sleep 1 + i=$((i + 1)) +done +if kill -0 "${pid}" 2>/dev/null; then + # Removing the package must not fail because of this, but the service is still running with its + # files gone, and the rc script that could stop it is gone too. + echo "thewatcher_@COMPONENT@: the service (supervisor pid ${pid}) did not stop within ${limit} seconds; stop it with: kill -TERM ${pid}" >&2 +fi +exit 0 +""" + + def render_freebsd_manifest(component, version, release, stage_dir, abi): """FreeBSD +MANIFEST (JSON) for a package staged under stage_dir. @@ -242,6 +478,7 @@ def render_freebsd_manifest(component, version, release, stage_dir, abi): "licenses": ["GPLv3"], "flatsize": sum(p.stat().st_size for p in files), "files": {"/" + p.relative_to(root).as_posix(): _sha256(p) for p in files}, + "scripts": render_freebsd_scripts(component), } return json.dumps(manifest, indent=2) + "\n" @@ -268,11 +505,15 @@ def _cmd_nfpm_config(args): sys.stdout.write( render_nfpm_config( args.component, by_id[args.distro], args.arch, args.version, args.release, - args.stage_dir, args.dashboard_dir, args.license_file, + args.stage_dir, args.dashboard_dir, args.license_file, args.packaging_dir, args.scripts_dir, ) ) +def _cmd_package_scripts(args): + write_package_scripts(args.component, args.format, args.out_dir) + + def _cmd_asset_name(args): print(asset_name(args.component, args.platform, args.arch, args.ext)) @@ -312,7 +553,9 @@ def command(name, handler, *options, positional=()): command( "nfpm-config", _cmd_nfpm_config, "component", "distro", "arch", "version", "release", "stage-dir", "dashboard-dir", "license-file", "catalogue", + "packaging-dir", "scripts-dir", ) + command("package-scripts", _cmd_package_scripts, "component", "format", "out-dir") command("asset-name", _cmd_asset_name, "component", "platform", "arch", "ext") command("checksums", _cmd_checksums, positional=("directory",)) command("stale-assets", _cmd_stale_assets, "existing", "new-dir") diff --git a/scripts/release/release_tool_test.py b/scripts/release/release_tool_test.py index 0cd83d2..adab497 100755 --- a/scripts/release/release_tool_test.py +++ b/scripts/release/release_tool_test.py @@ -5,6 +5,7 @@ `meson test --suite release`. Each test is one GIVEN / WHEN / THEN case. """ +import ast import hashlib import io import json @@ -32,6 +33,14 @@ "needs a POSIX shell; set RELEASE_TOOL_SHELL_TESTS=1 to run with Git Bash", ) +def shell_path(path): + """A path as the POSIX shell sees it: C:/dir becomes /c/dir under Git Bash on Windows.""" + text = Path(path).as_posix() + if len(text) > 1 and text[1] == ":": + text = "/" + text[0].lower() + text[2:] + return text + + # A stand-in for the GitHub CLI: logs every call and answers the few the publish # script depends on. FAKE_LOOKUP chooses what a release lookup returns. FAKE_GH = """#!/bin/sh @@ -249,6 +258,8 @@ def render(self, component, d=None, arch="x86_64", release="7"): stage_dir="/stage", dashboard_dir="/dash", license_file="/repo/LICENSE", + packaging_dir="/repo/packaging/linux", + scripts_dir="/scripts", ) ) @@ -276,6 +287,44 @@ def test_when_rendered_then_the_server_depends_on_the_distro_libraries_and_libpq config = self.render("server") self.assertEqual(config["depends"], ["libc6", "libstdc++6", "libpq5"]) + def test_when_rendered_then_the_service_helper_is_installed_executable(self): + helper = self.destinations(self.render("server"))["/usr/lib/thewatcher/service-setup-server"] + self.assertEqual(helper["src"], "/repo/packaging/linux/service-setup.sh") + self.assertEqual(helper["file_info"]["mode"], 0o755) + + def test_when_the_format_is_deb_rpm_or_archlinux_then_a_systemd_unit_is_installed(self): + for package_format in ("deb", "rpm", "archlinux"): + dst = self.destinations(self.render("server", distro(format=package_format))) + unit = dst["/usr/lib/systemd/system/thewatcher-server.service"] + self.assertEqual(unit["src"], "/repo/packaging/linux/systemd/thewatcher-server.service", package_format) + self.assertEqual(unit["file_info"]["mode"], 0o644, package_format) + self.assertNotIn("/etc/init.d/thewatcher-server", dst, package_format) + + def test_when_the_format_is_apk_then_an_openrc_script_is_installed_instead(self): + dst = self.destinations(self.render("server", distro(format="apk"))) + script = dst["/etc/init.d/thewatcher-server"] + self.assertEqual(script["src"], "/repo/packaging/linux/openrc/thewatcher-server") + self.assertEqual(script["file_info"]["mode"], 0o755) + self.assertNotIn("/usr/lib/systemd/system/thewatcher-server.service", dst) + + def test_when_rendered_then_the_install_and_remove_scripts_are_attached(self): + scripts = self.render("server")["scripts"] + self.assertEqual(scripts, {"postinstall": "/scripts/postinstall", "preremove": "/scripts/preremove"}) + + def test_when_the_format_is_deb_or_rpm_then_one_postinstall_script_covers_install_and_upgrade(self): + for package_format in ("deb", "rpm"): + config = self.render("server", distro(format=package_format)) + self.assertNotIn("apk", config, package_format) + self.assertNotIn("archlinux", config, package_format) + + def test_when_the_format_is_apk_then_a_separate_upgrade_script_is_attached(self): + config = self.render("server", distro(format="apk")) + self.assertEqual(config["apk"]["scripts"], {"postupgrade": "/scripts/postupgrade"}) + + def test_when_the_format_is_archlinux_then_a_separate_upgrade_script_is_attached(self): + config = self.render("server", distro(format="archlinux")) + self.assertEqual(config["archlinux"]["scripts"], {"postupgrade": "/scripts/postupgrade"}) + def test_when_the_arch_is_aarch64_then_nfpm_gets_arm64(self): self.assertEqual(self.render("server", arch="aarch64")["arch"], "arm64") @@ -303,6 +352,8 @@ def render(self): stage_dir="/stage", dashboard_dir="/dash", license_file="/repo/LICENSE", + packaging_dir="/repo/packaging/linux", + scripts_dir="/scripts", ) ) @@ -317,6 +368,707 @@ def test_when_rendered_then_it_has_no_dashboard_content(self): def test_when_rendered_then_it_does_not_depend_on_libpq(self): self.assertEqual(self.render()["depends"], ["libc6", "libstdc++6"]) + def test_when_rendered_then_it_installs_the_agent_unit_and_never_the_server_one(self): + dst = {c["dst"]: c for c in self.render()["contents"]} + self.assertEqual( + dst["/usr/lib/systemd/system/thewatcher-agent.service"]["src"], + "/repo/packaging/linux/systemd/thewatcher-agent.service", + ) + self.assertNotIn("/usr/lib/systemd/system/thewatcher-server.service", dst) + + def test_when_rendered_then_it_has_the_service_helper_and_the_install_scripts(self): + config = self.render() + destinations = {c["dst"] for c in config["contents"]} + self.assertIn("/usr/lib/thewatcher/service-setup-agent", destinations) + self.assertNotIn("/usr/lib/thewatcher/service-setup-server", destinations) + self.assertEqual(config["scripts"], {"postinstall": "/scripts/postinstall", "preremove": "/scripts/preremove"}) + + +@needs_posix_shell +class GivenTheMaintainerScriptsOfAPackage(unittest.TestCase): + """Each package manager calls its scripts differently; the service helper only + knows install, upgrade and remove. These run the generated scripts against a + stand-in helper that records how it was called.""" + + def setUp(self): + self.tmp = Path(tempfile.mkdtemp(prefix="thewatcher-scripts-")) + self.addCleanup(shutil.rmtree, self.tmp, True) + self.helper = self.tmp / "service-setup" + self.log = Path(str(self.helper) + ".log") + self.write_helper('echo "$*" >> "$0.log"') + + def write_helper(self, body): + self.helper.write_bytes(("#!/bin/sh\n" + body + "\n").encode("utf-8")) + self.helper.chmod(0o755) + + def run_script(self, package_format, name, *args, component="server", expect=0): + """Run one generated script with the package manager's arguments; return what the helper saw.""" + scripts = tool.render_package_scripts(component, package_format, helper_path=shell_path(self.helper)) + path = self.tmp / f"{package_format}-{name}" + path.write_bytes(scripts[name].encode("utf-8")) + self.log.unlink(missing_ok=True) + result = subprocess.run(["sh", shell_path(path), *args], capture_output=True, text=True, check=False) + self.assertEqual(result.returncode, expect, result.stderr) + return self.log.read_text(encoding="utf-8").splitlines() if self.log.exists() else [] + + def test_when_dpkg_configures_a_package_with_no_earlier_version_then_it_is_an_install(self): + self.assertEqual(self.run_script("deb", "postinstall", "configure"), ["server install"]) + + def test_when_dpkg_configures_over_an_earlier_version_then_it_is_an_upgrade(self): + self.assertEqual(self.run_script("deb", "postinstall", "configure", "0.10.1"), ["server upgrade"]) + + def test_when_dpkg_runs_postinst_for_anything_but_configure_then_nothing_happens(self): + for action in ("abort-upgrade", "abort-remove", "abort-deconfigure"): + self.assertEqual(self.run_script("deb", "postinstall", action, "0.10.1"), [], action) + + def test_when_dpkg_removes_the_package_then_the_service_is_stopped_and_disabled(self): + self.assertEqual(self.run_script("deb", "preremove", "remove"), ["server remove"]) + + def test_when_dpkg_upgrades_the_package_then_the_old_prerm_leaves_the_service_running(self): + self.assertEqual(self.run_script("deb", "preremove", "upgrade", "0.10.3"), []) + + def test_when_dpkg_deconfigures_the_package_then_the_service_and_its_firewall_rules_are_left_alone(self): + # "prerm deconfigure" can be undone by "postinst abort-deconfigure", which does + # nothing here, so a removal on deconfigure would leave the service off for good. + self.assertEqual(self.run_script("deb", "preremove", "deconfigure", "in-favour", "other", "1.0"), []) + + def test_when_the_helper_path_ends_in_a_newline_then_it_is_refused(self): + # The regex must match the whole path: a trailing newline would end the + # command and put the component and action on the next shell line. + with self.assertRaises(ValueError): + tool.render_package_scripts("server", "deb", helper_path="/usr/lib/thewatcher/helper\n") + + def test_when_rpm_installs_the_first_copy_then_it_is_an_install(self): + self.assertEqual(self.run_script("rpm", "postinstall", "1"), ["server install"]) + + def test_when_rpm_installs_a_second_copy_during_an_upgrade_then_it_is_an_upgrade(self): + self.assertEqual(self.run_script("rpm", "postinstall", "2"), ["server upgrade"]) + + def test_when_rpm_erases_the_last_copy_then_the_service_is_stopped_and_disabled(self): + self.assertEqual(self.run_script("rpm", "preremove", "0"), ["server remove"]) + + def test_when_rpm_removes_the_old_copy_during_an_upgrade_then_the_service_is_left_alone(self): + self.assertEqual(self.run_script("rpm", "preremove", "1"), []) + + def test_when_apk_or_pacman_installs_then_the_postinstall_script_is_an_install(self): + for package_format in ("apk", "archlinux"): + self.assertEqual(self.run_script(package_format, "postinstall"), ["server install"], package_format) + + def test_when_apk_or_pacman_upgrades_then_the_postupgrade_script_is_an_upgrade(self): + for package_format in ("apk", "archlinux"): + self.assertEqual(self.run_script(package_format, "postupgrade"), ["server upgrade"], package_format) + + def test_when_apk_or_pacman_removes_then_the_preremove_script_is_a_remove(self): + for package_format in ("apk", "archlinux"): + self.assertEqual(self.run_script(package_format, "preremove"), ["server remove"], package_format) + + def test_when_the_package_is_the_agent_then_the_helper_is_called_for_the_agent(self): + self.assertEqual(self.run_script("rpm", "postinstall", "1", component="agent"), ["agent install"]) + + def test_when_the_helper_fails_then_the_script_fails_so_the_package_manager_notices(self): + self.write_helper("exit 3") + self.run_script("deb", "postinstall", "configure", expect=3) + + +class GivenTheGeneratedScriptSet(unittest.TestCase): + def test_when_the_format_has_no_separate_upgrade_hook_then_no_postupgrade_script_is_made(self): + for package_format in ("deb", "rpm"): + self.assertEqual(sorted(tool.render_package_scripts("server", package_format)), ["postinstall", "preremove"]) + + def test_when_the_format_has_a_separate_upgrade_hook_then_a_postupgrade_script_is_made(self): + for package_format in ("apk", "archlinux"): + self.assertEqual( + sorted(tool.render_package_scripts("server", package_format)), ["postinstall", "postupgrade", "preremove"] + ) + + def test_when_a_script_is_made_then_it_is_a_posix_shell_script_with_unix_line_endings(self): + for package_format in ("deb", "rpm", "apk", "archlinux"): + for text in tool.render_package_scripts("agent", package_format).values(): + self.assertTrue(text.startswith("#!/bin/sh\n")) + self.assertNotIn("\r", text) + + def test_when_the_default_helper_path_is_used_then_it_is_where_the_package_installs_it(self): + text = tool.render_package_scripts("server", "deb")["postinstall"] + self.assertIn("/usr/lib/thewatcher/service-setup-server", text) + self.assertNotIn("/usr/lib/thewatcher/service-setup-agent", text) + + def test_when_the_format_or_component_is_unknown_then_value_error_is_raised(self): + with self.assertRaises(ValueError): + tool.render_package_scripts("server", "msi") + with self.assertRaises(ValueError): + tool.render_package_scripts("dashboard", "deb") + + def test_when_a_helper_path_could_break_out_of_the_script_then_it_is_refused(self): + for bad in ("/tmp/a b", "/tmp/a;rm -rf /", "/tmp/$(id)", "relative/helper"): + with self.assertRaises(ValueError, msg=bad): + tool.render_package_scripts("server", "deb", helper_path=bad) + + +class GivenTheInnoSetupCompiler(unittest.TestCase): + """The Windows installers are compiled with a pinned, verified Inno Setup 7. The + runner image only ships Inno Setup 6, and a download that is not pinned could + change what ships between two runs (docs/adr/0006).""" + + SCRIPT = REPO_ROOT / "scripts" / "release" / "install-inno-setup.ps1" + + @classmethod + def setUpClass(cls): + cls.script = cls.SCRIPT.read_text(encoding="utf-8") + cls.workflow = (REPO_ROOT / ".github" / "workflows" / "release.yml").read_text(encoding="utf-8") + + def setting(self, name): + match = re.search(r"\$" + name + r"\s*=\s*'([^']*)'", self.script) + self.assertIsNotNone(match, f"${name} is not set to a literal in {self.SCRIPT.name}") + return match.group(1) + + def test_when_the_compiler_is_pinned_then_it_is_inno_setup_7(self): + self.assertRegex(self.setting("Version"), r"^7\.\d+\.\d+$") + + def test_when_the_checksum_is_pinned_then_it_is_a_sha256(self): + self.assertRegex(self.setting("Sha256"), r"^[0-9A-Fa-f]{64}$") + + def test_when_the_download_is_made_then_it_is_https_from_the_vendors_release_of_the_pinned_version(self): + self.assertIn("https://github.com/jrsoftware/issrc/releases/download/is-$($Version -replace '\\.', '_')/", self.script) + self.assertIn("innosetup-$Version-x64.exe", self.script) + self.assertNotIn("http://", self.script) + + def test_when_the_installer_is_downloaded_then_it_is_checked_before_it_is_run(self): + checks = [self.script.index(marker) for marker in ("Get-FileHash", "Get-AuthenticodeSignature")] + self.assertLess(max(checks), self.script.index("Start-Process")) + + def test_when_the_installer_is_checked_then_the_publisher_must_be_the_vendors(self): + self.assertIn("Pyrsys B.V.", self.script) + self.assertIn("'Valid'", self.script) + + def test_when_the_installer_runs_then_it_is_silent(self): + for flag in ("/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART"): + self.assertIn(flag, self.script) + + def test_when_a_download_fails_then_it_is_retried(self): + self.assertRegex(self.script, r"(?s)for \(\$attempt = 1; \$attempt -le \d+; \$attempt\+\+\).*Invoke-WebRequest") + + def test_when_the_workflow_compiles_an_installer_then_it_uses_the_pinned_compiler(self): + self.assertEqual(self.workflow.count("scripts/release/install-inno-setup.ps1"), 2) + self.assertNotIn("Inno Setup 6", self.workflow) + self.assertNotIn("choco install innosetup", self.workflow) + + def test_when_the_docs_name_the_compiler_then_they_say_version_7(self): + for name in ("docs/installation.md", "docs/releases.md", "README.md"): + text = (REPO_ROOT / name).read_text(encoding="utf-8") + # assertFalse, not assertNotIn: its failure message would print the whole file. + self.assertFalse("Inno Setup 6" in text, f"{name} still names Inno Setup 6") + self.assertTrue( + "Inno Setup 7" in (REPO_ROOT / "docs" / "installation.md").read_text(encoding="utf-8"), + "docs/installation.md does not name Inno Setup 7", + ) + + def test_when_the_script_is_parsed_by_powershell_then_it_has_no_syntax_errors(self): + shell = shutil.which("pwsh") or shutil.which("powershell") + if shell is None: + self.skipTest("no PowerShell on this machine") + command = ( + "$errors = $null; " + "[System.Management.Automation.Language.Parser]::ParseFile($env:THEWATCHER_ISS, [ref]$null, [ref]$errors) | Out-Null; " + "if ($errors.Count) { $errors | ForEach-Object { $_.Message }; exit 1 }" + ) + # The path travels as data in the environment: a checkout directory such as + # "Developer's Checkout" would break a single-quoted PowerShell string. + environment = dict(os.environ, THEWATCHER_ISS=str(self.SCRIPT)) + result = subprocess.run( + [shell, "-NoProfile", "-NonInteractive", "-Command", command], + capture_output=True, text=True, check=False, env=environment, + ) + self.assertEqual(result.returncode, 0, result.stdout + result.stderr) + + +class GivenTheAgentInstallerArguments(unittest.TestCase): + """Inno Setup is not available here, so these read the script (CI compiles it and runs the + installers). The quoting was checked against the real agent with awkward tokens when it was + written; these keep the properties that check relied on.""" + + @classmethod + def setUpClass(cls): + cls.script = (REPO_ROOT / "packaging" / "windows" / "TheWatcher.iss").read_text(encoding="utf-8") + cls.workflow = (REPO_ROOT / ".github" / "workflows" / "release.yml").read_text(encoding="utf-8") + + def function(self, name): + match = re.search(rf"^(?:function|procedure) {name}\b.*?^end;", self.script, re.S | re.M) + self.assertIsNotNone(match, f"{name} is not in TheWatcher.iss") + return match.group(0) + + def test_when_the_arguments_are_quoted_then_the_backslash_literals_are_intact(self): + """A tool that strips backslashes turns '\\' into '' and the function into a no-op that still compiles.""" + body = self.function("QuoteArgument") + self.assertIn("if C = '\\' then", body) + self.assertEqual(body.count("StringOfChar('\\', "), 3) + self.assertNotIn("''", body.replace("Result := '\"'", "")) + + def test_when_an_argument_is_quoted_then_a_quote_is_escaped_and_the_trailing_backslashes_are_doubled(self): + body = self.function("QuoteArgument") + self.assertIn("Backslashes * 2 + 1", body) # backslashes before a quote, plus the escape + self.assertIn("Backslashes * 2) + '\"'", body) # backslashes before the closing quote + + def test_when_the_agent_is_set_up_then_every_value_on_its_command_line_is_quoted_by_the_function(self): + body = self.function("SetUpAgent") + for value in ("Conf", "AgentHost", "AgentToken"): + self.assertIn(f"QuoteArgument({value})", body) + self.assertNotIn("--enrollment-token \"'", body) + + def test_when_a_token_is_validated_then_spaces_and_quotes_are_allowed_but_line_breaks_are_not(self): + token = self.function("TokenProblem") + self.assertIn("< 32", token) + self.assertNotIn("<= 32", token) + self.assertNotIn("'\"'", token) + self.assertIn("<= 32", self.function("HostProblem")) + + def test_when_the_token_is_taken_then_it_comes_from_the_environment_and_never_from_a_switch(self): + self.assertIn("GetEnv('ENROLLMENT_TOKEN')", self.script) + self.assertNotIn("{param:TOKEN", self.script) + # Setup's /LOG= writes its whole command line to the log, which a switch would put the token in. + self.assertNotIn("/TOKEN=", self.workflow) + self.assertIn("the setup log does not contain the enrollment token", self.workflow) + + def test_when_no_server_address_was_given_then_the_manual_steps_offer_the_token_and_keep_the_plain_command_valid(self): + """The agent reads its token from --enrollment-token only, never from ENROLLMENT_TOKEN, so a + config made by the manual command alone has an empty token, and rerunning the installer keeps it.""" + body = self.function("SetUpAgent") + self.assertIn("--enrollment-token YOUR_TOKEN", body) + commands = [line for line in body.splitlines() if "--server-host YOUR_SERVER" in line] + self.assertTrue(commands, "the manual command is gone") + for line in commands: + # Pasted as it is, the command must work for a server that has no token. + self.assertNotIn("YOUR_TOKEN", line) + self.assertNotIn("[", line) + + def test_when_a_config_exists_and_a_server_address_is_given_then_the_installer_says_it_was_not_applied(self): + """An upgrade keeps the config, which holds the agent's identity. A /SERVER= that is dropped + without a word looks like it worked: exit code 0, and a service still on the old server.""" + body = self.function("SetUpAgent") + note = "The existing agent config was kept" + self.assertIn(note, body) + before = body[: body.index(note)] + guard = before[-400:] + self.assertIn("FileExists(Conf)", guard) + self.assertIn("AgentHost <> ''", guard) + self.assertIn("/SERVER=", body[body.index(note):][:200]) + + def test_when_setup_fails_before_the_service_is_registered_then_the_advice_creates_the_config_first(self): + """--install-service registers a service and nothing else: after a failed --init-config, or a token + refused before anything was written, it would leave a registered service with no config.""" + body = self.function("ReportPostInstallProblems") + # The command fragments, not the bare options: a comment may name them too. + self.assertIn("--init-config --config", body) + self.assertIn("FileExists(", body, "the config step is advised even when the config exists") + self.assertLess(body.index("--init-config --config"), body.index("--install-service --config")) + self.assertIn("--server-host YOUR_SERVER", body) + self.assertIn("--enrollment-token YOUR_TOKEN", body) + + +class GivenTheInstallerRemembersUnfinishedSteps(unittest.TestCase): + """Inno Setup is not available here, so these read the script (CI compiles it and runs the + installers). A step that failed after the service was registered must be finished by the + next run, which sees an existing service and would otherwise treat it as an upgrade.""" + + @classmethod + def setUpClass(cls): + cls.script = (REPO_ROOT / "packaging" / "windows" / "TheWatcher.iss").read_text(encoding="utf-8") + cls.workflow = (REPO_ROOT / ".github" / "workflows" / "release.yml").read_text(encoding="utf-8") + + def function(self, name): + match = re.search(rf"^(?:function|procedure) {name}\b.*?^end;", self.script, re.S | re.M) + self.assertIsNotNone(match, f"{name} is not in TheWatcher.iss") + return match.group(0) + + def test_when_the_firewall_rule_failed_then_the_next_run_tries_again(self): + body = self.function("RegisterAll") + self.assertIn("PendingFile('TheWatcherFirewall')", body) + # A setup that stopped after the service was registered still owes the rule. + self.assertIn("if (not ServerRegistered) and (not ServerExisted) then", body) + # The marker is written before the attempt and removed only after the rule is in place. + # The write that matters is the last one before the call: an earlier one belongs to the + # failed-registration path and says nothing about a call that raises. + attempt = body.index("OpenFirewall(") + guard = body.index("if (not ServerExisted) or FileExists(PendingFile('TheWatcherFirewall'))") + before_attempt = body.rfind("SetPending('TheWatcherFirewall', True)", 0, attempt) + self.assertGreater(before_attempt, guard, "the marker is not written between the guard and the attempt") + self.assertLess(attempt, body.index("SetPending('TheWatcherFirewall', False)")) + + def test_when_setup_failed_after_registration_then_the_intent_to_start_is_kept_for_the_next_run(self): + body = self.function("RegisterAll") + for service in ("TheWatcherServer", "TheWatcherAgent"): + with self.subTest(service=service): + self.assertIn(f"FileExists(PendingFile('{service}'))", body) + # The marker is written before the start is tried and cleared only after it worked. + first_marker = body.index(f"SetPending('{service}', True)") + start = body.index(f"StartServiceAgain('{service}')") + cleared = body.index(f"SetPending('{service}', False)") + self.assertLess(first_marker, start) + self.assertLess(start, cleared) + # A start that failed writes the marker again, in the failure branch: without it the + # next run, which sees a registered and stopped service, would never start it. A + # write on the success path only (before the marker is cleared) must not pass. + branch = body[start:body.index(f"AddStartError('{service}')", start)] + self.assertIn("else", branch, "the start has no failure branch") + failure = branch[branch.index("else"):] + self.assertIn(f"SetPending('{service}', True)", failure, "the marker is not re-armed after a failed start") + self.assertNotIn(f"SetPending('{service}', False)", failure) + + def test_when_the_service_is_already_registered_then_the_message_does_not_advise_registering_it_again(self): + body = self.function("ReportPostInstallProblems") + self.assertIn("if not ServiceExists('TheWatcherServer') then", body) + self.assertIn("if not ServiceExists('TheWatcherAgent') then", body) + self.assertIn("RecoveryCommands('TheWatcherServer', ", body) + self.assertIn("RecoveryCommands('TheWatcherAgent', ", body) + + def test_when_the_recovery_commands_are_given_then_they_include_the_failure_actions_and_the_start(self): + body = self.function("RecoveryCommands") + # "sc.exe failureflag" contains "sc.exe failure": the command itself needs its own check. + self.assertRegex(body, r"sc\.exe failure(?!flag) ") + self.assertIn("sc.exe failureflag", body) + self.assertIn("sc.exe start", body) + + def test_when_an_agent_already_has_a_config_then_the_address_and_token_are_not_validated(self): + """They are only used to create a config; a token inherited from the environment must not + stop the upgrade of an agent that does not use it, after the service was stopped.""" + body = self.function("SetUpAgent") + creation = body.index("else if AgentHost <> '' then") + # Inside the branch that creates the config: after its opening and before the service is + # registered. Anywhere else it would run for an upgrade too. + self.assertGreater(body.index("AgentSettingsProblem()"), creation) + self.assertLess(body.index("AgentSettingsProblem()"), body.index("--init-config", creation)) + self.assertLess(body.index("AgentSettingsProblem()"), body.index("RegisterService(")) + + def test_when_a_running_service_is_stopped_for_the_upgrade_then_its_start_is_recorded_before_anything_is_replaced(self): + """A setup cut off after the old registration was removed leaves a service that is not running, which + the next run cannot tell from one the administrator stopped, unless the owed start was written first.""" + body = self.function("PrepareToInstall") + for service, flag in (("TheWatcherServer", "ServerWasRunning"), ("TheWatcherAgent", "AgentWasRunning")): + with self.subTest(service=service): + write = f"SaveStringToFile(PendingFile('{service}')" + self.assertIn(write, body) + # Only for a service that was running: one the administrator had stopped stays stopped. + self.assertLess(body.rindex(f"if {flag} then", 0, body.index(write)), body.index(write)) + self.assertGreater(body.index(write), body.index("SecureConfigDir()")) + # It is used before it is defined otherwise. + self.assertLess(self.script.index("function PendingFile("), self.script.index("function PrepareToInstall(")) + + def test_when_a_later_step_fails_after_a_start_was_recorded_then_the_restart_clears_it(self): + """A failed prepare starts the stopped services again and resets the flags, so DeinitializeSetup finds + nothing to clear: the restart has to clear what was recorded. (Each installer handles one component, so + this guards a step added after the records are written, not a two-service case.)""" + body = self.function("PrepareToInstall") + restart = body.index("RestartStoppedService('TheWatcherServer', ServerWasRunning)") + for service, owed in (("TheWatcherServer", "ServerOwed"), ("TheWatcherAgent", "AgentOwed")): + with self.subTest(service=service): + clear = f"if {owed} and ServiceIsRunning('{service}') then" + self.assertIn(clear, body) + self.assertGreater(body.index(clear), restart) + self.assertLess(body.index(clear), body.rindex("ServerWasRunning := False;")) + + def test_when_the_install_is_cancelled_before_the_files_are_replaced_then_the_recorded_start_is_cleared(self): + body = self.function("DeinitializeSetup") + for service, owed in (("TheWatcherServer", "ServerOwed"), ("TheWatcherAgent", "AgentOwed")): + with self.subTest(service=service): + clear = f"SetPending('{service}', False)" + self.assertIn(clear, body) + # Cleared only for a service that is positively running again: RestartStoppedService returns a + # message whether or not the start worked, and "not stopped" would also be true when the query + # itself failed. A failed restart, or a state that cannot be told, keeps the reminder. + guard = f"if {owed} and ServiceIsRunning('{service}') then" + self.assertIn(guard, body) + self.assertLess(body.index(guard), body.index(clear)) + self.assertNotIn("Note = ''", body) + self.assertNotIn("not ServiceIsStopped", body) + running = self.function("ServiceIsRunning") + self.assertIn('find "RUNNING"', running) + self.assertIn("ResultCode = 0", running) + + def test_when_a_service_could_not_be_started_then_the_message_says_to_remove_its_reminder(self): + body = self.function("ReportPostInstallProblems") + self.assertIn("remove its reminder", body) + self.assertIn(".pending", body) + + def test_when_the_recovery_commands_are_given_then_they_remove_the_reminder_after_the_start(self): + body = self.function("RecoveryCommands") + self.assertIn("PendingFile(Name)", body) + self.assertLess(body.index("sc.exe start"), body.index("PendingFile(Name)")) + + def test_when_the_server_of_an_existing_agent_is_to_change_then_all_three_endpoint_keys_are_named(self): + body = self.function("SetUpAgent") + for key in ("THEWATCHER_SERVER", "SERVER_ADDRESS", "ENROLLMENT_ADDRESS"): + self.assertIn(key, body) + + def test_when_a_token_has_a_character_outside_ascii_then_it_is_refused(self): + """The agent reads its arguments through the process code page, which would change it.""" + body = self.function("TokenProblem") + self.assertIn("> 127", body) + self.assertIn("ASCII", body) + + def test_when_a_replacement_stopped_half_way_then_the_next_run_still_counts_as_an_upgrade(self): + """RegisterService tells the administrator to close services.msc and run the installer again. By + then the old service is gone, and a run that went by the service alone would take itself for a + first install: it would put back a firewall rule the administrator narrowed and start a service + they had stopped.""" + was = self.function("WasInstalled") + self.assertIn("ServiceExists(Name)", was) + self.assertIn("FileExists(ReplacingFile(Name))", was) + prepare = self.function("PrepareToInstall") + self.assertIn("WasInstalled('TheWatcherServer')", prepare) + self.assertIn("WasInstalled('TheWatcherAgent')", prepare) + self.assertNotIn("ServiceExists('TheWatcherServer')", prepare, "an upgrade is still told by the service alone") + + def test_when_a_registration_is_replaced_then_the_marker_outlives_the_old_one_and_goes_with_the_new_one(self): + body = self.function("RegisterService") + # Before the old registration is removed ... and written for real: a log line naming the file would + # not do, and a write that fails must stop the replacement before anything is removed. + self.assertIn("if not SaveStringToFile(ReplacingFile(Name)", body) + self.assertLess(body.index("SaveStringToFile(ReplacingFile(Name)"), body.index("RaiseException('Could not record")) + self.assertLess(body.index("RaiseException('Could not record"), body.index("--uninstall-service")) + # ... and dropped only once the new one is in place, after the check that raises when it is not. + self.assertGreater(body.rindex("DeleteFile(ReplacingFile(Name))"), body.index("Could not register")) + + def test_when_the_installer_is_uninstalled_then_a_leftover_replacement_marker_goes_with_it(self): + section = self.script.split("[UninstallDelete]", 1)[1].split("\n[", 1)[0] + self.assertIn(".replacing", section) + + def test_when_the_windows_job_installs_over_a_replaced_service_then_it_checks_the_narrowed_rule_stays(self): + self.assertIn("an interrupted replacement keeps the firewall rule the administrator narrowed", self.workflow) + + +class GivenTheReinstallGuidance(unittest.TestCase): + """Removing a package and installing it again: dpkg remembers the removed version and reports the + install as an upgrade, which leaves the service as removal left it. RPM, Arch and Alpine run the + install again and enable the service. Alpine has no systemctl, so the command is not for it.""" + + FILES = ("CHANGELOG.md", "docs/installation.md") + + def command_sentence(self, name): + text = (REPO_ROOT / name).read_text(encoding="utf-8") + block = next((b for b in re.split(r"\n\s*\n", text) if "enable --now thewatcher-server" in b), None) + self.assertIsNotNone(block, f"{name} no longer says how to enable the service after a reinstall") + flat = " ".join(block.split()) + return next(s for s in re.split(r"(?<=[.;])\s+", flat) if "systemctl" in s) + + def test_when_the_systemctl_command_is_given_then_it_is_for_debian_and_ubuntu_only(self): + for name in self.FILES: + with self.subTest(file=name): + sentence = self.command_sentence(name) + self.assertIn("Debian", sentence) + for other in ("Alpine", "RPM", "Arch", "Fedora"): + self.assertNotIn(other, sentence) + + def test_when_a_package_is_installed_again_then_the_guidance_says_the_other_formats_set_it_up_again(self): + for name in self.FILES: + with self.subTest(file=name): + text = " ".join((REPO_ROOT / name).read_text(encoding="utf-8").split()) + self.assertRegex(text, r"(RPM, Arch and Alpine|Alpine, RPM and Arch)[^.]*(again|new install)") + + +class GivenTheRestartPolicyGuidance(unittest.TestCase): + """The Windows installers register restart-on-failure recovery actions for the agent too, so a + sentence saying only systemd restarts it is wrong for anyone reading on Windows.""" + + FILES = ("CHANGELOG.md", "docs/installation.md") + + def test_when_the_agent_restart_policy_is_described_then_it_names_systemd_and_the_windows_recovery_actions(self): + for name in self.FILES: + with self.subTest(file=name): + text = " ".join((REPO_ROOT / name).read_text(encoding="utf-8").split()) + self.assertNotIn("by systemd only", text) + match = re.search(r"The agent is restarted after a failure by [^.]*\.", text) + self.assertIsNotNone(match, f"{name} no longer describes when the agent is restarted") + self.assertIn("systemd", match.group(0)) + self.assertIn("Windows", match.group(0)) + + +class GivenTheRemovalGuidance(unittest.TestCase): + """Removing the Linux server package takes back the firewall rules the install added, like the + Windows uninstaller; the guidance has to say so, or an administrator looks for rules that are gone.""" + + def test_when_a_package_is_removed_then_the_guidance_says_the_firewall_rules_it_added_are_removed(self): + for name in ("CHANGELOG.md", "docs/installation.md"): + with self.subTest(file=name): + text = " ".join((REPO_ROOT / name).read_text(encoding="utf-8").split()) + self.assertRegex(text, r"(?i)removal[^.]*(ufw|firewall)|removing[^.]*(ufw|firewall)[^.]*(rules|ports)") + + +@needs_posix_shell +class GivenTheServiceSmokeScript(unittest.TestCase): + """smoke-service.sh runs the installed binaries as their service users inside a clean + container, and a minimal image may have only some of the tools that can do that: Fedora's has + neither runuser nor su (the first CI run failed with "failed to run command 'su'"). start_as + is run here with only the named tools on PATH, and `timeout` replaced by one that records + what it was asked to run.""" + + SCRIPT = REPO_ROOT / "scripts" / "release" / "smoke-service.sh" + + def run_start_as(self, tools): + text = self.SCRIPT.read_text(encoding="utf-8") + function = re.search(r"^start_as\(\) \{.*?^\}", text, re.S | re.M) + self.assertIsNotNone(function, "start_as is not in smoke-service.sh") + with tempfile.TemporaryDirectory() as tmp: + bin_dir = Path(tmp) / "bin" + bin_dir.mkdir() + log = Path(tmp) / "timeout.log" + for name, body in [("timeout", '#!/bin/sh\necho "$*" >> "$TIMEOUT_LOG"\n')] + [(t, "#!/bin/sh\nexit 0\n") for t in tools]: + stub = bin_dir / name + stub.write_bytes(body.encode("utf-8")) + stub.chmod(0o755) + script = ( + 'fail() { echo "smoke-service: $*" >&2; exit 1; }\n' + + function.group(0) + + '\nstart_as thewatcher 5 "$OUT" /usr/bin/TheWatcherServer --config /etc/thewatcher/TheWatcherServer.conf\nwait\n' + ) + env = {"PATH": shell_path(bin_dir), "TIMEOUT_LOG": shell_path(log), "OUT": shell_path(Path(tmp) / "out")} + # An absolute path: with env= given, POSIX looks a bare "sh" up in the child's PATH, which + # here holds only the stubs (Windows uses the parent's, which hid this until Linux CI). + sh = shutil.which("sh") + self.assertIsNotNone(sh, "no sh on PATH") + result = subprocess.run([sh, "-c", script], env=env, capture_output=True, text=True, check=False) + ran = log.read_text(encoding="utf-8").strip() if log.exists() else "" + return result, ran + + # A /proc/net/tcp as the kernel writes it: state 0A is LISTEN, 01 is ESTABLISHED. + PROC_NET_TCP = ( + " sl local_address rem_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n" + " 0: 00000000:15B4 00000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 11111 1 0000 100 0 0 10 0\n" + " 1: 0100007F:1F90 00000000:0000 0A 00000000:00000000 00:00000000 00000000 998 0 22222 1 0000 100 0 0 10 0\n" + " 2: 0100007F:15B3 0100007F:A2C4 01 00000000:00000000 00:00000000 00000000 998 0 33333 1 0000 100 0 0 10 0\n" + ) + PROC_NET_TCP6 = ( + " sl local_address remote_address st tx_queue rx_queue tr tm->when retrnsmt uid timeout inode\n" + " 0: 00000000000000000000000000000000:2328 00000000000000000000000000000000:0000 0A 00000000:00000000 00:00000000 00000000 0 0 44444 1 0000 100 0 0 10 0\n" + ) + + def is_listening(self, port, *tables): + """Whether the script's is_listening sees `port` in the given /proc/net/tcp-style tables.""" + text = self.SCRIPT.read_text(encoding="utf-8") + function = re.search(r"^is_listening\(\) \{.*?^\}", text, re.S | re.M) + self.assertIsNotNone(function, "is_listening is not in smoke-service.sh") + with tempfile.TemporaryDirectory() as tmp: + paths = [] + for index, content in enumerate(tables): + path = Path(tmp) / f"tcp{index}" + path.write_bytes(content.encode("utf-8")) + paths.append(shell_path(path)) + script = function.group(0) + f"\nis_listening {port} " + " ".join(f"'{p}'" for p in paths) + "\n" + return subprocess.run(["sh", "-c", script], capture_output=True, text=True, check=False).returncode == 0 + + def test_when_a_socket_is_listening_on_the_port_then_it_is_seen(self): + self.assertTrue(self.is_listening(5556, self.PROC_NET_TCP)) # on every interface + self.assertTrue(self.is_listening(8080, self.PROC_NET_TCP)) # on loopback only + + def test_when_the_only_socket_on_the_port_is_an_established_connection_then_it_is_not_listening(self): + self.assertFalse(self.is_listening(5555, self.PROC_NET_TCP)) + + def test_when_nothing_uses_the_port_then_it_is_not_listening(self): + self.assertFalse(self.is_listening(9999, self.PROC_NET_TCP)) + + def test_when_the_socket_is_in_the_ipv6_table_then_it_is_seen(self): + self.assertTrue(self.is_listening(9000, self.PROC_NET_TCP, self.PROC_NET_TCP6)) # 0x2328 + + def test_when_a_table_cannot_be_read_then_it_is_skipped_and_the_port_is_not_listening(self): + self.assertFalse(self.is_listening(5556)) + + def test_when_the_server_is_waited_for_then_the_script_does_not_depend_on_a_flushed_info_line(self): + """The logger flushes only NOTICE and above at once (common/SingleLog.hpp), so INFO lines such + as "Running" stay in a buffer while stdout is redirected to a file, and a wait for them fails on + a healthy server.""" + text = self.SCRIPT.read_text(encoding="utf-8") + self.assertNotIn("wait_for_text /tmp/smoke-server.out 'Running'", text) + self.assertIn("wait_for_listen 5556", text) + + def test_when_runuser_exists_then_it_is_used(self): + result, ran = self.run_start_as(["runuser", "su", "chroot"]) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + ran, "5 runuser -u thewatcher -- /usr/bin/TheWatcherServer --config /etc/thewatcher/TheWatcherServer.conf" + ) + + def test_when_only_su_exists_then_it_is_used_as_on_alpine(self): + result, ran = self.run_start_as(["su"]) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue(ran.startswith("5 su -s /bin/sh thewatcher -c exec /usr/bin/TheWatcherServer"), ran) + + def test_when_neither_runuser_nor_su_exists_then_coreutils_chroot_runs_it_as_the_user(self): + """The Fedora container: coreutils is there, util-linux's runuser and su are not.""" + result, ran = self.run_start_as(["chroot"]) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual( + ran, + "5 chroot --userspec=thewatcher:thewatcher / /usr/bin/TheWatcherServer --config /etc/thewatcher/TheWatcherServer.conf", + ) + + def test_when_no_tool_can_switch_user_then_it_fails_and_says_so_instead_of_running_as_root(self): + result, ran = self.run_start_as([]) + self.assertNotEqual(result.returncode, 0) + self.assertIn("no way to run", result.stderr) + self.assertEqual(ran, "", "a command must never be run as root when the user switch is impossible") + + +class GivenTheRealCatalogueAndPackagingFiles(unittest.TestCase): + def test_when_the_catalogue_is_loaded_then_every_non_alpine_distro_depends_on_what_provides_useradd(self): + providers = {"passwd", "shadow-utils", "shadow"} + for entry in tool.load_distros(REAL_CATALOGUE): + if entry["format"] == "apk": + continue # busybox has adduser and addgroup + self.assertTrue(providers & set(entry["depends"]), f"{entry['id']} lacks a package that provides useradd") + + def test_when_both_packages_of_a_distro_are_rendered_then_no_file_is_shipped_by_both(self): + """The server and the agent are installed side by side on a host that monitors itself, and + dpkg, pacman, apk and pkg refuse to install a package that ships a file another installed + package owns (rpm only tolerates it when the contents match). The smoke test installs both.""" + for entry in tool.load_distros(REAL_CATALOGUE): + destinations = {} + for component in ("server", "agent"): + config = json.loads( + tool.render_nfpm_config( + component, entry, "x86_64", "0.0.0", "1", "/stage", "/dash", "/repo/LICENSE", + packaging_dir="/repo/packaging/linux", scripts_dir="/scripts", + ) + ) + destinations[component] = {c["dst"] for c in config["contents"]} + shared = destinations["server"] & destinations["agent"] + self.assertEqual(shared, set(), f"{entry['id']}: both packages ship {sorted(shared)}") + + def test_when_the_catalogue_is_loaded_then_the_alpine_package_depends_on_openrc_because_it_ships_an_openrc_script(self): + for entry in tool.load_distros(REAL_CATALOGUE): + if entry["format"] == "apk": + self.assertIn("openrc", entry["depends"], entry["id"]) + + def test_when_the_smoke_scripts_are_parsed_by_a_posix_shell_then_they_have_no_syntax_errors(self): + for name in ("smoke-install.sh", "smoke-service.sh", "freebsd-smoke.sh", "freebsd-package.sh"): + for shell in ("dash", "sh"): + if shutil.which(shell): + path = REPO_ROOT / "scripts" / "release" / name + result = subprocess.run([shell, "-n", str(path)], capture_output=True, text=True, check=False) + self.assertEqual(result.returncode, 0, f"{shell} -n {name}: {result.stderr}") + + def test_when_the_release_workflow_runs_the_freebsd_job_then_the_packages_are_smoke_tested(self): + workflow = (REPO_ROOT / ".github" / "workflows" / "release.yml").read_text(encoding="utf-8") + self.assertIn("sh scripts/release/freebsd-smoke.sh", workflow) + + def test_when_the_release_workflow_installs_a_linux_package_then_the_service_setup_is_checked_too(self): + workflow = (REPO_ROOT / ".github" / "workflows" / "release.yml").read_text(encoding="utf-8") + self.assertIn("sh /release/smoke-install.sh && sh /release/smoke-service.sh", workflow) + # The agent package can only finish its setup when it is told where the server is. + self.assertIn("--env THEWATCHER_SERVER=localhost --env ENROLLMENT_TOKEN=smoke-token", workflow) + + def test_when_every_real_package_is_rendered_then_each_packaging_file_it_names_is_in_the_repository(self): + packaging_dir = REPO_ROOT / "packaging" / "linux" + for entry in tool.load_distros(REAL_CATALOGUE): + for component in ("server", "agent"): + config = json.loads( + tool.render_nfpm_config( + component, entry, "x86_64", "0.0.0", "1", "/stage", "/dash", "/repo/LICENSE", + packaging_dir=packaging_dir.as_posix(), scripts_dir="/scripts", + ) + ) + packaged = [c for c in config["contents"] if str(c["src"]).startswith(packaging_dir.as_posix())] + self.assertGreaterEqual(len(packaged), 2, f"{entry['id']} {component}: helper and service file") + for content in packaged: + self.assertTrue(Path(content["src"]).is_file(), f"{entry['id']} {component}: {content['src']}") + class GivenReleaseNotes(unittest.TestCase): def test_when_rendered_then_they_identify_the_build_and_list_every_asset(self): @@ -381,6 +1133,190 @@ def test_when_the_stage_is_empty_then_value_error_is_raised(self): with tempfile.TemporaryDirectory() as tmp, self.assertRaises(ValueError): tool.render_freebsd_manifest("agent", "0.10.1", "7", tmp, "FreeBSD:14:amd64") + def manifest(self, component): + with tempfile.TemporaryDirectory() as tmp: + make_tree(tmp, {"usr/local/bin/TheWatcherAgent": b"x"}) + return json.loads(tool.render_freebsd_manifest(component, "0.10.1", "7", tmp, "FreeBSD:14:amd64")) + + def test_when_rendered_then_pkg_sets_the_service_up_after_install_and_stops_it_after_removal(self): + scripts = self.manifest("agent")["scripts"] + self.assertEqual(sorted(scripts), ["post-deinstall", "post-install"]) + self.assertIn("/usr/local/libexec/thewatcher/service-setup-agent agent setup", scripts["post-install"]) + # pkg kills what a script leaves running, so the hook asks the helper not to start it. + self.assertIn("THEWATCHER_NO_START=1 /usr/local/libexec", scripts["post-install"]) + + def test_when_a_package_is_upgraded_then_no_script_stops_the_service(self): + """pkg-script(5): an upgrade runs the new pre-install, the OLD pre-deinstall, replaces the files and + runs the new post-install; the old post-deinstall does not run. post-install cannot start the + service again (pkg kills what a script leaves running), so a stop in pre-deinstall would leave + every upgraded service down until an administrator notices. Only a removal may stop it.""" + for component in ("server", "agent"): + self.assertNotIn("pre-deinstall", self.manifest(component)["scripts"]) + + def test_when_the_package_is_removed_then_the_service_is_stopped_through_the_pid_file_not_through_removed_files(self): + for component in ("server", "agent"): + text = self.manifest(component)["scripts"]["post-deinstall"] + # The rc script and the helper are package files, gone before post-deinstall runs. + self.assertNotIn("service-setup", text) + self.assertNotIn("service thewatcher", text) + self.assertIn(f"/var/run/thewatcher_{component}.pid", text) + + def test_when_rendered_for_the_server_then_the_scripts_call_the_helper_for_the_server(self): + scripts = self.manifest("server")["scripts"] + self.assertIn("service-setup-server server setup", scripts["post-install"]) + + def test_when_a_script_is_rendered_then_it_is_a_posix_shell_script_with_unix_line_endings(self): + for text in tool.render_freebsd_scripts("server").values(): + self.assertTrue(text.startswith("#!/bin/sh\n")) + self.assertNotIn("\r", text) + + def test_when_the_component_is_unknown_then_no_scripts_are_rendered(self): + with self.assertRaises(ValueError): + tool.render_freebsd_scripts("dashboard") + + +@needs_posix_shell +class GivenAPackageRemovedWhileItsServiceRuns(unittest.TestCase): + """The generated post-deinstall script is what stops a FreeBSD service when its package is removed. + It runs after pkg deleted the files, so it cannot use the rc script or the helper: it signals the + supervisor daemon(8) recorded in the pid file, which forwards SIGTERM to the service. These run the + real generated text against a fake root and a real background process.""" + + def run_script(self, component, state, comm="daemon", command=None, wait=None): + """Runs post-deinstall with a pid file in `state` (live: names a running process, stubborn: names one + that ignores SIGTERM, junk: holds no number, none: absent); returns (the script's exit status, whether + that process was still alive). What the script wrote to stderr is left in self.stderr. `comm` and + `command` are what ps reports for that process: the supervisor of this service by default.""" + sh = shutil.which("sh") + self.assertIsNotNone(sh, "no sh on PATH") + text = tool.render_freebsd_scripts(component)["post-deinstall"] + if command is None: + # What FreeBSD's ps shows for a daemon(8) supervisor: daemon retitles itself, so the -P argument + # is not in it (the first version of this hook looked for it, and left every service running). + command = f"daemon: /usr/local/bin/TheWatcher{component.capitalize()}[1234] (daemon)" + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) / "root" + (root / "var" / "run").mkdir(parents=True) + stubs = Path(tmp) / "bin" + stubs.mkdir() + # ps -o comm= -p and ps -ww -o command= -p : what the process is called and how it was + # started, to tell a pid file left behind from a live one, and another service's supervisor from ours. + (stubs / "ps").write_bytes(b'#!/bin/sh\ncase "$*" in *command=*) echo "${STUB_COMMAND}" ;; *) echo "${STUB_COMM}" ;; esac\n') + (stubs / "ps").chmod(0o755) + script = Path(tmp) / "post-deinstall" + script.write_bytes(text.encode("utf-8")) + errors = Path(tmp) / "stderr" + # The process runs under a subshell that waits for it, so it is reaped the moment it dies: a + # process whose parent has gone and that nothing reaps stays a zombie, and kill -0 still finds it. + driver = ( + 'pidfile="$1/var/run/thewatcher_$5.pid"\n' + 'case "$4" in\n' + ' live) ( sleep 300 >/dev/null 2>&1 "$pidfile"; wait $spid ) & ;;\n' + " stubborn) ( sh -c 'trap \"\" TERM; while :; do sleep 1; done' >/dev/null 2>&1 \"$pidfile\"; wait $spid ) & ;;\n" + ' junk) echo "not a pid" >"$pidfile" ;;\n' + 'esac\n' + 'n=0; while [ "$4" != none ] && [ ! -s "$pidfile" ] && [ "$n" -lt 50 ]; do n=$((n + 1)); sleep 0.1; done\n' + 'pid=$(cat "$pidfile" 2>/dev/null || true)\n' + 'THEWATCHER_ROOT="$1" PATH="$2:$PATH" STUB_COMM="$6" STUB_COMMAND="$7" THEWATCHER_STOP_WAIT="$8" sh "$3" 2>"$9"\n' + 'status=$?\n' + 'lived=no\n' + 'case "$pid" in ""|*[!0-9]*) ;; *) if kill -0 "$pid" 2>/dev/null; then lived=yes; kill -KILL "$pid" 2>/dev/null; fi ;; esac\n' + 'echo "status=$status lived=$lived"\n' + ) + result = subprocess.run( + [sh, "-c", driver, "driver", shell_path(root), shell_path(stubs), shell_path(script), state, component, comm, + command, str(wait if wait is not None else 30), shell_path(errors)], + capture_output=True, text=True, timeout=120, check=False, + ) + self.stderr = errors.read_text(encoding="utf-8") if errors.exists() else "" + self.assertEqual(result.returncode, 0, result.stderr) + fields = dict(part.split("=") for part in result.stdout.split()) + return int(fields["status"]), fields["lived"] == "yes" + + def test_when_the_service_runs_then_its_supervisor_is_stopped(self): + for component in ("server", "agent"): + with self.subTest(component=component): + status, lived = self.run_script(component, "live") + self.assertEqual(status, 0) + self.assertFalse(lived, "the process named in the pid file was left running") + + def test_when_the_pid_file_names_something_else_then_it_is_left_alone(self): + """A pid file the service did not remove (a crash, a power cut) can name a process that + has the same number now; it is only signalled when it is a daemon.""" + status, lived = self.run_script("server", "live", comm="sleep") + self.assertEqual(status, 0) + self.assertTrue(lived, "a process that is not a daemon was killed") + + def test_when_the_pid_file_names_another_services_supervisor_then_it_is_left_alone(self): + """comm is "daemon" for every daemon(8) supervisor, so a stale pid file whose number now belongs to + another service's supervisor passes that check. Its title names the program it runs, not ours.""" + other = "daemon: /usr/local/bin/other_service[99] (daemon)" + status, lived = self.run_script("server", "live", command=other) + self.assertEqual(status, 0) + self.assertTrue(lived, "another service's supervisor was signalled") + + def test_when_the_service_does_not_stop_then_removal_goes_on_but_says_so(self): + """If the service ignores SIGTERM the package is still removed (its files and rc script go), so the + administrator is told how to stop it instead of finding it running with its binary deleted.""" + status, lived = self.run_script("server", "stubborn", wait=2) + self.assertEqual(status, 0) + self.assertTrue(lived) + self.assertIn("did not stop within 2 seconds", self.stderr) + self.assertIn("kill -TERM", self.stderr) + + def test_when_the_service_stops_in_time_then_nothing_is_said(self): + self.run_script("agent", "live") + self.assertEqual(self.stderr, "") + + def test_when_there_is_no_pid_file_then_removal_goes_on(self): + self.assertEqual(self.run_script("agent", "none")[0], 0) + + def test_when_the_pid_file_holds_no_number_then_removal_goes_on(self): + self.assertEqual(self.run_script("agent", "junk")[0], 0) + + +class GivenTheFreeBSDSmokeScript(unittest.TestCase): + """freebsd-smoke.sh only runs in the FreeBSD VM. Two things it has to do were found there.""" + + def setUp(self): + self.text = (REPO_ROOT / "scripts" / "release" / "freebsd-smoke.sh").read_text(encoding="utf-8") + + def test_when_a_package_is_installed_over_itself_then_a_running_service_is_still_running(self): + """pkg runs the old pre-deinstall during an upgrade; a package that stopped the service there left + every upgraded service down. `pkg add -f` takes the same upgrade path for a package that is installed.""" + self.assertRegex(self.text, r"pkg add -f ") + self.assertIn("still running after the packages were installed over themselves", self.text) + + def test_when_the_test_is_over_then_the_services_are_stopped_so_the_vm_session_can_end(self): + """A service that is left running can hold the session's output open, and the job then waits for it + for as long as the job lasts (the first full run did, for 75 minutes, after the test had passed).""" + tail = self.text[self.text.rindex("freebsd-smoke: ok") - 400 :] + self.assertIn("onestop", tail) + + +class GivenTheFreeBSDPackagingScript(unittest.TestCase): + """freebsd-package.sh only runs in the FreeBSD VM, so check here that it stages + what the manifest and the pkg scripts rely on.""" + + def setUp(self): + self.text = (REPO_ROOT / "scripts" / "release" / "freebsd-package.sh").read_text(encoding="utf-8") + + def test_when_it_stages_a_package_then_the_helper_goes_where_the_pkg_scripts_call_it(self): + self.assertIn("packaging/freebsd/service-setup.sh", self.text) + # One helper per package: pkg refuses to install a package that ships a file + # another installed package already owns, and both are installed on one host. + self.assertIn("usr/local/libexec/thewatcher/service-setup-${component}", self.text) + + def test_when_the_two_packages_are_staged_then_their_pkg_scripts_call_different_helpers(self): + server = tool.render_freebsd_scripts("server")["post-install"] + agent = tool.render_freebsd_scripts("agent")["post-install"] + self.assertIn("/usr/local/libexec/thewatcher/service-setup-server ", server) + self.assertIn("/usr/local/libexec/thewatcher/service-setup-agent ", agent) + + def test_when_it_stages_a_package_then_the_rc_script_goes_in_the_rc_d_directory(self): + self.assertIn("packaging/freebsd/thewatcher_${component}", self.text) + self.assertIn("usr/local/etc/rc.d", self.text) + class GivenTheCommandLine(unittest.TestCase): def test_when_the_matrix_command_runs_then_stdout_is_a_fromjson_include_list(self): @@ -418,6 +1354,29 @@ def test_when_the_stale_assets_command_runs_then_dropped_names_are_printed_one_p # existing.txt itself sits in --new-dir here, so it is "new"; only old.rpm is stale. self.assertEqual(out.split(), ["old.rpm"]) + def test_when_the_package_scripts_command_runs_then_the_scripts_are_written(self): + with tempfile.TemporaryDirectory() as tmp: + out_dir = Path(tmp) / "scripts" + code, _, err = run_cli( + "package-scripts", "--component", "server", "--format", "apk", "--out-dir", str(out_dir) + ) + written = sorted(p.name for p in out_dir.iterdir()) + executable = os.access(out_dir / "postinstall", os.X_OK) + self.assertEqual((code, err), (0, "")) + self.assertEqual(written, ["postinstall", "postupgrade", "preremove"]) + self.assertTrue(executable or sys.platform == "win32") + + def test_when_the_nfpm_config_command_runs_then_it_refers_to_the_scripts_and_packaging_directories(self): + code, out, err = run_cli( + "nfpm-config", "--component", "agent", "--distro", "debian-12", "--arch", "x86_64", "--version", "0.0.0", + "--release", "1", "--stage-dir", "stage", "--dashboard-dir", "dash", "--license-file", "LICENSE", + "--catalogue", str(REAL_CATALOGUE), "--packaging-dir", "packaging/linux", "--scripts-dir", "stage/scripts-agent", + ) + self.assertEqual((code, err), (0, "")) + config = json.loads(out) + self.assertEqual(config["scripts"]["postinstall"], "stage/scripts-agent/postinstall") + self.assertIn("packaging/linux/service-setup.sh", {c["src"] for c in config["contents"]}) + def test_when_the_command_is_unknown_then_the_exit_code_is_2(self): code, _, err = run_cli("bogus") self.assertEqual(code, 2) @@ -882,7 +1841,31 @@ def test_when_a_script_downloads_then_curl_enforces_https(self): # only retries 408/429/5xx, so a download that is fine a # second later would fail the build. self.assertIn("--retry-all-errors", line) - + # A fixed --retry-delay gives up after a few seconds; without it curl doubles the + # wait, so six retries ride out a minute-long GitHub error (a 500 from a release + # download failed a whole release job). + self.assertNotIn("--retry-delay", line) + self.assertRegex(line, r"--retry [6-9] ") + + +class GivenThePythonSources(unittest.TestCase): + """Rocky 9 runs these scripts on Python 3.9: nothing may need a newer one.""" + + def test_when_a_script_reads_or_writes_text_then_it_does_not_pass_newline(self): + # Path.write_text and Path.read_text only accept newline= from Python 3.10. + # A Windows host that writes text turns line feeds into CRLF, so write bytes. + offenders = [] + for source in sorted((REPO_ROOT / "scripts").rglob("*.py")): + tree = ast.parse(source.read_text(encoding="utf-8"), filename=str(source)) + for node in ast.walk(tree): + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and node.func.attr in ("write_text", "read_text") + and any(keyword.arg == "newline" for keyword in node.keywords) + ): + offenders.append(f"{source.relative_to(REPO_ROOT)}:{node.lineno}") + self.assertEqual([], offenders) if __name__ == "__main__": unittest.main() diff --git a/scripts/release/service_setup_test.py b/scripts/release/service_setup_test.py new file mode 100755 index 0000000..f950ff5 --- /dev/null +++ b/scripts/release/service_setup_test.py @@ -0,0 +1,1542 @@ +#!/usr/bin/env python3 +"""Behaviour tests for packaging/linux/service-setup.sh. + +The helper runs from the maintainer scripts of every Linux package and sets the +installed component up as a service (user, directories, config, enable, start, +firewall). These tests run it against a fake root directory with stand-in +commands on PATH, so nothing on the machine is touched: no user is created, no +service is started and no firewall rule is added. Each test is one +GIVEN / WHEN / THEN case. + +Run directly (python3 scripts/release/service_setup_test.py) or through +`meson test --suite release`. +""" + +import os +import shutil +import stat +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parents[2] +HELPER = REPO_ROOT / "packaging" / "linux" / "service-setup.sh" + +# Needs a POSIX shell. Linux and FreeBSD always have one; on Windows opt in with +# Git Bash, as for release_tool_test.py. +needs_posix_shell = unittest.skipIf( + sys.platform == "win32" and not os.environ.get("RELEASE_TOOL_SHELL_TESTS"), + "needs a POSIX shell; set RELEASE_TOOL_SHELL_TESTS=1 to run with Git Bash", +) + +# Stand-ins for the commands the helper calls. Every call is logged to +# $CALL_LOG as " ". State lives in files under $STATE so a +# later command sees what an earlier one did, as on a real host. +STUBS = { + # A user exists once useradd or adduser has created it. + "id": '[ -e "$STATE/users/$1" ]', + # Like the real useradd, --user-group fails when the group exists and makes it when not. + "useradd": """ +for last; do :; done +case " $* " in + *" --user-group "*) + [ ! -e "$STATE/groups/$last" ] || { echo "useradd: group $last exists - if you want to add this user to that group, use -g." >&2; exit 9; } + mkdir -p "$STATE/groups"; : > "$STATE/groups/$last" ;; +esac +mkdir -p "$STATE/users"; : > "$STATE/users/$last" +""", + "adduser": 'for last; do :; done; mkdir -p "$STATE/users"; : > "$STATE/users/$last"', + # Like the real addgroup, adding a group that exists is an error. + "addgroup": """ +for last; do :; done +[ ! -e "$STATE/groups/$last" ] || { echo "addgroup: group '$last' in use" >&2; exit 1; } +mkdir -p "$STATE/groups"; : > "$STATE/groups/$last" +""", + "getent": '[ "$1" = group ] && [ -e "$STATE/groups/$2" ]', + # FAIL_HANDOVER makes only the recursive hand-over to the service user fail. + "chown": """ +case "$*" in -R*) [ -z "${FAIL_HANDOVER:-}" ] || exit 1 ;; esac +exit 0 +""", + "systemctl": """ +for last; do :; done +case "$1" in + is-active) [ -e "$STATE/active/$last" ] ;; + start|restart) + [ -z "${FAIL_START:-}" ] || exit 1 + mkdir -p "$STATE/active"; : > "$STATE/active/$last" ;; + disable) rm -f "$STATE/active/$last" ;; + *) exit 0 ;; +esac +""", + "deb-systemd-invoke": """ +for last; do :; done +[ -z "${FAIL_START:-}" ] || exit 1 +mkdir -p "$STATE/active"; : > "$STATE/active/$last" +""", + "rc-update": "exit 0", + "rc-service": """ +svc="$1" +case "$2" in + status) [ -e "$STATE/active/$svc" ] ;; + start|restart) + [ -z "${FAIL_START:-}" ] || exit 1 + mkdir -p "$STATE/active"; : > "$STATE/active/$svc" ;; + stop) rm -f "$STATE/active/$svc" ;; + *) exit 0 ;; +esac +""", + "ufw": """ +case "$1" in + status) echo "Status: ${UFW_STATE:-inactive}"; [ -z "${UFW_RULES:-}" ] || echo "${UFW_RULES}" ;; + *) exit 0 ;; +esac +""", + "firewall-cmd": """ +# FW_ZONE is the default zone; FW_PERM_HAS and FW_RUN_HAS list ports ("5555/tcp") that are +# already open in the permanent and the running configuration. FAIL_PERMANENT and FAIL_RUNTIME +# refuse to add or remove a port in that configuration. +case "$*" in + *--query-port=*) + [ -z "${FW_QUERY_FAIL:-}" ] || exit 252 + case "$*" in *--permanent*) [ -z "${FW_PERM_QUERY_FAIL:-}" ] || exit 252 ;; esac + all="$*"; port="${all##*--query-port=}"; port="${port%% *}" + case "$*" in *--permanent*) has="${FW_PERM_HAS:-}" ;; *) has="${FW_RUN_HAS:-}" ;; esac + case " $has " in *" $port "*) exit 0 ;; *) exit 1 ;; esac ;; + *--get-default-zone*) [ -z "${FW_ZONE_FAIL:-}" ] || exit 1; echo "${FW_ZONE:-public}"; exit 0 ;; +esac +case "$1" in + --state) [ "${FIREWALLD_STATE:-not running}" = running ] && echo running || { echo "not running"; exit 252; } ;; + --permanent) case "$*" in *--add-port*|*--remove-port*) [ -z "${FAIL_PERMANENT:-}" ] || exit 1 ;; esac ;; + --zone=*) case "$*" in *--add-port*|*--remove-port*) [ -z "${FAIL_RUNTIME:-}" ] || exit 1 ;; esac ;; + *) exit 0 ;; +esac +""", +} + +# Stand-in for the installed binaries. Like the real --init-config it writes +# the config only when none exists, and never touches an existing one. +FAKE_BINARY = """#!/bin/sh +echo "$(basename "$0") $*" >> "$CALL_LOG" +[ -z "${FAIL_INIT:-}" ] || { echo "cannot create the config" >&2; exit 1; } +[ "$1" = "--init-config" ] || exit 0 +shift +conf="" +while [ $# -gt 0 ]; do + [ "$1" = "--config" ] && conf="$2" + shift +done +[ -e "$conf" ] || { mkdir -p "$(dirname "$conf")"; echo "created by --init-config" > "$conf"; } +""" + + +def write_script(path, body): + path.parent.mkdir(parents=True, exist_ok=True) + text = body if body.startswith("#!") else "#!/bin/sh\n" + body + path.write_bytes((text.replace("\r\n", "\n")).encode("utf-8")) + path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + + +class FakeHost: + """A root directory laid out like a host the package was just unpacked on.""" + + def __init__(self, flavour="systemd", running=True): + self.dir = Path(tempfile.mkdtemp(prefix="thewatcher-setup-")) + self.root = self.dir / "root" + self.state = self.dir / "state" + self.stubs = self.dir / "stubs" + self.call_log = self.dir / "calls.log" + self.call_log.write_text("", encoding="utf-8") + self.env_extra = {} + + # The package ships one service definition, chosen by its format. + for component in ("server", "agent"): + service = f"thewatcher-{component}" + write_script(self.root / "usr/bin" / f"TheWatcher{component.capitalize()}", FAKE_BINARY) + if flavour == "systemd": + (self.root / "usr/lib/systemd/system").mkdir(parents=True, exist_ok=True) + (self.root / f"usr/lib/systemd/system/{service}.service").write_text("[Unit]\n", encoding="utf-8") + elif flavour == "openrc": + write_script(self.root / "etc/init.d" / service, "exit 0") + if running: + run_dir = "run/systemd/system" if flavour == "systemd" else "run/openrc" + (self.root / run_dir).mkdir(parents=True, exist_ok=True) + + for name, body in STUBS.items(): + write_script(self.stubs / name, f'echo "{name} $*" >> "$CALL_LOG"\n{body}') + + def cleanup(self): + shutil.rmtree(self.dir, ignore_errors=True) + + def add_user(self, name): + (self.state / "users").mkdir(parents=True, exist_ok=True) + (self.state / "users" / name).write_text("", encoding="utf-8") + + def add_group(self, name): + (self.state / "groups").mkdir(parents=True, exist_ok=True) + (self.state / "groups" / name).write_text("", encoding="utf-8") + + def mark_active(self, service): + (self.state / "active").mkdir(parents=True, exist_ok=True) + (self.state / "active" / service).write_text("", encoding="utf-8") + + def add_config(self, directory, name, text="edited by the administrator\n"): + path = self.root / directory / name + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(text, encoding="utf-8") + return path + + def run(self, component, action, **env): + environment = dict(os.environ) + # The caller's own settings must not leak into the helper. + for name in ("THEWATCHER_SERVER", "ENROLLMENT_TOKEN"): + environment.pop(name, None) + environment.update( + { + "PATH": str(self.stubs) + os.pathsep + environment["PATH"], + "THEWATCHER_ROOT": str(self.root), + "STATE": str(self.state), + "CALL_LOG": str(self.call_log), + } + ) + environment.update(self.env_extra) + environment.update(env) + return subprocess.run( + ["sh", str(HELPER), component, action], + capture_output=True, text=True, env=environment, timeout=60, check=False, + ) + + def calls(self): + # Forward slashes throughout, so a Windows path from Git Bash compares like a POSIX one. + return self.call_log.read_text(encoding="utf-8").replace(chr(92), "/").splitlines() + + def called(self, prefix): + """True when a logged call starts with prefix (a command and its leading arguments).""" + prefix = prefix.replace(chr(92), "/") + return any(line == prefix or line.startswith(prefix + " ") for line in self.calls()) + + def calls_to(self, command): + return [line for line in self.calls() if line.split(" ", 1)[0] == command] + + +class HostCase(unittest.TestCase): + flavour = "systemd" + running = True + + def setUp(self): + self.host = FakeHost(self.flavour, self.running) + self.addCleanup(self.host.cleanup) + + +@needs_posix_shell +class GivenAServerPackageJustInstalledOnASystemdHost(HostCase): + def test_when_it_is_installed_then_a_system_user_is_created_for_the_service(self): + result = self.host.run("server", "install") + self.assertEqual(result.returncode, 0, result.stderr) + user_calls = self.host.calls_to("useradd") + self.assertEqual(len(user_calls), 1) + self.assertIn("--system", user_calls[0]) + self.assertIn("thewatcher", user_calls[0].split()) + + def test_when_it_is_installed_then_the_config_is_created_by_the_binary_with_init_config(self): + self.host.run("server", "install") + conf = self.host.root / "etc/thewatcher/TheWatcherServer.conf" + self.assertTrue(conf.is_file()) + self.assertTrue( + self.host.called(f"TheWatcherServer --init-config --config {conf} --db-path /var/lib/thewatcher/thewatcher.db"), + self.host.calls(), + ) + + def test_when_it_is_installed_then_the_database_goes_in_the_data_directory_not_the_config_directory(self): + self.host.run("server", "install") + init_call = next(c for c in self.host.calls() if "--init-config" in c) + self.assertIn("--db-path /var/lib/thewatcher/thewatcher.db", init_call) + self.assertNotIn("etc/thewatcher/thewatcher.db", init_call) + + def test_when_it_is_installed_then_the_config_and_data_directories_belong_to_the_service_user(self): + self.host.run("server", "install") + chowns = self.host.calls_to("chown") + self.assertTrue(any("thewatcher:thewatcher" in c and "etc/thewatcher" in c for c in chowns), chowns) + self.assertTrue(any("thewatcher:thewatcher" in c and "var/lib/thewatcher" in c for c in chowns), chowns) + + @unittest.skipIf(os.name != "posix", "file modes are only meaningful on POSIX") + def test_when_it_is_installed_then_the_config_directory_is_private(self): + self.host.run("server", "install") + mode = stat.S_IMODE((self.host.root / "etc/thewatcher").stat().st_mode) + self.assertEqual(mode, 0o700) + + def test_when_it_is_installed_then_the_service_is_enabled_and_started(self): + result = self.host.run("server", "install") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue(self.host.called("systemctl enable thewatcher-server"), self.host.calls()) + self.assertTrue(self.host.called("systemctl start thewatcher-server"), self.host.calls()) + + def test_when_it_is_installed_then_the_agent_ports_are_not_opened_without_a_firewall(self): + self.host.run("server", "install") + self.assertFalse(self.host.called("ufw allow")) + self.assertFalse(self.host.called("firewall-cmd --permanent")) + + def test_when_the_install_runs_twice_then_the_user_and_config_are_not_created_again(self): + self.host.run("server", "install") + before = (self.host.root / "etc/thewatcher/TheWatcherServer.conf").read_text(encoding="utf-8") + result = self.host.run("server", "install") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(self.host.calls_to("useradd")), 1) + self.assertEqual(len([c for c in self.host.calls() if "--init-config" in c]), 1) + self.assertEqual((self.host.root / "etc/thewatcher/TheWatcherServer.conf").read_text(encoding="utf-8"), before) + + +@needs_posix_shell +class GivenAServerPackageInstalledOnAHostWithAFirewall(HostCase): + def record(self): + path = self.host.root / "var/lib/thewatcher-setup/server.firewall" + return path.read_text(encoding="utf-8").splitlines() if path.exists() else [] + + def test_when_ufw_is_active_then_the_data_and_enrollment_ports_are_allowed_and_recorded(self): + self.host.run("server", "install", UFW_STATE="active") + self.assertTrue(self.host.called("ufw allow 5555/tcp"), self.host.calls()) + self.assertTrue(self.host.called("ufw allow 5556/tcp"), self.host.calls()) + self.assertEqual(self.record(), ["ufw 5555/tcp", "ufw 5556/tcp"]) + + def test_when_ufw_is_installed_but_inactive_then_no_rule_is_added(self): + self.host.run("server", "install", UFW_STATE="inactive") + self.assertFalse(self.host.called("ufw allow")) + + def test_when_ufw_already_allows_a_port_then_that_rule_is_left_alone_and_not_recorded(self): + self.host.run("server", "install", UFW_STATE="active", UFW_RULES="5555/tcp ALLOW 10.0.0.0/8") + self.assertFalse(self.host.called("ufw allow 5555/tcp"), self.host.calls()) + self.assertTrue(self.host.called("ufw allow 5556/tcp"), self.host.calls()) + self.assertEqual(self.record(), ["ufw 5556/tcp"]) + + def test_when_firewalld_is_running_then_both_ports_are_opened_in_the_running_and_permanent_zone(self): + self.host.run("server", "install", FIREWALLD_STATE="running") + calls = self.host.calls() + for port in ("5555/tcp", "5556/tcp"): + self.assertIn(f"firewall-cmd --permanent --zone=public --add-port={port}", calls) + self.assertIn(f"firewall-cmd --zone=public --add-port={port}", calls) + self.assertEqual(self.record(), ["firewalld public 5555/tcp", "firewalld public 5556/tcp"]) + + def test_when_firewalld_is_running_then_it_is_never_reloaded(self): + """A reload replaces the running rules with the permanent ones, which would throw away + every runtime-only change the administrator made for other services.""" + self.host.run("server", "install", FIREWALLD_STATE="running") + self.assertFalse(self.host.called("firewall-cmd --reload"), self.host.calls()) + + def test_when_the_default_zone_is_not_public_then_that_zone_is_used_and_recorded(self): + self.host.run("server", "install", FIREWALLD_STATE="running", FW_ZONE="internal") + self.assertIn("firewall-cmd --permanent --zone=internal --add-port=5555/tcp", self.host.calls()) + self.assertEqual(self.record()[0], "firewalld internal 5555/tcp") + + def test_when_firewalld_already_allows_a_port_then_it_is_left_alone_and_not_recorded(self): + self.host.run("server", "install", FIREWALLD_STATE="running", FW_PERM_HAS="5555/tcp") + self.assertNotIn("firewall-cmd --permanent --zone=public --add-port=5555/tcp", self.host.calls()) + self.assertEqual(self.record(), ["firewalld public 5556/tcp"]) + + def test_when_the_permanent_rule_exists_but_the_running_one_does_not_then_the_running_firewall_is_opened(self): + """The administrator's permanent rule is not loaded yet: the port would stay closed otherwise. + The rule is theirs, so it is not recorded and package removal does not take it away.""" + self.host.run("server", "install", FIREWALLD_STATE="running", FW_PERM_HAS="5555/tcp") + self.assertIn("firewall-cmd --zone=public --add-port=5555/tcp", self.host.calls()) + self.assertNotIn("firewall-cmd --permanent --zone=public --add-port=5555/tcp", self.host.calls()) + self.assertEqual(self.record(), ["firewalld public 5556/tcp"]) + + def test_when_the_port_is_open_only_in_the_running_firewall_then_only_the_permanent_rule_is_recorded(self): + """The running rule is the administrator's: removal must not close it.""" + self.host.run("server", "install", FIREWALLD_STATE="running", FW_RUN_HAS="5555/tcp") + self.assertIn("firewall-cmd --permanent --zone=public --add-port=5555/tcp", self.host.calls()) + self.assertNotIn("firewall-cmd --zone=public --add-port=5555/tcp", self.host.calls()) + self.assertEqual(self.record(), ["firewalld-permanent public 5555/tcp", "firewalld public 5556/tcp"]) + + def test_when_the_permanent_rule_fails_but_the_running_rule_is_added_then_only_the_running_rule_is_recorded(self): + """An administrator may add the permanent rule later: removal must not take it away.""" + self.host.run("server", "install", FIREWALLD_STATE="running", FAIL_PERMANENT="1") + self.assertEqual(self.record(), ["firewalld-runtime public 5555/tcp", "firewalld-runtime public 5556/tcp"]) + + def test_when_only_the_running_rule_is_pending_then_a_removed_permanent_rule_is_not_added_back(self): + """The permanent rule worked and the running one failed. The administrator then removed the + permanent rule: that is a choice, so the retry neither adds it back nor opens the port.""" + first = self.host.run("server", "install", FIREWALLD_STATE="running", FAIL_RUNTIME="1") + self.assertEqual(first.returncode, 0, first.stderr) + pending = self.host.root / "var/lib/thewatcher-setup/server.firewall-pending" + self.assertEqual(pending.read_text(encoding="utf-8").split(), ["5555", "running", "public", "5556", "running", "public"]) + before = len(self.host.calls()) + result = self.host.run("server", "upgrade", FIREWALLD_STATE="running") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse(any("--add-port" in call for call in self.host.calls()[before:]), self.host.calls()[before:]) + self.assertFalse(pending.exists()) + self.assertEqual(self.record(), []) + + def test_when_the_permanent_query_fails_but_the_running_one_says_absent_then_the_running_rule_is_recorded(self): + """The running rule was added by this install, so removal must take it back, and the + permanent configuration, whose state is unknown, stays pending until it can be told.""" + first = self.host.run("server", "install", FIREWALLD_STATE="running", FW_PERM_QUERY_FAIL="1") + self.assertEqual(first.returncode, 0, first.stderr) + calls = self.host.calls() + self.assertIn("firewall-cmd --zone=public --add-port=5555/tcp", calls) + self.assertNotIn("firewall-cmd --permanent --zone=public --add-port=5555/tcp", calls) + self.assertEqual(self.record(), ["firewalld-runtime public 5555/tcp", "firewalld-runtime public 5556/tcp"]) + pending = self.host.root / "var/lib/thewatcher-setup/server.firewall-pending" + self.assertEqual(pending.read_text(encoding="utf-8").split(), ["5555", "permanent", "public", "5556", "permanent", "public"]) + # The retry works: the permanent rule is added and the record covers both configurations. + self.host.run("server", "upgrade", FIREWALLD_STATE="running", FW_RUN_HAS="5555/tcp 5556/tcp") + self.assertEqual(self.record(), ["firewalld public 5555/tcp", "firewalld public 5556/tcp"]) + self.assertFalse(pending.exists()) + + def write_pending(self, *lines): + path = self.host.root / "var/lib/thewatcher-setup/server.firewall-pending" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(("".join(line + chr(10) for line in lines)).encode("utf-8")) + return path + + def prepare_upgrade(self): + self.host.add_user("thewatcher") + self.host.add_config("etc/thewatcher", "TheWatcherServer.conf") + + def write_record(self, *lines): + path = self.host.root / "var/lib/thewatcher-setup/server.firewall" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(("".join(line + chr(10) for line in lines)).encode("utf-8")) + + def test_when_only_firewalld_runs_at_the_retry_then_a_pending_ufw_entry_is_kept(self): + """Each entry is cleared only by its own firewall: ufw is not running, so its entry waits.""" + self.prepare_upgrade() + pending = self.write_pending("5556 ufw") + result = self.host.run("server", "upgrade", FIREWALLD_STATE="running", UFW_STATE="inactive") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(pending.read_text(encoding="utf-8").split(), ["5556", "ufw"]) + self.assertFalse(any("--add-port" in call for call in self.host.calls()), self.host.calls()) + + def test_when_a_new_firewalld_failure_is_recorded_then_an_unattempted_ufw_entry_is_kept_with_it(self): + self.prepare_upgrade() + pending = self.write_pending("5555 ufw", "5556 permanent public") + self.host.run("server", "upgrade", FIREWALLD_STATE="running", UFW_STATE="inactive", FAIL_PERMANENT="1") + self.assertEqual(pending.read_text(encoding="utf-8").split(), ["5555", "ufw", "5556", "permanent", "public"]) + + def test_when_ufw_starts_between_the_check_and_the_end_of_the_run_then_its_entry_is_still_kept(self): + """ufw was not running when the run looked, so its entry was not tried. That it is running a moment + later must not make the run think the entry was handled and drop it.""" + self.prepare_upgrade() + pending = self.write_pending("5556 ufw") + write_script( + self.host.stubs / "ufw", + 'echo "ufw $*" >> "$CALL_LOG"' + chr(10) + 'mkdir -p "$STATE"' + chr(10) + + 'case "$1" in status) n=$(cat "$STATE/ufw-calls" 2>/dev/null || echo 0); echo $((n + 1)) > "$STATE/ufw-calls";' + + ' if [ "$n" -eq 0 ]; then echo "Status: inactive"; else echo "Status: active"; fi ;; *) exit 0 ;; esac', + ) + result = self.host.run("server", "upgrade", FIREWALLD_STATE="running") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(pending.read_text(encoding="utf-8").split(), ["5556", "ufw"]) + self.assertFalse(self.host.called("ufw allow"), self.host.calls()) + + def test_when_ports_are_opened_in_different_zones_then_each_is_reported_with_its_own_zone(self): + self.prepare_upgrade() + self.write_pending("5555 running internal", "5556 running public") + result = self.host.run("server", "upgrade", FIREWALLD_STATE="running", FW_ZONE="public") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("5555/tcp (zone internal)", result.stdout) + self.assertIn("5556/tcp (zone public)", result.stdout) + + def test_when_the_default_zone_cannot_be_read_then_a_retry_keeps_its_original_scope(self): + self.prepare_upgrade() + pending = self.write_pending("5555 running") + self.host.run("server", "upgrade", FIREWALLD_STATE="running", FW_ZONE_FAIL="1") + self.assertEqual(pending.read_text(encoding="utf-8").split(), ["5555", "running"]) + self.assertFalse(any("--add-port" in call for call in self.host.calls()), self.host.calls()) + + def test_when_a_zone_was_stored_then_the_retry_works_in_that_zone_even_if_the_default_changed(self): + self.prepare_upgrade() + self.write_pending("5555 running internal") + self.host.run("server", "upgrade", FIREWALLD_STATE="running", FW_ZONE="public") + calls = self.host.calls() + self.assertIn("firewall-cmd --zone=internal --add-port=5555/tcp", calls) + self.assertNotIn("firewall-cmd --zone=public --add-port=5555/tcp", calls) + + def test_when_the_owned_permanent_rule_cannot_be_queried_then_the_running_retry_waits(self): + """If the administrator removed the permanent rule, opening the port would undo that; a + failed query cannot say, so nothing is opened and the entry stays pending.""" + self.prepare_upgrade() + self.write_record("firewalld-permanent public 5555/tcp") + pending = self.write_pending("5555 running public") + self.host.run("server", "upgrade", FIREWALLD_STATE="running", FW_PERM_QUERY_FAIL="1") + self.assertFalse(any("--add-port" in call for call in self.host.calls()), self.host.calls()) + self.assertEqual(pending.read_text(encoding="utf-8").split(), ["5555", "running", "public"]) + + def test_when_the_running_rule_is_gone_then_the_permanent_retry_waits_instead_of_being_cancelled(self): + """A firewalld reload drops running rules as well as an administrator's removal does, so the + two cannot be told apart: the port is not opened and the entry is not dropped.""" + self.prepare_upgrade() + self.write_record("firewalld-runtime public 5555/tcp") + pending = self.write_pending("5555 permanent public") + result = self.host.run("server", "upgrade", FIREWALLD_STATE="running") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse(any("--add-port" in call for call in self.host.calls()), self.host.calls()) + self.assertEqual(pending.read_text(encoding="utf-8").split(), ["5555", "permanent", "public", "runtime-gone"]) + self.assertIn("a reload or a removal", result.stderr) + # The running rule is confirmed absent, so it is no longer owned: an administrator who adds + # it later must not lose it when the package is removed. + self.assertFalse((self.host.root / "var/lib/thewatcher-setup/server.firewall").exists() and self.record(), self.record()) + + def test_when_the_running_rule_stays_gone_then_the_permanent_retry_keeps_waiting(self): + self.prepare_upgrade() + pending = self.write_pending("5555 permanent public runtime-gone") + self.host.run("server", "upgrade", FIREWALLD_STATE="running") + self.assertFalse(any("--add-port" in call for call in self.host.calls()), self.host.calls()) + self.assertEqual(pending.read_text(encoding="utf-8").split(), ["5555", "permanent", "public", "runtime-gone"]) + + def test_when_the_administrator_adds_the_running_rule_later_then_it_is_not_owned_and_the_permanent_retry_proceeds(self): + self.prepare_upgrade() + self.write_pending("5555 permanent public runtime-gone") + self.host.run("server", "upgrade", FIREWALLD_STATE="running", FW_RUN_HAS="5555/tcp") + calls = self.host.calls() + self.assertIn("firewall-cmd --permanent --zone=public --add-port=5555/tcp", calls) + self.assertNotIn("firewall-cmd --zone=public --add-port=5555/tcp", calls) + self.assertEqual(self.record(), ["firewalld-permanent public 5555/tcp"]) + # Removing the package takes back the permanent rule only: the running one is the administrator's. + self.host.run("server", "remove", FIREWALLD_STATE="running") + self.assertNotIn("firewall-cmd --zone=public --remove-port=5555/tcp", self.host.calls()) + + def test_when_both_configurations_already_allow_a_port_then_nothing_is_added(self): + self.host.run("server", "install", FIREWALLD_STATE="running", FW_PERM_HAS="5555/tcp", FW_RUN_HAS="5555/tcp") + self.assertFalse(any("--add-port=5555/tcp" in call for call in self.host.calls()), self.host.calls()) + + def test_when_only_one_port_failed_then_the_retry_opens_only_that_port(self): + """5555 opened and 5556 failed. The administrator may have removed the 5555 rule since, and + that choice must stand: only the failed port is tried again.""" + write_script( + self.host.stubs / "ufw", + 'echo "ufw $*" >> "$CALL_LOG"' + chr(10) + '[ "$1" = status ] && echo "Status: active"' + chr(10) + + '[ "$1" = allow ] && [ "$2" = 5556/tcp ] && exit 1' + chr(10) + 'exit 0', + ) + self.host.run("server", "install") + pending = self.host.root / "var/lib/thewatcher-setup/server.firewall-pending" + self.assertEqual(pending.read_text(encoding="utf-8").split(), ["5556", "ufw"]) + write_script(self.host.stubs / "ufw", 'echo "ufw $*" >> "$CALL_LOG"' + chr(10) + '[ "$1" = status ] && echo "Status: active"' + chr(10) + "exit 0") + before = [c for c in self.host.calls() if c.startswith("ufw allow")] + self.host.run("server", "upgrade", UFW_STATE="active") + retried = [c for c in self.host.calls() if c.startswith("ufw allow")][len(before):] + self.assertEqual(retried, ["ufw allow 5556/tcp comment TheWatcher agents"], retried) + # The rule the retry added is recorded, or removing the package would leave it open. + self.assertEqual(self.record(), ["ufw 5555/tcp", "ufw 5556/tcp"]) + + def test_when_no_firewall_is_running_at_the_retry_then_the_failed_ports_are_kept(self): + write_script(self.host.stubs / "ufw", 'echo "ufw $*" >> "$CALL_LOG"' + chr(10) + '[ "$1" = status ] && echo "Status: active"' + chr(10) + '[ "$1" = status ] || exit 1') + self.host.run("server", "install") + pending = self.host.root / "var/lib/thewatcher-setup/server.firewall-pending" + self.assertTrue(pending.exists()) + # The upgrade finds neither ufw nor firewalld running: nothing could be tried. + write_script(self.host.stubs / "ufw", 'echo "ufw $*" >> "$CALL_LOG"' + chr(10) + 'case "$1" in status) echo "Status: ${UFW_STATE:-inactive}" ;; *) exit 0 ;; esac') + result = self.host.run("server", "upgrade", UFW_STATE="inactive") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue(pending.exists(), "the list was cleared although no rule was opened") + self.assertEqual(pending.read_text(encoding="utf-8").split(), ["5555", "ufw", "5556", "ufw"]) + + def test_when_only_firewalld_failed_then_the_retry_does_not_add_back_a_ufw_rule_the_administrator_deleted(self): + """ufw worked and firewalld's permanent add failed. The administrator then deleted the broad + ufw rule: the retry is about firewalld, so ufw is left alone.""" + self.host.run("server", "install", UFW_STATE="active", FIREWALLD_STATE="running", FAIL_PERMANENT="1") + pending = self.host.root / "var/lib/thewatcher-setup/server.firewall-pending" + self.assertEqual(pending.read_text(encoding="utf-8").split(), ["5555", "permanent", "public", "5556", "permanent", "public"]) + before = len([c for c in self.host.calls() if c.startswith("ufw allow")]) + # The administrator deleted the ufw rules (the stand-in lists none), then the upgrade runs. + self.host.run("server", "upgrade", UFW_STATE="active", FIREWALLD_STATE="running") + self.assertEqual(len([c for c in self.host.calls() if c.startswith("ufw allow")]), before) + + def test_when_the_service_cannot_be_started_at_install_then_the_install_still_finishes_with_a_warning(self): + for environment in ({"DPKG_MAINTSCRIPT_NAME": "postinst"}, {}): + with self.subTest(environment=environment): + host = FakeHost("systemd", True) + self.addCleanup(host.cleanup) + result = host.run("server", "install", FAIL_START="1", **environment) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("could not start thewatcher-server", result.stderr) + # The install is complete, so no marker makes every later upgrade run it again. + self.assertFalse((host.root / "var/lib/thewatcher-setup/server.incomplete").exists()) + + def test_when_ufw_only_has_outbound_or_routed_rules_for_a_port_then_the_inbound_rule_is_added(self): + self.host.run("server", "install", UFW_STATE="active", UFW_RULES="5555/tcp ALLOW OUT Anywhere\n5556/tcp ALLOW FWD Anywhere") + self.assertTrue(self.host.called("ufw allow 5555/tcp"), self.host.calls()) + self.assertTrue(self.host.called("ufw allow 5556/tcp"), self.host.calls()) + + def test_when_the_permanent_rule_was_added_by_this_install_then_a_retry_records_the_running_rule_too(self): + """The permanent add worked and the running add failed, so only the permanent rule was + recorded. A retry must own the running rule it adds now, or removal leaves the port open.""" + first = self.host.run("server", "install", FIREWALLD_STATE="running", FAIL_RUNTIME="1") + self.assertEqual(first.returncode, 0, first.stderr) + self.assertEqual(self.record(), ["firewalld-permanent public 5555/tcp", "firewalld-permanent public 5556/tcp"]) + # The retry: the permanent rule exists now (the stand-in is told so) and the running one is added. + self.host.run("server", "upgrade", FIREWALLD_STATE="running", FW_PERM_HAS="5555/tcp 5556/tcp") + self.assertEqual(self.record(), ["firewalld public 5555/tcp", "firewalld public 5556/tcp"]) + + def test_when_firewalld_cannot_say_whether_a_port_is_open_then_nothing_is_added_for_it(self): + """A query that fails is not "absent": the rule may be the administrator's, and a rule + added blindly would never be recorded, so removal would leave it open.""" + result = self.host.run("server", "install", FIREWALLD_STATE="running", FW_QUERY_FAIL="1") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("could not tell whether 5555/tcp is already open", result.stderr) + self.assertFalse(any("--add-port" in call for call in self.host.calls()), self.host.calls()) + self.assertEqual(self.record(), []) + pending = self.host.root / "var/lib/thewatcher-setup/server.firewall-pending" + self.assertEqual(pending.read_text(encoding="utf-8").split(), ["5555", "both", "public", "5556", "both", "public"]) + + def test_when_a_failed_query_is_followed_by_a_successful_retry_then_the_rules_are_added_recorded_and_removable(self): + self.host.run("server", "install", FIREWALLD_STATE="running", FW_QUERY_FAIL="1") + self.host.run("server", "upgrade", FIREWALLD_STATE="running") + self.assertEqual(self.record(), ["firewalld public 5555/tcp", "firewalld public 5556/tcp"]) + self.assertFalse((self.host.root / "var/lib/thewatcher-setup/server.firewall-pending").exists()) + self.host.run("server", "remove", FIREWALLD_STATE="running") + calls = self.host.calls() + for port in ("5555/tcp", "5556/tcp"): + self.assertIn(f"firewall-cmd --permanent --zone=public --remove-port={port}", calls) + self.assertIn(f"firewall-cmd --zone=public --remove-port={port}", calls) + + def test_when_every_port_already_has_a_rule_then_nothing_is_said_to_be_opened_from_anywhere(self): + result = self.host.run("server", "install", UFW_STATE="active", UFW_RULES="5555/tcp ALLOW 10.0.0.0/8\n5556/tcp ALLOW 10.0.0.0/8") + self.assertNotIn("from anywhere", result.stdout) + + def test_when_a_firewall_rule_could_not_be_added_then_the_next_upgrade_tries_again_without_enabling_the_service(self): + """The failure is remembered on its own. Otherwise a refused rule would never be retried + and agents could not enroll, and retrying the whole install would re-enable a service the + administrator has stopped.""" + write_script(self.host.stubs / "ufw", 'echo "ufw $*" >> "$CALL_LOG"\n[ "$1" = status ] && echo "Status: active"\n[ "$1" = status ] || exit 1') + first = self.host.run("server", "install") + self.assertEqual(first.returncode, 0, first.stderr) + self.assertTrue((self.host.root / "var/lib/thewatcher-setup/server.firewall-pending").exists()) + self.assertFalse((self.host.root / "var/lib/thewatcher-setup/server.incomplete").exists()) + self.assertIn("tries again", first.stderr) + before = len([c for c in self.host.calls() if c.startswith("ufw allow")]) + enables = len([c for c in self.host.calls() if c.startswith("systemctl enable")]) + # ufw works again by the time of the upgrade. + write_script(self.host.stubs / "ufw", 'echo "ufw $*" >> "$CALL_LOG"\n[ "$1" = status ] && echo "Status: active"\nexit 0') + self.host.run("server", "upgrade", UFW_STATE="active") + self.assertGreater(len([c for c in self.host.calls() if c.startswith("ufw allow")]), before) + self.assertEqual(len([c for c in self.host.calls() if c.startswith("systemctl enable")]), enables) + self.assertEqual(self.record(), ["ufw 5555/tcp", "ufw 5556/tcp"], "the retried rules must be recorded for removal") + self.assertFalse((self.host.root / "var/lib/thewatcher-setup/server.firewall-pending").exists()) + + def test_when_the_http_api_port_is_considered_then_it_is_never_opened(self): + self.host.run("server", "install", UFW_STATE="active", FIREWALLD_STATE="running") + self.assertNotIn("8080", " ".join(self.host.calls())) + + def test_when_the_firewall_rule_fails_then_the_install_still_succeeds(self): + write_script(self.host.stubs / "ufw", 'echo "ufw $*" >> "$CALL_LOG"\n[ "$1" = status ] && echo "Status: active"\n[ "$1" = status ] || exit 1') + result = self.host.run("server", "install") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("warning", (result.stdout + result.stderr).lower()) + + def test_when_a_ufw_rule_fails_then_the_ports_are_not_reported_as_allowed_or_recorded(self): + write_script(self.host.stubs / "ufw", 'echo "ufw $*" >> "$CALL_LOG"\n[ "$1" = status ] && echo "Status: active"\n[ "$1" = status ] || exit 1') + result = self.host.run("server", "install") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("could not allow 5555/tcp in ufw", result.stderr) + self.assertNotIn("from anywhere", result.stdout, "claimed the ports were allowed after ufw refused") + self.assertEqual(self.record(), []) + + def test_when_firewalld_refuses_the_permanent_rule_then_the_warning_says_it_will_not_survive_a_reload(self): + result = self.host.run("server", "install", FIREWALLD_STATE="running", FAIL_PERMANENT="1") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("could not add 5555/tcp to the permanent configuration of firewalld zone public", result.stderr) + self.assertIn("firewall-cmd --zone=public --add-port=5555/tcp", self.host.calls(), "the running rule was still tried") + self.assertNotIn("from anywhere", result.stdout) + + def test_when_firewalld_refuses_the_running_rule_then_the_warning_says_it_is_not_open_yet(self): + result = self.host.run("server", "install", FIREWALLD_STATE="running", FAIL_RUNTIME="1") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("could not open 5555/tcp in the running firewalld zone public", result.stderr) + self.assertNotIn("from anywhere", result.stdout) + + +@needs_posix_shell +class GivenAServerPackageRemovedFromAHostWithAFirewall(HostCase): + """The helper opens 5555 and 5556 for the server it installs and records what it added. + Removing the server takes back exactly that, as the Windows uninstaller does with its own + rule, so no inbound rule is left for software that is gone and none the administrator + owns is deleted.""" + + def setUp(self): + super().setUp() + self.host.add_user("thewatcher") + self.host.add_config("etc/thewatcher", "TheWatcherServer.conf") + + def write_record(self, *lines): + path = self.host.root / "var/lib/thewatcher-setup/server.firewall" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(("".join(line + chr(10) for line in lines)).encode("utf-8")) + return path + + def test_when_ufw_rules_were_recorded_then_they_are_deleted(self): + self.write_record("ufw 5555/tcp", "ufw 5556/tcp") + result = self.host.run("server", "remove", UFW_STATE="active") + self.assertEqual(result.returncode, 0, result.stderr) + # --force: without it ufw asks for a confirmation that no package script can answer. + self.assertTrue(self.host.called("ufw --force delete allow 5555/tcp"), self.host.calls()) + self.assertTrue(self.host.called("ufw --force delete allow 5556/tcp"), self.host.calls()) + + def test_when_only_one_port_was_recorded_then_only_that_rule_is_deleted(self): + """The other rule was already there before the install, so it is not ours to delete.""" + self.write_record("ufw 5556/tcp") + self.host.run("server", "remove", UFW_STATE="active") + self.assertFalse(self.host.called("ufw --force delete allow 5555/tcp"), self.host.calls()) + self.assertTrue(self.host.called("ufw --force delete allow 5556/tcp"), self.host.calls()) + + def test_when_nothing_was_recorded_then_no_rule_is_deleted(self): + self.host.run("server", "remove", UFW_STATE="active", FIREWALLD_STATE="running") + self.assertFalse(self.host.called("ufw --force delete")) + self.assertFalse(any("--remove-port" in call for call in self.host.calls()), self.host.calls()) + + def test_when_ufw_is_not_running_then_the_rule_is_kept_and_the_warning_says_how_to_remove_it(self): + record = self.write_record("ufw 5555/tcp") + result = self.host.run("server", "remove", UFW_STATE="inactive") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse(self.host.called("ufw --force delete")) + self.assertIn("ufw delete allow 5555/tcp", result.stderr) + self.assertTrue(record.exists(), "the record is the only memory of what to remove") + + def test_when_firewalld_rules_were_recorded_then_they_are_removed_from_the_recorded_zone_without_a_reload(self): + self.write_record("firewalld public 5555/tcp", "firewalld public 5556/tcp") + # The default zone changed since the install: the rules are still in "public". + result = self.host.run("server", "remove", FIREWALLD_STATE="running", FW_ZONE="internal") + self.assertEqual(result.returncode, 0, result.stderr) + calls = self.host.calls() + for port in ("5555/tcp", "5556/tcp"): + self.assertIn(f"firewall-cmd --permanent --zone=public --remove-port={port}", calls) + self.assertIn(f"firewall-cmd --zone=public --remove-port={port}", calls) + self.assertFalse(self.host.called("firewall-cmd --reload"), calls) + + def test_when_only_the_permanent_rule_was_recorded_then_the_running_rule_is_left_open(self): + self.write_record("firewalld-permanent public 5555/tcp") + self.host.run("server", "remove", FIREWALLD_STATE="running") + calls = self.host.calls() + self.assertIn("firewall-cmd --permanent --zone=public --remove-port=5555/tcp", calls) + self.assertNotIn("firewall-cmd --zone=public --remove-port=5555/tcp", calls) + + def test_when_the_permanent_removal_fails_then_the_removal_still_succeeds_with_a_warning(self): + self.write_record("firewalld public 5555/tcp") + result = self.host.run("server", "remove", FIREWALLD_STATE="running", FAIL_PERMANENT="1", FW_PERM_HAS="5555/tcp") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("could not remove 5555/tcp from the permanent configuration of firewalld zone public", result.stderr) + + def test_when_the_running_removal_fails_then_it_is_reported_and_the_record_is_kept(self): + record = self.write_record("firewalld public 5555/tcp") + result = self.host.run("server", "remove", FIREWALLD_STATE="running", FAIL_RUNTIME="1", FW_RUN_HAS="5555/tcp") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("could not close 5555/tcp in the running firewalld zone public", result.stderr) + self.assertNotIn("removed 5555/tcp from firewalld", result.stdout) + self.assertTrue(record.exists(), "the record is the only memory of what is still open") + + def test_when_firewalld_is_not_running_at_removal_then_a_running_only_record_is_dropped_and_no_permanent_removal_is_advised(self): + record = self.write_record("firewalld-runtime public 5555/tcp") + result = self.host.run("server", "remove") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotIn("--permanent", result.stderr) + self.assertFalse(record.exists(), "a running rule is gone with firewalld; nothing is left to take back") + + def test_when_firewalld_is_not_running_at_removal_then_only_the_permanent_rule_stays_recorded(self): + record = self.write_record("firewalld public 5555/tcp") + result = self.host.run("server", "remove") + self.assertIn("firewall-cmd --permanent --zone=public --remove-port=5555/tcp", result.stderr) + self.assertEqual(record.read_text(encoding="utf-8").splitlines(), ["firewalld-permanent public 5555/tcp"]) + + def test_when_only_the_running_rule_was_recorded_then_the_permanent_rule_is_left_alone(self): + self.write_record("firewalld-runtime public 5555/tcp") + self.host.run("server", "remove", FIREWALLD_STATE="running") + calls = self.host.calls() + self.assertIn("firewall-cmd --zone=public --remove-port=5555/tcp", calls) + self.assertNotIn("firewall-cmd --permanent --zone=public --remove-port=5555/tcp", calls) + + def test_when_firewalld_stops_answering_then_the_removal_is_reported_as_unknown_and_the_record_is_kept(self): + record = self.write_record("firewalld public 5555/tcp") + result = self.host.run("server", "remove", FIREWALLD_STATE="running", FAIL_RUNTIME="1", FAIL_PERMANENT="1", FW_QUERY_FAIL="1") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("could not tell whether 5555/tcp is still open in the running firewalld zone public", result.stderr) + self.assertNotIn("removed 5555/tcp from firewalld", result.stdout) + self.assertTrue(record.exists()) + + def test_when_one_configuration_fails_to_clear_then_only_that_one_stays_in_the_record(self): + """The running rule is gone, so the record must not claim it: an administrator may add + it again, and a later removal would delete it.""" + record = self.write_record("firewalld public 5555/tcp") + self.host.run("server", "remove", FIREWALLD_STATE="running", FAIL_PERMANENT="1", FW_PERM_HAS="5555/tcp") + self.assertEqual(record.read_text(encoding="utf-8").splitlines(), ["firewalld-permanent public 5555/tcp"]) + + def test_when_one_port_fails_then_the_port_that_was_removed_leaves_the_record(self): + record = self.write_record("firewalld public 5555/tcp", "firewalld public 5556/tcp") + self.host.run("server", "remove", FIREWALLD_STATE="running", FAIL_RUNTIME="1", FW_RUN_HAS="5556/tcp") + self.assertEqual(record.read_text(encoding="utf-8").splitlines(), ["firewalld-runtime public 5556/tcp"]) + + def test_when_a_ufw_rule_cannot_be_deleted_then_it_stays_in_the_record(self): + record = self.write_record("ufw 5555/tcp") + write_script(self.host.stubs / "ufw", 'echo "ufw $*" >> "$CALL_LOG"\n[ "$1" = status ] && echo "Status: active"\n[ "$1" = status ] || exit 1') + self.host.run("server", "remove") + self.assertEqual(record.read_text(encoding="utf-8").splitlines(), ["ufw 5555/tcp"]) + + def test_when_the_port_is_already_gone_then_a_failing_removal_is_not_reported(self): + self.write_record("firewalld public 5555/tcp") + result = self.host.run("server", "remove", FIREWALLD_STATE="running", FAIL_RUNTIME="1", FAIL_PERMANENT="1") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertNotIn("could not", result.stderr) + + def test_when_a_rule_cannot_be_deleted_then_the_removal_still_succeeds_with_a_warning(self): + self.write_record("ufw 5555/tcp") + write_script(self.host.stubs / "ufw", 'echo "ufw $*" >> "$CALL_LOG"\n[ "$1" = status ] && echo "Status: active"\n[ "$1" = status ] || exit 1') + result = self.host.run("server", "remove") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("could not remove the ufw rule for 5555/tcp", result.stderr) + + def test_when_the_rules_are_removed_then_the_record_is_deleted(self): + record = self.write_record("ufw 5555/tcp") + self.host.run("server", "remove", UFW_STATE="active") + self.assertFalse(record.exists()) + + def test_when_the_agent_is_removed_then_the_firewall_is_not_touched(self): + self.host.add_user("thewatcher-agent") + self.write_record("ufw 5555/tcp", "firewalld public 5556/tcp") + self.host.run("agent", "remove", UFW_STATE="active", FIREWALLD_STATE="running") + self.assertFalse(self.host.called("ufw --force delete")) + self.assertFalse(any("--remove-port" in call for call in self.host.calls()), self.host.calls()) + + def test_when_the_server_is_upgraded_then_the_rules_stay(self): + self.write_record("ufw 5555/tcp", "ufw 5556/tcp") + self.host.run("server", "upgrade", UFW_STATE="active", FIREWALLD_STATE="running") + self.assertFalse(self.host.called("ufw --force delete")) + self.assertFalse(any("--remove-port" in call for call in self.host.calls()), self.host.calls()) + + +@needs_posix_shell +class GivenAServerPackageInstalledByDpkg(HostCase): + """dpkg sets DPKG_MAINTSCRIPT_NAME. Inside a maintainer script the service is driven through + deb-systemd-invoke, which honours policy-rc.d (a container or image build denies services + starting at install time). Run by hand, the helper calls systemctl directly.""" + + def test_when_a_maintainer_script_installs_the_package_then_the_service_is_started_through_deb_systemd_invoke(self): + result = self.host.run("server", "install", DPKG_MAINTSCRIPT_NAME="postinst") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue(self.host.called("deb-systemd-invoke start thewatcher-server"), self.host.calls()) + self.assertFalse(self.host.called("systemctl start"), self.host.calls()) + + def test_when_a_maintainer_script_upgrades_a_running_service_then_it_is_restarted_through_deb_systemd_invoke(self): + self.host.add_user("thewatcher") + self.host.add_config("etc/thewatcher", "TheWatcherServer.conf") + self.host.mark_active("thewatcher-server") + self.host.run("server", "upgrade", DPKG_MAINTSCRIPT_NAME="postinst") + self.assertTrue(self.host.called("deb-systemd-invoke restart thewatcher-server"), self.host.calls()) + self.assertFalse(self.host.called("systemctl restart"), self.host.calls()) + + def test_when_deb_systemd_invoke_fails_then_the_upgrade_still_succeeds_with_a_warning(self): + self.host.add_user("thewatcher") + self.host.add_config("etc/thewatcher", "TheWatcherServer.conf") + self.host.mark_active("thewatcher-server") + result = self.host.run("server", "upgrade", DPKG_MAINTSCRIPT_NAME="postinst", FAIL_START="1") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("could not restart thewatcher-server", result.stderr) + + def test_when_an_administrator_runs_the_helper_by_hand_then_systemctl_is_called_directly(self): + self.host.run("server", "install") + self.assertTrue(self.host.called("systemctl start thewatcher-server"), self.host.calls()) + self.assertFalse(self.host.called("deb-systemd-invoke"), self.host.calls()) + + +@needs_posix_shell +class GivenAConfigThatIsASymbolicLink(HostCase): + @unittest.skipIf(os.name != "posix", "symbolic links need POSIX") + def test_when_the_config_is_a_symbolic_link_then_its_target_is_not_changed(self): + self.host.add_user("thewatcher") + target = self.host.root / "elsewhere" + target.write_text("not ours" + chr(10), encoding="utf-8") + target.chmod(0o644) + conf = self.host.root / "etc/thewatcher/TheWatcherServer.conf" + conf.parent.mkdir(parents=True, exist_ok=True) + conf.symlink_to(target) + result = self.host.run("server", "upgrade") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(target.stat().st_mode & 0o777, 0o644) + self.assertIn("symbolic link", result.stderr) + + def test_when_the_config_exists_then_the_directory_is_taken_back_before_the_config_is_touched(self): + """The service user owns the directory, so it must not be able to swap the file under root.""" + self.host.add_user("thewatcher") + self.host.add_config("etc/thewatcher", "TheWatcherServer.conf") + self.host.run("server", "upgrade") + conf_dir = str(self.host.root / "etc/thewatcher").replace(chr(92), "/") + chowns = [c for c in self.host.calls_to("chown") if conf_dir in c] + self.assertTrue(chowns and chowns[0].startswith("chown root:root"), chowns) + # ...and given back to the service user afterwards, or the service could not write its config. + self.assertTrue(chowns[-1].startswith("chown -R thewatcher:thewatcher"), chowns) + + +@needs_posix_shell +class GivenAnAgentInstalledWithoutAServerAddress(HostCase): + def test_when_the_agent_has_no_server_address_then_the_message_mentions_the_enrollment_token_for_the_manual_route(self): + result = self.host.run("agent", "install") + self.assertEqual(result.returncode, 0, result.stderr) + # The manual alternative needs its own line for the token: the helper command above it + # already names the variable, so a bare containment check would pass without it. + self.assertRegex(result.stdout + result.stderr, r"or create [^\n]*\n[^\n]*ENROLLMENT_TOKEN=YOUR_TOKEN if the server has an enrollment token") + + +@needs_posix_shell +class GivenAnEarlierRunThatCreatedTheGroupButNotTheUser(HostCase): + """An install that stopped between creating the group and the user leaves the group behind, and + neither addgroup nor useradd --user-group accepts a group that exists. The retry has to use it.""" + + def test_when_the_group_exists_then_the_user_is_created_in_it_instead_of_failing(self): + self.host.add_group("thewatcher") + result = self.host.run("server", "install") + self.assertEqual(result.returncode, 0, result.stderr) + user_calls = self.host.calls_to("useradd") + self.assertEqual(len(user_calls), 1) + self.assertIn("--gid thewatcher", user_calls[0]) + self.assertNotIn("--user-group", user_calls[0]) + self.assertTrue(self.host.called("systemctl enable thewatcher-server"), self.host.calls()) + + def test_when_the_agent_group_exists_then_the_agent_user_is_created_in_it(self): + self.host.add_group("thewatcher-agent") + result = self.host.run("agent", "install") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("--gid thewatcher-agent", self.host.calls_to("useradd")[0]) + + def test_when_no_group_exists_then_the_user_gets_a_group_of_its_own(self): + result = self.host.run("server", "install") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("--user-group", self.host.calls_to("useradd")[0]) + self.assertNotIn("--gid", self.host.calls_to("useradd")[0]) + + +@needs_posix_shell +class GivenAnEarlierRunOnOpenRCThatCreatedTheGroupButNotTheUser(HostCase): + flavour = "openrc" + + def test_when_the_group_exists_then_the_user_is_created_in_it_and_the_group_is_not_added_again(self): + self.host.add_group("thewatcher") + result = self.host.run("server", "install") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.host.calls_to("addgroup"), []) + adduser_calls = self.host.calls_to("adduser") + self.assertEqual(len(adduser_calls), 1) + self.assertIn("-G thewatcher", adduser_calls[0]) + + def test_when_no_group_exists_then_it_is_added_first(self): + result = self.host.run("server", "install") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(self.host.calls_to("addgroup")), 1) + + +@needs_posix_shell +class GivenAServerPackageUpgraded(HostCase): + def setUp(self): + super().setUp() + self.host.add_user("thewatcher") + self.conf = self.host.add_config("etc/thewatcher", "TheWatcherServer.conf") + + def test_when_the_service_is_running_then_it_is_restarted_onto_the_new_binary(self): + self.host.mark_active("thewatcher-server") + result = self.host.run("server", "upgrade") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue(self.host.called("systemctl restart thewatcher-server"), self.host.calls()) + + def test_when_the_administrator_stopped_the_service_then_it_stays_stopped(self): + self.host.run("server", "upgrade") + self.assertFalse(self.host.called("systemctl start")) + self.assertFalse(self.host.called("systemctl restart")) + + def test_when_the_administrator_disabled_the_service_then_it_is_not_enabled_again(self): + self.host.run("server", "upgrade") + self.assertFalse(self.host.called("systemctl enable")) + + def test_when_upgraded_then_the_existing_config_is_left_alone(self): + self.host.run("server", "upgrade") + self.assertEqual(self.conf.read_text(encoding="utf-8"), "edited by the administrator\n") + self.assertFalse(any("--init-config" in c for c in self.host.calls())) + + def test_when_upgraded_then_a_firewall_rule_the_administrator_removed_is_not_added_back(self): + self.host.run("server", "upgrade", UFW_STATE="active", FIREWALLD_STATE="running") + self.assertFalse(self.host.called("ufw allow")) + self.assertFalse(self.host.called("firewall-cmd --permanent")) + + def test_when_upgraded_then_the_unit_files_are_reloaded_first(self): + self.host.mark_active("thewatcher-server") + self.host.run("server", "upgrade") + calls = self.host.calls() + reload_at = next(i for i, c in enumerate(calls) if c == "systemctl daemon-reload") + restart_at = next(i for i, c in enumerate(calls) if c.startswith("systemctl restart")) + self.assertLess(reload_at, restart_at) + + def test_when_the_restart_fails_then_the_upgrade_still_succeeds_with_a_warning(self): + self.host.mark_active("thewatcher-server") + result = self.host.run("server", "upgrade", FAIL_START="1") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("warning", (result.stdout + result.stderr).lower()) + + +@needs_posix_shell +class GivenAnUpgradeFromAPackageThatNeverSetUpTheService(HostCase): + """Packages before 0.10.3 installed only binaries, so there is no service user yet.""" + + def test_when_there_is_no_service_user_then_the_upgrade_sets_the_service_up_like_an_install(self): + old_conf = self.host.add_config("etc/thewatcher", "TheWatcherServer.conf", "created by hand as root\n") + result = self.host.run("server", "upgrade") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(len(self.host.calls_to("useradd")), 1) + self.assertTrue(self.host.called("systemctl enable thewatcher-server"), self.host.calls()) + self.assertEqual(old_conf.read_text(encoding="utf-8"), "created by hand as root\n") + self.assertTrue(any("thewatcher:thewatcher" in c and "etc/thewatcher" in c for c in self.host.calls_to("chown"))) + + +@needs_posix_shell +class GivenAnInstallThatFailedPartWay(HostCase): + """ensure_user runs before the config is created, so a failure to create the config leaves a + service user and no config. The package manager then retries, and a retry is an upgrade.""" + + MARKER = "var/lib/thewatcher-setup/server.incomplete" + + def test_when_the_user_was_made_by_hand_and_has_no_config_then_an_upgrade_adds_a_secure_config_but_enables_nothing(self): + """No marker: nothing here says this package began an install, so what the administrator + chose about the service is theirs. The config is still created, because a server that + starts without one writes its own with the API on every interface and no token.""" + self.host.add_user("thewatcher") + result = self.host.run("server", "upgrade") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue((self.host.root / "etc/thewatcher/TheWatcherServer.conf").is_file()) + self.assertFalse(self.host.called("systemctl enable")) + self.assertFalse(self.host.called("systemctl start")) + + def test_when_an_install_finishes_then_it_leaves_no_marker(self): + result = self.host.run("server", "install") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse((self.host.root / self.MARKER).exists()) + + def test_when_an_install_fails_then_it_leaves_a_marker_so_the_retry_is_an_install(self): + self.host.run("server", "install", FAIL_INIT="1") + self.assertTrue((self.host.root / self.MARKER).exists()) + + def test_when_the_handover_fails_after_the_config_was_created_then_a_retried_upgrade_finishes_the_install(self): + """The user and the config both exist by then, so only the marker says it is unfinished.""" + first = self.host.run("server", "install", FAIL_HANDOVER="1") + self.assertNotEqual(first.returncode, 0) + self.assertTrue((self.host.root / "etc/thewatcher/TheWatcherServer.conf").is_file()) + self.assertFalse(self.host.called("systemctl enable")) + + retry = self.host.run("server", "upgrade") + self.assertEqual(retry.returncode, 0, retry.stderr) + self.assertTrue(self.host.called("systemctl enable thewatcher-server"), self.host.calls()) + self.assertTrue(self.host.called("systemctl start thewatcher-server"), self.host.calls()) + self.assertFalse((self.host.root / self.MARKER).exists()) + + def test_when_the_retry_is_finished_then_the_next_upgrade_leaves_the_service_alone_again(self): + self.host.run("server", "install", FAIL_HANDOVER="1") + self.host.run("server", "upgrade") + enables = len([c for c in self.host.calls() if c == "systemctl enable thewatcher-server"]) + self.host.run("server", "upgrade") + self.assertEqual(len([c for c in self.host.calls() if c == "systemctl enable thewatcher-server"]), enables) + + def test_when_an_agent_without_a_server_address_was_installed_and_then_disabled_then_an_upgrade_does_not_enable_it_again(self): + """No config is the normal state of that agent, so it cannot be the sign of an unfinished install.""" + self.host.run("agent", "install") + self.assertFalse((self.host.root / "var/lib/thewatcher-setup/agent.incomplete").exists()) + enables = len([c for c in self.host.calls() if c == "systemctl enable thewatcher-agent"]) + self.assertEqual(enables, 1) + # The administrator disables it; nothing the helper sees records that, so the point is + # that an upgrade must not run the install steps again. + self.host.run("agent", "upgrade") + self.assertEqual(len([c for c in self.host.calls() if c == "systemctl enable thewatcher-agent"]), 1) + + def test_when_the_failed_install_is_retried_as_an_install_then_it_also_succeeds(self): + self.host.run("server", "install", FAIL_INIT="1") + result = self.host.run("server", "install") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue(self.host.called("systemctl enable thewatcher-server"), self.host.calls()) + + def test_when_the_failed_install_is_retried_as_an_upgrade_then_the_service_is_enabled_and_started(self): + first = self.host.run("server", "install", FAIL_INIT="1") + self.assertNotEqual(first.returncode, 0) + result = self.host.run("server", "upgrade") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue(self.host.called("systemctl enable thewatcher-server"), self.host.calls()) + self.assertTrue(self.host.called("systemctl start thewatcher-server"), self.host.calls()) + + def test_when_the_user_and_the_config_both_exist_then_an_upgrade_still_leaves_the_service_alone(self): + self.host.add_user("thewatcher") + self.host.add_config("etc/thewatcher", "TheWatcherServer.conf") + self.host.run("server", "upgrade") + self.assertFalse(self.host.called("systemctl enable")) + self.assertFalse(self.host.called("systemctl start")) + + +@needs_posix_shell +class GivenAServiceUserThatCanWriteItsOwnDirectories(HostCase): + """The service user owns its config and data directories, so a path inside them that root + writes to or reads is one the service user can aim: a symlink named like the file turns a root + `: > file` into truncating whatever the link names. The install marker therefore lives where + only root can write.""" + + STATE_DIR = "var/lib/thewatcher-setup" + + def state_dir(self): + return self.host.root / self.STATE_DIR + + def test_when_an_install_fails_then_the_marker_is_outside_the_directories_given_to_the_service_user(self): + self.host.run("server", "install", FAIL_INIT="1") + marker = self.state_dir() / "server.incomplete" + self.assertTrue(marker.exists()) + for owned in ("etc/thewatcher", "var/lib/thewatcher"): + self.assertNotIn(self.host.root / owned, marker.parents) + for call in self.host.calls_to("chown"): + # The fake host's own temp directory is also called thewatcher-setup-*, so match the real path. + self.assertNotIn(self.STATE_DIR, call, "the marker's directory must stay root's") + + def test_when_the_service_user_plants_a_file_named_like_the_old_marker_then_an_upgrade_ignores_it(self): + self.host.add_user("thewatcher") + self.host.add_config("etc/thewatcher", "TheWatcherServer.conf") + self.host.add_config("etc/thewatcher", ".setup-incomplete", "") + result = self.host.run("server", "upgrade") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse(self.host.called("systemctl enable"), "a file the service user can create started an install") + + def test_when_the_service_user_plants_a_symlink_named_like_the_old_marker_then_the_file_it_names_is_left_alone(self): + for action in ("upgrade", "install"): + with self.subTest(action=action): + victim = self.host.root / "etc/passwd" # stands in for any file only root may change + victim.parent.mkdir(parents=True, exist_ok=True) + victim.write_text("root:x:0:0:root:/root:/bin/sh\n", encoding="utf-8") + self.host.add_user("thewatcher") + self.host.add_config("etc/thewatcher", "TheWatcherServer.conf") + link = self.host.root / "etc/thewatcher/.setup-incomplete" + link.unlink(missing_ok=True) + try: + link.symlink_to(victim) + except (OSError, NotImplementedError): + self.skipTest("this host cannot create symbolic links") + result = self.host.run("server", action) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(victim.read_text(encoding="utf-8"), "root:x:0:0:root:/root:/bin/sh\n") + + @unittest.skipIf(sys.platform == "win32", "Windows has no POSIX file modes") + def test_when_the_marker_directory_is_created_then_no_one_but_root_can_write_to_it_whatever_the_umask(self): + previous = os.umask(0) + self.addCleanup(os.umask, previous) + self.host.run("server", "install", FAIL_INIT="1") + self.assertEqual(stat.S_IMODE(self.state_dir().stat().st_mode) & 0o022, 0) + + def test_when_a_package_with_an_unfinished_install_is_removed_then_its_marker_and_the_empty_directory_go(self): + self.host.run("server", "install", FAIL_INIT="1") + self.assertTrue((self.state_dir() / "server.incomplete").exists(), "the install left no marker to remove") + result = self.host.run("server", "remove") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertFalse((self.state_dir() / "server.incomplete").exists()) + self.assertFalse(self.state_dir().exists()) + + def test_when_one_of_two_packages_is_removed_then_the_other_ones_marker_stays(self): + self.host.run("server", "install", FAIL_INIT="1") + self.host.run("agent", "install", FAIL_INIT="1", THEWATCHER_SERVER="monitor.example") + self.host.run("server", "remove") + self.assertFalse((self.state_dir() / "server.incomplete").exists()) + self.assertTrue((self.state_dir() / "agent.incomplete").exists()) + + +@needs_posix_shell +class GivenTheCommandsTheHelperPrints(HostCase): + """A hint that is pasted into a shell must work there: an unquoted is a redirection.""" + + def test_when_the_agent_has_no_server_address_then_the_command_it_prints_is_safe_to_paste(self): + result = self.host.run("agent", "install") + output = result.stdout + result.stderr + commands = [line for line in output.splitlines() if "service-setup-agent" in line] + self.assertTrue(commands, output) + for line in commands: + self.assertNotIn("<", line) + self.assertNotIn(">", line) + self.assertIn("/usr/lib/thewatcher/service-setup-agent agent install", output) + + +@needs_posix_shell +class GivenAServerPackageOnAHostWithoutARunningInitSystem(HostCase): + """A container, a chroot or an image build: units can be enabled but nothing can start.""" + + running = False + + def test_when_it_is_installed_then_the_service_is_enabled_but_not_started(self): + result = self.host.run("server", "install") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue(self.host.called("systemctl enable thewatcher-server"), self.host.calls()) + self.assertFalse(self.host.called("systemctl start")) + + def test_when_it_is_installed_then_the_config_is_still_created(self): + self.host.run("server", "install") + self.assertTrue((self.host.root / "etc/thewatcher/TheWatcherServer.conf").is_file()) + + +@needs_posix_shell +class GivenAServerPackageThatCannotCreateItsConfig(HostCase): + def test_when_init_config_fails_then_the_install_fails_and_nothing_is_started(self): + result = self.host.run("server", "install", FAIL_INIT="1") + self.assertNotEqual(result.returncode, 0) + self.assertFalse(self.host.called("systemctl start")) + self.assertIn("cannot create the config", result.stderr) + + +@needs_posix_shell +class GivenAServerPackageThatIsRemoved(HostCase): + def setUp(self): + super().setUp() + self.host.add_user("thewatcher") + self.conf = self.host.add_config("etc/thewatcher", "TheWatcherServer.conf") + self.host.mark_active("thewatcher-server") + + def test_when_removed_then_the_service_is_stopped_and_disabled(self): + result = self.host.run("server", "remove") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue(self.host.called("systemctl disable --now thewatcher-server"), self.host.calls()) + + def test_when_removed_then_the_config_and_the_user_are_kept(self): + self.host.run("server", "remove") + self.assertTrue(self.conf.is_file()) + self.assertFalse(self.host.called("userdel")) + + def test_when_the_service_is_already_gone_then_removal_still_succeeds(self): + write_script(self.host.stubs / "systemctl", 'echo "systemctl $*" >> "$CALL_LOG"\nexit 1') + result = self.host.run("server", "remove") + self.assertEqual(result.returncode, 0, result.stderr) + + +@needs_posix_shell +class GivenAnAgentPackageJustInstalled(HostCase): + def test_when_the_server_address_is_in_the_environment_then_the_agent_config_is_created_from_it(self): + result = self.host.run( + "agent", "install", THEWATCHER_SERVER="monitor.example.internal", ENROLLMENT_TOKEN="abc123" + ) + self.assertEqual(result.returncode, 0, result.stderr) + conf = self.host.root / "etc/thewatcher-agent/TheWatcherAgent.conf" + self.assertTrue( + self.host.called( + f"TheWatcherAgent --init-config --config {conf} --server-host monitor.example.internal " + "--enrollment-token abc123" + ), + self.host.calls(), + ) + + def test_when_there_is_no_token_then_none_is_passed(self): + self.host.run("agent", "install", THEWATCHER_SERVER="monitor.example.internal") + init_calls = [c for c in self.host.calls() if "--init-config" in c] + self.assertEqual(len(init_calls), 1) + self.assertNotIn("--enrollment-token", init_calls[0]) + + def test_when_the_server_address_is_known_then_the_agent_runs_as_its_own_user_and_starts(self): + self.host.run("agent", "install", THEWATCHER_SERVER="monitor.example.internal") + self.assertIn("thewatcher-agent", self.host.calls_to("useradd")[0].split()) + self.assertTrue(any("thewatcher-agent:thewatcher-agent" in c for c in self.host.calls_to("chown"))) + self.assertTrue(self.host.called("systemctl enable thewatcher-agent"), self.host.calls()) + self.assertTrue(self.host.called("systemctl start thewatcher-agent"), self.host.calls()) + + def test_when_the_administrator_already_wrote_a_config_then_it_is_kept_and_used(self): + conf = self.host.add_config("etc/thewatcher-agent", "TheWatcherAgent.conf", "THEWATCHER_SERVER=chosen.example\n") + result = self.host.run("agent", "install") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(conf.read_text(encoding="utf-8"), "THEWATCHER_SERVER=chosen.example\n") + self.assertFalse(any("--init-config" in c for c in self.host.calls())) + # The directory holding the administrator's file is handed to the agent user, + # which has to read the config and rewrite it after enrollment. + self.assertTrue(any("-R thewatcher-agent:thewatcher-agent" in c and c.endswith("etc/thewatcher-agent") for c in self.host.calls_to("chown")), self.host.calls_to("chown")) + self.assertTrue(self.host.called("systemctl start thewatcher-agent"), self.host.calls()) + + def test_when_the_server_address_is_unknown_then_the_service_is_enabled_but_not_started(self): + result = self.host.run("agent", "install") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue(self.host.called("systemctl enable thewatcher-agent"), self.host.calls()) + self.assertFalse(self.host.called("systemctl start")) + self.assertFalse(any("--init-config" in c for c in self.host.calls())) + + def test_when_the_server_address_is_unknown_then_the_message_says_how_to_finish_the_setup(self): + result = self.host.run("agent", "install") + output = result.stdout + result.stderr + self.assertIn("THEWATCHER_SERVER=", output) + self.assertIn("TheWatcherAgent.conf", output) + self.assertIn("systemctl start thewatcher-agent", output) + + def test_when_the_setup_is_finished_later_with_the_server_address_then_the_agent_starts(self): + self.host.run("agent", "install") + self.assertFalse(self.host.called("systemctl start")) + + result = self.host.run("agent", "install", THEWATCHER_SERVER="monitor.example.internal", ENROLLMENT_TOKEN="abc123") + + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue((self.host.root / "etc/thewatcher-agent/TheWatcherAgent.conf").is_file()) + self.assertTrue(self.host.called("systemctl start thewatcher-agent"), self.host.calls()) + self.assertEqual(len(self.host.calls_to("useradd")), 1, "the user is created only once") + + def test_when_the_agent_is_installed_then_no_firewall_rule_is_added(self): + self.host.run("agent", "install", THEWATCHER_SERVER="monitor.example.internal", UFW_STATE="active", FIREWALLD_STATE="running") + self.assertFalse(self.host.called("ufw allow")) + self.assertFalse(self.host.called("firewall-cmd --permanent")) + + def test_when_the_agent_binary_rejects_the_server_address_then_the_install_fails_and_nothing_starts(self): + result = self.host.run("agent", "install", THEWATCHER_SERVER="bad host", FAIL_INIT="1") + self.assertNotEqual(result.returncode, 0) + self.assertFalse(self.host.called("systemctl start")) + + +@needs_posix_shell +class GivenAnAgentPackageUpgraded(HostCase): + def setUp(self): + super().setUp() + self.host.add_user("thewatcher-agent") + self.conf = self.host.add_config("etc/thewatcher-agent", "TheWatcherAgent.conf", "THEWATCHER_SERVER=chosen.example\n") + + def test_when_the_agent_is_running_then_it_is_restarted(self): + self.host.mark_active("thewatcher-agent") + self.host.run("agent", "upgrade", THEWATCHER_SERVER="ignored.example") + self.assertTrue(self.host.called("systemctl restart thewatcher-agent"), self.host.calls()) + + def test_when_upgraded_then_the_environment_does_not_replace_an_existing_config(self): + self.host.run("agent", "upgrade", THEWATCHER_SERVER="ignored.example") + self.assertEqual(self.conf.read_text(encoding="utf-8"), "THEWATCHER_SERVER=chosen.example\n") + + +@needs_posix_shell +class GivenAServerPackageOnAnOpenRCHost(HostCase): + flavour = "openrc" + + def test_when_it_is_installed_then_the_user_is_created_with_the_busybox_tools(self): + result = self.host.run("server", "install") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(self.host.calls_to("useradd"), []) + self.assertTrue(self.host.called("addgroup -S thewatcher"), self.host.calls()) + adduser = self.host.calls_to("adduser") + self.assertEqual(len(adduser), 1) + self.assertIn("-S", adduser[0].split()) + self.assertIn("thewatcher", adduser[0].split()) + + def test_when_it_is_installed_then_the_service_is_added_to_the_default_runlevel_and_started(self): + self.host.run("server", "install") + self.assertTrue(self.host.called("rc-update add thewatcher-server default"), self.host.calls()) + self.assertTrue(self.host.called("rc-service thewatcher-server start"), self.host.calls()) + self.assertEqual(self.host.calls_to("systemctl"), []) + + def test_when_upgraded_and_running_then_it_is_restarted_through_openrc(self): + self.host.add_user("thewatcher") + self.host.add_config("etc/thewatcher", "TheWatcherServer.conf") + self.host.mark_active("thewatcher-server") + self.host.run("server", "upgrade") + self.assertTrue(self.host.called("rc-service thewatcher-server restart"), self.host.calls()) + + def test_when_removed_then_it_is_stopped_and_taken_out_of_the_runlevel(self): + self.host.add_user("thewatcher") + self.host.run("server", "remove") + self.assertTrue(self.host.called("rc-service thewatcher-server stop"), self.host.calls()) + self.assertTrue(self.host.called("rc-update del thewatcher-server default"), self.host.calls()) + + +@needs_posix_shell +class GivenAnOpenRCHostThatIsNotRunning(HostCase): + flavour = "openrc" + running = False + + def test_when_it_is_installed_then_the_service_is_added_but_not_started(self): + result = self.host.run("server", "install") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertTrue(self.host.called("rc-update add thewatcher-server default"), self.host.calls()) + self.assertFalse(self.host.called("rc-service thewatcher-server start")) + + +@needs_posix_shell +class GivenAPackageWithoutAServiceDefinition(HostCase): + flavour = "none" + running = False + + def test_when_it_is_installed_then_it_warns_and_still_creates_the_config_without_failing(self): + result = self.host.run("server", "install") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("warning", (result.stdout + result.stderr).lower()) + self.assertTrue((self.host.root / "etc/thewatcher/TheWatcherServer.conf").is_file()) + + +@needs_posix_shell +class GivenBadArguments(HostCase): + def test_when_the_component_is_unknown_then_it_is_refused_before_anything_changes(self): + result = self.host.run("proxy", "install") + self.assertEqual(result.returncode, 2) + self.assertEqual(self.host.calls(), []) + + def test_when_the_action_is_unknown_then_it_is_refused_before_anything_changes(self): + result = self.host.run("server", "purge") + self.assertEqual(result.returncode, 2) + self.assertEqual(self.host.calls(), []) + + def test_when_an_argument_is_missing_then_the_usage_is_printed(self): + environment = dict(os.environ, THEWATCHER_ROOT=str(self.host.root)) + result = subprocess.run(["sh", str(HELPER), "server"], capture_output=True, text=True, env=environment, timeout=60, check=False) + self.assertEqual(result.returncode, 2) + self.assertIn("usage", result.stderr.lower()) + + +@needs_posix_shell +class GivenTheHelperScript(unittest.TestCase): + def test_when_it_is_parsed_by_a_strict_posix_shell_then_it_has_no_syntax_errors(self): + for shell in ("dash", "sh"): + if shutil.which(shell): + result = subprocess.run([shell, "-n", str(HELPER)], capture_output=True, text=True, check=False) + self.assertEqual(result.returncode, 0, f"{shell} -n: {result.stderr}") + + def test_when_the_config_directory_is_prepared_then_root_takes_it_before_its_mode_is_set(self): + """Mode first would let the service user, still the owner, make the directory writable + (0777) in the gap, and the chown would keep that mode.""" + text = HELPER.read_text(encoding="utf-8") + prepare = text[text.index("prepare_files() {"):] + self.assertLess(prepare.index('chown root:root "${conf_dir}"'), prepare.index('chmod 0700 "${conf_dir}"')) + + def test_when_it_is_read_then_it_uses_no_bashisms(self): + text = HELPER.read_text(encoding="utf-8") + for bashism in ("[[", "function ", "local ", "source ", "<<<", "$'", "${!", "=~"): + self.assertNotIn(bashism, text, f"bash-only syntax {bashism!r} breaks Alpine's busybox sh") + + def test_when_it_is_read_then_it_keeps_unix_line_endings(self): + self.assertNotIn(b"\r", HELPER.read_bytes()) + + +SYSTEMD_DIR = REPO_ROOT / "packaging" / "linux" / "systemd" +OPENRC_DIR = REPO_ROOT / "packaging" / "linux" / "openrc" + + +def helper_setting(component, name): + """A per-component variable from the helper's `case` block, e.g. user=thewatcher.""" + text = HELPER.read_text(encoding="utf-8") + block = text.split(f" {component})", 1)[1].split(";;", 1)[0] + for line in block.splitlines(): + line = line.strip() + if line.startswith(name + "="): + return line.split("=", 1)[1] + raise AssertionError(f"{name} not set for {component} in {HELPER.name}") + + +def unit_settings(path): + """The KEY=VALUE lines of a systemd unit as a dict (the last one wins).""" + settings = {} + for line in path.read_text(encoding="utf-8").splitlines(): + if "=" in line and not line.lstrip().startswith(("#", "[")): + key, _, value = line.partition("=") + settings[key.strip()] = value.strip() + return settings + + +class GivenTheSystemdUnits(unittest.TestCase): + def unit(self, component): + return unit_settings(SYSTEMD_DIR / f"thewatcher-{component}.service") + + def test_when_a_unit_is_read_then_it_runs_as_the_user_the_helper_creates(self): + for component in ("server", "agent"): + unit = self.unit(component) + self.assertEqual(unit["User"], helper_setting(component, "user")) + self.assertEqual(unit["Group"], helper_setting(component, "user")) + + def test_when_a_unit_is_read_then_it_never_runs_as_root(self): + for component in ("server", "agent"): + self.assertNotIn(self.unit(component)["User"], ("root", "0")) + + def test_when_a_unit_is_read_then_it_starts_the_installed_binary_with_the_config_the_helper_creates(self): + for component in ("server", "agent"): + expected = "/usr/bin/{} --config {}/{}".format( + helper_setting(component, "binary_name"), + helper_setting(component, "config_dir"), + helper_setting(component, "config_name"), + ) + self.assertEqual(self.unit(component)["ExecStart"], expected) + + def test_when_a_unit_is_read_then_it_may_write_only_the_directories_the_component_owns(self): + server = self.unit("server")["ReadWritePaths"].split() + self.assertEqual(sorted(server), sorted([helper_setting("server", "config_dir"), helper_setting("server", "data_dir")])) + self.assertEqual(self.unit("agent")["ReadWritePaths"].split(), [helper_setting("agent", "config_dir")]) + + def test_when_a_unit_is_read_then_it_is_hardened_and_restarts_after_a_failure(self): + for component in ("server", "agent"): + unit = self.unit(component) + self.assertEqual(unit["NoNewPrivileges"], "true") + self.assertEqual(unit["ProtectSystem"], "strict") + self.assertEqual(unit["PrivateTmp"], "true") + self.assertEqual(unit["Restart"], "on-failure") + self.assertEqual(unit["WantedBy"], "multi-user.target") + + def test_when_the_agent_has_no_config_yet_then_the_unit_is_skipped_instead_of_failing_every_boot(self): + agent = self.unit("agent") + self.assertEqual(agent["ConditionPathExists"], "{}/{}".format(helper_setting("agent", "config_dir"), helper_setting("agent", "config_name"))) + + def test_when_the_server_unit_is_read_then_it_has_no_condition_because_it_creates_its_own_config(self): + self.assertNotIn("ConditionPathExists", self.unit("server")) + + +class GivenTheOpenRCScripts(unittest.TestCase): + def script(self, component): + return (OPENRC_DIR / f"thewatcher-{component}").read_text(encoding="utf-8") + + def setting(self, component, name): + for line in self.script(component).splitlines(): + if line.startswith(name + "="): + return line.split("=", 1)[1].strip().strip('"') + raise AssertionError(f"{name} missing from the {component} OpenRC script") + + def function(self, component, name): + """The body of a shell function defined at the left margin: 'name() {' to the closing '}'.""" + lines = self.script(component).splitlines() + start = next((i for i, line in enumerate(lines) if line.startswith(name + "()")), None) + self.assertIsNotNone(start, f"{name}() missing from the {component} OpenRC script") + end = next(i for i in range(start + 1, len(lines)) if lines[i] == "}") + return "\n".join(lines[start:end + 1]) + + def test_when_a_script_is_read_then_it_is_an_openrc_run_script(self): + for component in ("server", "agent"): + self.assertTrue(self.script(component).startswith("#!/sbin/openrc-run" + chr(10))) + + def test_when_a_script_is_read_then_it_runs_as_the_user_the_helper_creates(self): + for component in ("server", "agent"): + user = helper_setting(component, "user") + self.assertEqual(self.setting(component, "command_user"), f"{user}:{user}") + + def test_when_a_script_is_read_then_it_starts_the_installed_binary_with_the_helpers_config(self): + for component in ("server", "agent"): + self.assertEqual(self.setting(component, "command"), "/usr/bin/" + helper_setting(component, "binary_name")) + self.assertEqual( + self.setting(component, "command_args"), + "--config {}/{}".format(helper_setting(component, "config_dir"), helper_setting(component, "config_name")), + ) + + def test_when_the_server_script_is_read_then_openrc_supervises_and_restarts_the_process(self): + self.assertEqual(self.setting("server", "supervisor"), "supervise-daemon") + + def test_when_the_agent_script_is_read_then_it_runs_unsupervised_so_a_disconnect_command_ends_it(self): + """supervise-daemon restarts a process however it exits, which would undo the + server's DISCONNECT command (issue #85). systemd's Restart=on-failure has no + OpenRC equivalent, so the agent is not restarted at all, as on FreeBSD.""" + script = self.script("agent") + self.assertFalse(any(line.startswith(("supervisor=", "respawn_")) for line in script.splitlines())) + self.assertEqual(self.setting("agent", "command_background"), "true") + self.assertEqual(self.setting("agent", "pidfile"), "/run/${RC_SVCNAME}.pid") + + def test_when_the_agent_has_no_config_yet_then_openrc_refuses_to_start_it(self): + body = self.function("agent", "start_pre") + config = "{}/{}".format(helper_setting("agent", "config_dir"), helper_setting("agent", "config_name")) + self.assertIn(config, body) + self.assertIn("return 1", body) + + def test_when_the_agent_script_is_read_then_it_has_no_required_files(self): + """openrc-run checks required_files for every command, stop and status included + (0.62.6, sh/openrc-run.sh.in). A missing config would then make `rc-service stop` fail + before it signals anything, and package removal ignores that failure and leaves the + agent running. Only start has to be refused.""" + for component in ("server", "agent"): + self.assertFalse( + any(line.startswith("required_files") for line in self.script(component).splitlines()), + component, + ) + + @needs_posix_shell + def test_when_a_script_is_parsed_by_a_posix_shell_then_it_has_no_syntax_errors(self): + for component in ("server", "agent"): + result = subprocess.run(["sh", "-n", str(OPENRC_DIR / f"thewatcher-{component}")], capture_output=True, text=True, check=False) + self.assertEqual(result.returncode, 0, result.stderr) + + def test_when_a_script_is_read_then_it_keeps_unix_line_endings(self): + for component in ("server", "agent"): + self.assertNotIn(bytes([13]), (OPENRC_DIR / f"thewatcher-{component}").read_bytes()) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/release/smoke-service.sh b/scripts/release/smoke-service.sh new file mode 100755 index 0000000..c2b102a --- /dev/null +++ b/scripts/release/smoke-service.sh @@ -0,0 +1,203 @@ +#!/bin/sh +# Prove an installed Linux package set its service up. +# +# Called by .github/workflows/release.yml right after smoke-install.sh, in the +# same clean container of the package's distro: +# docker run ... --env THEWATCHER_SERVER=localhost --env ENROLLMENT_TOKEN=smoke-token \ +# sh -c 'sh /release/smoke-install.sh && sh /release/smoke-service.sh' +# +# Installing is meant to leave a configured, enabled service behind. A container +# has no running init system, so the install does not start the services; this +# checks what it left, then runs each binary as its service user to prove that +# the generated config and its permissions work. +# +# Environment (also given to the install, for the package managers that pass it +# on to the install scripts): +# THEWATCHER_SERVER the server address the agent package is set up with +# ENROLLMENT_TOKEN the enrollment token the agent package is set up with + +set -eu + +: "${THEWATCHER_SERVER:?THEWATCHER_SERVER is required}" +: "${ENROLLMENT_TOKEN:?ENROLLMENT_TOKEN is required}" +# One helper per package, so that both can be installed together. +server_helper=/usr/lib/thewatcher/service-setup-server +agent_helper=/usr/lib/thewatcher/service-setup-agent +server_conf=/etc/thewatcher/TheWatcherServer.conf +agent_conf=/etc/thewatcher-agent/TheWatcherAgent.conf + +fail() { + printf 'smoke-service: %s\n' "$*" >&2 + exit 1 +} + +for helper in "${server_helper}" "${agent_helper}"; do + [ -x "${helper}" ] || fail "${helper} is missing from the packages" +done + +for user in thewatcher thewatcher-agent; do + id "${user}" >/dev/null 2>&1 || fail "the service user ${user} was not created" +done + +# An install leaves a marker while it is in progress and removes it when it finishes. +# One left behind would make every later upgrade run as a first install. It lives in a +# directory only root can write, not in the config directory the service user owns. +for marker in /var/lib/thewatcher-setup/server.incomplete /var/lib/thewatcher-setup/agent.incomplete; do + [ ! -e "${marker}" ] || fail "the install did not finish: ${marker} is still there" +done + +# Not every package manager passes the environment on to the install scripts. +# Running the helper again finishes the setup, which is also what the message +# printed for an agent without a server address tells an administrator to do. +if [ ! -f "${agent_conf}" ]; then + printf 'smoke-service: the install did not see THEWATCHER_SERVER; finishing the agent setup with the helper\n' + "${agent_helper}" agent install +fi + +# Owner and octal mode; GNU and busybox stat both take -c. +expect_owner_and_mode() { + found="$(stat -c '%U %a' "$1")" + [ "${found}" = "$2" ] || fail "$1 is '${found}', expected '$2'" +} +expect_owner_and_mode /etc/thewatcher "thewatcher 700" +expect_owner_and_mode "${server_conf}" "thewatcher 600" +expect_owner_and_mode /var/lib/thewatcher "thewatcher 750" +expect_owner_and_mode /etc/thewatcher-agent "thewatcher-agent 700" +expect_owner_and_mode "${agent_conf}" "thewatcher-agent 600" + +grep -q '^API_HOST=127.0.0.1$' "${server_conf}" || fail "the server API is not limited to loopback" +grep -Eq '^ENROLLMENT_TOKEN=[0-9a-f]{48}$' "${server_conf}" || fail "the server config has no generated enrollment token" +grep -Eq '^SERVER_PUBLIC_KEY=.{40}$' "${server_conf}" || fail "the server config has no CURVE public key" +grep -Eq '^SERVER_SECRET_KEY=.{40}$' "${server_conf}" || fail "the server config has no CURVE secret key" +grep -q '^DB_PATH=/var/lib/thewatcher/thewatcher.db$' "${server_conf}" || fail "the database is not in /var/lib/thewatcher" +# -Fx: the whole line, compared literally. A host such as [2001:db8::1] or a token such as +# abc[123] is not a regular expression, and a dotted name must not match another value. +grep -Fqx "THEWATCHER_SERVER=${THEWATCHER_SERVER}" "${agent_conf}" || fail "the agent config has no server address" +grep -Fqx "ENROLLMENT_TOKEN=${ENROLLMENT_TOKEN}" "${agent_conf}" || fail "the agent config has no enrollment token" + +# The package ships a systemd unit or an OpenRC script, depending on its format. +if [ -f /usr/lib/systemd/system/thewatcher-server.service ]; then + # Without systemctl (most containers) there is nothing to enable, and the + # helper warned about it. With it, enabling works without a running systemd. + if command -v systemctl >/dev/null 2>&1; then + for service in thewatcher-server thewatcher-agent; do + systemctl is-enabled --quiet "${service}" || + [ -L "/etc/systemd/system/multi-user.target.wants/${service}.service" ] || + fail "${service} is not enabled" + done + fi +elif [ -f /etc/init.d/thewatcher-server ]; then + for service in thewatcher-server thewatcher-agent; do + [ -e "/etc/runlevels/default/${service}" ] || fail "${service} is not in the default OpenRC runlevel" + done +else + fail "the server package has no service definition" +fi + +# Run a binary as its service user in the background, for at most `seconds`, and +# keep what it printed. timeout stops it then (exit 124), which is the normal end. +# The pid of the background job is left in $!. +start_as() { + service_user=$1 + seconds=$2 + output=$3 + shift 3 + if command -v runuser >/dev/null 2>&1; then + timeout "${seconds}" runuser -u "${service_user}" -- "$@" >"${output}" 2>&1 & + elif command -v su >/dev/null 2>&1; then + # busybox (Alpine): no runuser; su -s overrides the nologin shell. + timeout "${seconds}" su -s /bin/sh "${service_user}" -c "exec $*" >"${output}" 2>&1 & + elif command -v chroot >/dev/null 2>&1; then + # A minimal Fedora or Rocky image has neither runuser nor su (the first CI run + # failed on exactly that). GNU coreutils' chroot can switch user: chroot to / changes + # nothing but the account the command runs as. + timeout "${seconds}" chroot "--userspec=${service_user}:${service_user}" / "$@" >"${output}" 2>&1 & + else + fail "no way to run a command as ${service_user}: none of runuser, su or chroot is installed" + fi +} + +# True when something listens on a TCP port, given the port and the tables to look +# in (/proc/net/tcp and /proc/net/tcp6). Each line is one socket: the local address +# as HEXIP:HEXPORT and, after the remote address, the state, where 0A is LISTEN. It +# needs no extra tool: ss, nc and curl are missing from minimal images. +# +# The server is waited for this way, and not by watching its output for "Running", +# because the logger flushes only NOTICE and above at once (common/SingleLog.hpp): +# an INFO line stays in a buffer while stdout is a file, so the wait would fail on a +# healthy server. Its output is complete once it has exited, which is when it is read. +is_listening() { + hex_port="$(printf '%04X' "$1")" + shift + for table in "$@"; do + grep -Eq "^ *[0-9]+: [0-9A-F]+:${hex_port} [0-9A-F]+:[0-9A-F]+ 0A " "${table}" 2>/dev/null && return 0 + done + return 1 +} + +# Waits up to `seconds` for a port to be listening. +wait_for_listen() { + i=0 + while [ "${i}" -lt "$2" ]; do + is_listening "$1" /proc/net/tcp /proc/net/tcp6 && return 0 + sleep 1 + i=$((i + 1)) + done + return 1 +} + +# The server and the agent have to talk to each other for this to mean anything: +# an agent that was stopped while its enrollment was still being set up can print +# "Running" without ever having reached a server. So the server runs as thewatcher +# with the generated config, the agent runs as thewatcher-agent with its own, and +# what is checked is that the server received the agent's enrollment request (which +# it only logs after the enrollment token matches) and that the agent saw it pending. +# 50 seconds: up to 20 for the port to open, about 10 to prepare the agent, and the +# agent's own 20-second budget, so a slow start does not stop the server before the agent +# reaches it. +start_as thewatcher 50 /tmp/smoke-server.out /usr/bin/TheWatcherServer --config "${server_conf}" +server_job=$! +if ! wait_for_listen 5556 20; then + # Stop it first: its output is only complete once it has exited. + kill "${server_job}" 2>/dev/null || true + wait "${server_job}" || true + cat /tmp/smoke-server.out >&2 + cat /etc/thewatcher/TheWatcherServer.log >&2 2>/dev/null || true + fail "the server did not listen on the enrollment port as thewatcher with the generated config" +fi + +# The server made up its own token. Give the agent that one. cat > keeps the +# file's owner and mode, which sed -i or mv would not. +server_token="$(sed -n 's/^ENROLLMENT_TOKEN=//p' "${server_conf}")" +agent_config_copy="$(mktemp)" +sed "s/^ENROLLMENT_TOKEN=.*/ENROLLMENT_TOKEN=${server_token}/" "${agent_conf}" >"${agent_config_copy}" +cat "${agent_config_copy}" >"${agent_conf}" +rm -f "${agent_config_copy}" + +# 20 seconds, not 10: starting the agent and the enrollment exchange both fit in one +# window, and a slow runner must not kill it before it prints "Enrollment pending". +start_as thewatcher-agent 20 /tmp/smoke-agent.out /usr/bin/TheWatcherAgent --config "${agent_conf}" +agent_job=$! +wait "${agent_job}" || true +kill "${server_job}" 2>/dev/null || true +wait "${server_job}" || true + +if ! grep -q 'Enrollment request agent_id=' /tmp/smoke-server.out; then + cat /tmp/smoke-server.out /tmp/smoke-agent.out >&2 + fail "the server never received an enrollment request from the agent" +fi +if grep -q 'bad enrollment token' /tmp/smoke-server.out; then + fail "the server rejected the agent's enrollment token" +fi +if ! grep -q 'Enrollment pending' /tmp/smoke-agent.out; then + cat /tmp/smoke-agent.out >&2 + fail "the agent was not told its enrollment is pending approval" +fi + +# An upgrade must leave the config alone: it holds the CURVE secret key, and a +# new one would force every agent to enroll again. +before="$(cksum <"${server_conf}")" +"${server_helper}" server upgrade +[ "$(cksum <"${server_conf}")" = "${before}" ] || fail "an upgrade changed the server config" + +printf 'smoke-service: ok\n' diff --git a/server/config.cpp b/server/config.cpp index 006c4f3..2413b16 100644 --- a/server/config.cpp +++ b/server/config.cpp @@ -287,6 +287,23 @@ namespace if (cfg.db_type == "sqlite") cfg.db_path = resolve_sqlite_db_path(config_path, cfg.db_path); } + + // A default config for config_path with a freshly generated CURVE keypair. + // A config without a keypair would run the agent data port unencrypted, so + // every config this program creates goes through here. + ServerConfig new_config_with_keys(const fs::path& config_path) + { + ServerConfig cfg; + thewatcher::crypto::init(); + const auto kp = thewatcher::crypto::generate_curve_keypair(); + cfg.server_public_key = kp.public_key_z85; + cfg.server_secret_key = kp.secret_key_z85; + resolve_runtime_paths(cfg, config_path); + return cfg; + } + + // 24 random bytes (192 bits) as 48 hex characters. + constexpr std::size_t installed_enrollment_token_bytes = 24; } // namespace fs::path ServerConfig::existing_path_or_legacy(const fs::path& preferred, const fs::path& legacy) @@ -364,18 +381,64 @@ ServerConfig ServerConfig::load_or_create(const fs::path& path) } LOG_INFO("Server config does not exist; creating a new config with generated CURVE keys"); - ServerConfig cfg; - thewatcher::crypto::init(); - auto kp = thewatcher::crypto::generate_curve_keypair(); - cfg.server_public_key = kp.public_key_z85; - cfg.server_secret_key = kp.secret_key_z85; - resolve_runtime_paths(cfg, path); + auto cfg = new_config_with_keys(path); // save() creates (and, on POSIX, owner-restricts) any missing parent directory. cfg.save(path); return cfg; } +// Package and installer entry point (--init-config). Package scripts run it on +// every install and upgrade, so an existing file is never read or written. +// The existence check and the write are not one atomic step: package managers +// serialise their scripts, and save() renames a complete file into place, so a +// reader never sees a partial config. +bool ServerConfig::create_installed_default(const fs::path& path, const std::string& database_path) +{ + LOG_FUNCTION_TRACE + // Checked first, so a bad invocation is reported even when a config exists. + // A line break would start a new KEY=VALUE line; a relative path would + // depend on the directory the installer happened to run from. + if (!database_path.empty()) + { + if (database_path.find_first_of("\r\n") != std::string::npos) + throw std::invalid_argument("The database path must not contain a line break"); + // The loader trims every value, so the service would open a different path than the + // one the installer was given. Refusing is narrower than changing how values are read. + if (std::isspace(static_cast(database_path.front())) || + std::isspace(static_cast(database_path.back()))) + throw std::invalid_argument("The database path must not start or end with whitespace"); + if (!fs::path(database_path).is_absolute()) + throw std::invalid_argument("The database path must be absolute: " + database_path); + } + + std::error_code ec; + const auto existing = fs::status(path, ec); + // "Not found" is the answer we want; any other error means we cannot tell + // whether a config is there, and overwriting one would lose the CURVE keys. + if (ec && existing.type() != fs::file_type::not_found) + throw std::runtime_error("Cannot inspect " + path.string() + ": " + ec.message()); + if (fs::exists(existing)) + { + LOGF_INFO("Server config %s already exists; leaving it unchanged", path.string().c_str()); + return false; + } + + LOGF_INFO("Creating server config %s for a new installation", path.string().c_str()); + auto cfg = new_config_with_keys(path); + // Safe defaults for a fresh install: the API is plain HTTP, so keep it off + // the network until an administrator puts a TLS reverse proxy in front, and + // require a token so arbitrary hosts cannot create pending enrollments. + cfg.api_host = "127.0.0.1"; + cfg.enrollment_token = thewatcher::crypto::generate_hex_token(installed_enrollment_token_bytes); + // The config directory is for config and keys; a package puts the database + // in the data directory (backups, ownership and disk space differ). + if (!database_path.empty()) + cfg.db_path = fs::path(database_path).lexically_normal().string(); + cfg.save(path); + return true; +} + // Writes the config atomically: an owner-only temp file is renamed over the // target. Creates missing parent directories and limits those it created to the // owner on POSIX. Throws std::runtime_error on an empty filename or any diff --git a/server/config.hpp b/server/config.hpp index b77b05b..6e2675a 100644 --- a/server/config.hpp +++ b/server/config.hpp @@ -64,6 +64,16 @@ struct ServerConfig // Unknown keys only warn (see unknown_keys). SEC-15: warns when group or // others can read an existing file. static ServerConfig load_or_create(const std::filesystem::path& path); + // For package and installer scripts (--init-config): creates the config at + // path when it does not exist and returns true. It has the generated CURVE + // keypair, API_HOST=127.0.0.1 (the HTTP API is plain HTTP) and a random + // ENROLLMENT_TOKEN. An existing file is neither read nor written and the + // function returns false, so it is safe on every upgrade. A non-empty + // database_path becomes DB_PATH instead of the default beside the config; it + // must be absolute and on one line (std::invalid_argument otherwise, and + // nothing is written). Throws std::runtime_error when the path cannot be + // inspected or written. + static bool create_installed_default(const std::filesystem::path& path, const std::string& database_path = {}); // Writes the config to path atomically (SEC-15): an owner-only temp file is // flushed, then renamed over the target, so a crash cannot truncate an // existing config. On POSIX, directories created here are limited to the diff --git a/server/main.cpp b/server/main.cpp index b6965d3..36539a6 100644 --- a/server/main.cpp +++ b/server/main.cpp @@ -35,6 +35,11 @@ static void print_usage(const char* prog) << " --log-level Log file level: trace, debug, info, notice, warning, error,\n" << " critical or off (overrides LOG_LEVEL in the config)\n" << " --genkey Print a new CURVE keypair and exit\n" + << " --init-config Create the config if it does not exist, then exit. The new\n" + << " config has a CURVE keypair, API_HOST=127.0.0.1 and a random\n" + << " ENROLLMENT_TOKEN. An existing config is never changed.\n" + << " --db-path With --init-config: absolute path of the SQLite database\n" + << " (default: thewatcher.db beside the config)\n" << " --service Run under Windows Service Control Manager\n" << " --service-name Service name (default: TheWatcherServer)\n" << " --install-service Install the Windows service and exit\n" @@ -55,7 +60,9 @@ int main(int argc, char* argv[]) std::string config_path; std::string cli_log_level; std::string service_name = "TheWatcherServer"; + std::string init_db_path; bool do_genkey = false; + bool init_config = false; bool service_mode = false; bool install_service = false; bool uninstall_service = false; @@ -82,6 +89,14 @@ int main(int argc, char* argv[]) { do_genkey = true; } + else if (arg == "--init-config") + { + init_config = true; + } + else if (arg == "--db-path" && i + 1 < argc) + { + init_db_path = argv[++i]; + } else if (arg == "--service") { service_mode = true; @@ -132,6 +147,13 @@ int main(int argc, char* argv[]) return thewatcher::service::uninstall_windows_service(service_name); } + // Ignoring it would leave an administrator believing the database was moved. + if (!init_config && !init_db_path.empty()) + { + std::cerr << "--db-path can only be used with --init-config\n"; + return 1; + } + fs::path cfg_path; try { @@ -156,6 +178,25 @@ int main(int argc, char* argv[]) std::cerr << e.what() << "\n"; return 1; } + // Package scripts and installers run this on every install and upgrade. It + // comes before the log file is opened so that a script running as root + // leaves nothing behind that the service user cannot write. + if (init_config) + { + try + { + const bool created = ServerConfig::create_installed_default(cfg_path, init_db_path); + std::cout << (created ? "Created " : "Config already exists, left unchanged: ") << cfg_path.string() + << "\n"; + return 0; + } + catch (const std::exception& e) + { + std::cerr << "Cannot create the config: " << e.what() << "\n"; + return 1; + } + } + auto log_path = log_path_for_config(cfg_path, "TheWatcherServer.log"); auto& logger = thewatcher::logging::SingleLog::GetInstance(); logger.SetConsoleLogLevel(thewatcher::logging::LogLevel::L_INFO); diff --git a/server_tests/config_test.cpp b/server_tests/config_test.cpp index b9e204f..a466315 100644 --- a/server_tests/config_test.cpp +++ b/server_tests/config_test.cpp @@ -2,11 +2,13 @@ #include "test_support/temp_dir.hpp" #include +#include #include #include #include #include +#include #include using namespace thewatcher::server; @@ -28,6 +30,16 @@ std::string read_file(const std::filesystem::path& path) ss << f.rdbuf(); return ss.str(); } + +// The exact bytes. On Windows a text-mode read turns CRLF into LF, so a rewrite that only changed +// the line endings would still compare equal to the LF file a test wrote. +std::string read_bytes(const std::filesystem::path& path) +{ + std::ifstream f(path, std::ios::binary); + std::stringstream ss; + ss << f.rdbuf(); + return ss.str(); +} } // namespace SCENARIO("Server config default path uses TheWatcherServer.conf") @@ -667,3 +679,256 @@ SCENARIO("A preferred config path wins over the legacy one, which is used only w } } } + +SCENARIO("A package-created server config is loopback only and requires an enrollment token") +{ + GIVEN("a config path in a clean directory") + { + auto dir = unique_temp_dir("server-config-installed-default"); + auto path = dir / "TheWatcherServer.conf"; + + WHEN("the installer creates the config") + { + const bool created = ServerConfig::create_installed_default(path); + + THEN("the file was created") + { + REQUIRE(created); + REQUIRE(std::filesystem::exists(path)); + } + + AND_THEN("the plain HTTP API listens on loopback only") + { + auto cfg = ServerConfig::load_or_create(path); + REQUIRE(cfg.api_host == "127.0.0.1"); + } + + AND_THEN("a random 48 character hexadecimal enrollment token is set") + { + auto cfg = ServerConfig::load_or_create(path); + REQUIRE(cfg.enrollment_token.size() == 48); + REQUIRE(cfg.enrollment_token.find_first_not_of("0123456789abcdef") == std::string::npos); + } + + AND_THEN("a matching CURVE keypair is present, so the data port is encrypted") + { + // load_or_create throws when the keypair is half set or mismatched. + auto cfg = ServerConfig::load_or_create(path); + REQUIRE(cfg.server_public_key.size() == 40); + REQUIRE(cfg.server_secret_key.size() == 40); + } + +#ifndef _WIN32 + AND_THEN("only the owner can read the file") + { + const auto perms = std::filesystem::status(path).permissions(); + REQUIRE((perms & (std::filesystem::perms::group_all | std::filesystem::perms::others_all)) == + std::filesystem::perms::none); + } +#endif + } + } +} + +SCENARIO("A package upgrade never changes an existing server config") +{ + GIVEN("a config an administrator has edited") + { + auto dir = unique_temp_dir("server-config-installed-existing"); + auto path = dir / "TheWatcherServer.conf"; + const std::string edited = "API_HOST=10.1.2.3\nAPI_PORT=9090\n"; + { + std::ofstream f(path, std::ios::binary); + f << edited; + } + + WHEN("the installer asks for the config to be created") + { + const bool created = ServerConfig::create_installed_default(path); + + THEN("nothing is created") + { + REQUIRE_FALSE(created); + } + + AND_THEN("the file is byte for byte what the administrator left") + { + REQUIRE(read_bytes(path) == edited); + } + } + } +} + +SCENARIO("A package refuses to guess when it cannot tell whether a server config exists") +{ + GIVEN("a config path that cannot be inspected, because it is a symbolic link to itself") + { + auto dir = unique_temp_dir("server-config-installed-uninspectable"); + auto path = dir / "TheWatcherServer.conf"; + // Following the link never ends, so stat fails with a loop error rather than "no such + // file". That is the case where creating a config could overwrite one that is there, + // and the config holds the CURVE key pair every agent has pinned. + std::error_code link_error; + std::filesystem::create_symlink(path.filename(), path, link_error); + if (link_error) + SKIP("this host cannot create symbolic links: " << link_error.message()); + + WHEN("the installer asks for the config to be created") + { + THEN("it is refused, and the message says the path could not be inspected") + { + REQUIRE_THROWS_WITH(ServerConfig::create_installed_default(path), + Catch::Matchers::ContainsSubstring("Cannot inspect")); + } + + AND_THEN("the link is still there: nothing was created over it") + { + REQUIRE_THROWS(ServerConfig::create_installed_default(path)); + REQUIRE(std::filesystem::is_symlink(path)); + } + } + } +} + +// Kept apart from the scenario above, whose symbolic link may be impossible to make (Windows +// without the privilege): a skip there must not hide this one. +SCENARIO("A config path with no file is an ordinary first server install, not a failure to inspect") +{ + GIVEN("a config path whose file simply does not exist yet") + { + auto path = unique_temp_dir("server-config-installed-not-yet-there") / "TheWatcherServer.conf"; + + WHEN("the installer asks for the config to be created") + { + THEN("the config is created") + { + REQUIRE(ServerConfig::create_installed_default(path)); + REQUIRE(std::filesystem::exists(path)); + } + } + } +} + +SCENARIO("Every package-created server config gets its own enrollment token") +{ + GIVEN("two clean config directories") + { + auto first_path = unique_temp_dir("server-config-installed-token-a") / "TheWatcherServer.conf"; + auto second_path = unique_temp_dir("server-config-installed-token-b") / "TheWatcherServer.conf"; + + WHEN("the installer creates both") + { + ServerConfig::create_installed_default(first_path); + ServerConfig::create_installed_default(second_path); + + THEN("the tokens and the key pairs differ") + { + auto first = ServerConfig::load_or_create(first_path); + auto second = ServerConfig::load_or_create(second_path); + REQUIRE(first.enrollment_token != second.enrollment_token); + REQUIRE(first.server_secret_key != second.server_secret_key); + } + } + } +} + +SCENARIO("A package may keep the database outside the config directory") +{ + GIVEN("a clean config directory and an absolute database path elsewhere") + { + auto dir = unique_temp_dir("server-config-installed-db"); + auto path = dir / "TheWatcherServer.conf"; + const auto database = dir / "data" / "thewatcher.db"; + + WHEN("the installer creates the config with that database path") + { + ServerConfig::create_installed_default(path, database.string()); + + THEN("the server is configured to use it, not a file beside the config") + { + auto cfg = ServerConfig::load_or_create(path); + REQUIRE(std::filesystem::path(cfg.db_path) == database.lexically_normal()); + } + } + } + + GIVEN("a clean config directory and no database path") + { + auto dir = unique_temp_dir("server-config-installed-default-db"); + auto path = dir / "TheWatcherServer.conf"; + + WHEN("the installer creates the config") + { + ServerConfig::create_installed_default(path); + + THEN("the database is beside the config, as for any first run") + { + auto cfg = ServerConfig::load_or_create(path); + REQUIRE(std::filesystem::path(cfg.db_path) == dir / "thewatcher.db"); + } + } + } +} + +SCENARIO("A package refuses a database path that would corrupt the config") +{ + GIVEN("a clean config directory") + { + auto dir = unique_temp_dir("server-config-installed-bad-db"); + auto path = dir / "TheWatcherServer.conf"; + + WHEN("the database path is relative") + { + THEN("it is refused, because it would depend on the directory the installer ran from") + { + REQUIRE_THROWS_AS(ServerConfig::create_installed_default(path, "data/thewatcher.db"), + std::invalid_argument); + REQUIRE_FALSE(std::filesystem::exists(path)); + } + } + + WHEN("the database path starts or ends with whitespace that the loader would trim") + { + THEN("it is refused and nothing is written, so the service cannot open another path than the one given") + { + REQUIRE_THROWS_AS(ServerConfig::create_installed_default(path, (dir / "x.db").string() + " "), + std::invalid_argument); + REQUIRE_THROWS_AS(ServerConfig::create_installed_default(path, " " + (dir / "x.db").string()), + std::invalid_argument); + REQUIRE_FALSE(std::filesystem::exists(path)); + } + } + + WHEN("the database path contains a line break that would start a new KEY=VALUE line") + { + const auto database = (dir / "x.db").string() + "\nAPI_HOST=0.0.0.0"; + + THEN("it is refused and nothing is written") + { + REQUIRE_THROWS_AS(ServerConfig::create_installed_default(path, database), std::invalid_argument); + REQUIRE_FALSE(std::filesystem::exists(path)); + } + } + } + + GIVEN("a config the administrator already has") + { + auto dir = unique_temp_dir("server-config-installed-existing-db"); + auto path = dir / "TheWatcherServer.conf"; + { + std::ofstream f(path, std::ios::binary); + f << "DB_PATH=custom.db\n"; + } + + WHEN("the installer asks for a different database path") + { + const bool created = ServerConfig::create_installed_default(path, (dir / "other.db").string()); + + THEN("the existing config is kept") + { + REQUIRE_FALSE(created); + REQUIRE(read_bytes(path) == "DB_PATH=custom.db\n"); + } + } + } +}