feat: add versioned user runner installation and pairing
Persist independent onboarding prerequisites from accepted invitations. Add certified versioned runner and tool proxy installation, containment checks, typed pairing confirmation, and fixture coverage. Record pending copy and guard mutation evidence for the controller.
50 files changed,
+2,862
−430
.rastrillo/budgets.txt+1 −1Makefile+2 −0cmd/equipo-runner/install.go+108 −0cmd/equipo-runner/install_config.go+51 −0cmd/equipo-runner/main.go+10 −0cmd/equipo-runner/onboarding_test.go+17 −0docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md+146 −0internal/equipo/app.go+5 −1internal/equipo/config.go+2 −1internal/equipo/copy.go+81 −0internal/equipo/enrolment.go+11 −203internal/equipo/handlers.go+2 −1internal/equipo/migrations/0028_onboarding.sql+9 −0internal/equipo/migrations/schema.sql+9 −0internal/equipo/onboarding.go+34 −0internal/equipo/render.go+1 −1internal/equipo/runner_handlers.go+34 −8internal/equipo/runner_models.go+4 −38internal/equipo/setup/enrolment.go+241 −0internal/equipo/setup/invite_handlers.go+1 −1internal/equipo/setup/invites.go+4 −1internal/equipo/setup/onboarding.go+190 −0internal/equipo/setup/onboarding_handlers.go+92 −0internal/equipo/setup/onboarding_test.go+207 −0internal/equipo/setup/pairing.go+32 −0internal/equipo/setup/runner_models.go+45 −0internal/equipo/templates/onboarding.html+33 −0internal/equipo/templates/runners.html+5 −1internal/equipotest/enrolment_fixture_test.go+17 −0internal/equipotest/enrolment_test.go+30 −53internal/equipotest/runner_release_test.go+1 −0internal/plan3test/conversation_browser_test.go+0 −29internal/plan3test/forms_fixture.go+125 −0internal/plan3test/onboarding_install_test.go+111 −0internal/plan3test/person_api_test.go+0 −37internal/plan3test/plans_test.go+0 −26internal/plan3test/playbooks_forms_test.go+0 −19internal/release/install.go+78 −0internal/release/install_assets.go+84 −0internal/release/install_test.go+90 −0internal/runner/config.go+2 −1internal/runner/enrol.go+56 −8internal/runner/onboarding_test.go+73 −0internal/runner/setup/budget_test.go+9 −0internal/runner/setup/install.go+248 −0internal/runner/setup/install_test.go+245 −0internal/runner/setup/preflight.go+179 −0internal/runner/setup/service.go+79 −0packaging/install/install-v1.sh+33 −0scripts/runner-install-manifest.py+25 −0
CI failed — run details
Intent
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index e7c4bf50..189e064d 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 9300 8600 Task 7 fix round 3 keeps journal, service, HTTP classification and restart/refusal matrix tests beside the runner. Measured 9296 source and 8517 test lines; targeted coordinator runner tests measured 63.504s. The source and 330s time ceilings are unchanged. |
| +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. |
| 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/Makefile b/Makefile| index 6a236d2d..861aae25 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -181,4 +181,6 @@ release-runner: copy-release-check direct-release-check |
| -o $(RUNNER_RELEASE_DIR)/equipo-runner ./cmd/equipo-runner |
| cp packaging/equipo-runner.service internal/release/manifest.json $(RUNNER_RELEASE_DIR)/ |
| cp -R internal/release/evidence $(RUNNER_RELEASE_DIR)/evidence |
| + cp packaging/install/install-v1.sh $(RUNNER_RELEASE_DIR)/install-v1.sh |
| + python3 scripts/runner-install-manifest.py $(RUNNER_RELEASE_DIR) "$$(git rev-parse --short HEAD)" |
| @git rev-parse HEAD > $(RUNNER_RELEASE_DIR)/COMMIT |
diff --git a/cmd/equipo-runner/install.go b/cmd/equipo-runner/install.go| new file mode 100644 |
| index 00000000..5c45bc99 |
| --- /dev/null |
| +++ b/cmd/equipo-runner/install.go |
| @@ -0,0 +1,108 @@ |
| +package main |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "encoding/json" |
| + "flag" |
| + "fmt" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/release" |
| + "amadan.net/oficina/equipo/internal/runner" |
| + runnersetup "amadan.net/oficina/equipo/internal/runner/setup" |
| + "amadan.net/rastrillo/rastrillo" |
| +) |
| + |
| +func installRunner(ctx context.Context, args []string, input io.Reader, out, errout io.Writer, getenv func(string) string) int { |
| + fail := func(key string) int { fmt.Fprintln(errout, equipo.RunnerSetupCopy(key)); return 1 } |
| + flags := flag.NewFlagSet("install", flag.ContinueOnError) |
| + flags.SetOutput(io.Discard) |
| + home, e := os.UserHomeDir() |
| + if e != nil { |
| + return fail("runner.install.destination") |
| + } |
| + instance := flags.String("instance", "", "") |
| + version := flags.String("release", "", "") |
| + origin := flags.String("origin", "", "") |
| + root := flags.String("root", filepath.Join(home, ".local/share/equipo-runner"), "") |
| + if flags.Parse(args) != nil || flags.NArg() != 0 || *instance == "" || *version != rastrillo.BuildVersion || !release.BuildManifest().InstallCertified() { |
| + return fail("runner.install.release") |
| + } |
| + result, e := runnersetup.InstallUser(ctx, runnersetup.InstallOptions{Release: *version, Root: *root, InstanceOrigin: *origin}) |
| + if e != nil { |
| + for _, key := range result.Missing { |
| + fmt.Fprintln(errout, equipo.RunnerSetupCopy(key)) |
| + } |
| + 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') |
| + 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" { |
| + return fail("runner.install.unavailable") |
| + } |
| + // Runtime configuration stays explicit. The installer never guesses credential |
| + // paths or creates a provider home. Task 17 supplies the local account setup. |
| + cfg, e := installConfig(*root, *origin, *instance, *version, getenv) |
| + if e != nil { |
| + return fail("runner.install.config") |
| + } |
| + if cfg.Origin != *origin || cfg.StateDir != filepath.Join(*root, "state") { |
| + return fail("runner.install.config") |
| + } |
| + if release.BuildManifest().VerifyInstalled(map[string]string{"bwrap": cfg.BwrapPath, "claude": cfg.ClaudePath, "codex": cfg.CodexPath, "codex-code-mode-host": cfg.CodexCodeModeHostPath, "equipo-tool-proxy": cfg.ToolProxyPath}) != nil { |
| + return fail("runner.install.release") |
| + } |
| + cfg.MachineLabel = label |
| + if e = runner.Enrol(ctx, cfg, out); e != nil { |
| + return fail("runner.install.unavailable") |
| + } |
| + // Use the already configured environment file. Never copy the invoking |
| + // process's environment (which may contain credentials) into service metadata. |
| + if e = runnersetup.CheckServiceEnvironment(*root, cfg.Origin, cfg.StateDir); e != nil { |
| + return fail("runner.install.config") |
| + } |
| + result, e = runnersetup.InstallUser(ctx, runnersetup.InstallOptions{Release: *version, Root: *root, InstanceOrigin: *origin, EnableService: true}) |
| + if e != nil { |
| + for _, key := range result.Missing { |
| + fmt.Fprintln(errout, equipo.RunnerSetupCopy(key)) |
| + } |
| + return 1 |
| + } |
| + fmt.Fprintln(out, equipo.RunnerSetupCopy("runner.install."+result.State)) |
| + return 0 |
| +} |
| +func installManifest(args []string, out io.Writer) int { |
| + if len(args) != 1 { |
| + return 1 |
| + } |
| + b, e := os.ReadFile(args[0]) |
| + if e != nil { |
| + return 1 |
| + } |
| + var m release.InstallManifest |
| + if json.Unmarshal(b, &m) != nil || m.Validate(rastrillo.BuildVersion) != nil { |
| + return 1 |
| + } |
| + if json.NewEncoder(out).Encode(m) != nil { |
| + return 1 |
| + } |
| + return 0 |
| +} |
diff --git a/cmd/equipo-runner/install_config.go b/cmd/equipo-runner/install_config.go| new file mode 100644 |
| index 00000000..e46bf312 |
| --- /dev/null |
| +++ b/cmd/equipo-runner/install_config.go |
| @@ -0,0 +1,51 @@ |
| +package main |
| + |
| +import ( |
| + "fmt" |
| + "os/exec" |
| + "path/filepath" |
| + "sort" |
| + "strconv" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/runner" |
| + runnersetup "amadan.net/oficina/equipo/internal/runner/setup" |
| +) |
| + |
| +func installConfig(root, origin, instance, version string, getenv func(string) string) (runner.Config, error) { |
| + values := map[string]string{"EQUIPO_TOOL_PROXY_PATH": filepath.Join(root, "releases", version, "equipo-tool-proxy"), "EQUIPO_ORIGIN": origin, "EQUIPO_INSTANCE_ID": instance, "EQUIPO_RUNNER_STATE_DIR": filepath.Join(root, "state"), "EQUIPO_ACCOUNT_BINDINGS_PATH": filepath.Join(root, "accounts.json"), "EQUIPO_AMADAN_CREDENTIAL_PATH": filepath.Join(root, "amadan.json"), "EQUIPO_WORKSPACE_ROOT": filepath.Join(root, "work"), "EQUIPO_SCRATCH_ROOT": filepath.Join(root, "scratch")} |
| + for variable, binary := range map[string]string{"EQUIPO_BWRAP_PATH": "bwrap", "EQUIPO_CLAUDE_PATH": "claude", "EQUIPO_CODEX_PATH": "codex", "EQUIPO_CODEX_CODE_MODE_HOST_PATH": "codex-code-mode-host", "EQUIPO_GO_BINARY": "go", "EQUIPO_GIT_PATH": "git", "EQUIPO_AMADAN_PATH": "amadan"} { |
| + path := getenv(variable) |
| + if path == "" { |
| + var e error |
| + path, e = exec.LookPath(binary) |
| + if e != nil { |
| + return runner.Config{}, e |
| + } |
| + } |
| + values[variable] = path |
| + } |
| + values["EQUIPO_GO_ROOT"] = getenv("EQUIPO_GO_ROOT") |
| + if values["EQUIPO_GO_ROOT"] == "" { |
| + b, e := exec.Command(values["EQUIPO_GO_BINARY"], "env", "GOROOT").Output() |
| + if e != nil { |
| + return runner.Config{}, e |
| + } |
| + values["EQUIPO_GO_ROOT"] = strings.TrimSpace(string(b)) |
| + } |
| + values["EQUIPO_GO_MODULE_CACHE"] = getenv("EQUIPO_GO_MODULE_CACHE") |
| + cfg, e := runner.LoadConfig(func(k string) string { return values[k] }) |
| + if e != nil { |
| + return cfg, e |
| + } |
| + keys := make([]string, 0, len(values)) |
| + for k := range values { |
| + keys = append(keys, k) |
| + } |
| + sort.Strings(keys) |
| + var content strings.Builder |
| + for _, k := range keys { |
| + fmt.Fprintf(&content, "%s=%s\n", k, strconv.Quote(values[k])) |
| + } |
| + return cfg, runnersetup.SaveServiceEnvironment(root, []byte(content.String())) |
| +} |
diff --git a/cmd/equipo-runner/main.go b/cmd/equipo-runner/main.go| index cc752412..6e6dcc45 100644 |
| --- a/cmd/equipo-runner/main.go |
| +++ b/cmd/equipo-runner/main.go |
| @@ -13,6 +13,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo" |
| "amadan.net/oficina/equipo/internal/release" |
| "amadan.net/oficina/equipo/internal/runner" |
| + runnersetup "amadan.net/oficina/equipo/internal/runner/setup" |
| "amadan.net/rastrillo/rastrillo" |
| ) |
| @@ -28,6 +29,12 @@ func run(ctx context.Context, args []string, input io.Reader, output, errorOutpu |
| } |
| return 0 |
| } |
| + if len(args) > 0 && args[0] == "install" { |
| + return installRunner(ctx, args[1:], input, output, errorOutput, getenv) |
| + } |
| + if len(args) > 0 && args[0] == "verify-install-manifest" { |
| + return installManifest(args[1:], output) |
| + } |
| if len(args) != 1 { |
| return fail(nil) |
| } |
| @@ -76,6 +83,9 @@ func run(ctx context.Context, args []string, input io.Reader, output, errorOutpu |
| return 0 |
| } |
| func main() { |
| + if len(os.Args) == 2 && os.Args[1] == "__install_probe" { |
| + os.Exit(runnersetup.InstallProbeMain(os.Stdin, os.Stdout)) |
| + } |
| if len(os.Args) > 1 && os.Args[1] == "__namespace" { |
| os.Exit(namespace(os.Args[2:])) |
| } |
diff --git a/cmd/equipo-runner/onboarding_test.go b/cmd/equipo-runner/onboarding_test.go| new file mode 100644 |
| index 00000000..077b7899 |
| --- /dev/null |
| +++ b/cmd/equipo-runner/onboarding_test.go |
| @@ -0,0 +1,17 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func TestOnboardingInstallVersioned(t *testing.T) { |
| + for _, args := range [][]string{{"install", "--release", "latest"}, {"install", "--release", "fixture-16", "--origin", "https://example.test"}, {"install", "--root", "/usr/local"}} { |
| + var out, errout bytes.Buffer |
| + if run(context.Background(), args, strings.NewReader(""), &out, &errout, func(string) string { return "" }) != 1 || !strings.Contains(errout.String(), "certified") { |
| + t.Fatalf("uncertified install exposed: %s", errout.String()) |
| + } |
| + } |
| +} |
diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md| index b89d4abf..ff1cc304 100644 |
| --- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| +++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md |
| @@ -3914,3 +3914,149 @@ Copy remains pending review before release. Existing Task 16 onboarding and Task |
| - docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md (this section appended under Task 15) |
| Full report: `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-15-report.md`. That ignored report is saved locally; the controller report and code are committed. Task scratch is removed after recording this evidence. Go caches stayed at their defaults. No push, merge or deployment. Safe to close after the local commit. |
| + |
| +## Task 16 |
| + |
| +Status: DONE_WITH_CONCERNS. Implementation complete; copy review and certified release remain pending. |
| + |
| +Implemented resumable onboarding and the certified Linux/amd64 user installer. Accepted invitations initialize state in the same transaction without resetting an existing person's progress. Stage mutations recheck membership, compare revisions and canonical replay inputs, and commit their audit event with the state. Account choice is independent of login. Runner completion requires the person's consumed pairing grant and a recent, available, confined connection. The final stage requires a recommendation task. |
| + |
| +The installer authenticates the configured instance through HTTPS, rejects redirects, checks the immutable release version, certificates and exact namespace argument inventory, and verifies runner and tool proxy checksums. Downloads use private on-disk TMPDIR scratch. Installs stay inside the user's home, reject symlinks, use atomic exclusive writes and a state lock, and preserve unrelated files. Failed containment or missing user-service support leaves installation unavailable. The production probe checks the certified bubblewrap bytes and version, user namespaces, distinct PID/user/network namespaces, and pidfds using the release policy. AppArmor denial is reported without modifying the host. User lingering is observed, never enabled. Service creation/enabling is reachable only through the explicit production install action; tests substitute every host/service effect. |
| + |
| +Pairing now uses the actual hostname or edited label. The runner prints its code and verification address and saves a private pending request for retry. The browser accepts typed codes through POST, displays the same label and server creation time, and requires a separate, expiring confirmation bound to the verified person and code. GET links cannot prefill or approve. Existing device secrets, machine-key signatures, credential audiences, throttling, expiry, revocation and current-roster checks remain in force. A second approval for an already enrolled machine is refused. |
| + |
| +Release packaging adds install-v1.sh and an external install-manifest.json, avoiding an embedded runner checksum cycle. The configured `EQUIPO_RUNNER_RELEASE_DIR` serves only the versioned installer, manifest, runner and tool proxy after certificate/digest checks. The UI offers a command only when the configured HTTPS release is available. Hosted and Mac runners have pending labels with no launch routes. Runtime text remains in copy.go with individual COPY REVIEW REQUIRED markers. |
| + |
| +### Tests first and verification |
| + |
| +The required first red command exited 1 before implementation: InstallOptions, installHost, release.InstallManifest, Store.Onboarding and Store.AdvanceOnboarding did not exist. The command was `CGO_ENABLED=0 go test ./internal/runner/setup ./cmd/equipo-runner ./internal/plan3test -run '^TestOnboarding(Install|Pairing|Containment|Service|Hosted)' -count=1`. |
| + |
| +Additional observed red checks: |
| + |
| +- `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestOnboardingPairingBound$' -count=1`: exit 1, `link prefilled pairing code`, before replacing GET inspection. |
| +- `CGO_ENABLED=0 go test ./internal/runner -run '^TestOnboardingPairingBound$' -count=1`: exit 1, missing `Config.MachineLabel`, before adding hostname/editable labels and saved enrolment retries. |
| +- `CGO_ENABLED=0 go test ./internal/equipo/setup -run '^TestOnboardingInstallPrerequisites$' -count=1`: exit 1, `write task accepted as safe first task <nil>`. The implemented prerequisite now requires the person's persisted recommendation task. |
| +- `CGO_ENABLED=0 go test ./internal/runner/setup -run '^TestOnboardingInstallVersioned$' -count=1`: exit 1, `missing verified tool proxy`, before downloading and checking the helper belonging to the same release. |
| + |
| +All these targeted commands subsequently passed. Intermediate work also exposed missing JSON tags in the private retry journal, old GET/single-POST assumptions in pairing tests, and exhausted directory budgets. Those failures were corrected, not skipped. A test-only runner authentication endpoint was moved outside the person dispatcher so it tests RequireRunner directly; the production dispatcher continues rejecting bearer access to browser routes with 401. Device exchange rejects Authorization with 403. Submitted actor/person fields are now explicitly rejected with 422. |
| + |
| +| Command | Result | |
| +| --- | --- | |
| +| `CGO_ENABLED=0 go test ./internal/runner/setup ./cmd/equipo-runner ./internal/plan3test -run '^TestOnboarding(Install\|Pairing\|Containment\|Service\|Hosted)' -count=1` | Final PASS, exit 0: setup 0.624s, CLI 0.209s, integration 1.441s. | |
| +| `CGO_ENABLED=0 go test ./internal/equipo/setup ./internal/release ./internal/runner -run '^TestOnboarding\|^TestRunnerConfig$\|^TestEffectivePolicyReleaseManifest$' -count=1` | PASS, exit 0: app setup 2.317s, release 0.026s, runner 0.146s. Includes migration upgrade, prerequisite/audit rollback, confirmation expiry, duplicate-machine denial and durable runner retry. | |
| +| `CGO_ENABLED=0 go test ./internal/release -run '^TestOnboardingInstallPackaging$' -count=1` | Final PASS, exit 0, 0.025s after adding the verified tool proxy asset. | |
| +| `CGO_ENABLED=0 go test ./internal/equipotest -run '^TestEnrolment\|^TestRunnerReleaseContract\|^TestDirectReleaseRequiresCertification' -count=1` | PASS, exit 0, 13.852s. Packaging uses fake executables, synthetic manifests/evidence and private temporary roots. | |
| +| `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestInvite\|^TestPersonAPI\|^TestConversationScriptless$\|^TestPlanApprovalPrecedence$\|^TestPlaybook' -count=1` | PASS, exit 0, 28.388s. Rechecks invitation entry and the callers of relocated fixture helpers. | |
| +| `make migration-check` | PASS, exit 0: TestMigrationModels, 0.235s. | |
| +| `CGO_ENABLED=0 go test ./internal/equipo -run '^TestConversationMigrationSnapshot$' -count=1` | PASS, exit 0, 4.345s. | |
| +| `make budget` | PASS, exit 0: 34 directories within budget. | |
| +| `CGO_ENABLED=0 go vet ./internal/runner/setup ./internal/runner ./internal/release ./cmd/equipo-runner ./internal/equipo ./internal/equipo/setup ./internal/plan3test ./internal/equipotest` | PASS, exit 0. The changed installer, release and CLI packages passed again after the tool proxy fix. | |
| +| `CGO_ENABLED=0 go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./internal/runner/setup ./internal/runner ./internal/release ./cmd/equipo-runner ./internal/equipo ./internal/equipo/setup ./internal/plan3test ./internal/equipotest` | PASS, exit 0. The changed installer, release and CLI packages passed again after the tool proxy fix. | |
| +| `gofmt -l internal/equipo internal/runner internal/release internal/plan3test internal/equipotest cmd/equipo-runner` | PASS, exit 0, no output. | |
| +| `git diff --check` | PASS, exit 0, no output. | |
| + |
| +### Guard mutations |
| + |
| +All fifteen mutations were restored; each restored command passed with exit 0. |
| + |
| +| Guard | Command | Mutation result | Restoration | |
| +| --- | --- | --- | --- | |
| +| supported OS | `CGO_ENABLED=0 go test ./internal/runner/setup -run ^TestOnboardingInstallVersioned/os$ -count=1` | Exit 1: unsafe install: State:stops_at_logout, Missing:[], error <nil>, service=1 | Same command PASS, exit 0 | |
| +| user-only destination | `CGO_ENABLED=0 go test ./internal/runner/setup -run ^TestOnboardingInstallVersioned/root$ -count=1` | Exit 1: unsafe install: State:stops_at_logout, Missing:[], error <nil>, service=1 | Same command PASS, exit 0 | |
| +| containment prerequisite | `CGO_ENABLED=0 go test ./internal/runner/setup -run ^TestOnboardingContainmentPreflight$ -count=1` | Exit 1: preflight bypass: State:stops_at_logout, Missing:[], error <nil> | Same command PASS, exit 0 | |
| +| logout reporting | `CGO_ENABLED=0 go test ./internal/runner/setup -run ^TestOnboardingServiceLogout$ -count=1` | Exit 1: logout claim: State:installed, LingeringEnabled:false | Same command PASS, exit 0 | |
| +| service retry uniqueness | `CGO_ENABLED=0 go test ./internal/runner/setup -run ^TestOnboardingInstallResume$ -count=1` | Exit 1: duplicate service: 2 | Same command PASS, exit 0 | |
| +| typed entry | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestOnboardingPairingBound$ -count=1` | Exit 1: link prefilled pairing code | Same command PASS, exit 0 | |
| +| explicit confirmation | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestOnboardingPairingBound$ -count=1` | Exit 1: HTTP 303, want 403: | Same command PASS, exit 0 | |
| +| machine proof | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestOnboardingPairingBound$ -count=1` | Exit 1: wrong machine exchanged <nil> | Same command PASS, exit 0 | |
| +| runner uniqueness | `CGO_ENABLED=0 go test ./internal/equipo/setup -run ^TestOnboardingPairingUnique$ -count=1` | Exit 1: duplicate runner for machine <nil> | Same command PASS, exit 0 | |
| +| confirmation expiry | `CGO_ENABLED=0 go test ./internal/equipo/setup -run ^TestOnboardingPairingConfirmation$ -count=1` | Exit 1: confirmation binding or expiry bypass | Same command PASS, exit 0 | |
| +| persisted prerequisite | `CGO_ENABLED=0 go test ./internal/equipo/setup -run ^TestOnboardingInstallPrerequisites$ -count=1` | Exit 1: account without choice <nil> | Same command PASS, exit 0 | |
| +| safe first task | `CGO_ENABLED=0 go test ./internal/equipo/setup -run ^TestOnboardingInstallPrerequisites$ -count=1` | Exit 1: write task accepted as safe first task <nil> | Same command PASS, exit 0 | |
| +| manifest certification | `CGO_ENABLED=0 go test ./internal/runner/setup -run ^TestOnboardingInstallVersioned/uncertified$ -count=1` | Exit 1: unsafe install: State:stops_at_logout, Missing:[], error <nil>, service=1 | Same command PASS, exit 0 | |
| +| binary checksum | `CGO_ENABLED=0 go test ./internal/runner/setup -run ^TestOnboardingInstallVersioned/checksum$ -count=1` | Exit 1: unsafe install: State:stops_at_logout, Missing:[], error <nil>, service=1 | Same command PASS, exit 0 | |
| +| tool proxy checksum | `CGO_ENABLED=0 go test ./internal/runner/setup -run ^TestOnboardingInstallVersioned/helper_checksum$ -count=1` | Exit 1: unsafe install: State:stops_at_logout, Missing:[], error <nil>, service=1 | Same command PASS, exit 0 | |
| + |
| +### Self-review, budgets and concerns |
| + |
| +Self-review covered authorization before replay; transaction-bound state, roster and audit; invitation initialization without reset; explicit form fields; typed POST inspection and person/code-bound confirmation; machine proof and runner uniqueness; additive app schema; exact release identity and helper checksum; path/symlink checks; subprocess arguments without shell interpolation; private scratch ownership; namespace/pidfd prerequisites; lingering truthfulness; and unavailable states. Fifteen independent guard mutations failed and passed after restoring the exact source. The runner and helper checksum/certification mutations were repeated after the helper packaging fix. |
| + |
| +To retain the root ceiling, enrolment transaction code and its model types moved into setup with injected roster, audit, clock, credential and error callbacks. Root aliases preserve existing callers. Existing shared form/API fixture builders moved beside the established integration fixture harness; no tests or assertions were removed. Repeated error assertions in the enrolment tests use the existing executionMust helper. The runner source ceiling rose from 9,300 to 9,400 for the durable enrolment state and label plumbing; its 8,600 test ceiling and 330s time ceiling are unchanged. |
| + |
| +Final direct Go line counts (source / test): equipo 10,719 / 437; app setup 1,479 / 272; runner 9,336 / 8,590; runner setup 506 / 254; release 399 / 232; integration 741 / 7,998; equipotest 0 / 12,993; CLI 290 / 64. All directory budgets pass. No full suite or make ci ran. |
| + |
| +- Production release certificates and copy approval are still absent. The current build therefore offers no install command and refuses production installation. Fixture success is not live certification. |
| +- This task did not install a real user service, enable lingering, enrol this machine, create credential homes, sign in or run a provider. Namespace and service success cases use injected fixtures. Production service and host probes still require the explicit human release/install exercise. |
| +- Task 17 owns account login and local account bindings. The installer creates only its explicit local environment file and leaves credentials/account homes alone. A paired service cannot accept work until the required account bindings are supplied; onboarding stays on the runner step until a trusted connection report arrives. Provider CLIs, certified bubblewrap, Go, Git and Amadan remain local prerequisites; the installer downloads the Equipo runner and tool proxy only. |
| +- The instance must configure `EQUIPO_RUNNER_RELEASE_DIR` to the immutable packaging output matching its build version. Missing assets or digest/certificate mismatches produce unavailable, never a partial command. |
| +- Old pending pairing rows that predate the new creation-time column cannot be confirmed with an invented time. They must expire/retry. Existing enrolled runners, credentials, invitations and historical work remain intact. |
| +- Task 20 still owns the person API onboarding routes. Store.Onboarding, Store.AdvanceOnboarding and Store.ChooseOnboardingProvider are available through the shared application layer. AccountSetupID is persisted for Task 17 to populate through its guarded setup operations. |
| +- Pending mockup wording is listed below. No mockup HTML, README prose or vendored assets changed. No push, merge or deployment occurred. |
| + |
| +### New runtime copy (pending copy pass) |
| + |
| +All entries are individually marked COPY REVIEW REQUIRED in copy.go. |
| + |
| +| Key | Draft text | |
| +| --- | --- | |
| +| `onboarding.title` | Set up Equipo | |
| +| `onboarding.welcome` | Welcome | |
| +| `onboarding.account` | Choose a model account | |
| +| `onboarding.runner` | Set up your runner | |
| +| `onboarding.specialists` | Choose specialists | |
| +| `onboarding.first_task` | Choose a first task | |
| +| `onboarding.complete` | Setup complete | |
| +| `onboarding.choose` | Save choice | |
| +| `onboarding.continue` | Continue | |
| +| `onboarding.codex` | ChatGPT with Codex | |
| +| `onboarding.claude` | Claude | |
| +| `onboarding.account_pending` | Your choice is saved separately from sign-in. Sign in on your runner to finish connecting the account. | |
| +| `onboarding.own_machine` | Use your own Linux amd64 machine. The runner connects out to this team. | |
| +| `onboarding.pair` | Run the installer on your machine. Check or edit its machine label before enrolling. Type the code it prints into this browser, then confirm the label and request time. | |
| +| `onboarding.safe_first_task` | Start with a recommendation in your conversation. Ask what to work on next. | |
| +| `onboarding.hosted` | Hosted by Equipo | |
| +| `onboarding.later` | Hosted runners are coming later. | |
| +| `onboarding.mac` | Mac runner | |
| +| `onboarding.mac_later` | Mac runners are coming later. You can use a Linux runner from your Mac. | |
| +| `runner.requested` | Requested at | |
| +| `runner.install.unavailable` | Runner installation is unavailable. | |
| +| `runner.install.platform` | This release supports Linux amd64 runners only. | |
| +| `runner.install.release` | A certified, versioned runner release is not available. | |
| +| `runner.install.checksum` | The runner download did not match the release checksum. | |
| +| `runner.install.destination` | Choose a private, writable installation folder inside your home. | |
| +| `runner.install.scratch` | Set TMPDIR to a private scratch folder on disk. | |
| +| `runner.install.busy` | Another installation is using this folder. Try again when it finishes. | |
| +| `runner.install.bwrap` | This runner requires the certified bubblewrap 0.11.0 build. | |
| +| `runner.install.userns` | Unprivileged user namespaces are unavailable on this machine. | |
| +| `runner.install.apparmor` | AppArmor restricts unprivileged user namespaces on this machine. Runner installation is unavailable. | |
| +| `runner.install.pidfd` | This machine could not provide the process handles needed for containment. | |
| +| `runner.install.namespace` | The release containment probe failed. Runner installation is unavailable. | |
| +| `runner.install.service` | A working user service manager is required for this runner. | |
| +| `runner.install.lingering` | Equipo could not check whether your user service continues after logout. | |
| +| `runner.install.stops_at_logout` | Runner stops at logout. | |
| +| `runner.install.installed` | Runner installed. | |
| +| `runner.install.config` | Configure the runner environment before enabling its user service. | |
| +| `runner.install.label` | Machine label [%s]: | |
| +| `runner.install.enrol` | Enrol this machine with this label? Type yes: | |
| + |
| +### Onboarding mockup wording (pending copy pass) |
| + |
| +`docs/mockups/onboarding.html` is unchanged, as the controller ruled. Every proposal below is **COPY REVIEW REQUIRED**. Apply only the later approved words. |
| + |
| +| Existing area | Proposed draft wording or treatment | |
| +| --- | --- | |
| +| Intro promising hosted and Mac enrolment | From an invitation to a first recommendation. Choose a model account, set up a Linux runner, choose specialists, then ask for a recommendation. | |
| +| Account stage with an invented Claude device URL/code | Choose Claude or ChatGPT now. Sign in on the runner in the next step. | |
| +| Provider sign-in instructions | Codex uses supported device sign-in. Claude uses official browser sign-in. On a headless machine, enter any returned code only in the runner terminal. | |
| +| Hosted option and Quickest badge | Hosted by Equipo. Hosted runners are coming later. Remove the launch action and Quickest badge. | |
| +| Own-machine option | Use your own Linux amd64 machine. The runner connects out to this team. | |
| +| Add this Mac heading | Set up your Linux runner | |
| +| Unversioned installer command | Show the generated HTTPS command for the immutable release version only when its certified assets are available. | |
| +| Browser-generated pairing code | Run the installer on your machine. Check or edit its machine label before enrolling. Type the code it prints into this browser, then confirm the label and request time. | |
| +| Installed example naming paul-mbp | Render the actual machine label and server request time. Do not claim installation from a displayed code. | |
| +| Mac app enrolment note | Mac runners are coming later. You can use a Linux runner from your Mac. | |
| +| Persistence after logout | Runner stops at logout. Show this when user lingering is disabled. | |
| +| Account progress during runner setup | Your choice is saved separately from sign-in. Sign in on your runner to finish connecting the account. | |
| +| 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. |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go| index 44c8d7f1..39514e2c 100644 |
| --- a/internal/equipo/app.go |
| +++ b/internal/equipo/app.go |
| @@ -12,6 +12,7 @@ import ( |
| "github.com/go-chi/chi/v5" |
| "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/release" |
| "amadan.net/rastrillo/rastrillo" |
| "amadan.net/rastrillo/rastrillo/auth" |
| "amadan.net/rastrillo/rastrillo/background" |
| @@ -25,6 +26,7 @@ import ( |
| ) |
| type application struct { |
| + installAssets release.InstallAssets |
| executionEnabled bool |
| chi.Router |
| live *live.Hub |
| @@ -129,7 +131,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| if err != nil { |
| return nil, err |
| } |
| - a := &application{executionEnabled: cfg.ExecutionEnabled, Router: chi.NewRouter(), auth: authentication, store: store, logger: logger, nonces: pow.SQLNonces(d.Writer()), origin: cfg.Origin} |
| + 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} |
| 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 { |
| @@ -156,6 +158,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| person := store.personAPIRouter() |
| a.Use(personapi.Dispatcher(cfg.Origin, runner, person, func(w http.ResponseWriter) { runnerFailure(w, ErrForbidden) })) |
| a.Mount("/api/v1", person) |
| + a.Handle("/releases/*", a.installAssets) |
| a.Post("/api/enrolments", a.beginEnrolment) |
| a.Post("/api/enrolments/token", a.exchangeEnrolment) |
| a.Mount("/api/runner/v2", runner) |
| @@ -187,6 +190,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| r.Post("/settings/recovery/release", a.releaseRecovery) |
| r.Get("/", a.preferenceHandler().Landing) |
| a.preferenceHandler().Routes(r) |
| + a.onboardingHandler().Routes(r) |
| a.conversationHandler().Routes(r) |
| a.planHandler().Routes(r) |
| r.Post("/tasks/{id}/steps/{key}/selection", a.confirmPlanSelection) |
diff --git a/internal/equipo/config.go b/internal/equipo/config.go| index e4f24495..e6d16fee 100644 |
| --- a/internal/equipo/config.go |
| +++ b/internal/equipo/config.go |
| @@ -9,6 +9,7 @@ import ( |
| ) |
| type Config struct { |
| + RunnerReleaseDir string |
| ExecutionEnabled bool |
| ExecutionMarkerPath string |
| AlwaysOn bool |
| @@ -19,7 +20,7 @@ type Config struct { |
| } |
| func LoadConfig(getenv func(string) string) (Config, error) { |
| - cfg := Config{ |
| + cfg := Config{RunnerReleaseDir: getenv("EQUIPO_RUNNER_RELEASE_DIR"), |
| ExecutionEnabled: getenv("EQUIPO_EXECUTION_ENABLED") == "1", |
| ExecutionMarkerPath: getenv("EQUIPO_EXECUTION_MARKER_PATH"), |
| AlwaysOn: getenv("EQUIPO_ALWAYS_ON") == "1", |
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go| index 0e12db3b..a83f614c 100644 |
| --- a/internal/equipo/copy.go |
| +++ b/internal/equipo/copy.go |
| @@ -48,6 +48,85 @@ const BootLog = "Equipo could not start." |
| // COPY APPROVED BY DELEGATION (Luna pass, 2026-11-01, house rules). |
| var pageCopy = map[string]string{ |
| + // COPY REVIEW REQUIRED: onboarding.title |
| + "onboarding.title": "Set up Equipo", |
| + // COPY REVIEW REQUIRED: onboarding.welcome |
| + "onboarding.welcome": "Welcome", |
| + // COPY REVIEW REQUIRED: onboarding.account |
| + "onboarding.account": "Choose a model account", |
| + // COPY REVIEW REQUIRED: onboarding.runner |
| + "onboarding.runner": "Set up your runner", |
| + // COPY REVIEW REQUIRED: onboarding.specialists |
| + "onboarding.specialists": "Choose specialists", |
| + // COPY REVIEW REQUIRED: onboarding.first_task |
| + "onboarding.first_task": "Choose a first task", |
| + // COPY REVIEW REQUIRED: onboarding.complete |
| + "onboarding.complete": "Setup complete", |
| + // COPY REVIEW REQUIRED: onboarding.choose |
| + "onboarding.choose": "Save choice", |
| + // COPY REVIEW REQUIRED: onboarding.continue |
| + "onboarding.continue": "Continue", |
| + // COPY REVIEW REQUIRED: onboarding.codex |
| + "onboarding.codex": "ChatGPT with Codex", |
| + // COPY REVIEW REQUIRED: onboarding.claude |
| + "onboarding.claude": "Claude", |
| + // COPY REVIEW REQUIRED: onboarding.account_pending |
| + "onboarding.account_pending": "Your choice is saved separately from sign-in. Sign in on your runner to finish connecting the account.", |
| + // COPY REVIEW REQUIRED: onboarding.own_machine |
| + "onboarding.own_machine": "Use your own Linux amd64 machine. The runner connects out to this team.", |
| + // COPY REVIEW REQUIRED: onboarding.pair |
| + "onboarding.pair": "Run the installer on your machine. Check or edit its machine label before enrolling. Type the code it prints into this browser, then confirm the label and request time.", |
| + // COPY REVIEW REQUIRED: onboarding.safe_first_task |
| + "onboarding.safe_first_task": "Start with a recommendation in your conversation. Ask what to work on next.", |
| + // COPY REVIEW REQUIRED: onboarding.hosted |
| + "onboarding.hosted": "Hosted by Equipo", |
| + // COPY REVIEW REQUIRED: onboarding.later |
| + "onboarding.later": "Hosted runners are coming later.", |
| + // COPY REVIEW REQUIRED: onboarding.mac |
| + "onboarding.mac": "Mac runner", |
| + // COPY REVIEW REQUIRED: onboarding.mac_later |
| + "onboarding.mac_later": "Mac runners are coming later. You can use a Linux runner from your Mac.", |
| + // COPY REVIEW REQUIRED: runner.requested |
| + "runner.requested": "Requested at", |
| + // COPY REVIEW REQUIRED: runner.install.unavailable |
| + "runner.install.unavailable": "Runner installation is unavailable.", |
| + // COPY REVIEW REQUIRED: runner.install.platform |
| + "runner.install.platform": "This release supports Linux amd64 runners only.", |
| + // COPY REVIEW REQUIRED: runner.install.release |
| + "runner.install.release": "A certified, versioned runner release is not available.", |
| + // COPY REVIEW REQUIRED: runner.install.checksum |
| + "runner.install.checksum": "The runner download did not match the release checksum.", |
| + // COPY REVIEW REQUIRED: runner.install.destination |
| + "runner.install.destination": "Choose a private, writable installation folder inside your home.", |
| + // COPY REVIEW REQUIRED: runner.install.scratch |
| + "runner.install.scratch": "Set TMPDIR to a private scratch folder on disk.", |
| + // COPY REVIEW REQUIRED: runner.install.busy |
| + "runner.install.busy": "Another installation is using this folder. Try again when it finishes.", |
| + // COPY REVIEW REQUIRED: runner.install.bwrap |
| + "runner.install.bwrap": "This runner requires the certified bubblewrap 0.11.0 build.", |
| + // COPY REVIEW REQUIRED: runner.install.userns |
| + "runner.install.userns": "Unprivileged user namespaces are unavailable on this machine.", |
| + // COPY REVIEW REQUIRED: runner.install.apparmor |
| + "runner.install.apparmor": "AppArmor restricts unprivileged user namespaces on this machine. Runner installation is unavailable.", |
| + // COPY REVIEW REQUIRED: runner.install.pidfd |
| + "runner.install.pidfd": "This machine could not provide the process handles needed for containment.", |
| + // COPY REVIEW REQUIRED: runner.install.namespace |
| + "runner.install.namespace": "The release containment probe failed. Runner installation is unavailable.", |
| + // COPY REVIEW REQUIRED: runner.install.service |
| + "runner.install.service": "A working user service manager is required for this runner.", |
| + // COPY REVIEW REQUIRED: runner.install.lingering |
| + "runner.install.lingering": "Equipo could not check whether your user service continues after logout.", |
| + // COPY REVIEW REQUIRED: runner.install.stops_at_logout |
| + "runner.install.stops_at_logout": "Runner stops at logout.", |
| + // COPY REVIEW REQUIRED: runner.install.installed |
| + "runner.install.installed": "Runner installed.", |
| + // COPY REVIEW REQUIRED: runner.install.config |
| + "runner.install.config": "Configure the runner environment before enabling its user service.", |
| + // COPY REVIEW REQUIRED: runner.install.label |
| + "runner.install.label": "Machine label [%s]: ", |
| + // COPY REVIEW REQUIRED: runner.install.enrol |
| + "runner.install.enrol": "Enrol this machine with this label? Type yes: ", |
| + |
| // COPY REVIEW REQUIRED: invite.welcome |
| "invite.welcome": "Join the team", |
| // COPY REVIEW REQUIRED: invite.accept |
| @@ -936,3 +1015,5 @@ func CoordinatorToolCopy() runnerproto.CoordinatorToolCopy { |
| // COPY REVIEW REQUIRED: invite.expired |
| const copyInviteExpired = "This invitation is no longer valid. Ask a team owner for a new one." |
| + |
| +func RunnerSetupCopy(key string) string { return copyText(key) } |
diff --git a/internal/equipo/enrolment.go b/internal/equipo/enrolment.go| index 40df762a..6add5e0f 100644 |
| --- a/internal/equipo/enrolment.go |
| +++ b/internal/equipo/enrolment.go |
| @@ -2,16 +2,14 @@ package equipo |
| import ( |
| "context" |
| - "crypto/ed25519" |
| "crypto/rand" |
| "crypto/sha256" |
| - "encoding/base32" |
| "encoding/base64" |
| "encoding/hex" |
| "errors" |
| - "strings" |
| "time" |
| + "amadan.net/oficina/equipo/internal/equipo/setup" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| "gorm.io/gorm" |
| ) |
| @@ -78,208 +76,18 @@ func runnerRateAt(tx *gorm.DB, key string, now time.Time, period time.Duration, |
| return true, storeError(tx.Model(&runnerRate{}).Where("key = ?", key).Select("WindowStart", "Count").Updates(&rate).Error) |
| } |
| -func (s *Store) BeginEnrolment(ctx context.Context, machinePublicKey, label string) (runnerproto.DeviceCode, error) { |
| - if (runnerproto.BeginEnrolmentRequest{Version: 1, MachinePublicKey: machinePublicKey, Label: label}).Validate() != nil { |
| - return runnerproto.DeviceCode{}, ErrInvalid |
| - } |
| - var result runnerproto.DeviceCode |
| - var denied error |
| - err := s.write(ctx, func(tx *gorm.DB) error { |
| - instance, err := runnerInstance(tx) |
| - if err != nil { |
| - return err |
| - } |
| - now := s.runnerClock.Now().UTC() |
| - hash := runnerproto.MachineKeyHash(machinePublicKey) |
| - for _, rate := range []struct { |
| - key string |
| - period time.Duration |
| - limit int |
| - }{{"create:" + instance, time.Minute, 60}, {"machine:" + instance + ":" + hash, 10 * time.Minute, 5}} { |
| - allowed, err := runnerRateAt(tx, rate.key, now, rate.period, rate.limit) |
| - if err != nil { |
| - return err |
| - } |
| - if !allowed { |
| - denied = ErrRunnerRateLimited |
| - return nil |
| - } |
| - } |
| - userBytes := make([]byte, 7) |
| - rand.Read(userBytes) |
| - userCode := base32.NewEncoding("0123456789ABCDEFGHJKMNPQRSTVWXYZ").WithPadding(base32.NoPadding).EncodeToString(userBytes)[:10] |
| - secret := runnerSecret() |
| - grant := runnerEnrolment{ID: rand.Text(), InstanceID: instance, Audience: runnerproto.DeviceAudience, MachinePublicKey: machinePublicKey, MachineKeyHash: hash, Label: label, DeviceSecretHash: runnerHash(runnerproto.DeviceAudience, secret), UserCodeHash: runnerHash(instance, userCode), Challenge: runnerSecret(), ExpiresAt: now.Add(10 * time.Minute), NextPollAt: now} |
| - if err := tx.Create(&grant).Error; err != nil { |
| - return storeError(err) |
| - } |
| - result = runnerproto.DeviceCode{Version: 1, EnrolmentID: grant.ID, InstanceID: instance, DeviceSecret: secret, UserCode: userCode, Challenge: grant.Challenge, ExpiresAt: grant.ExpiresAt, PollIntervalSeconds: runnerproto.PollIntervalSeconds} |
| - return appendAudit(tx, Actor{Address: "device"}, "runner.enrolment.begin", grant.ID) |
| - }) |
| - if err != nil { |
| - return runnerproto.DeviceCode{}, err |
| - } |
| - if denied != nil { |
| - return runnerproto.DeviceCode{}, denied |
| - } |
| - return result, nil |
| -} |
| - |
| -func validUserCode(code string) bool { |
| - return len(code) == 10 && strings.Trim(code, "0123456789ABCDEFGHJKMNPQRSTVWXYZ") == "" |
| +func (s *Store) enrolments() *setup.Enrolments { |
| + return &setup.Enrolments{Write: s.write, Now: s.runnerClock.Now, Instance: runnerInstance, Rate: runnerRateAt, Secret: runnerSecret, Hash: runnerHash, Member: currentRunnerMember, Audit: appendAudit, Error: storeError, Runner: runnerAt, Mint: mintRunnerCredential, Invalid: ErrInvalid, Forbidden: ErrForbidden, Conflict: ErrConflict, RunnerRateLimited: ErrRunnerRateLimited, EnrolmentPending: ErrEnrolmentPending} |
| } |
| - |
| -func enrolmentByCode(tx *gorm.DB, instance, code string, now time.Time) (runnerEnrolment, error) { |
| - var grant runnerEnrolment |
| - if !validUserCode(code) { |
| - return grant, ErrInvalid |
| - } |
| - if err := tx.Where("user_code_hash = ?", runnerHash(instance, code)).First(&grant).Error; err != nil { |
| - if errors.Is(err, gorm.ErrRecordNotFound) { |
| - return grant, ErrForbidden |
| - } |
| - return grant, storeError(err) |
| - } |
| - if grant.InstanceID != instance || grant.Audience != runnerproto.DeviceAudience || !now.Before(grant.ExpiresAt) || grant.ApprovedAt != nil || grant.ConsumedAt != nil || grant.RevokedAt != nil { |
| - return grant, ErrForbidden |
| - } |
| - return grant, nil |
| +func (s *Store) BeginEnrolment(ctx context.Context, key, label string) (runnerproto.DeviceCode, error) { |
| + return s.enrolments().BeginEnrolment(ctx, key, label) |
| } |
| - |
| -func (s *Store) approveOrInspect(ctx context.Context, actor Actor, userCode string, approve bool) (Runner, error) { |
| - var result Runner |
| - var denied error |
| - err := s.write(ctx, func(tx *gorm.DB) error { |
| - member, err := currentRunnerMember(tx, actor.Address) |
| - if err != nil { |
| - return err |
| - } |
| - instance, err := runnerInstance(tx) |
| - if err != nil { |
| - return err |
| - } |
| - now := s.runnerClock.Now().UTC() |
| - allowed, err := runnerRateAt(tx, "approve:"+instance+":"+member.Address, now, time.Minute, 10) |
| - if err != nil { |
| - return err |
| - } |
| - if !allowed { |
| - denied = ErrRunnerRateLimited |
| - return nil |
| - } |
| - grant, err := enrolmentByCode(tx, instance, userCode, now) |
| - if err != nil { |
| - if errors.Is(err, ErrForbidden) || errors.Is(err, ErrInvalid) { |
| - denied = err |
| - return nil |
| - } |
| - return err |
| - } |
| - result = Runner{Person: member.Address, MachineKeyHash: grant.MachineKeyHash, Label: grant.Label, Revision: 1} |
| - if !approve { |
| - return nil |
| - } |
| - result.ID = rand.Text() |
| - if err := tx.Create(&runnerRecord{Runner: result, InstanceID: instance}).Error; err != nil { |
| - return storeError(err) |
| - } |
| - grant.Person = member.Address |
| - grant.RunnerID = result.ID |
| - grant.ApprovedAt = &now |
| - updated := tx.Model(&runnerEnrolment{}).Where("id = ? AND approved_at IS NULL AND revoked_at IS NULL", grant.ID).Select("Person", "RunnerID", "ApprovedAt").Updates(&grant) |
| - if updated.Error != nil { |
| - return storeError(updated.Error) |
| - } |
| - if updated.RowsAffected != 1 { |
| - return ErrConflict |
| - } |
| - return appendAudit(tx, actor, "runner.enrolment.approve", result.ID) |
| - }) |
| - if err != nil { |
| - return Runner{}, err |
| - } |
| - if denied != nil { |
| - return Runner{}, denied |
| - } |
| - return result, nil |
| +func (s *Store) ApproveEnrolment(ctx context.Context, a Actor, code string) error { |
| + return s.enrolments().ApproveEnrolment(ctx, a, code) |
| } |
| - |
| -func (s *Store) ApproveEnrolment(ctx context.Context, actor Actor, userCode string) error { |
| - _, err := s.approveOrInspect(ctx, actor, userCode, true) |
| - return err |
| +func (s *Store) ExchangeEnrolment(ctx context.Context, secret string, p runnerproto.ExchangeProof) (runnerproto.RunnerCredential, error) { |
| + return s.enrolments().ExchangeEnrolment(ctx, secret, p) |
| } |
| - |
| -func (s *Store) ExchangeEnrolment(ctx context.Context, deviceSecret string, proof runnerproto.ExchangeProof) (runnerproto.RunnerCredential, error) { |
| - if (runnerproto.ExchangeEnrolmentRequest{Version: 1, DeviceSecret: deviceSecret, Proof: proof}).Validate() != nil { |
| - return runnerproto.RunnerCredential{}, ErrForbidden |
| - } |
| - var result runnerproto.RunnerCredential |
| - var denied error |
| - err := s.write(ctx, func(tx *gorm.DB) error { |
| - instance, err := runnerInstance(tx) |
| - if err != nil { |
| - return err |
| - } |
| - now := s.runnerClock.Now().UTC() |
| - var grant runnerEnrolment |
| - if err := tx.Where("device_secret_hash = ?", runnerHash(runnerproto.DeviceAudience, deviceSecret)).First(&grant).Error; err != nil { |
| - if errors.Is(err, gorm.ErrRecordNotFound) { |
| - return ErrForbidden |
| - } |
| - return storeError(err) |
| - } |
| - if grant.Audience != runnerproto.DeviceAudience || grant.InstanceID != instance || grant.ID != proof.EnrolmentID || grant.Challenge != proof.Challenge || !now.Before(grant.ExpiresAt) || grant.ConsumedAt != nil || grant.RevokedAt != nil { |
| - return ErrForbidden |
| - } |
| - key, err := runnerproto.DecodeBytes(grant.MachinePublicKey, ed25519.PublicKeySize) |
| - if err != nil || runnerproto.MachineKeyHash(grant.MachinePublicKey) != grant.MachineKeyHash { |
| - return ErrForbidden |
| - } |
| - signature, _ := runnerproto.DecodeBytes(proof.Signature, ed25519.SignatureSize) |
| - if !ed25519.Verify(key, runnerproto.EnrolmentProofMessage(instance, proof), signature) { |
| - return ErrForbidden |
| - } |
| - if now.Before(grant.NextPollAt) { |
| - denied = ErrRunnerRateLimited |
| - return nil |
| - } |
| - grant.NextPollAt = now.Add(5 * time.Second) |
| - if err := tx.Model(&runnerEnrolment{}).Where("id = ?", grant.ID).Select("NextPollAt").Updates(&grant).Error; err != nil { |
| - return storeError(err) |
| - } |
| - if grant.ApprovedAt == nil { |
| - denied = ErrEnrolmentPending |
| - return nil |
| - } |
| - runner, err := runnerAt(tx, instance, grant.RunnerID) |
| - if err != nil { |
| - return err |
| - } |
| - if runner.Person != grant.Person || runner.MachineKeyHash != grant.MachineKeyHash { |
| - return ErrForbidden |
| - } |
| - if _, err := currentRunnerMember(tx, runner.Person); err != nil { |
| - return err |
| - } |
| - grant.ConsumedAt = &now |
| - updated := tx.Model(&runnerEnrolment{}).Where("id = ? AND consumed_at IS NULL AND revoked_at IS NULL", grant.ID).Select("ConsumedAt").Updates(&grant) |
| - if updated.Error != nil { |
| - return storeError(updated.Error) |
| - } |
| - if updated.RowsAffected != 1 { |
| - return ErrConflict |
| - } |
| - result, err = mintRunnerCredential(tx, runner, now) |
| - if err != nil { |
| - return err |
| - } |
| - return appendAudit(tx, Actor{Address: runner.Person}, "runner.enrolment.exchange", runner.ID) |
| - }) |
| - if err != nil { |
| - return runnerproto.RunnerCredential{}, err |
| - } |
| - if denied != nil { |
| - return runnerproto.RunnerCredential{}, denied |
| - } |
| - return result, nil |
| +func (s *Store) approveOrInspect(ctx context.Context, a Actor, code string, approve bool) (Runner, error) { |
| + return s.enrolments().ApproveOrInspect(ctx, a, code, approve) |
| } |
diff --git a/internal/equipo/handlers.go b/internal/equipo/handlers.go| index d04d861a..db558706 100644 |
| --- a/internal/equipo/handlers.go |
| +++ b/internal/equipo/handlers.go |
| @@ -28,6 +28,7 @@ type budgetForm struct { |
| Fields []budgetField |
| } |
| type pageData struct { |
| + Onboarding setup.OnboardingView |
| Invite setup.InviteView |
| Invitations []Invitation |
| Specialists []Specialist |
| @@ -48,7 +49,7 @@ type pageData struct { |
| Recovery *team.RecoverySnapshot |
| Question TaskQuestion |
| - Origin, UserCode string |
| + PairingConfirmation, Origin, UserCode string |
| Enrolment Runner |
| Runners []Runner |
| Nav []NavItem |
diff --git a/internal/equipo/migrations/0028_onboarding.sql b/internal/equipo/migrations/0028_onboarding.sql| new file mode 100644 |
| index 00000000..9c168957 |
| --- /dev/null |
| +++ b/internal/equipo/migrations/0028_onboarding.sql |
| @@ -0,0 +1,9 @@ |
| +CREATE TABLE onboarding_states ( |
| + person text PRIMARY KEY, |
| + revision integer, |
| + provider_choice text, |
| + runner_id text, |
| + account_setup_id text, |
| + completed text |
| +); |
| +ALTER TABLE runner_enrolments ADD COLUMN created_at datetime; |
diff --git a/internal/equipo/migrations/schema.sql b/internal/equipo/migrations/schema.sql| index 4df229d6..d8cc42ae 100644 |
| --- a/internal/equipo/migrations/schema.sql |
| +++ b/internal/equipo/migrations/schema.sql |
| @@ -418,3 +418,12 @@ CREATE TABLE invitation_requests ( |
| result text, |
| PRIMARY KEY(principal, operation, resource, request_id) |
| ); |
| +CREATE TABLE onboarding_states ( |
| + person text PRIMARY KEY, |
| + revision integer, |
| + provider_choice text, |
| + runner_id text, |
| + account_setup_id text, |
| + completed text |
| +); |
| +ALTER TABLE runner_enrolments ADD COLUMN created_at datetime; |
diff --git a/internal/equipo/onboarding.go b/internal/equipo/onboarding.go| new file mode 100644 |
| index 00000000..4db2f284 |
| --- /dev/null |
| +++ b/internal/equipo/onboarding.go |
| @@ -0,0 +1,34 @@ |
| +package equipo |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo/setup" |
| + "amadan.net/oficina/equipo/internal/release" |
| + "amadan.net/rastrillo/rastrillo" |
| + "amadan.net/rastrillo/rastrillo/auth" |
| + "net/http" |
| +) |
| + |
| +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, |
| + Actor: func(r *http.Request) (Actor, error) { |
| + id, ok := auth.From(r) |
| + if !ok { |
| + return Actor{}, ErrForbidden |
| + } |
| + return Actor{Address: id.Address}, nil |
| + }, |
| + Render: func(w http.ResponseWriter, r *http.Request, v setup.OnboardingView) { |
| + data, e := a.page(r, "connections") |
| + if e != nil { |
| + a.failure(w, r, e) |
| + return |
| + } |
| + data.Onboarding = v |
| + data.Title = "onboarding.title" |
| + render(w, "onboarding", data) |
| + }, |
| + } |
| +} |
diff --git a/internal/equipo/render.go b/internal/equipo/render.go| index 19cab6ac..32edfe99 100644 |
| --- a/internal/equipo/render.go |
| +++ b/internal/equipo/render.go |
| @@ -27,7 +27,7 @@ var assets = rastrillo.NewAssets(appFS) |
| var pages = map[string]*template.Template{} |
| func init() { |
| - for _, name := range []string{"invite", "playbooks", "playbook_form", "playbook_diff", "specialist_form", "template_library", "template_diff", "conversation", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "signin_page", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval"} { |
| + for _, name := range []string{"onboarding", "invite", "playbooks", "playbook_form", "playbook_diff", "specialist_form", "template_library", "template_diff", "conversation", "thread", "plan", "coordinator", "preferences", "index", "empty", "projects", "project", "project_form", "people", "settings", "specialist", "errors", "signin_page", "form_error", "runners", "tasks", "task", "task_form", "question", "merge", "connections", "recovery", "recovery_form", "rendered_approval"} { |
| page := template.Must(template.New("layout"). |
| Funcs(ui.Funcs(ui.WithIcons(icons.Icon, icons.Assets))). |
| Funcs(template.FuncMap{"projectAllows": library.ProjectAllowed, "asset": assets.Path, "copy": copyText, "taskGroups": func() []string { return []string{"needs-person", "running", "queued", "finished"} }, |
diff --git a/internal/equipo/runner_handlers.go b/internal/equipo/runner_handlers.go| index 49d886a3..266f68f8 100644 |
| --- a/internal/equipo/runner_handlers.go |
| +++ b/internal/equipo/runner_handlers.go |
| @@ -1,6 +1,7 @@ |
| package equipo |
| import ( |
| + "amadan.net/oficina/equipo/internal/equipo/setup" |
| "context" |
| "errors" |
| "mime" |
| @@ -124,6 +125,7 @@ func (a *application) exchangeEnrolment(w http.ResponseWriter, r *http.Request) |
| } |
| func (a *application) enrolmentPage(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| w.Header().Set("Referrer-Policy", "no-referrer") |
| data, err := a.page(r, "connections") |
| if err != nil { |
| @@ -142,17 +144,12 @@ func (a *application) enrolmentPage(w http.ResponseWriter, r *http.Request) { |
| a.failure(w, r, err) |
| return |
| } |
| - if code := r.URL.Query().Get("user_code"); code != "" { |
| - data.Enrolment, err = a.store.approveOrInspect(r.Context(), Actor{Address: id.Address}, code, false) |
| - if err != nil { |
| - a.runnerFormFailure(w, r, err) |
| - return |
| - } |
| - data.UserCode = code |
| - } |
| + |
| a.renderLive(w, r, "runners", data) |
| } |
| func (a *application) approveEnrolment(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + w.Header().Set("Referrer-Policy", "no-referrer") |
| r.Body = http.MaxBytesReader(w, r.Body, 4096) |
| if r.ParseForm() != nil { |
| a.failure(w, r, ErrInvalid) |
| @@ -163,6 +160,35 @@ func (a *application) approveEnrolment(w http.ResponseWriter, r *http.Request) { |
| a.failure(w, r, ErrForbidden) |
| return |
| } |
| + code := r.PostForm.Get("user_code") |
| + for k, v := range r.PostForm { |
| + if len(v) != 1 || (k != "user_code" && k != "action" && k != "confirmation") { |
| + a.failure(w, r, ErrInvalid) |
| + return |
| + } |
| + } |
| + if r.PostForm.Get("action") == "inspect" { |
| + data, err := a.page(r, "connections") |
| + if err != nil { |
| + a.failure(w, r, err) |
| + return |
| + } |
| + data.Enrolment, err = a.store.approveOrInspect(r.Context(), Actor{Address: id.Address}, code, false) |
| + if err != nil { |
| + a.runnerFormFailure(w, r, err) |
| + return |
| + } |
| + data.Title = "runner.title" |
| + data.Origin = a.origin |
| + data.UserCode = code |
| + data.PairingConfirmation = setup.PairingConfirmation(a.store.invitationKey, id.Address, code, a.store.runnerClock.Now()) |
| + render(w, "runners", data) |
| + return |
| + } |
| + if r.PostForm.Get("action") != "approve" || !setup.ConfirmPairing(a.store.invitationKey, id.Address, code, r.PostForm.Get("confirmation"), a.store.runnerClock.Now()) { |
| + a.failure(w, r, ErrForbidden) |
| + return |
| + } |
| if err := a.store.ApproveEnrolment(r.Context(), Actor{Address: id.Address}, r.PostForm.Get("user_code")); err != nil { |
| a.runnerFormFailure(w, r, err) |
| return |
diff --git a/internal/equipo/runner_models.go b/internal/equipo/runner_models.go| index 75228e47..1de08de6 100644 |
| --- a/internal/equipo/runner_models.go |
| +++ b/internal/equipo/runner_models.go |
| @@ -1,49 +1,15 @@ |
| package equipo |
| import ( |
| + "amadan.net/oficina/equipo/internal/equipo/setup" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| "time" |
| ) |
| -type Runner struct { |
| - TrialOwner string `gorm:"-"` |
| - TrialAt time.Time `gorm:"-"` |
| - TrialVersions string `gorm:"-"` |
| - ID string `gorm:"primaryKey"` |
| - Person string `gorm:"index:runner_person"` |
| - MachineKeyHash string |
| - Label string |
| - Revision int64 |
| - RevokedAt *time.Time |
| -} |
| - |
| +type Runner = setup.Runner |
| type RunnerPrincipal = runnerproto.RunnerPrincipal |
| - |
| -type runnerRecord struct { |
| - Runner `gorm:"embedded"` |
| - InstanceID string |
| -} |
| - |
| -func (runnerRecord) TableName() string { return "runners" } |
| - |
| -type runnerEnrolment struct { |
| - ID string `gorm:"primaryKey"` |
| - InstanceID string |
| - Audience string |
| - MachinePublicKey string |
| - MachineKeyHash string |
| - Label string |
| - DeviceSecretHash string `gorm:"uniqueIndex:runner_device_secret"` |
| - UserCodeHash string `gorm:"uniqueIndex:runner_user_code"` |
| - Challenge string |
| - ExpiresAt time.Time |
| - NextPollAt time.Time |
| - Person string |
| - RunnerID string |
| - ApprovedAt *time.Time |
| - ConsumedAt *time.Time |
| - RevokedAt *time.Time |
| -} |
| +type runnerRecord = setup.RunnerRecord |
| +type runnerEnrolment = setup.EnrolmentRecord |
| type runnerCredentialRecord struct { |
| ID string `gorm:"primaryKey"` |
diff --git a/internal/equipo/setup/enrolment.go b/internal/equipo/setup/enrolment.go| new file mode 100644 |
| index 00000000..3333ddcd |
| --- /dev/null |
| +++ b/internal/equipo/setup/enrolment.go |
| @@ -0,0 +1,241 @@ |
| +package setup |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/base32" |
| + "errors" |
| + "gorm.io/gorm" |
| + "strings" |
| + "time" |
| +) |
| + |
| +type Enrolments struct { |
| + Write func(context.Context, func(*gorm.DB) error) error |
| + Now func() time.Time |
| + Instance func(*gorm.DB) (string, error) |
| + Rate func(*gorm.DB, string, time.Time, time.Duration, int) (bool, error) |
| + Secret func() string |
| + Hash func(string, string) string |
| + Member func(*gorm.DB, string) (Member, error) |
| + Audit func(*gorm.DB, Actor, string, string) error |
| + Error func(error) error |
| + Runner func(*gorm.DB, string, string) (RunnerRecord, error) |
| + Mint func(*gorm.DB, RunnerRecord, time.Time) (runnerproto.RunnerCredential, error) |
| + Invalid, Forbidden, Conflict, RunnerRateLimited, EnrolmentPending error |
| +} |
| + |
| +func (s *Enrolments) BeginEnrolment(ctx context.Context, machinePublicKey, label string) (runnerproto.DeviceCode, error) { |
| + if (runnerproto.BeginEnrolmentRequest{Version: 1, MachinePublicKey: machinePublicKey, Label: label}).Validate() != nil { |
| + return runnerproto.DeviceCode{}, s.Invalid |
| + } |
| + var result runnerproto.DeviceCode |
| + var denied error |
| + err := s.Write(ctx, func(tx *gorm.DB) error { |
| + instance, err := s.Instance(tx) |
| + if err != nil { |
| + return err |
| + } |
| + now := s.Now().UTC() |
| + hash := runnerproto.MachineKeyHash(machinePublicKey) |
| + for _, rate := range []struct { |
| + key string |
| + period time.Duration |
| + limit int |
| + }{{"create:" + instance, time.Minute, 60}, {"machine:" + instance + ":" + hash, 10 * time.Minute, 5}} { |
| + allowed, err := s.Rate(tx, rate.key, now, rate.period, rate.limit) |
| + if err != nil { |
| + return err |
| + } |
| + if !allowed { |
| + denied = s.RunnerRateLimited |
| + return nil |
| + } |
| + } |
| + userBytes := make([]byte, 7) |
| + rand.Read(userBytes) |
| + userCode := base32.NewEncoding("0123456789ABCDEFGHJKMNPQRSTVWXYZ").WithPadding(base32.NoPadding).EncodeToString(userBytes)[:10] |
| + secret := s.Secret() |
| + grant := EnrolmentRecord{ID: rand.Text(), InstanceID: instance, Audience: runnerproto.DeviceAudience, MachinePublicKey: machinePublicKey, MachineKeyHash: hash, Label: label, CreatedAt: now, DeviceSecretHash: s.Hash(runnerproto.DeviceAudience, secret), UserCodeHash: s.Hash(instance, userCode), Challenge: s.Secret(), ExpiresAt: now.Add(10 * time.Minute), NextPollAt: now} |
| + if err := tx.Create(&grant).Error; err != nil { |
| + return s.Error(err) |
| + } |
| + result = runnerproto.DeviceCode{Version: 1, EnrolmentID: grant.ID, InstanceID: instance, DeviceSecret: secret, UserCode: userCode, Challenge: grant.Challenge, ExpiresAt: grant.ExpiresAt, PollIntervalSeconds: runnerproto.PollIntervalSeconds} |
| + return s.Audit(tx, Actor{Address: "device"}, "runner.enrolment.begin", grant.ID) |
| + }) |
| + if err != nil { |
| + return runnerproto.DeviceCode{}, err |
| + } |
| + if denied != nil { |
| + return runnerproto.DeviceCode{}, denied |
| + } |
| + return result, nil |
| +} |
| + |
| +func validUserCode(code string) bool { |
| + return len(code) == 10 && strings.Trim(code, "0123456789ABCDEFGHJKMNPQRSTVWXYZ") == "" |
| +} |
| + |
| +func (s *Enrolments) byCode(tx *gorm.DB, instance, code string, now time.Time) (EnrolmentRecord, error) { |
| + var grant EnrolmentRecord |
| + if !validUserCode(code) { |
| + return grant, s.Invalid |
| + } |
| + if err := tx.Where("user_code_hash = ?", s.Hash(instance, code)).First(&grant).Error; err != nil { |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return grant, s.Forbidden |
| + } |
| + return grant, s.Error(err) |
| + } |
| + if grant.CreatedAt.IsZero() || grant.InstanceID != instance || grant.Audience != runnerproto.DeviceAudience || !now.Before(grant.ExpiresAt) || grant.ApprovedAt != nil || grant.ConsumedAt != nil || grant.RevokedAt != nil { |
| + return grant, s.Forbidden |
| + } |
| + return grant, nil |
| +} |
| + |
| +func (s *Enrolments) ApproveOrInspect(ctx context.Context, actor Actor, userCode string, approve bool) (Runner, error) { |
| + var result Runner |
| + var denied error |
| + err := s.Write(ctx, func(tx *gorm.DB) error { |
| + member, err := s.Member(tx, actor.Address) |
| + if err != nil { |
| + return err |
| + } |
| + instance, err := s.Instance(tx) |
| + if err != nil { |
| + return err |
| + } |
| + now := s.Now().UTC() |
| + allowed, err := s.Rate(tx, "approve:"+instance+":"+member.Address, now, time.Minute, 10) |
| + if err != nil { |
| + return err |
| + } |
| + if !allowed { |
| + denied = s.RunnerRateLimited |
| + return nil |
| + } |
| + grant, err := s.byCode(tx, instance, userCode, now) |
| + if err != nil { |
| + if errors.Is(err, s.Forbidden) || errors.Is(err, s.Invalid) { |
| + denied = err |
| + return nil |
| + } |
| + return err |
| + } |
| + result = Runner{Person: member.Address, MachineKeyHash: grant.MachineKeyHash, Label: grant.Label, RequestedAt: grant.CreatedAt, Revision: 1} |
| + if !approve { |
| + return nil |
| + } |
| + 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 |
| + } |
| + if existing != 0 { |
| + return s.Conflict |
| + } |
| + result.ID = rand.Text() |
| + if err := tx.Create(&RunnerRecord{Runner: result, InstanceID: instance}).Error; err != nil { |
| + return s.Error(err) |
| + } |
| + grant.Person = member.Address |
| + grant.RunnerID = result.ID |
| + grant.ApprovedAt = &now |
| + updated := tx.Model(&EnrolmentRecord{}).Where("id = ? AND approved_at IS NULL AND revoked_at IS NULL", grant.ID).Select("Person", "RunnerID", "ApprovedAt").Updates(&grant) |
| + if updated.Error != nil { |
| + return s.Error(updated.Error) |
| + } |
| + if updated.RowsAffected != 1 { |
| + return s.Conflict |
| + } |
| + return s.Audit(tx, actor, "runner.enrolment.approve", result.ID) |
| + }) |
| + if err != nil { |
| + return Runner{}, err |
| + } |
| + if denied != nil { |
| + return Runner{}, denied |
| + } |
| + return result, nil |
| +} |
| + |
| +func (s *Enrolments) ApproveEnrolment(ctx context.Context, actor Actor, userCode string) error { |
| + _, err := s.ApproveOrInspect(ctx, actor, userCode, true) |
| + return err |
| +} |
| + |
| +func (s *Enrolments) ExchangeEnrolment(ctx context.Context, deviceSecret string, proof runnerproto.ExchangeProof) (runnerproto.RunnerCredential, error) { |
| + if (runnerproto.ExchangeEnrolmentRequest{Version: 1, DeviceSecret: deviceSecret, Proof: proof}).Validate() != nil { |
| + return runnerproto.RunnerCredential{}, s.Forbidden |
| + } |
| + var result runnerproto.RunnerCredential |
| + var denied error |
| + err := s.Write(ctx, func(tx *gorm.DB) error { |
| + instance, err := s.Instance(tx) |
| + if err != nil { |
| + return err |
| + } |
| + now := s.Now().UTC() |
| + var grant EnrolmentRecord |
| + if err := tx.Where("device_secret_hash = ?", s.Hash(runnerproto.DeviceAudience, deviceSecret)).First(&grant).Error; err != nil { |
| + if errors.Is(err, gorm.ErrRecordNotFound) { |
| + return s.Forbidden |
| + } |
| + return s.Error(err) |
| + } |
| + if grant.Audience != runnerproto.DeviceAudience || grant.InstanceID != instance || grant.ID != proof.EnrolmentID || grant.Challenge != proof.Challenge || !now.Before(grant.ExpiresAt) || grant.ConsumedAt != nil || grant.RevokedAt != nil { |
| + return s.Forbidden |
| + } |
| + key, err := runnerproto.DecodeBytes(grant.MachinePublicKey, ed25519.PublicKeySize) |
| + if err != nil || runnerproto.MachineKeyHash(grant.MachinePublicKey) != grant.MachineKeyHash { |
| + return s.Forbidden |
| + } |
| + signature, _ := runnerproto.DecodeBytes(proof.Signature, ed25519.SignatureSize) |
| + if !ed25519.Verify(key, runnerproto.EnrolmentProofMessage(instance, proof), signature) { |
| + return s.Forbidden |
| + } |
| + if now.Before(grant.NextPollAt) { |
| + denied = s.RunnerRateLimited |
| + return nil |
| + } |
| + grant.NextPollAt = now.Add(5 * time.Second) |
| + if err := tx.Model(&EnrolmentRecord{}).Where("id = ?", grant.ID).Select("NextPollAt").Updates(&grant).Error; err != nil { |
| + return s.Error(err) |
| + } |
| + if grant.ApprovedAt == nil { |
| + denied = s.EnrolmentPending |
| + return nil |
| + } |
| + runner, err := s.Runner(tx, instance, grant.RunnerID) |
| + if err != nil { |
| + return err |
| + } |
| + if runner.Person != grant.Person || runner.MachineKeyHash != grant.MachineKeyHash { |
| + return s.Forbidden |
| + } |
| + if _, err := s.Member(tx, runner.Person); err != nil { |
| + return err |
| + } |
| + grant.ConsumedAt = &now |
| + updated := tx.Model(&EnrolmentRecord{}).Where("id = ? AND consumed_at IS NULL AND revoked_at IS NULL", grant.ID).Select("ConsumedAt").Updates(&grant) |
| + if updated.Error != nil { |
| + return s.Error(updated.Error) |
| + } |
| + if updated.RowsAffected != 1 { |
| + return s.Conflict |
| + } |
| + result, err = s.Mint(tx, runner, now) |
| + if err != nil { |
| + return err |
| + } |
| + return s.Audit(tx, Actor{Address: runner.Person}, "runner.enrolment.exchange", runner.ID) |
| + }) |
| + if err != nil { |
| + return runnerproto.RunnerCredential{}, err |
| + } |
| + if denied != nil { |
| + return runnerproto.RunnerCredential{}, denied |
| + } |
| + return result, nil |
| +} |
diff --git a/internal/equipo/setup/invite_handlers.go b/internal/equipo/setup/invite_handlers.go| index 9ac709d5..1945f437 100644 |
| --- a/internal/equipo/setup/invite_handlers.go |
| +++ b/internal/equipo/setup/invite_handlers.go |
| @@ -174,7 +174,7 @@ func (h *Handler) Accept(w http.ResponseWriter, r *http.Request) { |
| h.failure(w, r, err) |
| return |
| } |
| - http.Redirect(w, r, "/conversation", http.StatusSeeOther) |
| + http.Redirect(w, r, "/onboarding", http.StatusSeeOther) |
| } |
| func (h *Handler) Revoke(w http.ResponseWriter, r *http.Request) { |
| privacy(w) |
diff --git a/internal/equipo/setup/invites.go b/internal/equipo/setup/invites.go| index 796a9e41..43aac92e 100644 |
| --- a/internal/equipo/setup/invites.go |
| +++ b/internal/equipo/setup/invites.go |
| @@ -40,7 +40,7 @@ type inviteRequest struct { |
| func (inviteRequest) TableName() string { return "invitation_requests" } |
| -var Models = []any{&InvitationRecord{}, &inviteRequest{}} |
| +var Models = []any{&InvitationRecord{}, &inviteRequest{}, &OnboardingRecord{}} |
| type Dependencies struct { |
| Normalize func(string) string |
| @@ -258,6 +258,9 @@ func (s *Store) Accept(a kernel.Actor, id, secret string, m kernel.Mutation) (ke |
| if err != nil { |
| return out, err |
| } |
| + if err = s.initializeOnboarding(a); err != nil { |
| + return out, err |
| + } |
| r.State = "accepted" |
| r.Revision++ |
| now := s.deps.Now |
diff --git a/internal/equipo/setup/onboarding.go b/internal/equipo/setup/onboarding.go| new file mode 100644 |
| index 00000000..2914b5cf |
| --- /dev/null |
| +++ b/internal/equipo/setup/onboarding.go |
| @@ -0,0 +1,190 @@ |
| +package setup |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "slices" |
| + "time" |
| + |
| + "gorm.io/gorm" |
| + "gorm.io/gorm/clause" |
| +) |
| + |
| +type OnboardingState struct { |
| + Revision int64 |
| + CurrentStep, ProviderChoice, RunnerID, AccountSetupID string |
| + Completed map[string]bool |
| +} |
| +type OnboardingRecord struct { |
| + Person string `gorm:"primaryKey"` |
| + Revision int64 |
| + ProviderChoice, RunnerID, AccountSetupID string |
| + Completed map[string]bool `gorm:"serializer:json"` |
| +} |
| + |
| +func (OnboardingRecord) TableName() string { return "onboarding_states" } |
| + |
| +var onboardingSteps = []string{"welcome", "account", "runner", "specialists", "first_task"} |
| + |
| +func (r OnboardingRecord) view() OnboardingState { |
| + out := OnboardingState{Revision: r.Revision, ProviderChoice: r.ProviderChoice, RunnerID: r.RunnerID, AccountSetupID: r.AccountSetupID, Completed: r.Completed, CurrentStep: "complete"} |
| + for _, step := range onboardingSteps { |
| + if !r.Completed[step] { |
| + out.CurrentStep = step |
| + break |
| + } |
| + } |
| + return out |
| +} |
| +func (s *Store) onboardingMember(a Actor) error { |
| + m, e := s.deps.Member(s.tx, a.Address) |
| + if e != nil { |
| + return e |
| + } |
| + if !m.Active || (m.Role != RoleOwner && m.Role != RoleMember) { |
| + return s.deps.Forbidden |
| + } |
| + return nil |
| +} |
| +func (s *Store) initializeOnboarding(a Actor) error { |
| + r := OnboardingRecord{Person: a.Address, Revision: 1, Completed: map[string]bool{}} |
| + return s.tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&r).Error |
| +} |
| +func (s *Store) onboarding(a Actor) (OnboardingRecord, error) { |
| + var r OnboardingRecord |
| + if e := s.onboardingMember(a); e != nil { |
| + return r, e |
| + } |
| + e := s.tx.Where("person=?", a.Address).First(&r).Error |
| + if errors.Is(e, gorm.ErrRecordNotFound) { |
| + return OnboardingRecord{Person: a.Address, Revision: 1, Completed: map[string]bool{}}, nil |
| + } |
| + return r, e |
| +} |
| +func (s *Application) Onboarding(ctx context.Context, a Actor) (out OnboardingState, err error) { |
| + a.Address = s.Normalize(a.Address) |
| + err = s.Read(ctx, func(tx *gorm.DB) error { r, e := s.At(tx).onboarding(a); out = r.view(); return e }) |
| + if err != nil { |
| + out = OnboardingState{} |
| + } |
| + return |
| +} |
| +func (s *Application) AdvanceOnboarding(ctx context.Context, a Actor, step string, m Mutation) (OnboardingState, error) { |
| + return s.changeOnboarding(ctx, a, step, "", m) |
| +} |
| +func (s *Application) ChooseOnboardingProvider(ctx context.Context, a Actor, choice string, m Mutation) (OnboardingState, error) { |
| + return s.changeOnboarding(ctx, a, "choose", choice, m) |
| +} |
| +func (s *Application) changeOnboarding(ctx context.Context, a Actor, step, choice string, m Mutation) (out OnboardingState, err error) { |
| + a.Address = s.Normalize(a.Address) |
| + err = s.Write(ctx, func(tx *gorm.DB) error { |
| + var e error |
| + out, e = s.At(tx).advanceOnboarding(a, step, choice, m) |
| + return e |
| + }) |
| + if err != nil { |
| + out = OnboardingState{} |
| + } |
| + return |
| +} |
| +func (s *Store) advanceOnboarding(a Actor, step, choice string, m Mutation) (OnboardingState, error) { |
| + r, e := s.onboarding(a) |
| + if e != nil { |
| + return OnboardingState{}, e |
| + } |
| + if step != "choose" && !slices.Contains(onboardingSteps, step) { |
| + return OnboardingState{}, s.deps.Invalid |
| + } |
| + if step == "choose" && choice != "codex" && choice != "claude" { |
| + return OnboardingState{}, s.deps.Invalid |
| + } |
| + input := struct { |
| + Step, Choice string |
| + Revision int64 |
| + }{step, choice, m.Revision} |
| + var out OnboardingState |
| + if ok, e := s.replay(a, "onboarding", a.Address, m, input, &out); ok || e != nil { |
| + return out, e |
| + } |
| + if r.Revision != m.Revision { |
| + return out, s.deps.Conflict |
| + } |
| + if step == "choose" { |
| + if r.Completed["account"] || r.view().CurrentStep != "account" { |
| + return out, s.deps.Conflict |
| + } |
| + r.ProviderChoice = choice |
| + } else { |
| + if r.view().CurrentStep != step { |
| + return out, s.deps.Conflict |
| + } |
| + if e = s.onboardingPrerequisite(a, &r, step); e != nil { |
| + return out, e |
| + } |
| + r.Completed[step] = true |
| + } |
| + if e = s.initializeOnboarding(a); e != nil { |
| + return out, e |
| + } |
| + r.Revision++ |
| + q := s.tx.Model(&OnboardingRecord{}).Where("person=? AND revision=?", a.Address, m.Revision).Select("Revision", "ProviderChoice", "RunnerID", "AccountSetupID", "Completed").Updates(&r) |
| + if q.Error != nil { |
| + return out, q.Error |
| + } |
| + if q.RowsAffected != 1 { |
| + return out, s.deps.Conflict |
| + } |
| + if e = s.deps.Audit(s.tx, a, "onboarding."+step, a.Address); e != nil { |
| + return out, e |
| + } |
| + out = r.view() |
| + return out, s.save(a, "onboarding", a.Address, m, input, out) |
| +} |
| +func (s *Store) onboardingPrerequisite(a Actor, r *OnboardingRecord, step string) error { |
| + switch step { |
| + case "account": |
| + if r.ProviderChoice == "" { |
| + return s.deps.Conflict |
| + } |
| + case "runner": |
| + // A server-observed credential exchange and connection are prerequisites. |
| + // Approval alone is not evidence of a paired, signed-in runner. |
| + var rows []struct{ ID, ReportsJSON string } |
| + q := s.tx.Raw(`SELECT runners.id, c.reports_json FROM runners JOIN runner_enrolments e ON e.runner_id=runners.id JOIN connections c ON c.runner_id=runners.id WHERE runners.person=? AND runners.revoked_at IS NULL AND e.consumed_at IS NOT NULL AND e.revoked_at IS NULL AND c.person=? AND c.last_seen>? ORDER BY runners.id`, a.Address, a.Address, s.deps.Now.Add(-2*time.Minute)).Scan(&rows) |
| + if q.Error != nil { |
| + return q.Error |
| + } |
| + for _, row := range rows { |
| + var reports []runnerproto.ConnectionReport |
| + if e := json.Unmarshal([]byte(row.ReportsJSON), &reports); e != nil { |
| + return e |
| + } |
| + for _, report := range reports { |
| + if report.Provider == r.ProviderChoice && report.Available && report.ReadIsolation { |
| + r.RunnerID = row.ID |
| + return nil |
| + } |
| + } |
| + } |
| + return s.deps.Conflict |
| + case "specialists": |
| + var count int64 |
| + if e := s.tx.Table("specialists").Where("archived=? AND key IN ?", false, []string{"product", "design", "copy", "engineering", "review"}).Count(&count).Error; e != nil { |
| + return e |
| + } |
| + if count != 5 { |
| + return s.deps.Conflict |
| + } |
| + case "first_task": |
| + var count int64 |
| + if e := s.tx.Table("tasks").Where("requester=? AND kind=?", a.Address, "recommendation").Count(&count).Error; e != nil { |
| + return e |
| + } |
| + if count == 0 { |
| + return s.deps.Conflict |
| + } |
| + } |
| + return nil |
| +} |
diff --git a/internal/equipo/setup/onboarding_handlers.go b/internal/equipo/setup/onboarding_handlers.go| new file mode 100644 |
| index 00000000..e6f84e77 |
| --- /dev/null |
| +++ b/internal/equipo/setup/onboarding_handlers.go |
| @@ -0,0 +1,92 @@ |
| +package setup |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "net/http" |
| + "strconv" |
| + |
| + "amadan.net/oficina/equipo/internal/release" |
| + "github.com/go-chi/chi/v5" |
| +) |
| + |
| +type OnboardingOperations interface { |
| + Onboarding(context.Context, Actor) (OnboardingState, error) |
| + AdvanceOnboarding(context.Context, Actor, string, Mutation) (OnboardingState, error) |
| + ChooseOnboardingProvider(context.Context, Actor, string, Mutation) (OnboardingState, error) |
| +} |
| +type OnboardingView struct { |
| + State OnboardingState |
| + RequestID, InstallCommand string |
| +} |
| +type OnboardingHandler struct { |
| + InstallAvailable func() bool |
| + Store OnboardingOperations |
| + Actor func(*http.Request) (Actor, error) |
| + Render func(http.ResponseWriter, *http.Request, OnboardingView) |
| + Failure func(http.ResponseWriter, *http.Request, error) |
| + Invalid error |
| + Origin, Version, InstanceID string |
| + Manifest release.Manifest |
| +} |
| + |
| +func (h *OnboardingHandler) Routes(r chi.Router) { |
| + r.Get("/onboarding", h.Page) |
| + r.Post("/onboarding/advance", h.Advance) |
| + r.Post("/onboarding/provider", h.Provider) |
| +} |
| +func (h *OnboardingHandler) Page(w http.ResponseWriter, r *http.Request) { |
| + privacy(w) |
| + a, e := h.Actor(r) |
| + if e != nil { |
| + h.Failure(w, r, e) |
| + return |
| + } |
| + state, e := h.Store.Onboarding(r.Context(), a) |
| + if e != nil { |
| + h.Failure(w, r, e) |
| + return |
| + } |
| + v := OnboardingView{State: state, RequestID: rand.Text()} |
| + if h.Manifest.InstallCertified() && h.InstallAvailable != nil && h.InstallAvailable() { |
| + v.InstallCommand, _ = release.InstallCommand(h.Origin, h.Version, h.InstanceID) |
| + } |
| + h.Render(w, r, v) |
| +} |
| +func (h *OnboardingHandler) change(w http.ResponseWriter, r *http.Request, provider bool) { |
| + privacy(w) |
| + a, e := h.Actor(r) |
| + if e != nil { |
| + h.Failure(w, r, e) |
| + return |
| + } |
| + r.Body = http.MaxBytesReader(w, r.Body, 4096) |
| + if r.ParseForm() != nil { |
| + h.Failure(w, r, h.Invalid) |
| + return |
| + } |
| + for k, v := range r.PostForm { |
| + if len(v) != 1 || (k != "revision" && k != "request_id" && k != "step" && k != "provider") { |
| + h.Failure(w, r, h.Invalid) |
| + return |
| + } |
| + } |
| + rev, e := strconv.ParseInt(r.PostForm.Get("revision"), 10, 64) |
| + if e != nil { |
| + h.Failure(w, r, h.Invalid) |
| + return |
| + } |
| + m := Mutation{Revision: rev, RequestID: r.PostForm.Get("request_id")} |
| + if provider { |
| + _, e = h.Store.ChooseOnboardingProvider(r.Context(), a, r.PostForm.Get("provider"), m) |
| + } else { |
| + _, e = h.Store.AdvanceOnboarding(r.Context(), a, r.PostForm.Get("step"), m) |
| + } |
| + if e != nil { |
| + h.Failure(w, r, e) |
| + return |
| + } |
| + http.Redirect(w, r, "/onboarding", http.StatusSeeOther) |
| +} |
| +func (h *OnboardingHandler) Advance(w http.ResponseWriter, r *http.Request) { h.change(w, r, false) } |
| +func (h *OnboardingHandler) Provider(w http.ResponseWriter, r *http.Request) { h.change(w, r, true) } |
diff --git a/internal/equipo/setup/onboarding_test.go b/internal/equipo/setup/onboarding_test.go| new file mode 100644 |
| index 00000000..9855b481 |
| --- /dev/null |
| +++ b/internal/equipo/setup/onboarding_test.go |
| @@ -0,0 +1,207 @@ |
| +package setup_test |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/base64" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "log/slog" |
| + "path/filepath" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/setup" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/migrate" |
| +) |
| + |
| +func onboardingStore(t *testing.T) (*equipo.Store, *db.DB, equipo.Actor) { |
| + t.Helper() |
| + d, e := db.Open(filepath.Join(t.TempDir(), "onboarding.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + if _, e = migrate.Apply(context.Background(), d, equipo.Schema); e != nil { |
| + t.Fatal(e) |
| + } |
| + s := equipo.NewStore(d) |
| + a := equipo.Actor{Address: "owner@example.com"} |
| + if e = s.Bootstrap(context.Background(), []string{a.Address}); e != nil { |
| + t.Fatal(e) |
| + } |
| + return s, d, a |
| +} |
| +func TestOnboardingInstallPrerequisites(t *testing.T) { |
| + ctx := context.Background() |
| + s, d, a := onboardingStore(t) |
| + state, e := s.Onboarding(ctx, a) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + advance := func(step string) { |
| + t.Helper() |
| + var err error |
| + state, err = s.AdvanceOnboarding(ctx, a, step, equipo.Mutation{RequestID: step, Revision: state.Revision}) |
| + if err != nil { |
| + t.Fatal(step, err) |
| + } |
| + } |
| + advance("welcome") |
| + if _, e = s.AdvanceOnboarding(ctx, a, "account", equipo.Mutation{RequestID: "no-choice", Revision: state.Revision}); !errors.Is(e, equipo.ErrConflict) { |
| + t.Fatal("account without choice", e) |
| + } |
| + state, e = s.ChooseOnboardingProvider(ctx, a, "codex", equipo.Mutation{RequestID: "choose", Revision: state.Revision}) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + advance("account") |
| + if state.CurrentStep != "runner" || !state.Completed["account"] || state.Completed["runner"] { |
| + t.Fatal("choice claims login", state) |
| + } |
| + if _, e = s.AdvanceOnboarding(ctx, a, "runner", equipo.Mutation{RequestID: "unpaired", Revision: state.Revision}); !errors.Is(e, equipo.ErrConflict) { |
| + t.Fatal("missing runner accepted", e) |
| + } |
| + exec := func(sql string, args ...any) { |
| + t.Helper() |
| + if e = d.G.Exec(sql, args...).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + exec("INSERT INTO runners(id,person,machine_key_hash,label,revision) VALUES('r',?,'machine','Fixture',1)", a.Address) |
| + exec("INSERT INTO runner_enrolments(id,runner_id) VALUES('e','r')") |
| + reports, _ := json.Marshal([]runnerproto.ConnectionReport{{Provider: "codex", Available: true, ReadIsolation: true}}) |
| + exec("INSERT INTO connections(id,runner_id,person,reports_json,last_seen) VALUES('c','r',?,?,?)", a.Address, string(reports), time.Now().UTC()) |
| + if _, e = s.AdvanceOnboarding(ctx, a, "runner", equipo.Mutation{RequestID: "approved-only", Revision: state.Revision}); !errors.Is(e, equipo.ErrConflict) { |
| + t.Fatal("approval claims exchange", e) |
| + } |
| + exec("UPDATE runner_enrolments SET consumed_at=?", time.Now().UTC()) |
| + exec("UPDATE connections SET person='other@example.com'") |
| + if _, e = s.AdvanceOnboarding(ctx, a, "runner", equipo.Mutation{RequestID: "other", Revision: state.Revision}); !errors.Is(e, equipo.ErrConflict) { |
| + t.Fatal("other person's account", e) |
| + } |
| + exec("UPDATE connections SET person=?", a.Address) |
| + exec("CREATE TRIGGER deny_onboarding_audit BEFORE INSERT ON audit_events BEGIN SELECT RAISE(ABORT,'fixture audit'); END") |
| + old := state.Revision |
| + if _, e = s.AdvanceOnboarding(ctx, a, "runner", equipo.Mutation{RequestID: "audit", Revision: old}); e == nil { |
| + t.Fatal("advance without audit") |
| + } |
| + state, e = s.Onboarding(ctx, a) |
| + if e != nil || state.Revision != old || state.Completed["runner"] { |
| + t.Fatal("non-atomic advance", state, e) |
| + } |
| + exec("DROP TRIGGER deny_onboarding_audit") |
| + advance("runner") |
| + if state.RunnerID != "r" { |
| + t.Fatal("missing persisted runner") |
| + } |
| + advance("specialists") |
| + if _, e = s.AdvanceOnboarding(ctx, a, "first_task", equipo.Mutation{RequestID: "missing-task", Revision: state.Revision}); !errors.Is(e, equipo.ErrConflict) { |
| + t.Fatal("invented first task", e) |
| + } |
| + exec("INSERT INTO tasks(id,requester,request_id) VALUES('task',?,'task')", a.Address) |
| + if _, e = s.AdvanceOnboarding(ctx, a, "first_task", equipo.Mutation{RequestID: "unsafe-task", Revision: state.Revision}); !errors.Is(e, equipo.ErrConflict) { |
| + t.Fatal("write task accepted as safe first task", e) |
| + } |
| + exec("UPDATE tasks SET kind='recommendation'") |
| + advance("first_task") |
| + if state.CurrentStep != "complete" { |
| + t.Fatal("incomplete", state) |
| + } |
| + if _, e = s.AdvanceOnboarding(ctx, a, "first_task", equipo.Mutation{RequestID: "first_task", Revision: 1}); !errors.Is(e, equipo.ErrConflict) { |
| + t.Fatal("changed replay input accepted", e) |
| + } |
| + exec("ALTER TABLE members RENAME TO missing_members") |
| + if _, e = s.Onboarding(ctx, a); e == nil { |
| + t.Fatal("roster error granted access") |
| + } |
| +} |
| +func TestOnboardingPairingConfirmation(t *testing.T) { |
| + now := time.Now().UTC() |
| + proof := setup.PairingConfirmation("key", "person", "0123456789", now) |
| + if !setup.ConfirmPairing("key", "person", "0123456789", proof, now) { |
| + t.Fatal("confirmation rejected") |
| + } |
| + for _, tc := range []struct { |
| + key, person, code string |
| + at time.Time |
| + }{{"key", "other", "0123456789", now}, {"key", "person", "1234567890", now}, {"other", "person", "0123456789", now}, {"key", "person", "0123456789", now.Add(5 * time.Minute)}} { |
| + if setup.ConfirmPairing(tc.key, tc.person, tc.code, proof, tc.at) { |
| + t.Fatal("confirmation binding or expiry bypass") |
| + } |
| + } |
| +} |
| + |
| +func TestOnboardingPairingUnique(t *testing.T) { |
| + s, _, a := onboardingStore(t) |
| + pub, _, e := ed25519.GenerateKey(rand.Reader) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + begin := func() runnerproto.DeviceCode { |
| + t.Helper() |
| + c, e := s.BeginEnrolment(context.Background(), base64.RawURLEncoding.EncodeToString(pub), "Fixture machine") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + return c |
| + } |
| + first, second := begin(), begin() |
| + if e = s.ApproveEnrolment(context.Background(), a, first.UserCode); e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = s.ApproveEnrolment(context.Background(), a, second.UserCode); !errors.Is(e, equipo.ErrConflict) { |
| + t.Fatal("duplicate runner for machine", e) |
| + } |
| +} |
| +func TestOnboardingInstallUpgrade(t *testing.T) { |
| + ctx := context.Background() |
| + d, e := db.Open(filepath.Join(t.TempDir(), "old.db"), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + defer d.Close() |
| + before := &migrate.Set{} |
| + for _, m := range equipo.Schema.All() { |
| + if m.ID != "equipo/0028_onboarding" { |
| + before.Add(m) |
| + } |
| + } |
| + if _, e = migrate.Apply(ctx, d, before); e != nil { |
| + t.Fatal(e) |
| + } |
| + s := equipo.NewStore(d) |
| + a := equipo.Actor{Address: "owner@example.com"} |
| + if e = s.Bootstrap(ctx, []string{a.Address}); e != nil { |
| + t.Fatal(e) |
| + } |
| + if e = d.G.Exec("INSERT INTO invitations(id,address,state,revision) VALUES('old',?,'accepted',2)", a.Address).Error; e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e = migrate.Apply(ctx, d, equipo.Schema); e != nil { |
| + t.Fatal(e) |
| + } |
| + var revision int64 |
| + if e = d.G.Raw("SELECT revision FROM invitations WHERE id='old'").Scan(&revision).Error; e != nil || revision != 2 { |
| + t.Fatal("historical invitation changed", e) |
| + } |
| + state, e := s.Onboarding(ctx, a) |
| + if e != nil || state.Revision != 1 || state.CurrentStep != "welcome" { |
| + t.Fatal("old invitee cannot resume", state, e) |
| + } |
| + if _, e = s.AdvanceOnboarding(ctx, a, "welcome", equipo.Mutation{RequestID: "resume", Revision: 1}); e != nil { |
| + t.Fatal(e) |
| + } |
| + if _, e = migrate.Apply(ctx, d, equipo.Schema); e != nil { |
| + t.Fatal(e) |
| + } |
| + state, e = s.Onboarding(ctx, a) |
| + if e != nil || state.CurrentStep != "account" || !state.Completed["welcome"] { |
| + t.Fatal("upgrade replay reset progress", state, e) |
| + } |
| +} |
diff --git a/internal/equipo/setup/pairing.go b/internal/equipo/setup/pairing.go| new file mode 100644 |
| index 00000000..26a05f15 |
| --- /dev/null |
| +++ b/internal/equipo/setup/pairing.go |
| @@ -0,0 +1,32 @@ |
| +package setup |
| + |
| +import ( |
| + "crypto/hmac" |
| + "crypto/sha256" |
| + "encoding/base64" |
| + "strconv" |
| + "strings" |
| + "time" |
| +) |
| + |
| +// PairingConfirmation binds the typed-code inspection to its verified person. |
| +func PairingConfirmation(key, person, code string, now time.Time) string { |
| + if key == "" || person == "" || !validUserCode(code) { |
| + return "" |
| + } |
| + expires := strconv.FormatInt(now.Add(5*time.Minute).Unix(), 10) |
| + return expires + "." + pairingMAC(key, person, code, expires) |
| +} |
| +func pairingMAC(key, person, code, expires string) string { |
| + h := hmac.New(sha256.New, []byte(key)) |
| + h.Write([]byte("equipo-pair-confirm\x00" + person + "\x00" + code + "\x00" + expires)) |
| + return base64.RawURLEncoding.EncodeToString(h.Sum(nil)) |
| +} |
| +func ConfirmPairing(key, person, code, proof string, now time.Time) bool { |
| + parts := strings.Split(proof, ".") |
| + if len(parts) != 2 || key == "" || !validUserCode(code) { |
| + return false |
| + } |
| + expires, e := strconv.ParseInt(parts[0], 10, 64) |
| + return e == nil && now.Unix() < expires && expires <= now.Add(5*time.Minute).Unix() && hmac.Equal([]byte(parts[1]), []byte(pairingMAC(key, person, code, parts[0]))) |
| +} |
diff --git a/internal/equipo/setup/runner_models.go b/internal/equipo/setup/runner_models.go| new file mode 100644 |
| index 00000000..757e0b19 |
| --- /dev/null |
| +++ b/internal/equipo/setup/runner_models.go |
| @@ -0,0 +1,45 @@ |
| +package setup |
| + |
| +import "time" |
| + |
| +type Runner struct { |
| + RequestedAt time.Time `gorm:"-"` |
| + TrialOwner string `gorm:"-"` |
| + TrialAt time.Time `gorm:"-"` |
| + TrialVersions string `gorm:"-"` |
| + ID string `gorm:"primaryKey"` |
| + Person string `gorm:"index:runner_person"` |
| + MachineKeyHash string |
| + Label string |
| + Revision int64 |
| + RevokedAt *time.Time |
| +} |
| + |
| +type RunnerRecord struct { |
| + Runner `gorm:"embedded"` |
| + InstanceID string |
| +} |
| + |
| +func (RunnerRecord) TableName() string { return "runners" } |
| + |
| +type EnrolmentRecord struct { |
| + CreatedAt time.Time |
| + ID string `gorm:"primaryKey"` |
| + InstanceID string |
| + Audience string |
| + MachinePublicKey string |
| + MachineKeyHash string |
| + Label string |
| + DeviceSecretHash string `gorm:"uniqueIndex:runner_device_secret"` |
| + UserCodeHash string `gorm:"uniqueIndex:runner_user_code"` |
| + Challenge string |
| + ExpiresAt time.Time |
| + NextPollAt time.Time |
| + Person string |
| + RunnerID string |
| + ApprovedAt *time.Time |
| + ConsumedAt *time.Time |
| + RevokedAt *time.Time |
| +} |
| + |
| +func (EnrolmentRecord) TableName() string { return "runner_enrolments" } |
diff --git a/internal/equipo/templates/onboarding.html b/internal/equipo/templates/onboarding.html| new file mode 100644 |
| index 00000000..eed0abc2 |
| --- /dev/null |
| +++ b/internal/equipo/templates/onboarding.html |
| @@ -0,0 +1,33 @@ |
| +{{define "content"}} |
| +<h1>{{copy "onboarding.title"}}</h1> |
| +<section equipo-card> |
| +<h2>{{copy (printf "onboarding.%s" .Onboarding.State.CurrentStep)}}</h2> |
| +{{if eq .Onboarding.State.CurrentStep "account"}} |
| +<p>{{copy "onboarding.account_pending"}}</p> |
| +<form method="post" action="/onboarding/provider" equipo-form> |
| +<input type="hidden" name="revision" value="{{.Onboarding.State.Revision}}"> |
| +<input type="hidden" name="request_id" value="{{.Onboarding.RequestID}}"> |
| +<label>{{copy "onboarding.account"}}<select name="provider" rst-select><option value="codex" {{if eq .Onboarding.State.ProviderChoice "codex"}}selected{{end}}>{{copy "onboarding.codex"}}</option><option value="claude" {{if eq .Onboarding.State.ProviderChoice "claude"}}selected{{end}}>{{copy "onboarding.claude"}}</option></select></label> |
| +<button rst-btn type="submit">{{copy "onboarding.choose"}}</button> |
| +</form> |
| +{{end}} |
| +{{if eq .Onboarding.State.CurrentStep "runner"}} |
| +<p>{{copy "onboarding.own_machine"}}</p> |
| +{{if .Onboarding.InstallCommand}}<pre>{{.Onboarding.InstallCommand}}</pre>{{else}}<p>{{copy "runner.install.release"}}</p>{{end}} |
| +<p>{{copy "onboarding.pair"}}</p><a href="/runners/enrol">{{copy "runner.title"}}</a> |
| +<p>{{copy "onboarding.account_pending"}}</p> |
| +{{end}} |
| +{{if eq .Onboarding.State.CurrentStep "specialists"}}<a href="/work">{{copy "onboarding.specialists"}}</a>{{end}} |
| +{{if eq .Onboarding.State.CurrentStep "first_task"}}<p>{{copy "onboarding.safe_first_task"}}</p><a href="/conversation">{{copy "conversation.title"}}</a>{{end}} |
| +{{if ne .Onboarding.State.CurrentStep "complete"}} |
| +<form method="post" action="/onboarding/advance" equipo-form> |
| +<input type="hidden" name="step" value="{{.Onboarding.State.CurrentStep}}"> |
| +<input type="hidden" name="revision" value="{{.Onboarding.State.Revision}}"> |
| +<input type="hidden" name="request_id" value="{{.Onboarding.RequestID}}-advance"> |
| +<button rst-btn="primary" type="submit">{{copy "onboarding.continue"}}</button> |
| +</form> |
| +{{else}}<a href="/conversation">{{copy "conversation.title"}}</a>{{end}} |
| +</section> |
| +<section equipo-card><h2>{{copy "onboarding.hosted"}}</h2><p>{{copy "onboarding.later"}}</p></section> |
| +<section equipo-card><h2>{{copy "onboarding.mac"}}</h2><p>{{copy "onboarding.mac_later"}}</p></section> |
| +{{end}} |
diff --git a/internal/equipo/templates/runners.html b/internal/equipo/templates/runners.html| index e321f20c..c03e18f4 100644 |
| --- a/internal/equipo/templates/runners.html |
| +++ b/internal/equipo/templates/runners.html |
| @@ -6,17 +6,21 @@ |
| <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.fingerprint"}}</dt><dd>{{.Enrolment.MachineKeyHash}}</dd> |
| <dt>{{copy "runner.person"}}</dt><dd>{{.Address}}</dd> |
| </dl> |
| <p>{{copy "runner.confirm"}}</p> |
| <form method="post" action="/runners/enrol" equipo-form> |
| +<input type="hidden" name="action" value="approve"> |
| +<input type="hidden" name="confirmation" value="{{.PairingConfirmation}}"> |
| <input type="hidden" name="user_code" value="{{.UserCode}}"> |
| <button rst-btn="primary" type="submit">{{copy "runner.approve"}}</button> |
| </form> |
| </section> |
| {{else}} |
| -<form method="get" action="/runners/enrol" equipo-form> |
| +<form method="post" action="/runners/enrol" equipo-form> |
| +<input type="hidden" name="action" value="inspect"> |
| <label>{{copy "runner.code"}}<input rst-input name="user_code" minlength="10" maxlength="10" autocomplete="off" required></label> |
| <button rst-btn="primary" type="submit">{{copy "runner.inspect"}}</button> |
| </form> |
diff --git a/internal/equipotest/enrolment_fixture_test.go b/internal/equipotest/enrolment_fixture_test.go| new file mode 100644 |
| index 00000000..c46592ce |
| --- /dev/null |
| +++ b/internal/equipotest/enrolment_fixture_test.go |
| @@ -0,0 +1,17 @@ |
| +package equipotest |
| + |
| +import ( |
| + "net/http" |
| + "net/url" |
| + "testing" |
| +) |
| + |
| +func inspectPairing(t *testing.T, c *http.Client, base, code string) string { |
| + t.Helper() |
| + res := clientPost(t, c, base+"/runners/enrol", testOrigin, url.Values{"user_code": {code}, "action": {"inspect"}}) |
| + body := readBody(t, res) |
| + if res.StatusCode != 200 { |
| + t.Fatalf("inspect HTTP %d", res.StatusCode) |
| + } |
| + return body |
| +} |
diff --git a/internal/equipotest/enrolment_test.go b/internal/equipotest/enrolment_test.go| index 3ea62d77..3ad681ef 100644 |
| --- a/internal/equipotest/enrolment_test.go |
| +++ b/internal/equipotest/enrolment_test.go |
| @@ -34,9 +34,7 @@ type enrolFixture struct { |
| func enrolStore(t *testing.T) enrolFixture { |
| t.Helper() |
| d, err := db.Open(schema.Path(t), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| + executionMust(t, err) |
| t.Cleanup(func() { d.Close() }) |
| s := equipo.NewStore(d) |
| if err := s.Bootstrap(context.Background(), []string{ownerAddress}); err != nil { |
| @@ -48,18 +46,14 @@ func enrolStore(t *testing.T) enrolFixture { |
| func machine(t *testing.T) (string, ed25519.PrivateKey) { |
| t.Helper() |
| pub, key, err := ed25519.GenerateKey(rand.Reader) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| + executionMust(t, err) |
| return base64.RawURLEncoding.EncodeToString(pub), key |
| } |
| func beginDevice(t *testing.T, s *equipo.Store) (runnerproto.DeviceCode, ed25519.PrivateKey) { |
| t.Helper() |
| pub, key := machine(t) |
| code, err := s.BeginEnrolment(context.Background(), pub, "Desk machine") |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| + executionMust(t, err) |
| return code, key |
| } |
| func deviceProof(code runnerproto.DeviceCode, key ed25519.PrivateKey) runnerproto.ExchangeProof { |
| @@ -78,9 +72,7 @@ func approveDevice(t *testing.T, s *equipo.Store, code runnerproto.DeviceCode, p |
| func claimDevice(t *testing.T, s *equipo.Store, code runnerproto.DeviceCode, key ed25519.PrivateKey) runnerproto.RunnerCredential { |
| t.Helper() |
| c, err := s.ExchangeEnrolment(context.Background(), code.DeviceSecret, deviceProof(code, key)) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| + executionMust(t, err) |
| return c |
| } |
| func mustSQL(t *testing.T, d *db.DB, q string, args ...any) { |
| @@ -235,9 +227,7 @@ func TestEnrolmentSingleUse(t *testing.T) { |
| approveDevice(t, f.s, code, ownerAddress) |
| c := claimDevice(t, f.s, code, key) |
| next, err := f.s.RotateRunnerCredential(ctx, c.Token) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| + executionMust(t, err) |
| if _, err = f.s.AuthenticateRunner(ctx, c.Token); err != nil { |
| t.Fatal("missing overlap", err) |
| } |
| @@ -392,7 +382,7 @@ func TestEnrolmentAudience(t *testing.T) { |
| if code.VerificationURI != testOrigin+"/runners/enrol" { |
| t.Fatal("untrusted verification origin") |
| } |
| - view := pageBody(t, c, f.server.URL, "/runners/enrol?user_code="+code.UserCode) |
| + view := inspectPairing(t, c, f.server.URL, code.UserCode) |
| for _, want := range []string{"Desk <machine>", runnerproto.MachineKeyHash(pub), testOrigin} { |
| if !strings.Contains(view, want) { |
| t.Fatalf("approval missing %q", want) |
| @@ -404,6 +394,9 @@ func TestEnrolmentAudience(t *testing.T) { |
| form := formFields(t, view, "/runners/enrol") |
| form.Set("person", memberAddress) |
| form.Set("actor", memberAddress) |
| + pagePost(t, c, f.server.URL, "/runners/enrol", testOrigin, form, 422) |
| + form.Del("person") |
| + form.Del("actor") |
| pagePost(t, c, f.server.URL, "/runners/enrol", testOrigin, form, 303) |
| status, body = enrolJSON(t, f.server.Client(), f.server.URL+"/api/enrolments/token", runnerproto.ExchangeEnrolmentRequest{Version: 1, DeviceSecret: code.DeviceSecret, Proof: deviceProof(code, key)}, "") |
| if status != 200 { |
| @@ -418,12 +411,10 @@ func TestEnrolmentAudience(t *testing.T) { |
| req, _ := http.NewRequest("GET", f.server.URL+"/runners/enrol", nil) |
| req.Header.Set("Authorization", "Bearer "+token) |
| res, err := c.Do(req) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| + executionMust(t, err) |
| readBody(t, res) |
| - if res.StatusCode != 403 { |
| - t.Fatal("bearer accessed browser UI") |
| + if res.StatusCode != 401 { |
| + t.Fatal("bearer accessed browser UI", res.StatusCode) |
| } |
| status, _ = enrolJSON(t, f.server.Client(), f.server.URL+"/api/enrolments/token", runnerproto.ExchangeEnrolmentRequest{Version: 1, DeviceSecret: code.DeviceSecret, Proof: deviceProof(code, key)}, token) |
| if status != 403 { |
| @@ -434,11 +425,9 @@ func TestEnrolmentAudience(t *testing.T) { |
| req.Header.Set("Origin", testOrigin) |
| req.Header.Set("Authorization", "Bearer "+token) |
| res, err = c.Do(req) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| + executionMust(t, err) |
| readBody(t, res) |
| - if res.StatusCode != 403 { |
| + if res.StatusCode != 401 { |
| t.Fatal("bearer approved device") |
| } |
| } |
| @@ -452,9 +441,7 @@ func TestEnrolmentAudience(t *testing.T) { |
| req.Header.Set("Authorization", "Bearer "+tc.token) |
| } |
| res, err := tc.client.Do(req) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| + executionMust(t, err) |
| readBody(t, res) |
| if res.StatusCode != tc.want { |
| t.Fatalf("runner audience: got %d want %d", res.StatusCode, tc.want) |
| @@ -490,9 +477,7 @@ func TestEnrolmentAudience(t *testing.T) { |
| } |
| for _, table := range []string{"runner_enrolments", "runner_credentials", "audit_events"} { |
| rows, err := f.db.Writer().Query("SELECT * FROM " + table) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| + executionMust(t, err) |
| cols, _ := rows.Columns() |
| for rows.Next() { |
| v := make([]any, len(cols)) |
| @@ -527,38 +512,35 @@ func newEnrolHTTP(t *testing.T) enrolHTTPFixture { |
| logger := slog.New(slog.NewTextHandler(logs, nil)) |
| m := &capturingMailer{} |
| r, err := equipo.Router(d, testConfig(testOrigin), m, logger) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| + executionMust(t, err) |
| guard := r.(interface { |
| RequireRunner(http.Handler) http.Handler |
| }) |
| - r.Handle("/test-runner", guard.RequireRunner(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + runnerGuard := guard.RequireRunner(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| p, ok := equipo.RunnerFrom(r) |
| if !ok || p.Person != ownerAddress { |
| t.Error("missing runner principal") |
| } |
| w.WriteHeader(204) |
| - }))) |
| - server := httptest.NewServer(equipo.Mux(r)) |
| + })) |
| + mux := http.NewServeMux() |
| + mux.Handle("/test-runner", runnerGuard) |
| + mux.Handle("/", equipo.Mux(r)) |
| + server := httptest.NewServer(mux) |
| t.Cleanup(server.Close) |
| return enrolHTTPFixture{authFixture{d, equipo.NewStore(d), m, server}, logs} |
| } |
| func enrolJSON(t *testing.T, c *http.Client, target string, payload any, token string) (int, []byte) { |
| t.Helper() |
| body, err := json.Marshal(payload) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| + executionMust(t, err) |
| req, _ := http.NewRequest("POST", target, bytes.NewReader(body)) |
| req.Header.Set("Content-Type", "application/json") |
| if token != "" { |
| req.Header.Set("Authorization", "Bearer "+token) |
| } |
| res, err := c.Do(req) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| + executionMust(t, err) |
| out := []byte(readBody(t, res)) |
| if res.Header.Get("Cache-Control") != "no-store" { |
| t.Fatal("cacheable credential response") |
| @@ -605,7 +587,8 @@ func TestEnrolmentCSRFAndRate(t *testing.T) { |
| for _, origin := range []string{"", "https://other.example"} { |
| pagePost(t, c, f.server.URL, "/runners/enrol", origin, url.Values{"user_code": {code.UserCode}}, 403) |
| } |
| - pagePost(t, c, f.server.URL, "/runners/enrol", testOrigin, url.Values{"user_code": {code.UserCode}}, 303) |
| + view := inspectPairing(t, c, f.server.URL, code.UserCode) |
| + pagePost(t, c, f.server.URL, "/runners/enrol", testOrigin, formFields(t, view, "/runners/enrol"), 303) |
| cred := claimDevice(t, f.store, code, key) |
| for _, origin := range []string{"", "https://other.example"} { |
| pagePost(t, c, f.server.URL, "/runners/"+cred.RunnerID+"/revoke", origin, url.Values{"revision": {"1"}}, 403) |
| @@ -626,9 +609,7 @@ func TestEnrolmentCSRFAndRate(t *testing.T) { |
| req, _ := http.NewRequest("POST", f.server.URL+"/api/enrolments", strings.NewReader(body)) |
| req.Header.Set("Content-Type", "application/json") |
| res, err := f.server.Client().Do(req) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| + executionMust(t, err) |
| readBody(t, res) |
| if res.StatusCode != 422 { |
| t.Fatalf("loose JSON accepted: %d", res.StatusCode) |
| @@ -640,9 +621,7 @@ func TestEnrolmentCSRFAndRate(t *testing.T) { |
| req, _ := http.NewRequest("POST", f.server.URL+"/api/enrolments", bytes.NewReader(body)) |
| req.Header.Set("Content-Type", content) |
| res, err := f.server.Client().Do(req) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| + executionMust(t, err) |
| readBody(t, res) |
| if res.StatusCode != 422 { |
| t.Fatal("simple cross-origin content accepted") |
| @@ -772,9 +751,7 @@ func TestEnrolmentIndependentGuards(t *testing.T) { |
| req, _ := http.NewRequest("GET", f.server.URL+"/test-runner", nil) |
| req.Header.Set("Authorization", "Bearer "+c.Token) |
| res, err := f.server.Client().Do(req) |
| - if err != nil { |
| - t.Fatal(err) |
| - } |
| + executionMust(t, err) |
| readBody(t, res) |
| return res.StatusCode |
| } |
diff --git a/internal/equipotest/runner_release_test.go b/internal/equipotest/runner_release_test.go| index 7caf4cca..69303ebb 100644 |
| --- a/internal/equipotest/runner_release_test.go |
| +++ b/internal/equipotest/runner_release_test.go |
| @@ -156,6 +156,7 @@ func TestRunnerReleaseContractUnlistedReport(t *testing.T) { |
| func installCertificationFixture(t *testing.T, root string, m *release.Manifest, scenario string) { |
| t.Helper() |
| m.LiveGateCopyReviewed = scenario != "pending_live_copy" |
| + m.UncertifiedPolicies = nil |
| binaryHashes := map[string]string{"runner": strings.Repeat("b", 64)} |
| for _, b := range m.Binaries { |
| binaryHashes[b.Name] = b.SHA256 |
diff --git a/internal/plan3test/conversation_browser_test.go b/internal/plan3test/conversation_browser_test.go| index 7c84fc50..0aecbcdf 100644 |
| --- a/internal/plan3test/conversation_browser_test.go |
| +++ b/internal/plan3test/conversation_browser_test.go |
| @@ -15,38 +15,9 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo" |
| "amadan.net/oficina/equipo/internal/equipo/conversation" |
| - "amadan.net/oficina/equipo/internal/taskplan" |
| "amadan.net/rastrillo/rastrillo/mail" |
| ) |
| -func formPost(t *testing.T, f *fixture, actor equipo.Actor, path string, v url.Values) *httptest.ResponseRecorder { |
| - t.Helper() |
| - r := httptest.NewRequest("POST", path, strings.NewReader(v.Encode())) |
| - r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| - r.Header.Set("Origin", origin) |
| - r.AddCookie(f.Cookies[actor.Address]) |
| - w := httptest.NewRecorder() |
| - f.Handler.ServeHTTP(w, r) |
| - return w |
| -} |
| -func actionForm(id string, revision int64) url.Values { |
| - return url.Values{"request_id": {id}, "revision": {fmt.Sprint(revision)}} |
| -} |
| -func planForm(p taskplan.Plan, id string) url.Values { |
| - v := actionForm(id, p.Revision) |
| - v.Set("kind", string(p.Kind)) |
| - v.Set("project_id", fmt.Sprint(p.ProjectID)) |
| - v.Set("playbook_id", p.PlaybookID) |
| - v.Set("playbook_revision", fmt.Sprint(p.PlaybookRevision)) |
| - v.Set("step_count", fmt.Sprint(len(p.Steps))) |
| - for i, s := range p.Steps { |
| - prefix := fmt.Sprintf("step_%d_", i) |
| - for k, value := range map[string]string{"key": s.Key, "specialist": s.Specialist, "action": s.Action, "instructions": s.Instructions, "connection": s.ConnectionID, "model": s.Model, "reason": s.SelectionReason, "depends_on": strings.Join(s.DependsOn, ","), "position": fmt.Sprint(i + 1)} { |
| - v.Set(prefix+k, value) |
| - } |
| - } |
| - return v |
| -} |
| func TestConversationScriptless(t *testing.T) { |
| f := newFixture(t) |
| p := proposed(t, f) |
diff --git a/internal/plan3test/forms_fixture.go b/internal/plan3test/forms_fixture.go| new file mode 100644 |
| index 00000000..2ec03991 |
| --- /dev/null |
| +++ b/internal/plan3test/forms_fixture.go |
| @@ -0,0 +1,125 @@ |
| +package plan3test |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/equipo/library" |
| + "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/taskplan" |
| + "amadan.net/rastrillo/rastrillo/mail" |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "log/slog" |
| + "net/http/httptest" |
| + "net/url" |
| + "strconv" |
| + "strings" |
| + "testing" |
| +) |
| + |
| +func apiRequest(t *testing.T, f *fixture, actor equipo.Actor, method, path, body, key, revision string) *httptest.ResponseRecorder { |
| + t.Helper() |
| + r := httptest.NewRequest(method, path, strings.NewReader(body)) |
| + if actor.Address != "" { |
| + r.AddCookie(f.Cookies[actor.Address]) |
| + } |
| + r.Header.Set("Origin", origin) |
| + r.Header.Set("Content-Type", "application/json") |
| + if key != "" { |
| + r.Header.Set("Idempotency-Key", key) |
| + } |
| + if revision != "" { |
| + r.Header.Set("If-Match", revision) |
| + } |
| + w := httptest.NewRecorder() |
| + f.Handler.ServeHTTP(w, r) |
| + return w |
| +} |
| +func apiValue[T any](t *testing.T, w *httptest.ResponseRecorder) T { |
| + t.Helper() |
| + var out T |
| + must(t, json.Unmarshal(w.Body.Bytes(), &out)) |
| + return out |
| +} |
| +func apiRouter(t *testing.T, f *fixture, verifier personapi.VerifyPersonBearer) { |
| + t.Helper() |
| + if verifier != nil { |
| + equipo.WithPersonBearerVerifier(verifier)(f.Store) |
| + } |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + r, err := equipo.RouterWithStore(f.DB, equipo.Config{Origin: origin, InstanceKey: "plan3-fixture", AllowLoggedMail: true, Owners: []string{owner.Address}}, mail.Logged(logger), logger, f.Store) |
| + must(t, err) |
| + f.Handler = equipo.Mux(r) |
| +} |
| +func formPost(t *testing.T, f *fixture, actor equipo.Actor, path string, v url.Values) *httptest.ResponseRecorder { |
| + t.Helper() |
| + r := httptest.NewRequest("POST", path, strings.NewReader(v.Encode())) |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + r.Header.Set("Origin", origin) |
| + r.AddCookie(f.Cookies[actor.Address]) |
| + w := httptest.NewRecorder() |
| + f.Handler.ServeHTTP(w, r) |
| + return w |
| +} |
| +func actionForm(id string, revision int64) url.Values { |
| + return url.Values{"request_id": {id}, "revision": {fmt.Sprint(revision)}} |
| +} |
| +func planForm(p taskplan.Plan, id string) url.Values { |
| + v := actionForm(id, p.Revision) |
| + v.Set("kind", string(p.Kind)) |
| + v.Set("project_id", fmt.Sprint(p.ProjectID)) |
| + v.Set("playbook_id", p.PlaybookID) |
| + v.Set("playbook_revision", fmt.Sprint(p.PlaybookRevision)) |
| + v.Set("step_count", fmt.Sprint(len(p.Steps))) |
| + for i, s := range p.Steps { |
| + prefix := fmt.Sprintf("step_%d_", i) |
| + for k, value := range map[string]string{"key": s.Key, "specialist": s.Specialist, "action": s.Action, "instructions": s.Instructions, "connection": s.ConnectionID, "model": s.Model, "reason": s.SelectionReason, "depends_on": strings.Join(s.DependsOn, ","), "position": fmt.Sprint(i + 1)} { |
| + v.Set(prefix+k, value) |
| + } |
| + } |
| + return v |
| +} |
| +func proposed(t *testing.T, f *fixture) taskplan.Plan { |
| + task := f.createTask(t) |
| + p := taskplan.BugPlan(task.ID, task.ProjectID) |
| + p.Steps[0].Instructions = "fixture symptom" |
| + p.TaskID = "" |
| + p.Revision = 0 |
| + result, err := f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: "proposal"}) |
| + must(t, err) |
| + if result.TaskID == "" || result.Revision != 1 { |
| + t.Fatal("proposal lacks server identity", result) |
| + } |
| + replay, err := f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: "proposal"}) |
| + must(t, err) |
| + if replay.TaskID != result.TaskID { |
| + t.Fatal("proposal replay duplicated task") |
| + } |
| + if f.count(t, "SELECT count(*) FROM conversation_threads WHERE task_id=?", result.TaskID) != 1 || f.count(t, "SELECT count(*) FROM conversation_cards WHERE resource_id=?", result.TaskID) != 1 || f.count(t, "SELECT count(*) FROM task_outboxes WHERE task_id=?", result.TaskID) != 1 { |
| + t.Fatal("proposal incomplete") |
| + } |
| + page, err := f.Store.Conversation(ctx, owner, "", 50) |
| + must(t, err) |
| + if len(page.Cards) != 1 || page.Cards[0].ResourceID != result.TaskID { |
| + t.Fatal("proposal card is not visible in conversation") |
| + } |
| + return result |
| +} |
| +func playbookForm(in library.PlaybookInput, request string, revision int64) url.Values { |
| + v := actionForm(request, revision) |
| + v.Set("name", in.Name) |
| + v.Set("kind", string(in.Kind)) |
| + v.Set("template_id", in.Template.ID) |
| + v.Set("template_version", strconv.FormatInt(in.Template.Version, 10)) |
| + v.Set("step_count", strconv.Itoa(len(in.Steps))) |
| + for i, st := range in.Steps { |
| + prefix := "step_" + strconv.Itoa(i) + "_" |
| + for key, value := range map[string]string{"key": st.Key, "specialist": st.Specialist, "action": st.Action, "instructions": st.Instructions, "position": strconv.Itoa(i + 1), "depends": strings.Join(st.DependsOn, ",")} { |
| + v.Set(prefix+key, value) |
| + } |
| + } |
| + for _, id := range in.ProjectIDs { |
| + v.Add("project", strconv.FormatInt(id, 10)) |
| + } |
| + return v |
| +} |
diff --git a/internal/plan3test/onboarding_install_test.go b/internal/plan3test/onboarding_install_test.go| new file mode 100644 |
| index 00000000..b4521994 |
| --- /dev/null |
| +++ b/internal/plan3test/onboarding_install_test.go |
| @@ -0,0 +1,111 @@ |
| +package plan3test |
| + |
| +import ( |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/base64" |
| + "errors" |
| + "net/url" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| +) |
| + |
| +func TestOnboardingInstallResume(t *testing.T) { |
| + f := newFixture(t) |
| + in, secret := issueInvite(t, f, invitee.Address) |
| + _, err := f.Store.AcceptInvitation(ctx, invitee, in.ID, secret, equipo.Mutation{RequestID: "join", Revision: 1}) |
| + must(t, err) |
| + state, err := f.Store.Onboarding(ctx, invitee) |
| + must(t, err) |
| + if state.Revision != 1 || state.CurrentStep != "welcome" { |
| + t.Fatalf("initial state %+v", state) |
| + } |
| + m := equipo.Mutation{RequestID: "welcome", Revision: 1} |
| + state, err = f.Store.AdvanceOnboarding(ctx, invitee, "welcome", m) |
| + must(t, err) |
| + again, err := f.Store.AdvanceOnboarding(ctx, invitee, "welcome", m) |
| + must(t, err) |
| + if again.Revision != state.Revision || !again.Completed["welcome"] { |
| + t.Fatal("duplicate advance") |
| + } |
| + _, err = f.Store.AdvanceOnboarding(ctx, invitee, "runner", equipo.Mutation{RequestID: "skip", Revision: state.Revision}) |
| + if !errors.Is(err, equipo.ErrConflict) { |
| + t.Fatal("skipped prerequisites", err) |
| + } |
| + in, secret = issueInvite(t, f, invitee.Address) |
| + _, err = f.Store.AcceptInvitation(ctx, invitee, in.ID, secret, equipo.Mutation{RequestID: "join-again", Revision: 1}) |
| + must(t, err) |
| + again, err = f.Store.Onboarding(ctx, invitee) |
| + must(t, err) |
| + if again.Revision != state.Revision { |
| + t.Fatal("invitation overwrote setup") |
| + } |
| + must(t, f.Store.SetMember(ctx, owner, invitee.Address, equipo.RoleMember, false, 1)) |
| + _, err = f.Store.AdvanceOnboarding(ctx, invitee, "welcome", m) |
| + if !errors.Is(err, equipo.ErrForbidden) { |
| + t.Fatal("removed member replay", err) |
| + } |
| +} |
| +func TestOnboardingHostedUnavailable(t *testing.T) { |
| + f := newFixture(t) |
| + w := f.get(t, owner, "/onboarding") |
| + expectHTTP(t, w, 200) |
| + for _, word := range []string{"Hosted by Equipo", "coming later", "Mac"} { |
| + if !strings.Contains(w.Body.String(), word) { |
| + t.Fatalf("missing %s", word) |
| + } |
| + } |
| + expectHTTP(t, inviteRequest(t, f, owner, "POST", "/onboarding/advance", url.Values{"step": {"hosted"}, "request_id": {"hosted"}, "revision": {"1"}}, nil), 422) |
| + expectHTTP(t, inviteRequest(t, f, owner, "POST", "/onboarding/hosted", nil, nil), 404) |
| +} |
| +func TestOnboardingPairingBound(t *testing.T) { |
| + f := newFixture(t) |
| + pub, key, e := ed25519.GenerateKey(rand.Reader) |
| + must(t, e) |
| + code, e := f.Store.BeginEnrolment(ctx, base64.RawURLEncoding.EncodeToString(pub), "Edited kitchen machine") |
| + must(t, e) |
| + w := f.get(t, owner, "/runners/enrol?user_code="+code.UserCode) |
| + expectHTTP(t, w, 200) |
| + if strings.Contains(w.Body.String(), "Edited kitchen machine") || strings.Contains(w.Body.String(), `value="`+code.UserCode+`"`) { |
| + t.Fatal("link prefilled pairing code") |
| + } |
| + values := url.Values{"user_code": {code.UserCode}, "action": {"approve"}} |
| + expectHTTP(t, inviteRequest(t, f, owner, "POST", "/runners/enrol", values, nil), 403) |
| + 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")) { |
| + t.Fatal("missing actual label or server time") |
| + } |
| + proof := regexp.MustCompile(`name="confirmation" value="([^"]+)"`).FindStringSubmatch(w.Body.String()) |
| + if len(proof) != 2 { |
| + t.Fatal("missing inspection proof") |
| + } |
| + values.Set("confirmation", proof[1]) |
| + values.Set("action", "approve") |
| + expectHTTP(t, inviteRequest(t, f, peer, "POST", "/runners/enrol", values, nil), 403) |
| + expectHTTP(t, inviteRequest(t, f, owner, "POST", "/runners/enrol", values, nil, "https://other.test"), 403) |
| + expectHTTP(t, inviteRequest(t, f, owner, "POST", "/runners/enrol", values, nil), 303) |
| + p := runnerproto.ExchangeProof{EnrolmentID: code.EnrolmentID, Challenge: code.Challenge, ExchangeNonce: base64.RawURLEncoding.EncodeToString(make([]byte, 32))} |
| + _, wrong, e := ed25519.GenerateKey(rand.Reader) |
| + must(t, e) |
| + p.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(wrong, runnerproto.EnrolmentProofMessage(code.InstanceID, p))) |
| + if _, e = f.Store.ExchangeEnrolment(ctx, code.DeviceSecret, p); !errors.Is(e, equipo.ErrForbidden) { |
| + t.Fatal("wrong machine exchanged", e) |
| + } |
| + p.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(key, runnerproto.EnrolmentProofMessage(code.InstanceID, p))) |
| + credential, e := f.Store.ExchangeEnrolment(ctx, code.DeviceSecret, p) |
| + must(t, e) |
| + if credential.Person != owner.Address { |
| + t.Fatal("wrong person paired") |
| + } |
| + if _, e = f.Store.ExchangeEnrolment(ctx, code.DeviceSecret, p); !errors.Is(e, equipo.ErrForbidden) { |
| + t.Fatal("exchange replay accepted", e) |
| + } |
| + expectHTTP(t, inviteRequest(t, f, owner, "POST", "/runners/enrol", values, nil), 403) |
| +} |
diff --git a/internal/plan3test/person_api_test.go b/internal/plan3test/person_api_test.go| index 31ad5b3d..7c24c760 100644 |
| --- a/internal/plan3test/person_api_test.go |
| +++ b/internal/plan3test/person_api_test.go |
| @@ -4,8 +4,6 @@ import ( |
| "context" |
| "encoding/json" |
| "fmt" |
| - "io" |
| - "log/slog" |
| "net/http/httptest" |
| "net/url" |
| "strings" |
| @@ -14,43 +12,8 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo" |
| "amadan.net/oficina/equipo/internal/equipo/personapi" |
| - "amadan.net/rastrillo/rastrillo/mail" |
| ) |
| -func apiRequest(t *testing.T, f *fixture, actor equipo.Actor, method, path, body, key, revision string) *httptest.ResponseRecorder { |
| - t.Helper() |
| - r := httptest.NewRequest(method, path, strings.NewReader(body)) |
| - if actor.Address != "" { |
| - r.AddCookie(f.Cookies[actor.Address]) |
| - } |
| - r.Header.Set("Origin", origin) |
| - r.Header.Set("Content-Type", "application/json") |
| - if key != "" { |
| - r.Header.Set("Idempotency-Key", key) |
| - } |
| - if revision != "" { |
| - r.Header.Set("If-Match", revision) |
| - } |
| - w := httptest.NewRecorder() |
| - f.Handler.ServeHTTP(w, r) |
| - return w |
| -} |
| -func apiValue[T any](t *testing.T, w *httptest.ResponseRecorder) T { |
| - t.Helper() |
| - var out T |
| - must(t, json.Unmarshal(w.Body.Bytes(), &out)) |
| - return out |
| -} |
| -func apiRouter(t *testing.T, f *fixture, verifier personapi.VerifyPersonBearer) { |
| - t.Helper() |
| - if verifier != nil { |
| - equipo.WithPersonBearerVerifier(verifier)(f.Store) |
| - } |
| - logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| - r, err := equipo.RouterWithStore(f.DB, equipo.Config{Origin: origin, InstanceKey: "plan3-fixture", AllowLoggedMail: true, Owners: []string{owner.Address}}, mail.Logged(logger), logger, f.Store) |
| - must(t, err) |
| - f.Handler = equipo.Mux(r) |
| -} |
| func TestPersonAPIBrowserCSRF(t *testing.T) { |
| f := newFixture(t) |
| apiRouter(t, f, func(_ context.Context, token string) (personapi.PersonPrincipal, error) { |
diff --git a/internal/plan3test/plans_test.go b/internal/plan3test/plans_test.go| index 5183f240..63599db1 100644 |
| --- a/internal/plan3test/plans_test.go |
| +++ b/internal/plan3test/plans_test.go |
| @@ -10,32 +10,6 @@ import ( |
| "testing" |
| ) |
| -func proposed(t *testing.T, f *fixture) taskplan.Plan { |
| - task := f.createTask(t) |
| - p := taskplan.BugPlan(task.ID, task.ProjectID) |
| - p.Steps[0].Instructions = "fixture symptom" |
| - p.TaskID = "" |
| - p.Revision = 0 |
| - result, err := f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: "proposal"}) |
| - must(t, err) |
| - if result.TaskID == "" || result.Revision != 1 { |
| - t.Fatal("proposal lacks server identity", result) |
| - } |
| - replay, err := f.Store.ProposePlan(ctx, owner, p, equipo.Mutation{RequestID: "proposal"}) |
| - must(t, err) |
| - if replay.TaskID != result.TaskID { |
| - t.Fatal("proposal replay duplicated task") |
| - } |
| - if f.count(t, "SELECT count(*) FROM conversation_threads WHERE task_id=?", result.TaskID) != 1 || f.count(t, "SELECT count(*) FROM conversation_cards WHERE resource_id=?", result.TaskID) != 1 || f.count(t, "SELECT count(*) FROM task_outboxes WHERE task_id=?", result.TaskID) != 1 { |
| - t.Fatal("proposal incomplete") |
| - } |
| - page, err := f.Store.Conversation(ctx, owner, "", 50) |
| - must(t, err) |
| - if len(page.Cards) != 1 || page.Cards[0].ResourceID != result.TaskID { |
| - t.Fatal("proposal card is not visible in conversation") |
| - } |
| - return result |
| -} |
| func TestPlanApprovalPrecedence(t *testing.T) { |
| f := newFixture(t) |
| p := proposed(t, f) |
diff --git a/internal/plan3test/playbooks_forms_test.go b/internal/plan3test/playbooks_forms_test.go| index 52dd7f4b..d27aff33 100644 |
| --- a/internal/plan3test/playbooks_forms_test.go |
| +++ b/internal/plan3test/playbooks_forms_test.go |
| @@ -1,7 +1,6 @@ |
| package plan3test |
| import ( |
| - "net/url" |
| "strconv" |
| "strings" |
| "testing" |
| @@ -11,24 +10,6 @@ import ( |
| "amadan.net/oficina/equipo/internal/taskplan" |
| ) |
| -func playbookForm(in library.PlaybookInput, request string, revision int64) url.Values { |
| - v := actionForm(request, revision) |
| - v.Set("name", in.Name) |
| - v.Set("kind", string(in.Kind)) |
| - v.Set("template_id", in.Template.ID) |
| - v.Set("template_version", strconv.FormatInt(in.Template.Version, 10)) |
| - v.Set("step_count", strconv.Itoa(len(in.Steps))) |
| - for i, st := range in.Steps { |
| - prefix := "step_" + strconv.Itoa(i) + "_" |
| - for key, value := range map[string]string{"key": st.Key, "specialist": st.Specialist, "action": st.Action, "instructions": st.Instructions, "position": strconv.Itoa(i + 1), "depends": strings.Join(st.DependsOn, ",")} { |
| - v.Set(prefix+key, value) |
| - } |
| - } |
| - for _, id := range in.ProjectIDs { |
| - v.Add("project", strconv.FormatInt(id, 10)) |
| - } |
| - return v |
| -} |
| func TestPlaybookForms(t *testing.T) { |
| f := newFixture(t) |
| base := f.createTask(t) |
diff --git a/internal/release/install.go b/internal/release/install.go| new file mode 100644 |
| index 00000000..859a7725 |
| --- /dev/null |
| +++ b/internal/release/install.go |
| @@ -0,0 +1,78 @@ |
| +package release |
| + |
| +import ( |
| + "encoding/hex" |
| + "net/url" |
| + "reflect" |
| + "regexp" |
| + "strings" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| +) |
| + |
| +// InstallManifest is transported over HTTPS from the configured instance. The |
| +// runner digest lives outside the embedded policy manifest to avoid a hash cycle. |
| +type InstallManifest struct { |
| + Version string `json:"version"` |
| + Target string `json:"target"` |
| + RunnerSHA256 string `json:"runner_sha256"` |
| + NamespaceArgs []string `json:"namespace_args"` |
| + Release Manifest `json:"release"` |
| +} |
| + |
| +var installVersion = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$`) |
| + |
| +func ValidInstallVersion(v string) bool { |
| + return installVersion.MatchString(v) && v != "dev" && v != "latest" |
| +} |
| +func InstallOrigin(origin string) bool { |
| + u, e := url.Parse(origin) |
| + return e == nil && u.Scheme == "https" && u.Host != "" && u.User == nil && u.Path == "" && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && !strings.ContainsAny(origin, "\r\n\x00'\"`$\\#") |
| +} |
| +func (m Manifest) InstallCertified() bool { |
| + if m.Schema != 2 || m.RunnerTarget != "linux/amd64" || m.BwrapVersion != "0.11.0" || !m.LiveGateCopyReviewed || len(m.UncertifiedPolicies) != 0 || len(m.DirectPolicies) == 0 { |
| + return false |
| + } |
| + for _, p := range m.DirectPolicies { |
| + if m.CertifiedAuthHost(p.Provider, p.ProviderVersion, p.PolicyHash) == "" { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| +func (m InstallManifest) Validate(version string) error { |
| + digest, e := hex.DecodeString(m.RunnerSHA256) |
| + if !ValidInstallVersion(version) || m.Version != version || m.Target != "linux/amd64" || e != nil || len(digest) != 32 || !m.Release.InstallCertified() || !reflect.DeepEqual(m.NamespaceArgs, provider.NamespaceArguments()) { |
| + return errManifest |
| + } |
| + return nil |
| +} |
| + |
| +// InstallCommand uses positional arguments and shell quoting, never an origin |
| +// or path interpolated as shell source. The bootstrap verifies before executing. |
| +func InstallCommand(origin, version string, instance ...string) (string, error) { |
| + if !InstallOrigin(origin) || !ValidInstallVersion(version) { |
| + return "", errManifest |
| + } |
| + extra := "" |
| + if len(instance) > 0 { |
| + if !installVersion.MatchString(instance[0]) { |
| + return "", errManifest |
| + } |
| + extra = " '" + instance[0] + "'" |
| + } |
| + return "curl --fail --silent --show-error --proto '=https' --tlsv1.2 '" + origin + "/releases/" + version + "/install-v1.sh' | sh -s -- '" + origin + "' '" + version + "'" + extra, nil |
| +} |
| +func (m Manifest) ToolProxySHA256() string { |
| + hash := "" |
| + for _, b := range m.Binaries { |
| + if b.Name == "equipo-tool-proxy" { |
| + decoded, e := hex.DecodeString(b.SHA256) |
| + if hash != "" || b.Version != m.LauncherVersion || e != nil || len(decoded) != 32 { |
| + return "" |
| + } |
| + hash = b.SHA256 |
| + } |
| + } |
| + return hash |
| +} |
diff --git a/internal/release/install_assets.go b/internal/release/install_assets.go| new file mode 100644 |
| index 00000000..dd1d0ad3 |
| --- /dev/null |
| +++ b/internal/release/install_assets.go |
| @@ -0,0 +1,84 @@ |
| +package release |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| +) |
| + |
| +type InstallAssets struct { |
| + Root, Version string |
| + Manifest Manifest |
| +} |
| + |
| +func (a InstallAssets) read(name string) ([]byte, error) { |
| + if !filepath.IsAbs(a.Root) || filepath.Clean(a.Root) != a.Root { |
| + return nil, errManifest |
| + } |
| + path := filepath.Join(a.Root, name) |
| + real, e := filepath.EvalSymlinks(path) |
| + if e != nil || real != path { |
| + return nil, errManifest |
| + } |
| + i, e := os.Stat(path) |
| + if e != nil || !i.Mode().IsRegular() || i.Size() > 128<<20 { |
| + return nil, errManifest |
| + } |
| + return os.ReadFile(path) |
| +} |
| +func (a InstallAssets) Available() bool { |
| + if !ValidInstallVersion(a.Version) || !a.Manifest.InstallCertified() { |
| + return false |
| + } |
| + b, e := a.read("install-manifest.json") |
| + if e != nil { |
| + return false |
| + } |
| + var m InstallManifest |
| + if json.Unmarshal(b, &m) != nil || m.Validate(a.Version) != nil || !reflect.DeepEqual(m.Release, a.Manifest) { |
| + return false |
| + } |
| + binary, e := a.read("equipo-runner") |
| + if e != nil { |
| + return false |
| + } |
| + hash := sha256.Sum256(binary) |
| + if hex.EncodeToString(hash[:]) != m.RunnerSHA256 { |
| + return false |
| + } |
| + helper, e := a.read("equipo-tool-proxy") |
| + if e != nil { |
| + return false |
| + } |
| + helperHash := sha256.Sum256(helper) |
| + if a.Manifest.ToolProxySHA256() == "" || hex.EncodeToString(helperHash[:]) != a.Manifest.ToolProxySHA256() { |
| + return false |
| + } |
| + _, e = a.read("install-v1.sh") |
| + return e == nil |
| +} |
| +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") { |
| + w.WriteHeader(http.StatusNotFound) |
| + return |
| + } |
| + if !a.Available() { |
| + w.WriteHeader(http.StatusServiceUnavailable) |
| + return |
| + } |
| + b, e := a.read(name) |
| + if e != nil { |
| + 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) |
| +} |
diff --git a/internal/release/install_test.go b/internal/release/install_test.go| new file mode 100644 |
| index 00000000..840084b6 |
| --- /dev/null |
| +++ b/internal/release/install_test.go |
| @@ -0,0 +1,90 @@ |
| +package release |
| + |
| +import ( |
| + "crypto/sha256" |
| + "encoding/json" |
| + "fmt" |
| + "net/http/httptest" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| +) |
| + |
| +func TestOnboardingInstallPackaging(t *testing.T) { |
| + root := t.TempDir() |
| + m := BuildManifest() |
| + m.LiveGateCopyReviewed = true |
| + m.UncertifiedPolicies = nil |
| + hash := strings.Repeat("b", 64) |
| + m.DirectPolicies = []PolicyCertificate{{Provider: "codex", ProviderVersion: m.Codex, LauncherVersion: m.LauncherVersion, BwrapVersion: m.BwrapVersion, PolicyHash: hash, CertifiedRefresh: CertifiedRefresh{AuthHost: "auth.openai.com", EvidenceSHA256: hash}}} |
| + m.Binaries = []BinaryDigest{{Name: "equipo-tool-proxy", Version: m.LauncherVersion, SHA256: fmt.Sprintf("%x", sha256.Sum256([]byte("fixture helper")))}} |
| + m.Certifications = []Certification{{Provider: "codex", PolicyHash: hash, Path: "fixture", SHA256: hash}} |
| + binary := []byte("fixture binary, never executed") |
| + write := func(name string, b []byte) { |
| + t.Helper() |
| + if e := os.WriteFile(filepath.Join(root, name), b, 0600); e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + raw, _ := json.Marshal(m) |
| + write("manifest.json", raw) |
| + write("equipo-runner", binary) |
| + write("equipo-tool-proxy", []byte("fixture helper")) |
| + script, e := os.ReadFile("../../packaging/install/install-v1.sh") |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + write("install-v1.sh", script) |
| + cmd := exec.Command("python3", "../../scripts/runner-install-manifest.py", root, "fixture-16") |
| + if b, e := cmd.CombinedOutput(); e != nil { |
| + t.Fatalf("packaging %v %s", e, b) |
| + } |
| + raw, e = os.ReadFile(filepath.Join(root, "install-manifest.json")) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + var manifest InstallManifest |
| + if json.Unmarshal(raw, &manifest) != nil || manifest.Validate("fixture-16") != nil { |
| + t.Fatal("packaged policy differs from actual runner", string(raw)) |
| + } |
| + if manifest.RunnerSHA256 != fmt.Sprintf("%x", sha256.Sum256(binary)) { |
| + t.Fatal("checksum mismatch") |
| + } |
| + assets := InstallAssets{Root: root, Version: "fixture-16", Manifest: m} |
| + if !assets.Available() { |
| + t.Fatal("fixture assets unavailable") |
| + } |
| + for _, name := range []string{"install-v1.sh", "install-manifest.json", "equipo-runner", "equipo-tool-proxy"} { |
| + w := httptest.NewRecorder() |
| + assets.ServeHTTP(w, httptest.NewRequest("GET", "/releases/fixture-16/"+name, nil)) |
| + if w.Code != 200 || w.Body.Len() == 0 { |
| + t.Fatal("missing release asset", name, w.Code) |
| + } |
| + } |
| + write("equipo-runner", []byte("changed")) |
| + if assets.Available() { |
| + t.Fatal("tampered binary served") |
| + } |
| + for _, bad := range []string{"http://equipo.test", "https://equipo.test/$(touch bad)", "https://equipo.test'", "https://equipo.test#"} { |
| + if _, e := InstallCommand(bad, "fixture-16"); e == nil { |
| + t.Fatal("origin interpolation", bad) |
| + } |
| + } |
| + command, e := InstallCommand("https://equipo.test", "fixture-16", "team") |
| + if e != nil || !strings.Contains(command, "/releases/fixture-16/install-v1.sh") || !strings.HasSuffix(command, "'team'") { |
| + t.Fatal("unversioned install", command, e) |
| + } |
| + manifest.NamespaceArgs = []string{"--unshare-user"} |
| + if manifest.Validate("fixture-16") == nil { |
| + t.Fatal("weakened namespace policy") |
| + } |
| + manifest.NamespaceArgs = provider.NamespaceArguments() |
| + manifest.Release = BuildManifest() |
| + if manifest.Validate("fixture-16") == nil { |
| + t.Fatal("uncertified release accepted") |
| + } |
| +} |
diff --git a/internal/runner/config.go b/internal/runner/config.go| index 2ddf7820..2ee30917 100644 |
| --- a/internal/runner/config.go |
| +++ b/internal/runner/config.go |
| @@ -12,6 +12,7 @@ import ( |
| ) |
| type Config struct { |
| + MachineLabel string |
| ToolProxyPath, BwrapPath, ModuleCache string |
| ClaudePath, CodexCodeModeHostPath string |
| Report func(string) |
| @@ -22,7 +23,7 @@ type Config struct { |
| } |
| func LoadConfig(getenv func(string) string) (Config, error) { |
| - c := Config{ToolProxyPath: getenv("EQUIPO_TOOL_PROXY_PATH"), CodexCodeModeHostPath: getenv("EQUIPO_CODEX_CODE_MODE_HOST_PATH"), BwrapPath: getenv("EQUIPO_BWRAP_PATH"), ModuleCache: getenv("EQUIPO_GO_MODULE_CACHE"), ClaudePath: getenv("EQUIPO_CLAUDE_PATH"), Origin: getenv("EQUIPO_ORIGIN"), StateDir: getenv("EQUIPO_RUNNER_STATE_DIR"), AmadanCredentialPath: getenv("EQUIPO_AMADAN_CREDENTIAL_PATH"), AccountBindingsPath: getenv("EQUIPO_ACCOUNT_BINDINGS_PATH"), CodexPath: getenv("EQUIPO_CODEX_PATH"), GoRoot: getenv("EQUIPO_GO_ROOT"), GoBinary: getenv("EQUIPO_GO_BINARY"), WorkspaceRoot: getenv("EQUIPO_WORKSPACE_ROOT"), ScratchRoot: getenv("EQUIPO_SCRATCH_ROOT"), GitPath: getenv("EQUIPO_GIT_PATH"), AmadanPath: getenv("EQUIPO_AMADAN_PATH"), InstanceID: getenv("EQUIPO_INSTANCE_ID")} |
| + c := Config{MachineLabel: getenv("EQUIPO_MACHINE_LABEL"), ToolProxyPath: getenv("EQUIPO_TOOL_PROXY_PATH"), CodexCodeModeHostPath: getenv("EQUIPO_CODEX_CODE_MODE_HOST_PATH"), BwrapPath: getenv("EQUIPO_BWRAP_PATH"), ModuleCache: getenv("EQUIPO_GO_MODULE_CACHE"), ClaudePath: getenv("EQUIPO_CLAUDE_PATH"), Origin: getenv("EQUIPO_ORIGIN"), StateDir: getenv("EQUIPO_RUNNER_STATE_DIR"), AmadanCredentialPath: getenv("EQUIPO_AMADAN_CREDENTIAL_PATH"), AccountBindingsPath: getenv("EQUIPO_ACCOUNT_BINDINGS_PATH"), CodexPath: getenv("EQUIPO_CODEX_PATH"), GoRoot: getenv("EQUIPO_GO_ROOT"), GoBinary: getenv("EQUIPO_GO_BINARY"), WorkspaceRoot: getenv("EQUIPO_WORKSPACE_ROOT"), ScratchRoot: getenv("EQUIPO_SCRATCH_ROOT"), GitPath: getenv("EQUIPO_GIT_PATH"), AmadanPath: getenv("EQUIPO_AMADAN_PATH"), InstanceID: getenv("EQUIPO_INSTANCE_ID")} |
| var err error |
| c.Executable, err = os.Executable() |
| if err != nil { |
diff --git a/internal/runner/enrol.go b/internal/runner/enrol.go| index 10b47af8..1e873dd4 100644 |
| --- a/internal/runner/enrol.go |
| +++ b/internal/runner/enrol.go |
| @@ -11,6 +11,7 @@ import ( |
| "net/url" |
| "os" |
| "path/filepath" |
| + "strings" |
| "time" |
| "amadan.net/oficina/equipo/internal/runner/provider" |
| @@ -23,7 +24,7 @@ func outboundClient() *http.Client { |
| func Enrol(ctx context.Context, c Config, output io.Writer) (resultErr error) { |
| variable := "EQUIPO_RUNNER_STATE_DIR" |
| defer func() { resultErr = diagnosticAt(resultErr, variable) }() |
| - if err := c.validate(); err != nil { |
| + if err := c.validateEnrolment(); err != nil { |
| return err |
| } |
| lock, err := lockState(c.StateDir) |
| @@ -38,7 +39,11 @@ func Enrol(ctx context.Context, c Config, output io.Writer) (resultErr error) { |
| return err |
| } |
| if time.Now().Before(old.Bearer.ExpiresAt) { |
| - return provider.ErrIdentity |
| + var saved pendingEnrolment |
| + if privateJSON(filepath.Join(c.StateDir, "enrolment.json"), &saved) != nil || saved.Origin != c.Origin || saved.Code.InstanceID != c.InstanceID { |
| + return provider.ErrIdentity |
| + } |
| + return nil |
| } |
| journalPath := filepath.Join(c.StateDir, "journal.db") |
| if _, err = os.Stat(journalPath); err == nil { |
| @@ -105,21 +110,47 @@ func Enrol(ctx context.Context, c Config, output io.Writer) (resultErr error) { |
| } |
| return resp.StatusCode, runnerproto.DecodeLimit(resp.Body, out, 64<<10) |
| } |
| - var code runnerproto.DeviceCode |
| - _, err = post("/api/enrolments", runnerproto.BeginEnrolmentRequest{Version: 1, MachinePublicKey: base64.RawURLEncoding.EncodeToString(ed25519.PrivateKey(key).Public().(ed25519.PublicKey)), Label: "equipo-runner"}, &code) |
| - if err != nil { |
| + label := c.MachineLabel |
| + if label == "" { |
| + label, err = os.Hostname() |
| + if err != nil { |
| + return err |
| + } |
| + } |
| + if len(label) > 128 || strings.TrimSpace(label) == "" || strings.ContainsAny(label, "\r\n\x00") { |
| + return provider.ErrContract |
| + } |
| + 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 |
| } |
| + if os.IsNotExist(err) || !time.Now().Before(pending.Code.ExpiresAt) { |
| + 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 { |
| + return err |
| + } |
| + pending = pendingEnrolment{Origin: c.Origin, Label: label, Code: code} |
| + pending.Proof = runnerproto.ExchangeProof{EnrolmentID: code.EnrolmentID, Challenge: code.Challenge, ExchangeNonce: base64.RawURLEncoding.EncodeToString(randomBytes(32))} |
| + pending.Proof.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(ed25519.PrivateKey(key), runnerproto.EnrolmentProofMessage(code.InstanceID, pending.Proof))) |
| + if err = runnerproto.JournalCredentials(pendingPath, pending); err != nil { |
| + return err |
| + } |
| + } |
| + 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 || code.InstanceID != c.InstanceID || code.PollIntervalSeconds < 5 || code.PollIntervalSeconds > 60 || !time.Now().Before(code.ExpiresAt) { |
| + 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) { |
| return provider.ErrIdentity |
| } |
| if _, err = io.WriteString(output, "["+code.VerificationURI+"]("+code.VerificationURI+")\n"+code.UserCode+"\n"); err != nil { |
| return err |
| } |
| - proof := runnerproto.ExchangeProof{EnrolmentID: code.EnrolmentID, Challenge: code.Challenge, ExchangeNonce: base64.RawURLEncoding.EncodeToString(randomBytes(32))} |
| - proof.Signature = base64.RawURLEncoding.EncodeToString(ed25519.Sign(ed25519.PrivateKey(key), runnerproto.EnrolmentProofMessage(code.InstanceID, proof))) |
| for time.Now().Before(code.ExpiresAt) { |
| timer := time.NewTimer(time.Duration(code.PollIntervalSeconds) * time.Second) |
| select { |
| @@ -150,3 +181,20 @@ func randomBytes(n int) []byte { |
| } |
| return b |
| } |
| + |
| +type pendingEnrolment struct { |
| + Origin string `json:"origin"` |
| + Label string `json:"label"` |
| + Code runnerproto.DeviceCode `json:"code"` |
| + Proof runnerproto.ExchangeProof `json:"proof"` |
| +} |
| + |
| +func (c Config) validateEnrolment() error { |
| + if !validOrigin(c.Origin) || c.InstanceID == "" { |
| + return provider.ErrContract |
| + } |
| + if !filepath.IsAbs(c.StateDir) || filepath.Clean(c.StateDir) != c.StateDir || c.StateDir == "/" { |
| + return provider.ErrPolicy |
| + } |
| + return nil |
| +} |
diff --git a/internal/runner/onboarding_test.go b/internal/runner/onboarding_test.go| new file mode 100644 |
| index 00000000..f95df12b |
| --- /dev/null |
| +++ b/internal/runner/onboarding_test.go |
| @@ -0,0 +1,73 @@ |
| +package runner |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "io" |
| + "net/http" |
| + "os" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +type enrolTransport func(*http.Request) (*http.Response, error) |
| + |
| +func (f enrolTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| + |
| +type enrolOutput struct { |
| + bytes.Buffer |
| + cancel context.CancelFunc |
| +} |
| + |
| +func (w *enrolOutput) Write(p []byte) (int, error) { |
| + n, e := w.Buffer.Write(p) |
| + w.cancel() |
| + return n, e |
| +} |
| +func TestOnboardingPairingBound(t *testing.T) { |
| + old := http.DefaultTransport |
| + t.Cleanup(func() { http.DefaultTransport = old }) |
| + for _, label := range []string{"", "Edited kitchen machine"} { |
| + c := configFixture(t) |
| + c.MachineLabel = label |
| + want := label |
| + if want == "" { |
| + var e error |
| + want, e = os.Hostname() |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + 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) |
| + } |
| + if in.Label != want || in.MachinePublicKey == "" { |
| + t.Fatalf("wrong machine label/key: %+v", in) |
| + } |
| + 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 |
| + }) |
| + for range 2 { |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + out := &enrolOutput{cancel: cancel} |
| + e := Enrol(ctx, c, out) |
| + cancel() |
| + if e == nil || !strings.Contains(out.String(), "0123456789") || !strings.Contains(out.String(), c.Origin+"/runners/enrol") { |
| + t.Fatalf("missing code or verification address %q %v", out.String(), e) |
| + } |
| + } |
| + if calls != 1 { |
| + t.Fatalf("retry created duplicate enrolment: %d", calls) |
| + } |
| + } |
| +} |
| +func (w *enrolOutput) WriteString(s string) (int, error) { return w.Write([]byte(s)) } |
diff --git a/internal/runner/setup/budget_test.go b/internal/runner/setup/budget_test.go| new file mode 100644 |
| index 00000000..191f5199 |
| --- /dev/null |
| +++ b/internal/runner/setup/budget_test.go |
| @@ -0,0 +1,9 @@ |
| +package runnersetup |
| + |
| +import ( |
| + "amadan.net/rastrillo/rastrillo/budget" |
| + "os" |
| + "testing" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
diff --git a/internal/runner/setup/install.go b/internal/runner/setup/install.go| new file mode 100644 |
| index 00000000..f5b78ce3 |
| --- /dev/null |
| +++ b/internal/runner/setup/install.go |
| @@ -0,0 +1,248 @@ |
| +package runnersetup |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "io" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "runtime" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/release" |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +type InstallOptions struct { |
| + Release, Root, InstanceOrigin string |
| + EnableService bool |
| +} |
| +type InstallResult struct { |
| + Version, BinaryPath, ServicePath, State string |
| + Missing []string |
| + LingeringEnabled bool |
| +} |
| + |
| +var errUnavailable = errors.New("runner.install.unavailable") |
| + |
| +type installHost struct { |
| + home, goos, goarch string |
| + fetch func(context.Context, string, int64) ([]byte, error) |
| + preflight func(context.Context, string, release.InstallManifest) []string |
| + service func(context.Context, string) error |
| + lingering func(context.Context) (bool, error) |
| + serviceAvailable func(context.Context) bool |
| +} |
| + |
| +func InstallUser(ctx context.Context, opts InstallOptions) (InstallResult, error) { |
| + home, err := os.UserHomeDir() |
| + 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}) |
| +} |
| +func installUser(ctx context.Context, o InstallOptions, h installHost) (r InstallResult, err error) { |
| + r = InstallResult{Version: o.Release, State: "unavailable"} |
| + fail := func(key string) (InstallResult, error) { r.Missing = []string{key}; return r, errUnavailable } |
| + if h.goos != "linux" || h.goarch != "amd64" { |
| + return fail("runner.install.platform") |
| + } |
| + if !release.InstallOrigin(o.InstanceOrigin) || !release.ValidInstallVersion(o.Release) { |
| + return fail("runner.install.release") |
| + } |
| + if !within(h.home, o.Root) || o.Root == h.home || !privateDirectory(o.Root) { |
| + return fail("runner.install.destination") |
| + } |
| + lock, e := os.OpenFile(filepath.Join(o.Root, "install.lock"), os.O_CREATE|os.O_RDWR|unix.O_NOFOLLOW, 0600) |
| + if e != nil { |
| + return fail("runner.install.destination") |
| + } |
| + defer lock.Close() |
| + if unix.Flock(int(lock.Fd()), unix.LOCK_EX|unix.LOCK_NB) != nil { |
| + return fail("runner.install.busy") |
| + } |
| + defer unix.Flock(int(lock.Fd()), unix.LOCK_UN) |
| + base := o.InstanceOrigin + "/releases/" + o.Release + "/" |
| + raw, e := h.fetch(ctx, base+"install-manifest.json", 1<<20) |
| + if e != nil { |
| + return fail("runner.install.release") |
| + } |
| + var m release.InstallManifest |
| + if json.Unmarshal(raw, &m) != nil || m.Validate(o.Release) != nil { |
| + return fail("runner.install.release") |
| + } |
| + // Each attempt owns exactly one private scratch directory on the configured disk. |
| + if os.Getenv("TMPDIR") == "" { |
| + return fail("runner.install.scratch") |
| + } |
| + scratch, e := os.MkdirTemp(os.Getenv("TMPDIR"), "equipo-install-") |
| + if e != nil { |
| + return fail("runner.install.scratch") |
| + } |
| + defer os.RemoveAll(scratch) |
| + binary, e := h.fetch(ctx, base+"equipo-runner", 128<<20) |
| + if e != nil { |
| + return fail("runner.install.release") |
| + } |
| + sum := sha256.Sum256(binary) |
| + if hex.EncodeToString(sum[:]) != m.RunnerSHA256 { |
| + return fail("runner.install.checksum") |
| + } |
| + candidate := filepath.Join(scratch, "equipo-runner") |
| + if os.WriteFile(candidate, binary, 0700) != nil { |
| + return fail("runner.install.destination") |
| + } |
| + if missing := h.preflight(ctx, candidate, m); len(missing) > 0 { |
| + r.Missing = missing |
| + return r, errUnavailable |
| + } |
| + if !h.serviceAvailable(ctx) { |
| + return fail("runner.install.service") |
| + } |
| + linger, e := h.lingering(ctx) |
| + if e != nil { |
| + return fail("runner.install.lingering") |
| + } |
| + r.LingeringEnabled = linger |
| + helper, e := h.fetch(ctx, base+"equipo-tool-proxy", 128<<20) |
| + if e != nil { |
| + return fail("runner.install.release") |
| + } |
| + helperHash := sha256.Sum256(helper) |
| + if m.Release.ToolProxySHA256() == "" || hex.EncodeToString(helperHash[:]) != m.Release.ToolProxySHA256() { |
| + return fail("runner.install.checksum") |
| + } |
| + dir := filepath.Join(o.Root, "releases", o.Release) |
| + if !privateDirectory(dir) { |
| + return fail("runner.install.destination") |
| + } |
| + r.BinaryPath = filepath.Join(dir, "equipo-runner") |
| + if e = writeOwned(r.BinaryPath, binary, 0700); e != nil { |
| + return fail("runner.install.destination") |
| + } |
| + if e = writeOwned(filepath.Join(dir, "equipo-tool-proxy"), helper, 0700); e != nil { |
| + return fail("runner.install.destination") |
| + } |
| + r.ServicePath = filepath.Join(o.Root, "equipo-runner.service") |
| + unit := serviceUnit(r.BinaryPath, filepath.Join(o.Root, "runner.env")) |
| + if e = writeOwned(r.ServicePath, []byte(unit), 0600); e != nil { |
| + return fail("runner.install.destination") |
| + } |
| + if o.EnableService { |
| + marker := filepath.Join(o.Root, "service-enabled.json") |
| + identity, _ := json.Marshal([]string{o.InstanceOrigin, o.Release, m.RunnerSHA256}) |
| + old, readErr := os.ReadFile(marker) |
| + if readErr != nil && !os.IsNotExist(readErr) { |
| + return fail("runner.install.service") |
| + } |
| + if string(old) != string(identity) { |
| + if h.service(ctx, r.ServicePath) != nil { |
| + return fail("runner.install.service") |
| + } |
| + if e = writeOwned(marker, identity, 0600); e != nil { |
| + return fail("runner.install.service") |
| + } |
| + } |
| + } |
| + r.State = "installed" |
| + if !r.LingeringEnabled { |
| + r.State = "stops_at_logout" |
| + } |
| + return r, nil |
| +} |
| +func within(home, path string) bool { |
| + if !filepath.IsAbs(path) || filepath.Clean(path) != path { |
| + return false |
| + } |
| + rel, e := filepath.Rel(home, path) |
| + return e == nil && rel != ".." && !strings.HasPrefix(rel, "../") |
| +} |
| +func privateDirectory(path string) bool { |
| + // Reject symlinks in existing ancestors before creating anything. |
| + for p := path; p != "/"; p = filepath.Dir(p) { |
| + i, e := os.Lstat(p) |
| + if os.IsNotExist(e) { |
| + continue |
| + } |
| + if e != nil || !i.IsDir() || i.Mode()&os.ModeSymlink != 0 { |
| + return false |
| + } |
| + } |
| + if os.MkdirAll(path, 0700) != nil { |
| + return false |
| + } |
| + i, e := os.Stat(path) |
| + if e != nil || i.Mode().Perm() != 0700 { |
| + return false |
| + } |
| + var stat unix.Stat_t |
| + return unix.Stat(path, &stat) == nil && stat.Uid == uint32(os.Geteuid()) && unix.Access(path, unix.W_OK) == nil |
| +} |
| +func writeOwned(path string, data []byte, mode os.FileMode) error { |
| + if i, e := os.Lstat(path); e == nil { |
| + if !i.Mode().IsRegular() { |
| + return errUnavailable |
| + } |
| + old, e := os.ReadFile(path) |
| + if e != nil { |
| + return e |
| + } |
| + if string(old) == string(data) { |
| + return nil |
| + } |
| + return errUnavailable |
| + } else if !os.IsNotExist(e) { |
| + return e |
| + } |
| + f, e := os.CreateTemp(filepath.Dir(path), ".install-write-") |
| + if e != nil { |
| + return e |
| + } |
| + defer os.Remove(f.Name()) |
| + if e = f.Chmod(mode); e != nil { |
| + f.Close() |
| + return e |
| + } |
| + _, e = f.Write(data) |
| + if e == nil { |
| + e = f.Sync() |
| + } |
| + closeErr := f.Close() |
| + if e = errors.Join(e, closeErr); e != nil { |
| + return e |
| + } |
| + if e = os.Link(f.Name(), path); e != nil { |
| + return e |
| + } |
| + dir, e := os.Open(filepath.Dir(path)) |
| + if e != nil { |
| + return e |
| + } |
| + defer dir.Close() |
| + return dir.Sync() |
| +} |
| +func fetchRelease(ctx context.Context, url string, limit int64) ([]byte, error) { |
| + c := http.Client{Timeout: 2 * time.Minute, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| + req, e := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| + if e != nil { |
| + return nil, e |
| + } |
| + resp, e := c.Do(req) |
| + if e != nil { |
| + return nil, e |
| + } |
| + defer resp.Body.Close() |
| + if resp.StatusCode != http.StatusOK { |
| + return nil, errUnavailable |
| + } |
| + b, e := io.ReadAll(io.LimitReader(resp.Body, limit+1)) |
| + if e != nil || int64(len(b)) > limit { |
| + return nil, errUnavailable |
| + } |
| + return b, nil |
| +} |
diff --git a/internal/runner/setup/install_test.go b/internal/runner/setup/install_test.go| new file mode 100644 |
| index 00000000..bfdd51a2 |
| --- /dev/null |
| +++ b/internal/runner/setup/install_test.go |
| @@ -0,0 +1,245 @@ |
| +package runnersetup |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/json" |
| + "fmt" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/release" |
| + "amadan.net/oficina/equipo/internal/runner/provider" |
| +) |
| + |
| +func installFixture(t *testing.T) (InstallOptions, installHost, *int) { |
| + t.Helper() |
| + home := t.TempDir() |
| + binary := []byte("fixture runner bytes") |
| + m := release.InstallManifest{Version: "fixture-16", Target: "linux/amd64", RunnerSHA256: fmt.Sprintf("%x", sha256.Sum256(binary)), NamespaceArgs: provider.NamespaceArguments(), Release: release.BuildManifest()} |
| + m.Release.Binaries = []release.BinaryDigest{{Name: "equipo-tool-proxy", Version: m.Release.LauncherVersion, SHA256: fmt.Sprintf("%x", sha256.Sum256([]byte("fixture tool proxy")))}} |
| + m.Release.UncertifiedPolicies = nil |
| + m.Release.LiveGateCopyReviewed = true |
| + hash := strings.Repeat("a", 64) |
| + m.Release.DirectPolicies = []release.PolicyCertificate{{Provider: "codex", ProviderVersion: m.Release.Codex, LauncherVersion: m.Release.LauncherVersion, BwrapVersion: "0.11.0", PolicyHash: hash, CertifiedRefresh: release.CertifiedRefresh{AuthHost: "auth.openai.com", EvidenceSHA256: hash}}} |
| + m.Release.Certifications = []release.Certification{{Provider: "codex", PolicyHash: hash, Path: "fixture.json", SHA256: hash}} |
| + raw, err := json.Marshal(m) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + calls := new(int) |
| + h := installHost{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 |
| + } |
| + if strings.HasSuffix(url, "equipo-tool-proxy") { |
| + return []byte("fixture tool proxy"), nil |
| + } |
| + return binary, nil |
| + }, preflight: func(context.Context, string, release.InstallManifest) []string { return nil }, service: func(context.Context, string) error { *calls++; return nil }, lingering: func(context.Context) (bool, error) { return false, nil }, serviceAvailable: func(context.Context) bool { return true }} |
| + return InstallOptions{Release: m.Version, Root: filepath.Join(home, "runner"), InstanceOrigin: "https://equipo.example", EnableService: true}, h, calls |
| +} |
| +func TestOnboardingInstallVersioned(t *testing.T) { |
| + o, h, calls := installFixture(t) |
| + got, err := installUser(context.Background(), o, h) |
| + if err != nil || got.Version != o.Release || got.State != "stops_at_logout" || *calls != 1 { |
| + t.Fatalf("install: %+v %v calls=%d", got, err, *calls) |
| + } |
| + b, err := os.ReadFile(got.BinaryPath) |
| + if err != nil || string(b) != "fixture runner bytes" { |
| + t.Fatal("binary not verified", err) |
| + } |
| + helper, e := os.ReadFile(filepath.Join(filepath.Dir(got.BinaryPath), "equipo-tool-proxy")) |
| + if e != nil || string(helper) != "fixture tool proxy" { |
| + t.Fatal("missing verified tool proxy", e) |
| + } |
| + for _, tc := range []string{"checksum", "helper_checksum", "uncertified", "version", "os", "arch", "root", "origin", "release", "symlink"} { |
| + t.Run(tc, func(t *testing.T) { |
| + o, h, calls := installFixture(t) |
| + old := h.fetch |
| + switch tc { |
| + case "checksum", "helper_checksum": |
| + h.fetch = func(c context.Context, u string, n int64) ([]byte, error) { |
| + b, e := old(c, u, n) |
| + if (tc == "checksum" && strings.HasSuffix(u, "/equipo-runner")) || (tc == "helper_checksum" && strings.HasSuffix(u, "/equipo-tool-proxy")) { |
| + b = []byte("tampered") |
| + } |
| + return b, e |
| + } |
| + case "uncertified", "version": |
| + h.fetch = func(c context.Context, u string, n int64) ([]byte, error) { |
| + b, e := old(c, u, n) |
| + if strings.HasSuffix(u, ".json") { |
| + var m release.InstallManifest |
| + _ = json.Unmarshal(b, &m) |
| + if tc == "uncertified" { |
| + m.Release.DirectPolicies = nil |
| + } else { |
| + m.Version = "other" |
| + } |
| + b, _ = json.Marshal(m) |
| + } |
| + return b, e |
| + } |
| + case "os": |
| + h.goos = "darwin" |
| + case "arch": |
| + h.goarch = "arm64" |
| + case "root": |
| + o.Root = filepath.Join(t.TempDir(), "outside-home") |
| + case "origin": |
| + o.InstanceOrigin = "https://example.test/$(touch nope)" |
| + case "release": |
| + o.Release = "../../escape" |
| + case "symlink": |
| + target := t.TempDir() |
| + if e := os.Symlink(target, o.Root); e != nil { |
| + t.Fatal(e) |
| + } |
| + } |
| + r, e := installUser(context.Background(), o, h) |
| + if e == nil || r.State != "unavailable" || len(r.Missing) == 0 || *calls != 0 { |
| + t.Fatalf("unsafe install: %+v %v service=%d", r, e, *calls) |
| + } |
| + }) |
| + } |
| + o, h, _ = installFixture(t) |
| + o.Root = filepath.Join(h.home, "literal $(touch nope) ' directory") |
| + if _, err = installUser(context.Background(), o, h); err != nil { |
| + t.Fatal("literal path rejected", err) |
| + } |
| + if _, err = os.Stat(filepath.Join(h.home, "nope")); !os.IsNotExist(err) { |
| + t.Fatal("shell interpolation") |
| + } |
| +} |
| +func TestOnboardingContainmentPreflight(t *testing.T) { |
| + for _, missing := range []string{"runner.install.bwrap", "runner.install.userns", "runner.install.apparmor", "runner.install.pidfd", "runner.install.namespace"} { |
| + t.Run(missing, func(t *testing.T) { |
| + o, h, calls := installFixture(t) |
| + h.preflight = func(context.Context, string, release.InstallManifest) []string { return []string{missing} } |
| + r, e := installUser(context.Background(), o, h) |
| + if e == nil || r.State != "unavailable" || len(r.Missing) != 1 || r.Missing[0] != missing || *calls != 0 { |
| + t.Fatalf("preflight bypass %+v %v", r, e) |
| + } |
| + }) |
| + } |
| + o, h, calls := installFixture(t) |
| + h.serviceAvailable = func(context.Context) bool { return false } |
| + r, e := installUser(context.Background(), o, h) |
| + if e == nil || r.State != "unavailable" || *calls != 0 { |
| + t.Fatal("missing user service accepted") |
| + } |
| +} |
| +func TestOnboardingServiceLogout(t *testing.T) { |
| + o, h, _ := installFixture(t) |
| + r, e := installUser(context.Background(), o, h) |
| + if e != nil || r.LingeringEnabled || r.State != "stops_at_logout" { |
| + t.Fatalf("logout claim %+v %v", r, e) |
| + } |
| + h.lingering = func(context.Context) (bool, error) { return true, nil } |
| + r, e = installUser(context.Background(), o, h) |
| + if e != nil || !r.LingeringEnabled || r.State != "installed" { |
| + t.Fatalf("linger observation %+v %v", r, e) |
| + } |
| +} |
| +func TestOnboardingInstallResume(t *testing.T) { |
| + o, h, calls := installFixture(t) |
| + var scratch string |
| + h.preflight = func(_ context.Context, path string, _ release.InstallManifest) []string { |
| + scratch = filepath.Dir(path) |
| + return nil |
| + } |
| + o.EnableService = false |
| + r, e := installUser(context.Background(), o, h) |
| + if e != nil { |
| + t.Fatal(e) |
| + } |
| + sentinel := filepath.Join(o.Root, "unrelated") |
| + if e = os.WriteFile(sentinel, []byte("keep"), 0600); e != nil { |
| + t.Fatal(e) |
| + } |
| + o.EnableService = true |
| + for range 2 { |
| + next, e := installUser(context.Background(), o, h) |
| + if e != nil || next.BinaryPath != r.BinaryPath { |
| + t.Fatal("retry failed", e) |
| + } |
| + } |
| + if *calls != 1 { |
| + t.Fatalf("duplicate service: %d", *calls) |
| + } |
| + if _, e = os.Stat(sentinel); e != nil { |
| + t.Fatal("removed unowned file", e) |
| + } |
| + if _, e = os.Stat(scratch); !os.IsNotExist(e) { |
| + t.Fatal("owned scratch leaked", scratch, e) |
| + } |
| + t.Run("service retry", func(t *testing.T) { |
| + o, h, calls := installFixture(t) |
| + h.service = func(context.Context, string) error { |
| + *calls++ |
| + if *calls == 1 { |
| + return os.ErrPermission |
| + } |
| + return nil |
| + } |
| + if r, e := installUser(context.Background(), o, h); e == nil || r.State != "unavailable" { |
| + t.Fatal("service failure claimed success") |
| + } |
| + for range 2 { |
| + if _, e := installUser(context.Background(), o, h); e != nil { |
| + t.Fatal("resume after service failure", e) |
| + } |
| + } |
| + if *calls != 2 { |
| + t.Fatal("service retried after success", *calls) |
| + } |
| + }) |
| +} |
| +func TestOnboardingContainmentPreflightProbe(t *testing.T) { |
| + for _, tc := range []string{"success", "missing", "version", "userns", "apparmor", "pidfd", "namespace"} { |
| + t.Run(tc, func(t *testing.T) { |
| + calls := 0 |
| + h := probeHost{read: func(path string) ([]byte, error) { |
| + if tc == "userns" && strings.HasSuffix(path, "unprivileged_userns_clone") { |
| + return []byte("0"), nil |
| + } |
| + if tc == "apparmor" && strings.HasSuffix(path, "apparmor_restrict_unprivileged_userns") { |
| + return []byte("1"), nil |
| + } |
| + return nil, os.ErrNotExist |
| + }, version: func(context.Context) (string, error) { |
| + if tc == "missing" { |
| + return "", os.ErrNotExist |
| + } |
| + if tc == "version" { |
| + return "bubblewrap 0.10.0\n", nil |
| + } |
| + return "bubblewrap 0.11.0\n", nil |
| + }, namespace: func(_ context.Context, _ string, args []string) error { |
| + calls++ |
| + if fmt.Sprint(args) != fmt.Sprint(provider.NamespaceArguments()) { |
| + t.Fatal("wrong release namespace policy") |
| + } |
| + if tc == "pidfd" { |
| + return errPIDFD |
| + } |
| + if tc == "apparmor" || tc == "namespace" { |
| + return os.ErrPermission |
| + } |
| + return nil |
| + }} |
| + got := probeContainment(context.Background(), "fixture", release.InstallManifest{NamespaceArgs: provider.NamespaceArguments()}, h) |
| + want := map[string]string{"missing": "bwrap", "version": "bwrap", "userns": "userns", "apparmor": "apparmor", "pidfd": "pidfd", "namespace": "namespace"}[tc] |
| + if tc == "success" { |
| + if len(got) != 0 || calls != 1 { |
| + t.Fatal("missing namespace/pidfd probe", got, calls) |
| + } |
| + } else if len(got) != 1 || got[0] != "runner.install."+want { |
| + t.Fatalf("diagnostic %v want %s", got, want) |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/runner/setup/preflight.go b/internal/runner/setup/preflight.go| new file mode 100644 |
| index 00000000..cc72476a |
| --- /dev/null |
| +++ b/internal/runner/setup/preflight.go |
| @@ -0,0 +1,179 @@ |
| +package runnersetup |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "encoding/json" |
| + "io" |
| + "os" |
| + "os/exec" |
| + "strconv" |
| + "strings" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/release" |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +type probeHost struct { |
| + read func(string) ([]byte, error) |
| + version func(context.Context) (string, error) |
| + namespace func(context.Context, string, []string) error |
| +} |
| + |
| +func containmentPreflight(ctx context.Context, binary string, m release.InstallManifest) []string { |
| + path, e := exec.LookPath("bwrap") |
| + if e != nil { |
| + return []string{"runner.install.bwrap"} |
| + } |
| + file, e := os.Open(path) |
| + if e != nil { |
| + return []string{"runner.install.bwrap"} |
| + } |
| + hash := sha256.New() |
| + _, e = io.Copy(hash, file) |
| + closeErr := file.Close() |
| + if e != nil || closeErr != nil { |
| + return []string{"runner.install.bwrap"} |
| + } |
| + matched := false |
| + for _, entry := range m.Release.Binaries { |
| + if entry.Name == "bwrap" && entry.Version == "0.11.0" && entry.SHA256 == hex.EncodeToString(hash.Sum(nil)) { |
| + matched = true |
| + } |
| + } |
| + if !matched { |
| + return []string{"runner.install.bwrap"} |
| + } |
| + |
| + return probeContainment(ctx, binary, m, probeHost{read: os.ReadFile, version: func(ctx context.Context) (string, error) { |
| + b, e := exec.CommandContext(ctx, "bwrap", "--version").Output() |
| + return string(b), e |
| + }, namespace: namespaceProbe}) |
| +} |
| +func probeContainment(ctx context.Context, binary string, m release.InstallManifest, h probeHost) []string { |
| + version, e := h.version(ctx) |
| + if e != nil || version != "bubblewrap 0.11.0\n" { |
| + return []string{"runner.install.bwrap"} |
| + } |
| + for _, path := range []string{"/proc/sys/kernel/unprivileged_userns_clone", "/proc/sys/user/max_user_namespaces"} { |
| + b, e := h.read(path) |
| + if e == nil && strings.TrimSpace(string(b)) == "0" { |
| + return []string{"runner.install.userns"} |
| + } |
| + if e != nil && !os.IsNotExist(e) { |
| + return []string{"runner.install.userns"} |
| + } |
| + } |
| + if e = h.namespace(ctx, binary, m.NamespaceArgs); e != nil { |
| + if e == errPIDFD { |
| + return []string{"runner.install.pidfd"} |
| + } |
| + restriction, _ := h.read("/proc/sys/kernel/apparmor_restrict_unprivileged_userns") |
| + if strings.TrimSpace(string(restriction)) == "1" { |
| + return []string{"runner.install.apparmor"} |
| + } |
| + return []string{"runner.install.namespace"} |
| + } |
| + return nil |
| +} |
| + |
| +var errPIDFD = &probeError{} |
| + |
| +type probeError struct{} |
| + |
| +func (*probeError) Error() string { return "runner.install.pidfd" } |
| +func namespaceProbe(ctx context.Context, binary string, policy []string) error { |
| + ctx, cancel := context.WithTimeout(ctx, 10*time.Second) |
| + defer cancel() |
| + statusR, statusW, e := os.Pipe() |
| + if e != nil { |
| + return e |
| + } |
| + defer statusR.Close() |
| + defer statusW.Close() |
| + args := append([]string{}, policy...) |
| + args = append(args, "--ro-bind", binary, "/equipo-probe", "--proc", "/proc", "--dev", "/dev", "--tmpfs", "/tmp", "--", "/equipo-probe", "__install_probe") |
| + cmd := exec.CommandContext(ctx, "bwrap", args...) |
| + cmd.Env = []string{} |
| + cmd.ExtraFiles = []*os.File{statusW} |
| + input, e := cmd.StdinPipe() |
| + if e != nil { |
| + return e |
| + } |
| + defer input.Close() |
| + output, e := cmd.StdoutPipe() |
| + if e != nil { |
| + return e |
| + } |
| + if e = cmd.Start(); e != nil { |
| + return e |
| + } |
| + statusW.Close() |
| + defer func() { cancel(); _ = cmd.Wait() }() |
| + done := make(chan error, 1) |
| + go func() { |
| + var status struct { |
| + PID int `json:"child-pid"` |
| + } |
| + if json.NewDecoder(io.LimitReader(statusR, 4096)).Decode(&status) != nil || status.PID < 1 { |
| + done <- errUnavailable |
| + return |
| + } |
| + var ready struct{ PID int } |
| + if json.NewDecoder(io.LimitReader(output, 4096)).Decode(&ready) != nil || ready.PID != 1 { |
| + done <- errUnavailable |
| + return |
| + } |
| + for _, ns := range []string{"pid", "user", "net"} { |
| + host, e := os.Readlink("/proc/self/ns/" + ns) |
| + child, ce := os.Readlink("/proc/" + strconv.Itoa(status.PID) + "/ns/" + ns) |
| + if e != nil || ce != nil || host == child { |
| + done <- errUnavailable |
| + return |
| + } |
| + } |
| + fd, e := unix.PidfdOpen(status.PID, 0) |
| + if e != nil { |
| + done <- errPIDFD |
| + return |
| + } |
| + defer unix.Close(fd) |
| + if unix.PidfdSendSignal(fd, 0, nil, 0) != nil { |
| + done <- errPIDFD |
| + return |
| + } |
| + _, e = input.Write([]byte{1}) |
| + done <- e |
| + }() |
| + select { |
| + case e = <-done: |
| + case <-ctx.Done(): |
| + statusR.Close() |
| + output.Close() |
| + e = <-done |
| + if e == nil { |
| + e = ctx.Err() |
| + } |
| + } |
| + if e != nil { |
| + return e |
| + } |
| + return cmd.Wait() |
| +} |
| + |
| +// InstallProbeMain is a no-provider child of the release's namespace policy. |
| +func InstallProbeMain(input io.Reader, output io.Writer) int { |
| + if os.Getpid() != 1 { |
| + return 125 |
| + } |
| + if json.NewEncoder(output).Encode(struct{ PID int }{os.Getpid()}) != nil { |
| + return 125 |
| + } |
| + var token [1]byte |
| + if _, e := io.ReadFull(input, token[:]); e != nil || token[0] != 1 { |
| + return 125 |
| + } |
| + return 0 |
| +} |
diff --git a/internal/runner/setup/service.go b/internal/runner/setup/service.go| new file mode 100644 |
| index 00000000..9e8f7881 |
| --- /dev/null |
| +++ b/internal/runner/setup/service.go |
| @@ -0,0 +1,79 @@ |
| +package runnersetup |
| + |
| +import ( |
| + "context" |
| + "os" |
| + "os/exec" |
| + "strconv" |
| + "strings" |
| +) |
| + |
| +func systemdQuote(s string) string { return strconv.Quote(strings.ReplaceAll(s, "%", "%%")) } |
| +func serviceUnit(binary, env string) string { |
| + return "[Unit]\nDescription=equipo-runner\n[Service]\nType=simple\nEnvironmentFile=" + systemdQuote(env) + "\nExecStart=" + systemdQuote(strings.ReplaceAll(binary, "$", "$$")) + " run\nRestart=on-failure\nRestartSec=5\nTimeoutStopSec=45\nKillMode=control-group\nUMask=0077\nNoNewPrivileges=yes\n[Install]\nWantedBy=default.target\n" |
| +} |
| +func userServiceAvailable(ctx context.Context) bool { |
| + return exec.CommandContext(ctx, "systemctl", "--user", "show-environment").Run() == nil |
| +} |
| +func readLingering(ctx context.Context) (bool, error) { |
| + b, e := exec.CommandContext(ctx, "loginctl", "show-user", strconv.Itoa(os.Getuid()), "--property=Linger", "--value").Output() |
| + if e != nil { |
| + return false, e |
| + } |
| + switch strings.TrimSpace(string(b)) { |
| + case "yes": |
| + return true, nil |
| + case "no": |
| + return false, nil |
| + default: |
| + return false, errUnavailable |
| + } |
| +} |
| +func enableService(ctx context.Context, path string) error { |
| + for _, args := range [][]string{{"--user", "link", path}, {"--user", "daemon-reload"}, {"--user", "enable", "--now", "equipo-runner.service"}} { |
| + if e := exec.CommandContext(ctx, "systemctl", args...).Run(); e != nil { |
| + return e |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// CheckServiceEnvironment refuses to enable a unit without its private local |
| +// configuration. It reads only the explicit installation root. |
| +func CheckServiceEnvironment(root, origin, state string) error { |
| + path := root + "/runner.env" |
| + i, e := os.Lstat(path) |
| + if e != nil || !i.Mode().IsRegular() || i.Mode().Perm() != 0600 { |
| + return errUnavailable |
| + } |
| + b, e := os.ReadFile(path) |
| + if e != nil { |
| + return e |
| + } |
| + values := map[string]string{} |
| + for _, line := range strings.Split(string(b), "\n") { |
| + if strings.HasPrefix(line, "#") || line == "" { |
| + continue |
| + } |
| + k, v, ok := strings.Cut(line, "=") |
| + if !ok || values[k] != "" { |
| + return errUnavailable |
| + } |
| + if strings.HasPrefix(v, "\"") { |
| + var err error |
| + v, err = strconv.Unquote(v) |
| + if err != nil { |
| + return errUnavailable |
| + } |
| + } |
| + values[k] = v |
| + } |
| + if values["EQUIPO_ORIGIN"] != origin || values["EQUIPO_RUNNER_STATE_DIR"] != state { |
| + return errUnavailable |
| + } |
| + return nil |
| +} |
| + |
| +func SaveServiceEnvironment(root string, data []byte) error { |
| + return writeOwned(root+"/runner.env", data, 0600) |
| +} |
diff --git a/packaging/install/install-v1.sh b/packaging/install/install-v1.sh| new file mode 100644 |
| index 00000000..15fa8685 |
| --- /dev/null |
| +++ b/packaging/install/install-v1.sh |
| @@ -0,0 +1,33 @@ |
| +#!/bin/sh |
| +set -eu |
| +umask 077 |
| +origin=$1 |
| +version=$2 |
| +instance=$3 |
| +case "$origin" in https://*) ;; *) exit 1 ;; esac |
| +case "$version" in ''|*[!a-zA-Z0-9._-]*|latest|dev) exit 1 ;; esac |
| +# TMPDIR is required: the download never falls back to a shared RAM disk. |
| +: "${TMPDIR:?}" |
| +scratch=$(mktemp -d "$TMPDIR/equipo-bootstrap-XXXXXXXX") |
| +trap 'rm -rf "$scratch"' EXIT |
| +trap 'exit 1' HUP INT TERM |
| +curl --fail --silent --show-error --proto '=https' --tlsv1.2 "$origin/releases/$version/install-manifest.json" -o "$scratch/manifest.json" |
| +# Python parses data, not shell source. TLS authenticates the configured origin. |
| +digest=$(python3 - "$scratch/manifest.json" "$version" <<'PY' |
| +import json, re, sys |
| +m = json.load(open(sys.argv[1])) |
| +r = m['release'] |
| +assert m['version'] == sys.argv[2] and m['target'] == 'linux/amd64' |
| +assert r['live_gate_copy_reviewed'] and r['direct_policies'] and r['certifications'] |
| +assert not r.get('uncertified_policies') |
| +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 |
diff --git a/scripts/runner-install-manifest.py b/scripts/runner-install-manifest.py| new file mode 100644 |
| index 00000000..be61bb1a |
| --- /dev/null |
| +++ b/scripts/runner-install-manifest.py |
| @@ -0,0 +1,25 @@ |
| +#!/usr/bin/env python3 |
| +"""Write the external runner checksum after the existing certification gate.""" |
| +import hashlib |
| +import json |
| +import pathlib |
| +import re |
| +import sys |
| + |
| +root, version = pathlib.Path(sys.argv[1]), sys.argv[2] |
| +assert re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}", version) |
| +assert version not in ("dev", "latest") |
| +release = json.loads((root / "manifest.json").read_text()) |
| +assert release["live_gate_copy_reviewed"] and release["direct_policies"] |
| +assert release["certifications"] and not release.get("uncertified_policies") |
| +manifest = { |
| + "version": version, |
| + "target": "linux/amd64", |
| + "runner_sha256": hashlib.sha256((root / "equipo-runner").read_bytes()).hexdigest(), |
| + "namespace_args": ["--unshare-user", "--unshare-pid", "--unshare-ipc", |
| + "--unshare-uts", "--unshare-cgroup", "--unshare-net", |
| + "--die-with-parent", "--new-session", "--as-pid-1", |
| + "--cap-drop", "ALL", "--json-status-fd", "3"], |
| + "release": release, |
| +} |
| +(root / "install-manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") |