oficina / equipo Public

fix: harden runner install script, release assets and label retry

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev 0fcd1d948024f9239e40439e6302f0abe4ee6d44 parent 3375df3
23 files changed, +788 −76
  • .rastrillo/budgets.txt +1 −1
  • cmd/equipo-runner/install.go +17 −9
  • cmd/equipo-runner/main.go +7 −1
  • cmd/equipo-runner/onboarding_test.go +32 −0
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +146 −0
  • internal/equipo/app.go +2 −2
  • internal/equipo/copy.go +4 −0
  • internal/equipo/onboarding.go +1 −1
  • internal/equipo/setup/enrolment.go +1 −1
  • internal/equipo/setup/onboarding_test.go +46 −0
  • internal/equipo/templates/runners.html +1 −1
  • internal/plan3test/onboarding_install_test.go +1 −1
  • internal/release/install_assets.go +114 −26
  • internal/release/install_script_test.go +75 −0
  • internal/release/install_test.go +39 −1
  • internal/runner/connections.go +4 −1
  • internal/runner/enrol.go +26 −8
  • internal/runner/onboarding_test.go +129 −0
  • internal/runner/runtime.go +20 −9
  • internal/runner/setup/install.go +36 −11
  • internal/runner/setup/install_test.go +79 −1
  • internal/runner/setup/service.go +1 −1
  • packaging/install/install-v1.sh +6 −1

CI failed — run details

diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt
index 189e064d..39a44646 100644
--- a/.rastrillo/budgets.txt
+++ b/.rastrillo/budgets.txt
@@ -21,7 +21,7 @@ time internal/runner 330s Final corrected package rerun measured 152.897s; revie
perf GET /live skip Authorized notification stream, bounded to 30 seconds; not a GET screen.
perf GET /api/runner/v2/artifacts/{assignment}/{artifact} skip Authenticated runner artifact download, not a browser GET screen. Runner long-poll and blob downloads use POST and are outside the screen inventory.
-size internal/runner 9400 8600 Task 16 retains machine-key enrolment and durable pairing retries beside the runner state lock and credential journal. Measured 9336 source and 8590 test lines; the installer lives in runner/setup. The 330s time ceiling is unchanged.
+size internal/runner 9400 8800 Task 16 fix round 1 retains machine-key enrolment, retry validation and idle service reporting beside the runner state lock and journal. Measured 9368 source and 8719 test lines; the 119-line test overflow adds label retry and no-account startup guards. Source and 330s time ceilings are unchanged.
time internal/runner/provider/claude 45s Task 5 measured 32.430s for fake CLI sessions and fsynced account, policy, capture and refresh checks; 45s gives 38 percent headroom on the shared runner.
time internal/runner/provider/codex 15s Task 11a full branch gate measured 11.659s (prior attempt 11.464s) for schema, native approval and fsynced capture fixtures; 15s gives 29 percent headroom under shared-runner load.
diff --git a/cmd/equipo-runner/install.go b/cmd/equipo-runner/install.go
index 5c45bc99..1eef13c8 100644
--- a/cmd/equipo-runner/install.go
+++ b/cmd/equipo-runner/install.go
@@ -40,19 +40,11 @@ func installRunner(ctx context.Context, args []string, input io.Reader, out, err
}
return 1
}
- label, e := os.Hostname()
- if e != nil {
- return fail("runner.install.unavailable")
- }
- fmt.Fprintf(out, equipo.RunnerSetupCopy("runner.install.label"), label)
reader := bufio.NewReader(input)
- edited, e := reader.ReadString('\n')
+ label, e := promptMachineLabel(reader, out, *root, *origin, *instance)
if e != nil {
return fail("runner.install.unavailable")
}
- if strings.TrimSpace(edited) != "" {
- label = strings.TrimSpace(edited)
- }
fmt.Fprint(out, equipo.RunnerSetupCopy("runner.install.enrol"))
confirm, e := reader.ReadString('\n')
if e != nil || strings.TrimSpace(confirm) != "yes" {
@@ -106,3 +98,19 @@ func installManifest(args []string, out io.Writer) int {
}
return 0
}
+
+func promptMachineLabel(reader *bufio.Reader, out io.Writer, root, origin, instance string) (string, error) {
+ label, e := runner.DefaultMachineLabel(filepath.Join(root, "state"), origin, instance)
+ if e != nil {
+ return "", e
+ }
+ fmt.Fprintf(out, equipo.RunnerSetupCopy("runner.install.label"), label)
+ edited, e := reader.ReadString('\n')
+ if e != nil {
+ return "", e
+ }
+ if strings.TrimSpace(edited) != "" {
+ label = strings.TrimSpace(edited)
+ }
+ return label, nil
+}
diff --git a/cmd/equipo-runner/main.go b/cmd/equipo-runner/main.go
index 6e6dcc45..287948cb 100644
--- a/cmd/equipo-runner/main.go
+++ b/cmd/equipo-runner/main.go
@@ -62,7 +62,13 @@ func run(ctx context.Context, args []string, input io.Reader, output, errorOutpu
return fail(err)
}
cfg.Copy = equipo.RunnerToolCopy()
- cfg.Report = func(code string) { _, _ = fmt.Fprintf(errorOutput, equipo.CopyRunnerDiagnostic, code, "-") }
+ cfg.Report = func(code string) {
+ if code == "runner.waiting_accounts" {
+ _, _ = fmt.Fprintln(errorOutput, equipo.RunnerText(code))
+ return
+ }
+ _, _ = fmt.Fprintf(errorOutput, equipo.CopyRunnerDiagnostic, code, "-")
+ }
switch args[0] {
case "enrol":
err = runner.Enrol(ctx, cfg, output)
diff --git a/cmd/equipo-runner/onboarding_test.go b/cmd/equipo-runner/onboarding_test.go
index 077b7899..1e0aab82 100644
--- a/cmd/equipo-runner/onboarding_test.go
+++ b/cmd/equipo-runner/onboarding_test.go
@@ -1,10 +1,15 @@
package main
import (
+ "bufio"
"bytes"
"context"
+ "encoding/json"
+ "os"
+ "path/filepath"
"strings"
"testing"
+ "time"
)
func TestOnboardingInstallVersioned(t *testing.T) {
@@ -15,3 +20,30 @@ func TestOnboardingInstallVersioned(t *testing.T) {
}
}
}
+
+func TestOnboardingInstallLabelPrompt(t *testing.T) {
+ root := t.TempDir()
+ if e := os.Mkdir(filepath.Join(root, "state"), 0700); e != nil {
+ t.Fatal(e)
+ }
+ pending := map[string]any{
+ "origin": "https://equipo.example", "label": "Edited desk",
+ "code": map[string]any{"version": 1, "instance_id": "team", "enrolment_id": "request", "device_secret": "secret", "user_code": "0123456789", "challenge": "challenge", "verification_uri": "https://equipo.example/runners/enrol", "expires_at": time.Now().Add(time.Minute), "poll_interval_seconds": 5},
+ "proof": map[string]any{"enrolment_id": "request", "challenge": "challenge", "signature": "signature", "exchange_nonce": "nonce"},
+ }
+ b, _ := json.Marshal(pending)
+ if e := os.WriteFile(filepath.Join(root, "state/enrolment.json"), b, 0600); e != nil {
+ t.Fatal(e)
+ }
+ for _, input := range []string{"\n", "New desk\n"} {
+ var out bytes.Buffer
+ label, e := promptMachineLabel(bufio.NewReader(strings.NewReader(input)), &out, root, "https://equipo.example", "team")
+ want := "Edited desk"
+ if input != "\n" {
+ want = "New desk"
+ }
+ if e != nil || label != want || !strings.Contains(out.String(), "Edited desk") {
+ t.Fatalf("prompt %q label %q err %v", out.String(), label, e)
+ }
+ }
+}
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index ff1cc304..75906801 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -4060,3 +4060,149 @@ All entries are individually marked COPY REVIEW REQUIRED in copy.go.
| Safe first task | Start with a recommendation in your conversation. Ask what to work on next. |
Full report: `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-16-report.md`. No agents, copy-review server, live providers, real user services, host changes, push, merge or deployment.
+
+## Fix round 1
+
+Task 16 review fixes are complete. Status: DONE_WITH_CONCERNS. The remaining concerns are release certification, the pending copy pass and the filesystem requirement described below. No push, merge or deployment.
+
+Commit subject: `fix: harden runner install script, release assets and label retry`.
+Required author: `codex <codex~paul@keymail.dev>`.
+
+### Changes and evidence
+
+Release assets are verified at application construction, with lazy verification available to direct callers. A mutex protects a cached verdict keyed by file identity, modification time, size and mode for the manifest, script and both binaries. Unchanged requests do not hash again. Changed files invalidate the cache. Downloads use an open file and `http.ServeContent`, including range and HEAD support. The onboarding handler uses metadata-only `CachedAvailable`, so a page request never hashes a binary. The packaging fixture counts exactly two digest calls across repeated availability checks and asset requests, checks a byte-range response and rejects changed files. Self-review also caught and fixed acceptance of trailing manifest JSON after switching to a streaming decoder.
+
+Enrolment validates saved state before reuse. Expired, malformed or otherwise unusable requests are replaced with a new request; file permission and filesystem errors still deny access. A valid saved request retains its original label even if the current requested label differs. The install prompt defaults to that saved label. Tests cover an edited label followed by Enter, an explicit new label, expiry, a bad verification address and malformed saved JSON. Valid retries create no duplicate request.
+
+The shell installer now has an explicit platform refusal before the first download. Its whole body is inside `main()`, called only after the closing brace. Executed shell tests provide fake uname, curl and sha256sum on PATH under TMPDIR. Linux/x86_64 reaches the checksum check, where the fake checksum tool deliberately refuses; Darwin and Linux/aarch64 download nothing. A truncated stream invokes no commands and creates no scratch. All fixtures are removed by the tests.
+
+Installer-owned files now carry the `user.equipo.installer.sha256` extended attribute. Replacement requires a regular file owned by the current uid and a marker matching its current contents. New bytes and their marker are written and synced together before atomic rename; new destinations retain exclusive-link creation. Unmarked and edited files are refused. The v1-to-v2 fixture upgrades the service, runner environment and service-version marker and preserves unrelated files. Self-review found that enabling an already-running unit would retain the old process, so activation now enables and restarts the unit. A fake systemctl proves v1 changes to v2 without calling the real service manager.
+
+The helper checksum must match both the downloaded manifest and the running installer's embedded BuildManifest. Tests inject fixture manifests through the private host adapter and prove that a mismatch refuses installation before any service call. Production always supplies release.BuildManifest.
+
+Duplicate-machine query errors now pass through s.Error. A direct Enrolments test bypasses the facade's general error wrapper and injects a query failure, proving this specific mapping. The approval page formats its UTC request time explicitly, using the pending copy key below.
+
+### Authentication status finding
+
+The 401 assertions are retained. This was an existing intended auth-dispatch change, not a Task 16 production change. Commit `03cef4b` (`feat: expose person API v1 through explicit auth and CSRF lanes`, Task 10) introduced the Dispatcher branch that returns `401 unauthenticated` for any Authorization header outside registered protocol/person routes. The same branch appears at lines 106–108 of `git show f01a407:internal/equipo/personapi/auth.go`, the pre-Task-16 baseline. Thus the old browser-route 403 expectations were stale. Device endpoint audience violations remain 403. The targeted EnrolmentAudience regression passes for both GET and POST browser attempts using device/runner credentials. No production auth behavior changed in this fix round.
+
+### No-account startup finding
+
+A missing accounts file and an empty list previously failed startup. They now mean no configured connections. Malformed or unreadable bindings still fail. Runtime recovery runs first, then the runner sends an empty connection heartbeat, reports `runner.waiting_accounts` locally and waits five seconds before rereading bindings. It does not poll or claim work while there are no connections. Configured accounts still go through the existing validation and containment paths.
+
+TestOnboardingServiceWithoutAccounts runs the real Run/openRuntime/wire/service loop with fixture tools and an injected HTTP transport. For missing and empty bindings it observes the empty heartbeat and waiting status, checks that no work request occurs, leaves the loop alive, then cancels it. Malformed JSON must fail before a heartbeat. No provider launches or real account homes are used. The instance's existing runnerproto heartbeat handler and Store.ReportConnections accept the empty list; only lists over 256 entries or invalid individual reports are refused.
+
+### Tests first
+
+Each command below exited 1 before its implementation, and the named tests pass after restoration:
+
+- `CGO_ENABLED=0 go test ./internal/release -run '^TestOnboardingInstall(Packaging|Shell)$' -count=1`: missing cache digest hook and CachedAvailable.
+- `CGO_ENABLED=0 go test ./internal/release/install_script_test.go -run '^TestOnboardingInstallShell$' -count=1`: Darwin and aarch64 downloaded; truncated script ran successfully.
+- `CGO_ENABLED=0 go test ./internal/runner/setup -run '^TestOnboardingInstallUpgrade$' -count=1`: v2 returned runner.install.destination and only one service call.
+- `CGO_ENABLED=0 go test ./internal/runner/setup -run '^TestOnboardingInstallEmbeddedProxy$' -count=1`: embedded manifest seam absent.
+- `CGO_ENABLED=0 go test ./internal/runner -run '^TestOnboardingPairingLabelRetry$' -count=1`: valid, expired, unusable and malformed retries all printed no pairing code.
+- `CGO_ENABLED=0 go test ./cmd/equipo-runner -run '^TestOnboardingInstallLabelPrompt$' -count=1`: promptMachineLabel absent.
+- `CGO_ENABLED=0 go test ./internal/runner -run '^TestOnboardingServiceWithoutAccounts$' -count=1`: missing bindings returned runner.file_missing; empty bindings returned runner.identity.
+- `CGO_ENABLED=0 go test ./internal/equipo/setup -run '^TestOnboardingPairingCountError$' -count=1`: raw count fixture failure escaped the injected error mapper.
+- `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestOnboardingPairingBound$' -count=1`: missing human-readable server date.
+- `CGO_ENABLED=0 go test ./internal/release -run '^TestOnboardingInstallPackaging$' -count=1`: trailing manifest data accepted.
+- `CGO_ENABLED=0 go test ./internal/runner/setup -run '^TestOnboardingServiceUpgrade$' -count=1`: running version remained v1 after v2 installation.
+
+### Final checks
+
+All exited 0:
+
+- `CGO_ENABLED=0 go test ./internal/runner ./internal/runner/setup ./internal/release ./internal/equipo/setup ./internal/plan3test ./cmd/equipo-runner -run '^TestOnboarding(Install|Pairing|Containment|Service|Hosted)' -count=1`. Final package times: 0.731s, 0.640s, 0.065s, 1.958s, 0.921s and 0.103s.
+- `CGO_ENABLED=0 go test ./internal/equipotest -run '^TestEnrolment(Audience|SingleUse|IndependentGuards)$' -count=1`: 6.929s.
+- `CGO_ENABLED=0 go test ./internal/runner -run '^Test(AccountHomeConfigured|DirectBugRuntime|RunnerConfig|RunnerServiceLifecycle)' -count=1`: 0.635s.
+- `CGO_ENABLED=0 go vet ./internal/release ./internal/runner ./internal/runner/setup ./internal/equipo ./internal/equipo/setup ./internal/plan3test ./cmd/equipo-runner`.
+- `CGO_ENABLED=0 go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./internal/release ./internal/runner ./internal/runner/setup ./internal/equipo ./internal/equipo/setup ./internal/plan3test ./cmd/equipo-runner`.
+- `make migration-check`: runs only TestMigrationModels; 0.178s.
+- `git diff --check` and gofmt checks of every changed Go file plus the new shell test file: no output.
+
+No full suite or make ci was run. Directory line counts were measured using physical lines, matching Rastrillo's documented size counting. internal/runner is 9368 source and 8719 test lines. The source ceiling remains 9400; the test ceiling changes from 8600 to 8800 for the new retry and idle-startup regression tests. Its time ceiling remains 330s. internal/equipo is 10723 source and 437 test lines, within its existing ceiling.
+
+### Guard mutations
+
+Each mutation was applied alone, the command below exited 1 at the stated assertion, and the original code was restored immediately. The final combined test command above ran after all restorations.
+
+- cache reuse: `CGO_ENABLED=0 go test ./internal/release -run ^TestOnboardingInstallPackaging$ -count=1`. Exit 1. install_test.go:81: rehashed unchanged assets: 16. Restored.
+
+- cache metadata: `CGO_ENABLED=0 go test ./internal/release -run ^TestOnboardingInstallPackaging$ -count=1`. Exit 1. install_test.go:92: cached availability ignored changed file. Restored.
+
+- shell platform: `CGO_ENABLED=0 go test ./internal/release -run ^TestOnboardingInstallShell$ -count=1`. Exit 1. install_script_test.go:60: refused host downloaded: download; install_script_test.go:60: refused host downloaded: download. Restored.
+
+- shell truncation: `CGO_ENABLED=0 go test ./internal/release -run ^TestOnboardingInstallShell$ -count=1`. Exit 1. install_script_test.go:64: truncated stream executed commands. Restored.
+
+- retry expiry: `CGO_ENABLED=0 go test ./internal/runner -run ^TestOnboardingPairingLabelRetry$ -count=1`. Exit 1. onboarding_test.go:108: retry blocked: ""; onboarding_test.go:108: retry blocked: "". Restored.
+
+- prompt default: `CGO_ENABLED=0 go test ./cmd/equipo-runner -run ^TestOnboardingInstallLabelPrompt$ -count=1`. Exit 1. onboarding_test.go:46: prompt "Machine label [DOCS-T1]: " label "DOCS-T1" err <nil>. Restored.
+
+- upgrade: `CGO_ENABLED=0 go test ./internal/runner/setup -run ^TestOnboardingInstallUpgrade$ -count=1`. Exit 1. install_test.go:272: upgrade failed: {Version:fixture-17 BinaryPath:/home/paulca/.cache/tmp/TestOnboardingInstallUpgrade3083008475/001/runner/releases/fixture-17/equipo-runner ServicePath:/home/paulca/.cache/tmp/TestOnboardingInstallUpgrade3083008475/001/runner/equipo-runner.service State:unavailable Missing:[runner.install.destination] LingeringEnabled:false} runner.install.unavailable calls=1. Restored.
+
+- ownership: `CGO_ENABLED=0 go test ./internal/runner/setup -run ^TestOnboardingInstallUpgrade$ -count=1`. Exit 1. install_test.go:287: overwrote unowned or edited file unowned. Restored.
+
+- embedded proxy: `CGO_ENABLED=0 go test ./internal/runner/setup -run ^TestOnboardingInstallEmbeddedProxy$ -count=1`. Exit 1. install_test.go:297: embedded helper mismatch accepted: {Version:fixture-16 BinaryPath:/home/paulca/.cache/tmp/TestOnboardingInstallEmbeddedProxy2490313199/001/runner/releases/fixture-16/equipo-runner ServicePath:/home/paulca/.cache/tmp/TestOnboardingInstallEmbeddedProxy2490313199/001/runner/equipo-runner.service State:stops_at_logout Missing:[] LingeringEnabled:false} <nil>. Restored.
+
+- missing accounts: `CGO_ENABLED=0 go test ./internal/runner -run ^TestOnboardingServiceWithoutAccounts$ -count=1`. Exit 1. onboarding_test.go:198: not idle until cancelled: err=runner.file_missing:EQUIPO_ACCOUNT_BINDINGS_PATH heartbeats=0 polls=0 idle=0. Restored.
+
+- mapped count error: `CGO_ENABLED=0 go test ./internal/equipo/setup -run ^TestOnboardingPairingCountError$ -count=1`. Exit 1. onboarding_test.go:250: unmapped count error: count fixture failure. Restored.
+
+- human timestamp: `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestOnboardingPairingBound$ -count=1`. Exit 1. onboarding_install_test.go:83: missing actual label or server time. Restored.
+
+- manifest trailing data: `CGO_ENABLED=0 go test ./internal/release -run ^TestOnboardingInstallPackaging$ -count=1`. Exit 1. install_test.go:92: trailing manifest data accepted. Restored.
+
+- service upgrade activation: `CGO_ENABLED=0 go test ./internal/runner/setup -run ^TestOnboardingServiceUpgrade$ -count=1`. Exit 1. install_test.go:320: service kept old release: "v1" want "v2": <nil>. Restored.
+
+### Copy inventory (COPY REVIEW REQUIRED)
+
+| Key | Draft text | Context |
+| --- | --- | --- |
+| runner.waiting_accounts | Waiting for a model account. | Local idle-service status before Task 17 creates a connection. |
+| runner.requested_format | 2 Jan 2006, 15:04 UTC | Go date layout for the server's pairing request time. Preserve the reference-date semantics during copy review. |
+
+The existing runner.install.label text is unchanged; it now displays the saved pending label as its default. Its existing %s placeholder must survive the later copy pass. No other new runtime wording was introduced.
+
+### Onboarding mockup wording (pending copy pass)
+
+docs/mockups/onboarding.html remains unchanged. The original Task 16 wording proposals above remain pending. For this fix round, show the actual request time in a form such as “4 Nov 2026, 10:00 UTC” and use “Waiting for a model account.” while the runner is connected but account setup is unfinished. Both proposals require the same later copy pass.
+
+### Self-review and remaining concerns
+
+The fixes use fixture manifests and local transports. Uncertified releases remain unavailable. Real containment, AppArmor behavior, provider sign-in and the production systemd install still require the controller's release validation; they were not exercised here.
+
+The ownership marker requires filesystem support for user extended attributes. A filesystem that rejects them fails installation closed. Existing files made by the earlier unmarked development installer are deliberately not adopted automatically. No released installation exists in this task's fixture-only scope. Per-file writes are atomic; the entire collection of files is not one filesystem transaction, so the existing installation lock and retry behavior remain necessary.
+
+The source-limit increase from the original Task 16 report remains a controller decision. This fix adds the measured test-limit adjustment described above. Review minor notes about symlinked home ancestors, propagation of runnerInstance lookup errors and the lack of a composed live install test remain outside this requested fix round. The new prompt and fake-service tests cover their relevant seams without real installation.
+
+### Files changed in fix round 1
+
+- `.rastrillo/budgets.txt`
+- `cmd/equipo-runner/install.go`
+- `cmd/equipo-runner/main.go`
+- `cmd/equipo-runner/onboarding_test.go`
+- `docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md`
+- `internal/equipo/app.go`
+- `internal/equipo/copy.go`
+- `internal/equipo/onboarding.go`
+- `internal/equipo/setup/enrolment.go`
+- `internal/equipo/setup/onboarding_test.go`
+- `internal/equipo/templates/runners.html`
+- `internal/plan3test/onboarding_install_test.go`
+- `internal/release/install_assets.go`
+- `internal/release/install_script_test.go`
+- `internal/release/install_test.go`
+- `internal/runner/connections.go`
+- `internal/runner/enrol.go`
+- `internal/runner/onboarding_test.go`
+- `internal/runner/runtime.go`
+- `internal/runner/setup/install.go`
+- `internal/runner/setup/install_test.go`
+- `internal/runner/setup/service.go`
+- `packaging/install/install-v1.sh`
+
+The full task report is also appended at .superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-16-report.md, which remains intentionally ignored by git.
+
+### Session
+
+All verification processes have exited. No server, watcher or real user service was started. No sign-in, provider session, machine enrolment, lingering, sysctl, AppArmor or real user config operation occurred. Go caches remained at their defaults. The task's TMPDIR scratch is removed before handoff. Source and controller-report changes are committed locally; the ignored task report is saved in place. Safe to close.
diff --git a/internal/equipo/app.go b/internal/equipo/app.go
index 39514e2c..3b4377bf 100644
--- a/internal/equipo/app.go
+++ b/internal/equipo/app.go
@@ -26,7 +26,7 @@ import (
)
type application struct {
- installAssets release.InstallAssets
+ installAssets *release.InstallAssets
executionEnabled bool
chi.Router
live *live.Hub
@@ -131,7 +131,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg
if err != nil {
return nil, err
}
- a := &application{installAssets: release.InstallAssets{Root: cfg.RunnerReleaseDir, Version: rastrillo.BuildVersion, Manifest: release.BuildManifest()}, executionEnabled: cfg.ExecutionEnabled, Router: chi.NewRouter(), auth: authentication, store: store, logger: logger, nonces: pow.SQLNonces(d.Writer()), origin: cfg.Origin}
+ a := &application{installAssets: release.NewInstallAssets(cfg.RunnerReleaseDir, rastrillo.BuildVersion, release.BuildManifest()), executionEnabled: cfg.ExecutionEnabled, Router: chi.NewRouter(), auth: authentication, store: store, logger: logger, nonces: pow.SQLNonces(d.Writer()), origin: cfg.Origin}
if cfg.AlwaysOn {
a.live, err = live.New(live.Config{Path: "/live", Topics: map[string]live.Allow{"jobs": a.allowJob, "personal": a.preferenceHandler().Allow, "conversation": a.allowConversation}, Lifetime: 30 * time.Second})
if err != nil {
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index a83f614c..5ecc7c86 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -629,6 +629,10 @@ func RunnerToolCopy() runner.ToolCopy {
// runnerDraftCopy is the Task 16 runtime inventory. Each entry needs review.
var runnerDraftCopy = map[string]string{
+ // COPY REVIEW REQUIRED: runner.requested_format
+ "runner.requested_format": "2 Jan 2006, 15:04 UTC",
+ // COPY REVIEW REQUIRED: runner.waiting_accounts
+ "runner.waiting_accounts": "Waiting for a model account.",
// COPY REVIEW REQUIRED: coordinator.connection
"coordinator.connection": "Coordinator connection",
// COPY REVIEW REQUIRED: coordinator.unavailable
diff --git a/internal/equipo/onboarding.go b/internal/equipo/onboarding.go
index 4db2f284..94ddae51 100644
--- a/internal/equipo/onboarding.go
+++ b/internal/equipo/onboarding.go
@@ -12,7 +12,7 @@ type OnboardingState = setup.OnboardingState
func (a *application) onboardingHandler() *setup.OnboardingHandler {
instance, _ := runnerInstance(a.store.db.G)
- return &setup.OnboardingHandler{InstanceID: instance, InstallAvailable: a.installAssets.Available, Store: a.store, Origin: a.origin, Version: rastrillo.BuildVersion, Manifest: release.BuildManifest(), Invalid: ErrInvalid, Failure: a.failure,
+ return &setup.OnboardingHandler{InstanceID: instance, InstallAvailable: a.installAssets.CachedAvailable, Store: a.store, Origin: a.origin, Version: rastrillo.BuildVersion, Manifest: release.BuildManifest(), Invalid: ErrInvalid, Failure: a.failure,
Actor: func(r *http.Request) (Actor, error) {
id, ok := auth.From(r)
if !ok {
diff --git a/internal/equipo/setup/enrolment.go b/internal/equipo/setup/enrolment.go
index 3333ddcd..2b20acff 100644
--- a/internal/equipo/setup/enrolment.go
+++ b/internal/equipo/setup/enrolment.go
@@ -130,7 +130,7 @@ func (s *Enrolments) ApproveOrInspect(ctx context.Context, actor Actor, userCode
}
var existing int64
if err := tx.Model(&RunnerRecord{}).Where("instance_id=? AND machine_key_hash=? AND revoked_at IS NULL", instance, grant.MachineKeyHash).Count(&existing).Error; err != nil {
- return err
+ return s.Error(err)
}
if existing != 0 {
return s.Conflict
diff --git a/internal/equipo/setup/onboarding_test.go b/internal/equipo/setup/onboarding_test.go
index 9855b481..9d112563 100644
--- a/internal/equipo/setup/onboarding_test.go
+++ b/internal/equipo/setup/onboarding_test.go
@@ -7,6 +7,7 @@ import (
"encoding/base64"
"encoding/json"
"errors"
+ "gorm.io/gorm"
"io"
"log/slog"
"path/filepath"
@@ -205,3 +206,48 @@ func TestOnboardingInstallUpgrade(t *testing.T) {
t.Fatal("upgrade replay reset progress", state, e)
}
}
+
+func TestOnboardingPairingCountError(t *testing.T) {
+ s, d, a := onboardingStore(t)
+ pub, _, e := ed25519.GenerateKey(rand.Reader)
+ if e != nil {
+ t.Fatal(e)
+ }
+ code, e := s.BeginEnrolment(context.Background(), base64.RawURLEncoding.EncodeToString(pub), "Fixture machine")
+ if e != nil {
+ t.Fatal(e)
+ }
+ sentinel := errors.New("count fixture failure")
+ if e = d.G.Callback().Query().Before("gorm:query").Register("fixture_count_error", func(tx *gorm.DB) {
+ if tx.Statement.Table == "runners" {
+ tx.AddError(sentinel)
+ }
+ }); e != nil {
+ t.Fatal(e)
+ }
+
+ var grant setup.EnrolmentRecord
+ if e = d.G.First(&grant).Error; e != nil {
+ t.Fatal(e)
+ }
+ mapped := errors.New("mapped error")
+ enrolments := setup.Enrolments{
+ Write: func(ctx context.Context, fn func(*gorm.DB) error) error { return d.G.WithContext(ctx).Transaction(fn) },
+ Now: time.Now,
+ Instance: func(*gorm.DB) (string, error) { return code.InstanceID, nil },
+ Rate: func(*gorm.DB, string, time.Time, time.Duration, int) (bool, error) { return true, nil },
+ Hash: func(string, string) string { return grant.UserCodeHash },
+ Member: func(*gorm.DB, string) (setup.Member, error) { return setup.Member{Address: a.Address}, nil },
+ Error: func(err error) error {
+ if errors.Is(err, sentinel) {
+ return mapped
+ }
+ return err
+ },
+ }
+ _, e = enrolments.ApproveOrInspect(context.Background(), a, code.UserCode, true)
+ if !errors.Is(e, mapped) {
+ t.Fatalf("unmapped count error: %v", e)
+ }
+
+}
diff --git a/internal/equipo/templates/runners.html b/internal/equipo/templates/runners.html
index c03e18f4..d385f326 100644
--- a/internal/equipo/templates/runners.html
+++ b/internal/equipo/templates/runners.html
@@ -6,7 +6,7 @@
<h2>{{copy "runner.approve-title"}}</h2>
<dl equipo-metadata>
<dt>{{copy "runner.label"}}</dt><dd>{{.Enrolment.Label}}</dd>
-<dt>{{copy "runner.requested"}}</dt><dd>{{.Enrolment.RequestedAt}}</dd>
+<dt>{{copy "runner.requested"}}</dt><dd>{{.Enrolment.RequestedAt.UTC.Format (copy "runner.requested_format")}}</dd>
<dt>{{copy "runner.fingerprint"}}</dt><dd>{{.Enrolment.MachineKeyHash}}</dd>
<dt>{{copy "runner.person"}}</dt><dd>{{.Address}}</dd>
</dl>
diff --git a/internal/plan3test/onboarding_install_test.go b/internal/plan3test/onboarding_install_test.go
index b4521994..e7c59c0d 100644
--- a/internal/plan3test/onboarding_install_test.go
+++ b/internal/plan3test/onboarding_install_test.go
@@ -79,7 +79,7 @@ func TestOnboardingPairingBound(t *testing.T) {
values.Set("action", "inspect")
w = inviteRequest(t, f, owner, "POST", "/runners/enrol", values, nil)
expectHTTP(t, w, 200)
- if !strings.Contains(w.Body.String(), "Edited kitchen machine") || !strings.Contains(w.Body.String(), time.Now().UTC().Format("2006-01-02")) {
+ if !strings.Contains(w.Body.String(), "Edited kitchen machine") || !strings.Contains(w.Body.String(), time.Now().UTC().Format("2 Jan 2006")) {
t.Fatal("missing actual label or server time")
}
proof := regexp.MustCompile(`name="confirmation" value="([^"]+)"`).FindStringSubmatch(w.Body.String())
diff --git a/internal/release/install_assets.go b/internal/release/install_assets.go
index dd1d0ad3..faae403b 100644
--- a/internal/release/install_assets.go
+++ b/internal/release/install_assets.go
@@ -4,19 +4,34 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
+ "io"
"net/http"
"os"
"path/filepath"
"reflect"
"strings"
+ "sync"
)
+// InstallAssets is configured before use and must not be copied after use.
type InstallAssets struct {
Root, Version string
Manifest Manifest
+ mu sync.Mutex
+ files map[string]os.FileInfo
+ available bool
+ digest func(io.Reader) (string, error)
}
-func (a InstallAssets) read(name string) ([]byte, error) {
+func NewInstallAssets(root, version string, manifest Manifest) *InstallAssets {
+ a := &InstallAssets{Root: root, Version: version, Manifest: manifest}
+ a.Available()
+ return a
+}
+
+var installAssetNames = []string{"install-manifest.json", "equipo-runner", "equipo-tool-proxy", "install-v1.sh"}
+
+func (a *InstallAssets) open(name string) (*os.File, error) {
if !filepath.IsAbs(a.Root) || filepath.Clean(a.Root) != a.Root {
return nil, errManifest
}
@@ -25,46 +40,110 @@ func (a InstallAssets) read(name string) ([]byte, error) {
if e != nil || real != path {
return nil, errManifest
}
- i, e := os.Stat(path)
- if e != nil || !i.Mode().IsRegular() || i.Size() > 128<<20 {
+ f, e := os.Open(path)
+ if e != nil {
+ return nil, e
+ }
+ i, e := f.Stat()
+ limit := int64(128 << 20)
+ if name == "install-manifest.json" || name == "install-v1.sh" {
+ limit = 1 << 20
+ }
+ if e != nil || !i.Mode().IsRegular() || i.Size() > limit {
+ f.Close()
return nil, errManifest
}
- return os.ReadFile(path)
+ return f, nil
+}
+func sameInstallFile(a, b os.FileInfo) bool {
+ return a != nil && b != nil && os.SameFile(a, b) && a.Size() == b.Size() && a.ModTime() == b.ModTime() && a.Mode() == b.Mode()
+}
+func (a *InstallAssets) unchanged() bool {
+ for _, name := range installAssetNames {
+ f, e := a.open(name)
+ if e != nil {
+ return false
+ }
+ i, e := f.Stat()
+ f.Close()
+ if e != nil || !sameInstallFile(a.files[name], i) {
+ return false
+ }
+ }
+ return true
+}
+
+// CachedAvailable only checks metadata. Page rendering never hashes a release.
+func (a *InstallAssets) CachedAvailable() bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+ return a.available && a.unchanged()
}
-func (a InstallAssets) Available() bool {
+func (a *InstallAssets) Available() bool {
+ a.mu.Lock()
+ defer a.mu.Unlock()
if !ValidInstallVersion(a.Version) || !a.Manifest.InstallCertified() {
return false
}
- b, e := a.read("install-manifest.json")
- if e != nil {
- return false
+ if a.files != nil && a.unchanged() {
+ return a.available
+ }
+ a.available = false
+ files := map[string]*os.File{}
+ infos := map[string]os.FileInfo{}
+ defer func() {
+ for _, f := range files {
+ f.Close()
+ }
+ }()
+ for _, name := range installAssetNames {
+ f, e := a.open(name)
+ if e != nil {
+ a.files = nil
+ return false
+ }
+ files[name] = f
+ infos[name], e = f.Stat()
+ if e != nil {
+ a.files = nil
+ return false
+ }
}
+ a.files = infos
var m InstallManifest
- if json.Unmarshal(b, &m) != nil || m.Validate(a.Version) != nil || !reflect.DeepEqual(m.Release, a.Manifest) {
+ decoder := json.NewDecoder(files["install-manifest.json"])
+ if decoder.Decode(&m) != nil || m.Validate(a.Version) != nil || !reflect.DeepEqual(m.Release, a.Manifest) {
return false
}
- binary, e := a.read("equipo-runner")
- if e != nil {
+ if decoder.Decode(new(any)) != io.EOF {
return false
}
- hash := sha256.Sum256(binary)
- if hex.EncodeToString(hash[:]) != m.RunnerSHA256 {
- return false
+ digest := a.digest
+ if digest == nil {
+ digest = func(r io.Reader) (string, error) {
+ h := sha256.New()
+ _, e := io.Copy(h, r)
+ return hex.EncodeToString(h.Sum(nil)), e
+ }
}
- helper, e := a.read("equipo-tool-proxy")
- if e != nil {
- return false
+ for name, want := range map[string]string{"equipo-runner": m.RunnerSHA256, "equipo-tool-proxy": a.Manifest.ToolProxySHA256()} {
+ got, e := digest(files[name])
+ if e != nil || want == "" || got != want {
+ return false
+ }
}
- helperHash := sha256.Sum256(helper)
- if a.Manifest.ToolProxySHA256() == "" || hex.EncodeToString(helperHash[:]) != a.Manifest.ToolProxySHA256() {
+ // A replacement or write during verification must not enter the cache.
+ if !a.unchanged() {
+ a.files = nil
return false
}
- _, e = a.read("install-v1.sh")
- return e == nil
+ a.available = true
+ return true
}
-func (a InstallAssets) ServeHTTP(w http.ResponseWriter, r *http.Request) {
- name := strings.TrimPrefix(r.URL.Path, "/releases/"+a.Version+"/")
- if r.Method != "GET" || (name != "install-v1.sh" && name != "install-manifest.json" && name != "equipo-runner" && name != "equipo-tool-proxy") {
+func (a *InstallAssets) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ prefix := "/releases/" + a.Version + "/"
+ name := strings.TrimPrefix(r.URL.Path, prefix)
+ if !strings.HasPrefix(r.URL.Path, prefix) || (r.Method != "GET" && r.Method != "HEAD") || (name != "install-v1.sh" && name != "install-manifest.json" && name != "equipo-runner" && name != "equipo-tool-proxy") {
w.WriteHeader(http.StatusNotFound)
return
}
@@ -72,13 +151,22 @@ func (a InstallAssets) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
- b, e := a.read(name)
+ f, e := a.open(name)
if e != nil {
w.WriteHeader(http.StatusServiceUnavailable)
return
}
+ defer f.Close()
+ i, e := f.Stat()
+ a.mu.Lock()
+ valid := e == nil && a.available && sameInstallFile(a.files[name], i)
+ a.mu.Unlock()
+ if !valid {
+ w.WriteHeader(http.StatusServiceUnavailable)
+ return
+ }
w.Header().Set("Content-Type", "application/octet-stream")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
- _, _ = w.Write(b)
+ http.ServeContent(w, r, name, i.ModTime(), f)
}
diff --git a/internal/release/install_script_test.go b/internal/release/install_script_test.go
new file mode 100644
index 00000000..b8444fbd
--- /dev/null
+++ b/internal/release/install_script_test.go
@@ -0,0 +1,75 @@
+package release
+
+import (
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+func TestOnboardingInstallShell(t *testing.T) {
+ script, err := os.ReadFile("../../packaging/install/install-v1.sh")
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, platform := range []string{"Linux/x86_64", "Darwin/x86_64", "Linux/aarch64", "truncated"} {
+ t.Run(platform, func(t *testing.T) {
+ root := t.TempDir()
+ parts := strings.Split(platform+"/unused", "/")
+ write := func(name, body string) {
+ t.Helper()
+ if err := os.WriteFile(filepath.Join(root, name), []byte(body), 0700); err != nil {
+ t.Fatal(err)
+ }
+ }
+ write("uname", "#!/bin/sh\necho uname >> \"$TMPDIR/started\"\ncase \"$1\" in -s) echo "+parts[0]+";; -m) echo "+parts[1]+";; esac\n")
+ write("curl", `#!/bin/sh
+echo download >> "$TMPDIR/downloads"
+while [ "$1" != "-o" ]; do shift; done
+case "$2" in
+*/manifest.json) printf '%s' '{"version":"fixture-16","target":"linux/amd64","runner_sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","release":{"live_gate_copy_reviewed":true,"direct_policies":[{}],"certifications":[{}]}}' > "$2" ;;
+*) printf '#!/bin/sh\nexit 99\n' > "$2" ;;
+esac
+`)
+ write("sha256sum", `#!/bin/sh
+cat > "$TMPDIR/checksum-input"
+echo checked > "$TMPDIR/checked"
+exit 1
+`)
+ input := string(script)
+ if platform == "truncated" {
+ input = input[:strings.Index(input, "curl --fail")]
+ }
+ cmd := exec.Command("sh", "-s", "--", "https://equipo.example", "fixture-16", "team")
+ cmd.Stdin = strings.NewReader(input)
+ cmd.Env = append(os.Environ(), "PATH="+root+":"+os.Getenv("PATH"), "TMPDIR="+root)
+ out, err := cmd.CombinedOutput()
+ if err == nil {
+ t.Fatalf("expected refusal or fake download failure: %s", out)
+ }
+ b, _ := os.ReadFile(filepath.Join(root, "downloads"))
+ if platform == "Linux/x86_64" {
+ if string(b) != "download\ndownload\n" {
+ t.Fatalf("supported host did not reach download: %s %s", b, out)
+ }
+ if _, e := os.Stat(filepath.Join(root, "checked")); e != nil {
+ t.Fatal("supported host skipped checksum")
+ }
+ } else if len(b) != 0 {
+ t.Fatalf("refused host downloaded: %s", b)
+ }
+ if platform == "truncated" {
+ if _, e := os.Stat(filepath.Join(root, "started")); !os.IsNotExist(e) {
+ t.Fatal("truncated stream executed commands")
+ }
+ }
+ entries, _ := os.ReadDir(root)
+ for _, e := range entries {
+ if strings.HasPrefix(e.Name(), "equipo-bootstrap-") {
+ t.Fatal("scratch leaked")
+ }
+ }
+ })
+ }
+}
diff --git a/internal/release/install_test.go b/internal/release/install_test.go
index 840084b6..7d7bae7d 100644
--- a/internal/release/install_test.go
+++ b/internal/release/install_test.go
@@ -4,6 +4,7 @@ import (
"crypto/sha256"
"encoding/json"
"fmt"
+ "io"
"net/http/httptest"
"os"
"os/exec"
@@ -54,7 +55,13 @@ func TestOnboardingInstallPackaging(t *testing.T) {
if manifest.RunnerSHA256 != fmt.Sprintf("%x", sha256.Sum256(binary)) {
t.Fatal("checksum mismatch")
}
- assets := InstallAssets{Root: root, Version: "fixture-16", Manifest: m}
+ hashes := 0
+ assets := InstallAssets{Root: root, Version: "fixture-16", Manifest: m, digest: func(r io.Reader) (string, error) {
+ hashes++
+ h := sha256.New()
+ _, e := io.Copy(h, r)
+ return fmt.Sprintf("%x", h.Sum(nil)), e
+ }}
if !assets.Available() {
t.Fatal("fixture assets unavailable")
}
@@ -65,7 +72,38 @@ func TestOnboardingInstallPackaging(t *testing.T) {
t.Fatal("missing release asset", name, w.Code)
}
}
+ for range 3 {
+ if !assets.Available() || !assets.CachedAvailable() {
+ t.Fatal("cached assets unavailable")
+ }
+ }
+ if hashes != 2 {
+ t.Fatalf("rehashed unchanged assets: %d", hashes)
+ }
+ w := httptest.NewRecorder()
+ req := httptest.NewRequest("GET", "/releases/fixture-16/equipo-runner", nil)
+ req.Header.Set("Range", "bytes=0-6")
+ assets.ServeHTTP(w, req)
+ if w.Code != 206 || w.Body.String() != "fixture" {
+ t.Fatal("missing streamed range", w.Code, w.Body.String())
+ }
+ write("install-manifest.json", append(append([]byte(nil), raw...), []byte("{}")...))
+ if assets.Available() {
+ t.Fatal("trailing manifest data accepted")
+ }
+ write("install-manifest.json", raw)
+ if !assets.Available() {
+ t.Fatal("restored manifest unavailable")
+ }
+ hashesBeforeMetadata := hashes
+ // Same inode, changed size/mtime must invalidate without hashing on the page.
write("equipo-runner", []byte("changed"))
+ if assets.CachedAvailable() {
+ t.Fatal("cached availability ignored changed file")
+ }
+ if hashes != hashesBeforeMetadata {
+ t.Fatal("onboarding availability hashed files")
+ }
if assets.Available() {
t.Fatal("tampered binary served")
}
diff --git a/internal/runner/connections.go b/internal/runner/connections.go
index a0593a1e..27be1dce 100644
--- a/internal/runner/connections.go
+++ b/internal/runner/connections.go
@@ -96,9 +96,12 @@ type DirectAccount struct {
func loadDirectBindings(path string) ([]AccountBinding, error) {
var bs []AccountBinding
if e := privateJSON(path, &bs); e != nil {
+ if os.IsNotExist(e) {
+ return nil, nil
+ }
return nil, e
}
- if len(bs) == 0 || len(bs) > 256 {
+ if len(bs) > 256 {
return nil, provider.ErrIdentity
}
seen := map[string]bool{}
diff --git a/internal/runner/enrol.go b/internal/runner/enrol.go
index 1e873dd4..d7313a63 100644
--- a/internal/runner/enrol.go
+++ b/internal/runner/enrol.go
@@ -6,6 +6,7 @@ import (
"crypto/ed25519"
"crypto/rand"
"encoding/base64"
+ "errors"
"io"
"net/http"
"net/url"
@@ -123,13 +124,13 @@ func Enrol(ctx context.Context, c Config, output io.Writer) (resultErr error) {
pendingPath := filepath.Join(c.StateDir, "enrolment.json")
var pending pendingEnrolment
err = privateJSON(pendingPath, &pending)
- if err == nil && (pending.Origin != c.Origin || pending.Code.InstanceID != c.InstanceID || pending.Label != label) {
- return provider.ErrIdentity
- }
if err != nil && !os.IsNotExist(err) {
- return err
+ // Malformed JSON is unusable retry state; permission and I/O errors still deny.
+ if !errors.Is(err, runnerproto.ErrInvalid) {
+ return err
+ }
}
- if os.IsNotExist(err) || !time.Now().Before(pending.Code.ExpiresAt) {
+ if err != nil || !pending.usable(c.Origin, c.InstanceID) {
var code runnerproto.DeviceCode
_, err = post("/api/enrolments", runnerproto.BeginEnrolmentRequest{Version: 1, MachinePublicKey: base64.RawURLEncoding.EncodeToString(ed25519.PrivateKey(key).Public().(ed25519.PublicKey)), Label: label}, &code)
if err != nil {
@@ -143,9 +144,7 @@ func Enrol(ctx context.Context, c Config, output io.Writer) (resultErr error) {
}
}
code, proof := pending.Code, pending.Proof
- u, err := url.Parse(code.VerificationURI)
- origin, _ := url.Parse(c.Origin)
- if err != nil || u.Scheme != origin.Scheme || u.Host != origin.Host || u.User != nil || u.Path != "/runners/enrol" || u.RawQuery != "" || u.Fragment != "" || code.InstanceID != c.InstanceID || code.PollIntervalSeconds < 5 || code.PollIntervalSeconds > 60 || !time.Now().Before(code.ExpiresAt) {
+ if !pending.usable(c.Origin, c.InstanceID) {
return provider.ErrIdentity
}
if _, err = io.WriteString(output, "["+code.VerificationURI+"]("+code.VerificationURI+")\n"+code.UserCode+"\n"); err != nil {
@@ -198,3 +197,22 @@ func (c Config) validateEnrolment() error {
}
return nil
}
+
+func (p pendingEnrolment) usable(origin, instance string) bool {
+ u, e := url.Parse(p.Code.VerificationURI)
+ base, _ := url.Parse(origin)
+ return e == nil && p.Origin == origin && p.Code.InstanceID == instance &&
+ u.Scheme == base.Scheme && u.Host == base.Host && u.User == nil && u.Path == "/runners/enrol" && u.RawQuery == "" && u.Fragment == "" &&
+ p.Code.Version == 1 && p.Code.EnrolmentID != "" && p.Code.DeviceSecret != "" && p.Code.UserCode != "" && p.Code.Challenge != "" &&
+ p.Proof.EnrolmentID == p.Code.EnrolmentID && p.Proof.Challenge == p.Code.Challenge && p.Proof.Signature != "" && p.Proof.ExchangeNonce != "" &&
+ p.Label != "" && len(p.Label) <= 128 && !strings.ContainsAny(p.Label, "\r\n\x00") &&
+ p.Code.PollIntervalSeconds >= 5 && p.Code.PollIntervalSeconds <= 60 && time.Now().Before(p.Code.ExpiresAt)
+}
+
+func DefaultMachineLabel(stateDir, origin, instance string) (string, error) {
+ var saved pendingEnrolment
+ if privateJSON(filepath.Join(stateDir, "enrolment.json"), &saved) == nil && saved.usable(origin, instance) {
+ return saved.Label, nil
+ }
+ return os.Hostname()
+}
diff --git a/internal/runner/onboarding_test.go b/internal/runner/onboarding_test.go
index f95df12b..78d448aa 100644
--- a/internal/runner/onboarding_test.go
+++ b/internal/runner/onboarding_test.go
@@ -4,9 +4,11 @@ import (
"bytes"
"context"
"encoding/json"
+ "errors"
"io"
"net/http"
"os"
+ "path/filepath"
"strings"
"testing"
"time"
@@ -71,3 +73,130 @@ func TestOnboardingPairingBound(t *testing.T) {
}
}
func (w *enrolOutput) WriteString(s string) (int, error) { return w.Write([]byte(s)) }
+
+func TestOnboardingPairingLabelRetry(t *testing.T) {
+ old := http.DefaultTransport
+ t.Cleanup(func() { http.DefaultTransport = old })
+ for _, state := range []string{"valid", "expired", "unusable", "malformed"} {
+ t.Run(state, func(t *testing.T) {
+ c := configFixture(t)
+ c.MachineLabel = "Edited machine"
+ calls := 0
+ http.DefaultTransport = enrolTransport(func(r *http.Request) (*http.Response, error) {
+ calls++
+ var in runnerproto.BeginEnrolmentRequest
+ if e := json.NewDecoder(r.Body).Decode(&in); e != nil {
+ t.Fatal(e)
+ }
+ want := "Edited machine"
+ if calls > 1 {
+ want = "New label"
+ }
+ if in.Label != want {
+ t.Fatalf("label %q want %q", in.Label, want)
+ }
+ code := runnerproto.DeviceCode{Version: 1, EnrolmentID: "fixture", InstanceID: c.InstanceID, DeviceSecret: strings.Repeat("s", 43), UserCode: "0123456789", Challenge: "challenge", VerificationURI: c.Origin + "/runners/enrol", ExpiresAt: time.Now().Add(time.Minute), PollIntervalSeconds: 5}
+ b, _ := json.Marshal(code)
+ return &http.Response{StatusCode: 201, Body: io.NopCloser(bytes.NewReader(b)), Header: http.Header{}}, nil
+ })
+ attempt := func() {
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ out := &enrolOutput{cancel: cancel}
+ _ = Enrol(ctx, c, out)
+ if !strings.Contains(out.String(), "0123456789") {
+ t.Fatalf("retry blocked: %q", out.String())
+ }
+ }
+ attempt()
+ defaultLabel, e := DefaultMachineLabel(c.StateDir, c.Origin, c.InstanceID)
+ if e != nil || defaultLabel != "Edited machine" {
+ t.Fatalf("saved prompt default: %q %v", defaultLabel, e)
+ }
+ path := filepath.Join(c.StateDir, "enrolment.json")
+ var saved pendingEnrolment
+ if e := privateJSON(path, &saved); e != nil {
+ t.Fatal(e)
+ }
+ switch state {
+ case "expired":
+ saved.Code.ExpiresAt = time.Now().Add(-time.Minute)
+ case "unusable":
+ saved.Code.VerificationURI = "https://wrong.example/runners/enrol"
+ }
+ if e := runnerproto.JournalCredentials(path, saved); e != nil {
+ t.Fatal(e)
+ }
+ if state == "malformed" {
+ if e := os.WriteFile(path, []byte("{"), 0600); e != nil {
+ t.Fatal(e)
+ }
+ }
+ c.MachineLabel = "New label"
+ attempt()
+ wantCalls := 2
+ if state == "valid" {
+ wantCalls = 1
+ }
+ if calls != wantCalls {
+ t.Fatalf("requests %d want %d", calls, wantCalls)
+ }
+ })
+ }
+}
+
+func TestOnboardingServiceWithoutAccounts(t *testing.T) {
+ old := http.DefaultTransport
+ t.Cleanup(func() { http.DefaultTransport = old })
+ for _, state := range []string{"missing", "empty", "invalid"} {
+ t.Run(state, func(t *testing.T) {
+ c := directRuntimeFixture(t)
+ if state == "missing" {
+ mustJournal(t, os.Remove(c.AccountBindingsPath))
+ } else {
+ data := "[]"
+ if state == "invalid" {
+ data = "{"
+ }
+ mustJournal(t, os.WriteFile(c.AccountBindingsPath, []byte(data), 0600))
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ heartbeats, polls, idle := 0, 0, 0
+ c.Report = func(key string) {
+ if key == "runner.waiting_accounts" {
+ idle++
+ }
+ }
+ http.DefaultTransport = enrolTransport(func(req *http.Request) (*http.Response, error) {
+ switch {
+ case strings.HasSuffix(req.URL.Path, "/heartbeat"):
+ var h runnerproto.HeartbeatRequest
+ if e := json.NewDecoder(req.Body).Decode(&h); e != nil {
+ t.Fatal(e)
+ }
+ if string(h.Reports) != "[]" {
+ t.Fatalf("invented connections: %s", h.Reports)
+ }
+ heartbeats++
+ time.AfterFunc(20*time.Millisecond, cancel)
+ case strings.HasSuffix(req.URL.Path, "/poll"):
+ polls++
+ default:
+ t.Fatalf("unexpected request while idle: %s", req.URL.Path)
+ }
+ return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(`{"version":2,"result":null}`)), Header: http.Header{}}, nil
+ })
+ err := Run(ctx, c)
+ if state == "invalid" {
+ if err == nil || heartbeats != 0 {
+ t.Fatal("invalid bindings treated as empty", err)
+ }
+ return
+ }
+ if !errors.Is(err, context.Canceled) || heartbeats != 1 || polls != 0 || idle < 1 {
+ t.Fatalf("not idle until cancelled: err=%v heartbeats=%d polls=%d idle=%d", err, heartbeats, polls, idle)
+ }
+ })
+ }
+}
diff --git a/internal/runner/runtime.go b/internal/runner/runtime.go
index 15310208..6676c2c1 100644
--- a/internal/runner/runtime.go
+++ b/internal/runner/runtime.go
@@ -208,16 +208,27 @@ func (r *Runtime) Poll(ctx context.Context) ([]runnerproto.Assignment, error) {
r.mu.Lock()
r.current = nil
r.mu.Unlock()
- reports, err := r.discoverNamespaces(ctx)
- if err != nil {
- return nil, err
- }
- if err = r.api.Heartbeat(ctx, reports); err != nil {
- return nil, err
+ for {
+ reports, err := r.discoverNamespaces(ctx)
+ if err != nil {
+ return nil, err
+ }
+ if len(reports) == 0 && r.cfg.Report != nil {
+ r.cfg.Report("runner.waiting_accounts")
+ }
+ if err = r.api.Heartbeat(ctx, reports); err != nil {
+ return nil, err
+ }
+ r.mu.Lock()
+ r.lastReports = append([]runnerproto.ConnectionReport(nil), reports...)
+ r.mu.Unlock()
+ if len(reports) > 0 {
+ break
+ }
+ if err := waitService(ctx, 5*time.Second); err != nil {
+ return nil, err
+ }
}
- r.mu.Lock()
- r.lastReports = append([]runnerproto.ConnectionReport(nil), reports...)
- r.mu.Unlock()
return r.api.Poll(ctx)
}
func (r *Runtime) Claim(ctx context.Context, q runnerproto.ClaimRequest) (runnerproto.ClaimResponse, error) {
diff --git a/internal/runner/setup/install.go b/internal/runner/setup/install.go
index f5b78ce3..86eb38ce 100644
--- a/internal/runner/setup/install.go
+++ b/internal/runner/setup/install.go
@@ -31,6 +31,7 @@ type InstallResult struct {
var errUnavailable = errors.New("runner.install.unavailable")
type installHost struct {
+ manifest release.Manifest
home, goos, goarch string
fetch func(context.Context, string, int64) ([]byte, error)
preflight func(context.Context, string, release.InstallManifest) []string
@@ -44,7 +45,7 @@ func InstallUser(ctx context.Context, opts InstallOptions) (InstallResult, error
if err != nil {
return InstallResult{State: "unavailable", Missing: []string{"runner.install.destination"}}, errUnavailable
}
- return installUser(ctx, opts, installHost{home: home, goos: runtime.GOOS, goarch: runtime.GOARCH, fetch: fetchRelease, preflight: containmentPreflight, service: enableService, lingering: readLingering, serviceAvailable: userServiceAvailable})
+ return installUser(ctx, opts, installHost{manifest: release.BuildManifest(), home: home, goos: runtime.GOOS, goarch: runtime.GOARCH, fetch: fetchRelease, preflight: containmentPreflight, service: enableService, lingering: readLingering, serviceAvailable: userServiceAvailable})
}
func installUser(ctx context.Context, o InstallOptions, h installHost) (r InstallResult, err error) {
r = InstallResult{Version: o.Release, State: "unavailable"}
@@ -114,7 +115,7 @@ func installUser(ctx context.Context, o InstallOptions, h installHost) (r Instal
return fail("runner.install.release")
}
helperHash := sha256.Sum256(helper)
- if m.Release.ToolProxySHA256() == "" || hex.EncodeToString(helperHash[:]) != m.Release.ToolProxySHA256() {
+ if m.Release.ToolProxySHA256() == "" || hex.EncodeToString(helperHash[:]) != m.Release.ToolProxySHA256() || hex.EncodeToString(helperHash[:]) != h.manifest.ToolProxySHA256() {
return fail("runner.install.checksum")
}
dir := filepath.Join(o.Root, "releases", o.Release)
@@ -183,19 +184,33 @@ func privateDirectory(path string) bool {
var stat unix.Stat_t
return unix.Stat(path, &stat) == nil && stat.Uid == uint32(os.Geteuid()) && unix.Access(path, unix.W_OK) == nil
}
+
+const installOwnership = "user.equipo.installer.sha256"
+
func writeOwned(path string, data []byte, mode os.FileMode) error {
+ replace := false
if i, e := os.Lstat(path); e == nil {
if !i.Mode().IsRegular() {
return errUnavailable
}
+ var stat unix.Stat_t
+ if unix.Lstat(path, &stat) != nil || stat.Uid != uint32(os.Geteuid()) {
+ return errUnavailable
+ }
old, e := os.ReadFile(path)
if e != nil {
return e
}
- if string(old) == string(data) {
+ marker := make([]byte, 64)
+ n, e := unix.Getxattr(path, installOwnership, marker)
+ sum := sha256.Sum256(old)
+ if e != nil || n != 64 || string(marker) != hex.EncodeToString(sum[:]) {
+ return errUnavailable
+ }
+ if string(old) == string(data) && i.Mode().Perm() == mode {
return nil
}
- return errUnavailable
+ replace = true
} else if !os.IsNotExist(e) {
return e
}
@@ -204,19 +219,29 @@ func writeOwned(path string, data []byte, mode os.FileMode) error {
return e
}
defer os.Remove(f.Name())
+ defer f.Close()
if e = f.Chmod(mode); e != nil {
- f.Close()
return e
}
- _, e = f.Write(data)
- if e == nil {
- e = f.Sync()
+ if _, e = f.Write(data); e != nil {
+ return e
}
- closeErr := f.Close()
- if e = errors.Join(e, closeErr); e != nil {
+ sum := sha256.Sum256(data)
+ if e = unix.Fsetxattr(int(f.Fd()), installOwnership, []byte(hex.EncodeToString(sum[:])), 0); e != nil {
return e
}
- if e = os.Link(f.Name(), path); e != nil {
+ if e = f.Sync(); e != nil {
+ return e
+ }
+ if e = f.Close(); e != nil {
+ return e
+ }
+ if replace {
+ e = os.Rename(f.Name(), path)
+ } else {
+ e = os.Link(f.Name(), path)
+ }
+ if e != nil {
return e
}
dir, e := os.Open(filepath.Dir(path))
diff --git a/internal/runner/setup/install_test.go b/internal/runner/setup/install_test.go
index bfdd51a2..3f3b36b9 100644
--- a/internal/runner/setup/install_test.go
+++ b/internal/runner/setup/install_test.go
@@ -30,7 +30,7 @@ func installFixture(t *testing.T) (InstallOptions, installHost, *int) {
t.Fatal(err)
}
calls := new(int)
- h := installHost{home: home, goos: "linux", goarch: "amd64", fetch: func(_ context.Context, url string, _ int64) ([]byte, error) {
+ h := installHost{manifest: m.Release, home: home, goos: "linux", goarch: "amd64", fetch: func(_ context.Context, url string, _ int64) ([]byte, error) {
if strings.HasSuffix(url, "install-manifest.json") {
return raw, nil
}
@@ -243,3 +243,81 @@ func TestOnboardingContainmentPreflightProbe(t *testing.T) {
})
}
}
+
+func TestOnboardingInstallUpgrade(t *testing.T) {
+ o, h, calls := installFixture(t)
+ first, e := installUser(context.Background(), o, h)
+ if e != nil {
+ t.Fatal(e)
+ }
+ if e = SaveServiceEnvironment(o.Root, []byte("version=1")); e != nil {
+ t.Fatal(e)
+ }
+ oldFetch := h.fetch
+ o.Release = "fixture-17"
+ h.fetch = func(ctx context.Context, url string, n int64) ([]byte, error) {
+ b, e := oldFetch(ctx, url, n)
+ if strings.HasSuffix(url, "install-manifest.json") {
+ var m release.InstallManifest
+ if e = json.Unmarshal(b, &m); e != nil {
+ return nil, e
+ }
+ m.Version = o.Release
+ b, e = json.Marshal(m)
+ }
+ return b, e
+ }
+ next, e := installUser(context.Background(), o, h)
+ if e != nil || *calls != 2 || next.BinaryPath == first.BinaryPath {
+ t.Fatalf("upgrade failed: %+v %v calls=%d", next, e, *calls)
+ }
+ if e = SaveServiceEnvironment(o.Root, []byte("version=2")); e != nil {
+ t.Fatal("environment upgrade", e)
+ }
+ b, _ := os.ReadFile(next.ServicePath)
+ if !strings.Contains(string(b), next.BinaryPath) {
+ t.Fatal("old service binary")
+ }
+ for _, name := range []string{"unowned", "equipo-runner.service"} {
+ path := filepath.Join(o.Root, name)
+ if e = os.WriteFile(path, []byte("person's file"), 0600); e != nil {
+ t.Fatal(e)
+ }
+ if e = writeOwned(path, []byte("overwrite"), 0600); e == nil {
+ t.Fatal("overwrote unowned or edited file", name)
+ }
+ }
+}
+
+func TestOnboardingInstallEmbeddedProxy(t *testing.T) {
+ o, h, calls := installFixture(t)
+ h.manifest.Binaries = []release.BinaryDigest{{Name: "equipo-tool-proxy", Version: h.manifest.LauncherVersion, SHA256: strings.Repeat("b", 64)}}
+ got, e := installUser(context.Background(), o, h)
+ if e == nil || got.State != "unavailable" || *calls != 0 {
+ t.Fatalf("embedded helper mismatch accepted: %+v %v", got, e)
+ }
+}
+
+func TestOnboardingServiceUpgrade(t *testing.T) {
+ root := t.TempDir()
+ systemctl := filepath.Join(root, "systemctl")
+ // The fake service manager leaves an already-running unit alone on enable --now.
+ script := "#!/bin/sh\ncase \"$*\" in\n*restart*) cp \"$TMPDIR/unit-version\" \"$TMPDIR/running-version\" ;;\n*enable*--now*) if [ ! -f \"$TMPDIR/running-version\" ]; then cp \"$TMPDIR/unit-version\" \"$TMPDIR/running-version\"; fi ;;\nesac\n"
+ if e := os.WriteFile(systemctl, []byte(script), 0700); e != nil {
+ t.Fatal(e)
+ }
+ t.Setenv("PATH", root+":"+os.Getenv("PATH"))
+ t.Setenv("TMPDIR", root)
+ for _, version := range []string{"v1", "v2"} {
+ if e := os.WriteFile(filepath.Join(root, "unit-version"), []byte(version), 0600); e != nil {
+ t.Fatal(e)
+ }
+ if e := enableService(context.Background(), filepath.Join(root, "equipo-runner.service")); e != nil {
+ t.Fatal(e)
+ }
+ b, e := os.ReadFile(filepath.Join(root, "running-version"))
+ if e != nil || string(b) != version {
+ t.Fatalf("service kept old release: %q want %q: %v", b, version, e)
+ }
+ }
+}
diff --git a/internal/runner/setup/service.go b/internal/runner/setup/service.go
index 9e8f7881..a3db761f 100644
--- a/internal/runner/setup/service.go
+++ b/internal/runner/setup/service.go
@@ -30,7 +30,7 @@ func readLingering(ctx context.Context) (bool, error) {
}
}
func enableService(ctx context.Context, path string) error {
- for _, args := range [][]string{{"--user", "link", path}, {"--user", "daemon-reload"}, {"--user", "enable", "--now", "equipo-runner.service"}} {
+ for _, args := range [][]string{{"--user", "link", path}, {"--user", "daemon-reload"}, {"--user", "enable", "equipo-runner.service"}, {"--user", "restart", "equipo-runner.service"}} {
if e := exec.CommandContext(ctx, "systemctl", args...).Run(); e != nil {
return e
}
diff --git a/packaging/install/install-v1.sh b/packaging/install/install-v1.sh
index 15fa8685..594abf30 100644
--- a/packaging/install/install-v1.sh
+++ b/packaging/install/install-v1.sh
@@ -1,5 +1,9 @@
#!/bin/sh
+main() {
set -eu
+if [ "$(uname -s)" != Linux ] || [ "$(uname -m)" != x86_64 ]; then
+ exit 1
+fi
umask 077
origin=$1
version=$2
@@ -24,10 +28,11 @@ assert re.fullmatch('[0-9a-f]{64}', m['runner_sha256'])
print(m['runner_sha256'])
PY
)
-[ "$(uname -s)" = Linux ] && [ "$(uname -m)" = x86_64 ]
curl --fail --silent --show-error --proto '=https' --tlsv1.2 "$origin/releases/$version/equipo-runner" -o "$scratch/equipo-runner"
printf '%s %s\n' "$digest" "$scratch/equipo-runner" | sha256sum --check --status
chmod 700 "$scratch/equipo-runner"
"$scratch/equipo-runner" verify-install-manifest "$scratch/manifest.json" >/dev/null
# Prompts read the terminal because the bootstrap script may arrive on stdin.
"$scratch/equipo-runner" install --release "$version" --origin "$origin" --instance "$instance" </dev/tty
+}
+main "$@"