Repository navigation
feat(agent): verify an upgrade offline against its Sigstore signature (part of #240) - #441
Merged
Merged
Conversation
… signature agent/internal/upgrade is what an agent checks before it replaces its binary (ADR 0028): a release version, the GitHub address built from it, a bounded download whose redirects stay on GitHub's release storage, the archive's Sigstore bundle verified offline against an embedded trusted root and the exact identity of release.yml at that tag, and the binary extracted alone. Tested against the real signatures of v0.1.0-alpha.3 and malicious inputs. Adds sigstore-go v1.3.0 (Apache-2.0), the last release that keeps Go 1.26. Part of #240. Signed-off-by: samuel mbabhazi <[email protected]>
|
Warning Review limit reachedYou've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository. Next included review available in 33 minutes. View limit details
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. |
This was referenced Nov 23, 2026
samuelmbabhazi
added a commit
that referenced
this pull request
Nov 24, 2026
…olls it back (part of #240) (#442) ## Task Part of #240, step 1b of ADR 0028 (#436): the `UpgradeAgent` handler, the journaled swap, the confirmation on the first `Hello`, and the upgrade guard mode. It builds on the offline verification of #441, now in `main`. The installer's unit follows in the next pull request, stacked on this one. This one is safe to merge alone: without `NOTIFY_SOCKET` the agent notifies nothing, and without the guard line in its unit it refuses every `UpgradeAgent`. The control plane does not send the action yet (step 1c). ## What changed **The swap (`agent/internal/upgrade/swap.go`):** - **The upgrade record**, `upgrade.json` in the state directory: from, to, binary, digest, state, attempts. - It is written through a temporary file, fsync and rename, and bounded to 4 KiB. - It is refused unless it names an absolute, clean path whose base is `shipkeep-agent`, with a known state and a plausible count. - **`WriteNext`** writes the verified binary as `shipkeep-agent.next`, mode 0755, synced. - **`LinkPrevious`** removes a stale `.previous.new`, hard-links the running binary there, and renames it over `.previous`. The running binary never leaves its path. - **`Swap`** renames `.next` over the binary. Run again after it happened, it finds the expected digest and succeeds. - **`Guard`** works on a pending record only. It counts this start; after 3 starts it renames `.previous` back and records the rollback. **`UpgradeAgent` (`agent/internal/actions/upgrade.go`):** - **Before any download**, the plan refuses: - an invalid version; - a `url` other than the release address the agent builds from the version and its architecture; - a digest that is not 64 lowercase hex characters; - a bundle that is empty or larger than 64 KiB. - **Three steps**, all safe to retry, under plan `upgrade-agent-v1`: 1. `fetch`: - refuses a development build, a version that is not newer, and a unit without the guard line; - then downloads within bounds, checks the SHA-256 and then the Sigstore bundle, and extracts the agent into `.next`. 2. `keep`: links the running binary as `.previous`, and refuses when `.next` is the running binary. 3. `swap`: writes the pending record, renames, and asks for a restart. - **The new binary**, on redelivery or when it resumes, skips `keep` and `swap` for its own version, so it answers from the journal and downloads nothing again. - **Five fixed failure texts**, listed in SPEC 3.4, with nothing else about the failure leaving the server. **Startup and restart (`agent/internal/agent/upgrade.go`):** - **A normal start** sends `READY=1` at once, without the control plane (rule 10). - **A new binary with an upgrade pending to its own version:** - it sends `READY=1` only after the control plane's first Welcome, then clears the record; - after 5 minutes without one, it exits with code 4. - **The previous binary, after a rollback**, logs the rolled-back upgrade at error level and clears the record. A record about other versions is cleared as stale. - **After the swap**, the agent stops once the `SUCCEEDED` update of that action is written to the stream (the Runner's new `Sent` hook), or after 2 minutes. It then exits 0, and systemd starts the new binary. **Smaller parts:** - **`agent/internal/sdnotify`:** one datagram on `$NOTIFY_SOCKET`, abstract namespace included, and a no-op without it. - **`shipkeep-agent upgrade-guard --config …`:** loads the configuration, runs `Guard`, logs what it did, and always exits 0. **Docs:** - SPEC: the `UpgradeAgent` row, and the five texts with their reason codes; - ARCHITECTURE: the agent's binary and unit; - THREAT_MODEL T1: the rollback, the guard, and their tests. **Size:** about 1,670 changed lines: 780 of code, 780 of tests, and about 120 of docs, most of them Prettier re-padding SPEC and THREAT_MODEL tables. The installer part went into its own PR to keep this one reviewable. ## Why ADR 0028: an agent upgrade must not depend on the new binary to undo itself. The guard runs from the installer's root-owned copy of the agent, which an upgrade never replaces. It counts each start of the new binary, whatever ends it (a crash, the 5-minute deadline, or systemd's start timeout), and puts the previous binary back after 3. ## How it was tested - **`go test ./agent/... ./lib/...`** passes. `-race` passes on `agent`, `actions`, `upgrade`, `sdnotify`, `gateway` and `cmd/shipkeep-agent`. `golangci-lint run ./agent/... ./cli/... ./lib/...` reports 0 issues. - **Coverage:** - `internal/actions`: 86.4 %, against 86.1 % before; - `internal/upgrade`: 88.7 %. The rest is I/O failures after a successful open. - **The handler:** - the full swap: the hard link (`os.SameFile`), the record, and the restart request; - a redelivery to the new binary, answered from the journal without a download; - a resume at each step converging, including a stop at `swap` resumed by the new binary; - `keep` never keeping the new binary. - **Malicious requests (12):** another URL, host, architecture or version, an injected or traversing version, a bad digest, an empty or oversized bundle, and no action. All are refused before anything is downloaded. - **Refusals at run time:** - a development build, the same version, an older one; - a unit without the guard, and no unit; - an archive that does not match its digest, a failed verification, an oversized archive, an archive without an agent. Each one sends its fixed text, and leaves no binary changed, no `.next`, no record and no restart. - **Swap and guard:** - counting to 3, then the rollback; - a missing `.previous`, or a directory in its place; - a second upgrade over a stale staging link; - a stale temporary file, missing directories, and a file larger than a binary; - records naming another file: relative, `/etc/passwd`, traversal, a bad state, negative attempts, not JSON, oversized. - **Startup:** - ready at once on a normal start; - an upgraded binary ready only once welcomed, and giving up at its deadline; - a rollback reported and cleared, a stale record cleared; - the restart once the result is sent, or after the fallback; - the guard mode exiting 0 on every path. - **Real systemd (Ubuntu 24.04, systemd 255, throwaway privileged container):** the installer's unit from the next PR, with these binaries. A silent TCP listener stood in for the control plane. - **A normal start:** `systemctl start` returned as soon as the agent ran, and the unit was active. - **A new binary that crashes at once:** started 3 times, then put back by the guard after about 16 s. The previous binary logged the rollback, and the record was gone. - **A new binary that never reaches the control plane:** held in `activating`, stopped by the start timeout 3 times (shortened to 12 s for the test), then put back on the 4th start. Not covered there: the confirmation against a real control plane, and the agent's own 5-minute deadline, which unit tests cover. Both are left to the VM acceptance (#200). ## Security considerations - **No shell, no process.** The agent writes, links and renames files next to its own binary, in a directory that `shipkeep` owns. The proto is unchanged: `UpgradeAgent` was already in the action list. - **The control plane names a version only.** The address must equal the one the agent builds. The archive's digest and its Sigstore bundle are both checked before anything is written next to the binary, and no downgrade is accepted. - **The guard gives no privilege.** It runs as `shipkeep` (the unit's `User=`). It acts only on a record that names an absolute `shipkeep-agent` path, and never on a directory or a link in place of `.previous`. Whoever can write the record can already replace the binary. - **Residual risk.** A release that passes verification can, once running, disable its own rollback: it owns `.previous` and the record. The trust is in the signature (THREAT_MODEL T1). - **No secret exposure.** What leaves the server is one of the fixed texts. Errors logged on the server name the agent's own files and directories, never their contents. The record holds versions, a path and a digest. - **Open points for step 1c:** - `Hello` has no field for a rolled-back upgrade. The control plane sees the previous version in `Hello`, and the agent logs the rollback. - A rollback runs the previous binary on a journal the new one has used, so the journal's schema has to stay readable by the previous release. - **Noticed, not changed:** during enrollment, a refused connection ends the agent with "gateway TLS verification failed" (`gateway/client.go`, dial error), and systemd starts it again after 5 s. ## Checklist - [ ] Acceptance criteria from `docs/PLAN.md` are met and the task is ticked: not yet, #240 continues with the installer PR and step 1c - [x] Lint, TS tests, Go tests and `buf lint` pass (Go and lint locally; no TS or proto change) - [x] Tests added, including malicious-input tests where relevant - [x] No new shell invocation and no new secret exposure path - [x] Audit events emitted for new state changes: none on the control plane here; the agent journals each step - [x] SPEC, ARCHITECTURE, THREAT_MODEL or an ADR updated if a contract or decision changed <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Agents can securely upgrade themselves to verified newer releases and restart to apply updates. * New versions must connect successfully to be confirmed; if startup or confirmation fails after repeated attempts, the previous version is restored. * Upgrade results include clearer reasons when an upgrade cannot proceed. * **Documentation** * Updated architecture, operation, and security documentation to describe upgrades, startup confirmation, and rollback behavior. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: samuel mbabhazi <[email protected]>
samuelmbabhazi
added a commit
that referenced
this pull request
Nov 24, 2026
…part of #240) (#446) ## Task Part of #240, step 1c of ADR 0028 (#436). The building blocks of the agent rollout: what it decides for each server, and how the control plane reads a release. Nothing calls them yet. The next pull request adds the rollout's table, queue, API and audit events on top. ## What changed **Release versions (`fleet/domain/agent-upgrade.ts`), with the agent's rules (`agent/internal/upgrade`):** - `parseReleaseVersion` accepts `MAJOR.MINOR.PATCH` with an optional prerelease. It refuses build metadata, leading zeros, numbers over 9 digits, texts over 64 characters, and `dev`. - `compareVersions` follows semantic versioning precedence, prereleases included. - `agentArchive` and `releaseFile` give the names and addresses that `release.yml` publishes. **The rollout's decisions, pure:** - `upgradeCandidates` lists the servers to upgrade: not removed, on a release older than the target, on `amd64` or `arm64`. A `dev` agent is left out, since the agent refuses to upgrade one. - `nextUpgradeStep` decides, for the server whose turn it is: `send`, `wait`, `skip`, `done`, `finish`, or `fail` with a reason: - **Before sending.** A server that is gone, already on the target version, or that cannot take a release is skipped. A server that is not connected gets 5 minutes (`node_unavailable`). A server with any other unfinished action, which is how a deployment touching it shows, gets 30 minutes (`node_busy`). This is ADR 0028's "never while a deployment touches that server". - **After sending.** An action that did not succeed stops the rollout (`action_failed`, with the action's reason). An action that never ends, because the server never came back, stops it after 35 minutes (`not_confirmed`). - **After success.** The new version showing up means `done`. A heartbeat recorded more than 150 seconds after the success, still on the previous version, means `rolled_back`: the previous binary stops within 2 minutes of its result (the agent's `restartWithin`), so a later heartbeat comes from a process started after it, and the guard put the previous binary back. With no new version within 25 minutes, the rollout stops with `not_confirmed`. **Reading a release (`fleet/infrastructure/github-agent-releases.ts`):** - It reads the archive's SHA-256 from the release's `checksums.txt`: one line, lowercase hex, listed once. - It reads the archive's `.sigstore.json` bundle: a JSON object with a Sigstore bundle media type. - It uses HTTPS only, to GitHub's release hosts only, and checks every redirect against that list. No credentials, no other port, at most 5 redirects, 20 seconds, and 64 KiB per file, declared or streamed. - It returns `null` on any failure, and logs only the kind of failure. - Nothing it reads is trusted: the agent checks the digest and verifies the bundle offline (#441). ## Why ADR 0028 section 2: the control plane names the version, relays the digest and the bundle, sends `UpgradeAgent` to one server at a time, waits for that agent to report the new version, and stops at the first failure. The decisions are pure so they can be tested on their own, including every timing. ## How it was tested - `agent-upgrade.spec.ts`, 16 tests: - versions, valid and malicious; - precedence, checked on every pair of 13 versions; - candidates; - every branch of `nextUpgradeStep`, at each timing boundary. - Coverage: 100 % of lines, 96 % of branches. - `github-agent-releases.spec.ts`: - the happy path; - a redirect to release storage; - redirects refused to another host, plain HTTP, credentials, another port, a lookalike host and `file:`; - a redirect loop, and a redirect without a location; - files over their bounds, declared or streamed; - a missing digest or bundle, an invalid bundle, a network failure; - the `checksums.txt` parser. - Coverage: 97 % of lines. - `pnpm nx run-many -t lint,typecheck,test -p api` passes. ## Security considerations - The control plane reaches GitHub's release hosts only, with the same allow-list as the agent's download (#441). - What it reads is relayed, never trusted: a wrong digest or bundle makes the agent refuse (`upgrade_unverified`). - Nothing read from GitHub is logged. --------- Signed-off-by: samuel mbabhazi <[email protected]>
samuelmbabhazi
added a commit
that referenced
this pull request
Nov 24, 2026
… (#447) ## Task Part of #240, step 1c of ADR 0028: the control plane rolls `UpgradeAgent` out to an organization's servers, one at a time. It is stacked on #446, which adds the decisions and the release reader. It uses the version from each hello, added by #445; until #445 merges, a turn sees the new version at the agent's next `CollectFacts`. The web UI is the next pull request. ## What changed **The rollout's table (`agent_upgrades`):** - It holds: - the version, which is the control plane's own; - the servers, in turn order; - the position, and the action of the current turn; - when the turn started; - the failure: server, reason, and the action's reason. - Constraints: - at most one running rollout per organization, through a partial unique index; - a version pattern; - between 1 and 1,000 servers; - known failure reasons; - a failure exactly when failed, an end time exactly when ended. - Forced row security, and the table is in `TENANT_TABLES`. - The runtime role may select, insert and update it, never delete: rollouts are kept as their history. **The rollout's runs (`AgentUpgrades.advance`, a pg-boss queue and its worker):** - Each run reads the turn under the tenant scope and decides with `nextUpgradeStep` (#446). - It ends every turn it can right away: skipped servers, servers already on the version. It returns when a turn has to wait. - **Sending.** The release's digest and bundle are read outside any transaction. `UpgradeAgent` is then enqueued under the key `au:<rollout>:<node>`, with a 30-minute deadline, and the turn's new start is written in the same transaction. - **Concurrency.** Every write is a compare-and-swap on the position and action just read, so a concurrent run rolls back instead of doing a turn twice. - **Wake-ups.** - A finished action wakes its rollout through the key. - `fleet.node.agent_version_changed` (#445) and `fleet.node.ready` wake the organization's running rollout. - Otherwise the rollout looks again every 15 seconds. - **Audit:** `fleet.agent_upgrade.started` with the actor, then `node_upgraded` or `node_skipped`, then `succeeded` or `failed` with the server and the reasons. **HTTP (`node.manage`):** - `GET /organizations/{organizationId}/agent-upgrades`: - the control plane's version; - the servers on an older release; - the newest rollout. - `POST /organizations/{organizationId}/agent-upgrades` with `{version}`, answering 202: - **The version must still be the control plane's.** The client names the version it saw, so a control plane upgraded in the meantime refuses the rollout. This also keeps the route-role matrix's rule that an empty body stops at validation. - **The release is read first.** The release of each needed architecture must be readable before anything starts. - **Errors** are stable 409 codes: `agent_upgrade_unavailable`, `agent_upgrade_version_changed`, `agent_upgrade_running`, `agent_upgrade_not_needed`, `agent_upgrade_too_many` and `agent_release_unavailable`. **Docs:** a SPEC section on the routes, the turns, the timings and the audit events. The route-role matrix and `openapi.json` are regenerated. ## Why ADR 0028, section 2. The control plane sends `UpgradeAgent` to one server at a time. It never sends it while a deployment touches that server, which shows as any other unfinished action there. It waits for that agent to report the new version, and stops at the first failure. ## How it was tested - **Unit (`agent-upgrades.spec.ts`):** - **Start:** - candidates are listed by name, and the releases are read for both architectures; - every refusal leaves nothing behind. - **A full rollout:** A, then B. No second action goes out while A's runs, the action carries the release, and every audit event is checked. - **The other turns:** - stopping at the first failure, with the agent's reason; - skipped servers; - waiting while another action runs; - a release unavailable at a server's turn; - the overview. - Coverage: 97 % of lines. - **Integration (`agent-upgrades.integration.spec.ts`, real PostgreSQL, through HTTP and the restricted runtime role):** - **Access:** the overview, 404 for roles without `node.manage`, 400 for an empty or malformed version. - **The rollout:** 202, then 409 for a second one. The run puts the `upgradeAgent` action in the database; after the agent's success and new version, the rollout succeeds with its three audit events, and a new start answers `agent_upgrade_not_needed`. - **The table itself:** through the admin login, the partial unique index, the failure check and the version pattern. - **Local checks:** - `pnpm nx run-many -t lint,typecheck,test -p api` passes, and so does the web typecheck. - The whole API integration suite passes locally on PostgreSQL 18, except the three known 23001 tests and two files that need Docker. A first run caught the missing runtime grant: the queue reads the table inside the agent stream. **Size:** about 1,050 lines of code and 600 of tests, over the 500-line target. The table, the queue and the routes only make sense together, and the decisions are already in their own pull request. ## Security considerations - **No URL from a client.** The rollout's target is the control plane's own version, never one a client supplies; the body only confirms it. - **What the control plane relays.** It sends only what the release published. The agent rebuilds the address, checks the digest and verifies the bundle offline (#441, #442). - **No new outside service.** The control plane reaches GitHub's release hosts, which ADR 0028 names. - **No secret moves.** The bundle and the digest are public. - **Every state change is audited, and rollouts cannot be deleted.** <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **New Features** * Organization administrators can start agent upgrades and check the rollout’s status, target version, and pending servers. * Upgrades proceed server by server, with progress and success or failure details recorded. Servers that are already up to date or otherwise ineligible may be skipped. * **Documentation** * Added specification details for the upgrade endpoints, rollout behavior, and retained rollout history. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: samuel mbabhazi <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of #240, step 1 of ADR 0028: what an agent checks before it replaces its own binary. The
UpgradeAgenthandler that uses it, the swap and the rollback unit follow in the next pull request. Nothing calls this package yet.What changed
agent/internal/upgrade:ParseVersionandCompare. Semantic versioning without build metadata. It refuses leading zeros, avprefix, any whitespace or path character, and more than 64 characters. Ordering follows semver precedence, soalpha.3 < alpha.10 < beta.1 < release. The handler will refuse anything that is not newer.ArchiveURL. It buildshttps://github.com/shipkeepdev/shipkeep/releases/download/v<version>/shipkeep-agent_<version>_linux_<arch>.tar.gzfrom the version and the architecture (amd64orarm64only). The control plane names a version, never an address.Download.github.com, and on redirect to GitHub's release storage hosts, at most five redirects.Content-Lengthand the bytes read, and a 10-minute timeout.Verify.sigstore-gochecks the archive's Sigstore bundle offline:trusted_root.json, taken through Sigstore's TUF repository bygo generate);…/.github/workflows/release.yml@refs/tags/v<version>, from GitHub's OIDC issuer;ExtractAgent. It takes theshipkeep-agentregular file at the root of the archive, present once and bounded in size. It refuses the whole archive for an absolute or climbing entry, for a symlink, hard link or directory namedshipkeep-agent, for a cut entry, and for more than 64 entries.Dependency:
sigstore-gov1.3.0 (Apache-2.0), with its modules, all Apache-2.0, MIT or BSD. v1.4.x needs Go 1.27, and this keeps the repository on Go 1.26.Docs:
UpgradeAgentrow;The signed fixtures and the trusted root are kept out of Prettier, byte for byte.
How it was tested
v0.1.0-alpha.3(testdata/, identical to the release files):checksums.txtverify against their bundles, offline;file:;go test ./agent/...andgolangci-lint: 0 issues.Security considerations