equipo: hosted enrolment and renewal bound to one job
POST /api/hosted/enrol (public) trades a hosted VM's single-use instance code for a worker credential bound to its job, once the controller's admission record shows the VM running, certified, at the job's epoch. POST /api/runner/v2/hosted/challenge and /hosted/renew renew it against a single-use nonce signed by the enrolled machine key. Credentials last an hour, never past the job's deadline. Routes only with EQUIPO_HOSTED_RUNNERS=1 and the dispatcher's admission reader.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
15 files changed,
+1,298
−35
.rastrillo/budgets.txt+2 −2docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+23 −0internal/equipo/app.go+2 −0internal/equipo/chat/hosted_enrol.go+131 −0internal/equipo/chat/hosted_run.go+24 −16internal/equipo/enrolment.go+1 −1internal/equipo/hosted_enrol.go+356 −0internal/equipo/hosted_enrol_test.go+640 −0internal/equipo/hostedrun/admitter.go+38 −0internal/equipo/hostedrun/admitter_test.go+51 −0internal/equipo/hostedrun/dispatcher.go+0 −11internal/equipo/personapi/auth.go+3 −1internal/equipo/runner_rotation.go+1 −1internal/equipo/runners.go+22 −3internal/equipo/store.go+4 −0
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 8753c704..9f406c4d 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -15,7 +15,7 @@ time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial re |
| time internal/equipotest 300s Final fix package rerun measured 187.035s (review 172.4s); 300s gives 60 percent headroom for HTTP, sandbox, authority and final regression coverage. |
| time internal/equipo/hostedrun 60s Hosted slice 2 Task 21: TestDispatcherSimulation runs 200 seeds of the real chat store (SQLite) and dispatcher against a fake controller, with unlinked VMs that run to their 90-minute lifetime since review round 1, and one test drives the real controller over TLS for 90 simulated minutes; about 35 s of CPU in parallel subtests; measured 14 s on a 16 CPU docs-t1 under load 2.4; 60s covers a loaded 4 CPU runner. |
| -size internal/equipo 24867 - Preview, retry, merges, kept work, check-db, notifications, places, GitHub routes, installer, abilities, lookups, Mac waits, slice F codes, D1, probe details, Design's copy, /api/team; measured 24735. Hosted slice 2 Task 15 review 1: work.reason.pack_incomplete (pending); 24736. Task 17: work.reason.deps_conflict, deps_new_module, deps_missing, deps_too_large and token_renewal_failed (pending); 24741. Task 18: the owner setting "Run checks in a hosted VM" (config flag, routes, section, handler, four pending keys); 24825. Its review round 1: chatMe reports a roster denial as chat.ErrForbidden too (chatDenied); 24837. Task 21: the hosted dispatcher started only with EQUIPO_HOSTED_RUNNERS=1, execution on and a controller configured (EQUIPO_HOSTED_* config, RevokeRunner wiring), and the work.reason words for hosted_enrol_timeout, hosted_vm_lost and hosted_unavailable (pending); 24867. |
| +size internal/equipo 25248 8563 Preview, retry, merges, kept work, check-db, notifications, places, GitHub routes, installer, abilities, lookups, Mac waits, slice F codes, D1, probe details, Design's copy, /api/team; measured 24735. Hosted slice 2 Task 15 review 1: work.reason.pack_incomplete (pending); 24736. Task 17: work.reason.deps_conflict, deps_new_module, deps_missing, deps_too_large and token_renewal_failed (pending); 24741. Task 18: the owner setting "Run checks in a hosted VM" (config flag, routes, section, handler, four pending keys); 24825. Its review round 1: chatMe reports a roster denial as chat.ErrForbidden too (chatDenied); 24837. Task 21: the hosted dispatcher started only with EQUIPO_HOSTED_RUNNERS=1, execution on and a controller configured (EQUIPO_HOSTED_* config, RevokeRunner wiring), and the work.reason words for hosted_enrol_timeout, hosted_vm_lost and hosted_unavailable (pending); 24867. Task 22: hosted_enrol.go, a hosted VM's enrolment (POST /api/hosted/enrol) and its runner's challenge and renewal under /api/runner/v2 (the store methods over the runner and credential rows, the handlers, the routes only with EQUIPO_HOSTED_RUNNERS=1 and an admission reader), and mintRunnerCredential's lifetime and cap; 25248. Its tests (hosted_enrol_test.go: the routes through the whole application, and the runner's hosted.Start end to end through the test proxy) drive the unexported store, router and admission reader, so they live beside them and take the directory past the 8000-line test default; measured 8563 test lines. |
| size internal/wire 9899 - Protocols 31 to 35 (facts, diffs, evidence, CI units, files, places), abilities, 36 lookups, 37 Mac Engineering, 38 Design, unproven and probe detail codes, 39 hosted runners (hosted.go: placement, hosted_pack and deps transfer limits, enrolment types); measured 9848. Task 15 opened TransferHeader.Valid to hosted_pack (inbound, base then candidate) and added ReasonPackIncomplete; 9860. Its review round 1 registered it in StepReasons; 9862. Task 17: the hosted worker's reasons (deps_conflict, deps_new_module, deps_missing, deps_too_large, token_renewal_failed) registered in StepReasons, and TransferHeader.Valid opened to deps with the hosted_pack rules (the worker accepts the bundle; Task 23 sends it); 9884. Task 21: ReasonHostedEnrolTimeout, ReasonHostedVMLost and ReasonHostedUnavailable, registered in StepReasons; 9899. |
| size internal/equipotest - 12693 GitHub connect value search, lifecycle and sweep-log contracts; Task 21 migration fixtures, Rastrillo asset contract, renderer archive link; measured 0/12693 source/test lines. |
| time internal/runner/checks 90s CI worker measured 44.553s (44.6s rounded); |
| @@ -60,7 +60,7 @@ perf GET /api/v1/assistant/snapshot skip Assistant person API: bearer-only JSON |
| perf GET /api/v1/assistant/messages skip Assistant person API: bearer-only JSON for Base's chat, not a browser screen. |
| perf GET /api/v1/assistant/events skip Assistant event stream (Server-Sent Events), bearer-only and long-lived; not a screen. |
| perf GET /api/v1/assistant/abilities skip Assistant person API: bearer-only JSON for Base's Settings line, not a browser screen. |
| -size internal/equipo/chat 46709 20971 File facts/diffs, previews, merges, unfinished work, CI, receipts, Assistant files, places, abilities, lookups, go-aheads, Mac work, D1, Design specialists, grants, captures; 45093/18782. Hosted slice 2 Task 15: openHostedPack (the instance's send_pack for a hosted pack) and its test; 45105/18883. Its review round 1 added the report-ingestion test for pack_incomplete; 45105/18911. Task 18: hosted_setting.go (SetHostedChecks, hostedChecks, HostedSettings; owner only, roster in the transaction, audited) and its tests; 45208/19070. Its review round 1: the audit atomicity test; 45208/19113. Task 19: hosted_jobs.go (the hosted_jobs and hosted_challenges tables, HostedJob and its lifecycle: newHostedJob, the listed moves only, ended and failed only with stop proof or never-launched evidence, settleHostedJob once, hostedJobForRunner; each move audited in its transaction) and its tests, TestMigrationAdditive included; 45658/19577. Its review round 1: the never-launched evidence contract (HostedNeverLaunched, launch_by and launching_since, hostedLaunchReturned) and tests for it, settlement of unproven terminal records and audit atomicity; 45728/19739. Task 20: hosted_limits.go (per-person hosted limits, S2-9: hostedAdmit held in the write by a per-person lock row, hostedHoldFor, Allocate, hostedSettle at 4x the baseline, SetHostedLimits owner only with the roster, revision and audit in the transaction) and its tests; 46013/20214. Its coordinator ruling: a limit counts only while its setting owner is a current owner (defaults otherwise, checked in the admission transaction) and TestOwnerRaisesLimitRevoked; 46022/20284. Its review round 1: Allocate returns nothing for an empty or reversed span before widening, and its assertions; 46025/20290. Hosted slice 2 Task 21: placement on hosted VMs (placeHosted before the checks early return, its five rules), the bound runner's fits, Authorize by job identity, the hosted offline rule and withdrawal exemption, the hosted pack at dispatch, the step-terminal hook, and the dispatcher's store methods (HostedLive, HostedSweep, HostedLaunching with relaunch, HostedLaunched, HostedAdmitted, HostedFailed, HostedStopped, HostedNeverLaunched, HostedReplaces, PlaceHosted; end, settle, revoke, step moved on) in hosted_run.go, and hosted_place_test.go; 46665/20804. Task 21 review round 1: abandoned-intent evidence waits for the job's lifetime, the job keeps its lifetime and first running sight, admission takes the placing transaction's step attempt, provider-valid attempt IDs, HostedRunning, and the Retry, replacement-runner, cancelled-task and stopping-VM tests; 46709/20937. Its review round 2: TestHostedReplacesNeedsProof; 46709/20971. |
| +size internal/equipo/chat 46848 20971 File facts/diffs, previews, merges, unfinished work, CI, receipts, Assistant files, places, abilities, lookups, go-aheads, Mac work, D1, Design specialists, grants, captures; 45093/18782. Hosted slice 2 Task 15: openHostedPack (the instance's send_pack for a hosted pack) and its test; 45105/18883. Its review round 1 added the report-ingestion test for pack_incomplete; 45105/18911. Task 18: hosted_setting.go (SetHostedChecks, hostedChecks, HostedSettings; owner only, roster in the transaction, audited) and its tests; 45208/19070. Its review round 1: the audit atomicity test; 45208/19113. Task 19: hosted_jobs.go (the hosted_jobs and hosted_challenges tables, HostedJob and its lifecycle: newHostedJob, the listed moves only, ended and failed only with stop proof or never-launched evidence, settleHostedJob once, hostedJobForRunner; each move audited in its transaction) and its tests, TestMigrationAdditive included; 45658/19577. Its review round 1: the never-launched evidence contract (HostedNeverLaunched, launch_by and launching_since, hostedLaunchReturned) and tests for it, settlement of unproven terminal records and audit atomicity; 45728/19739. Task 20: hosted_limits.go (per-person hosted limits, S2-9: hostedAdmit held in the write by a per-person lock row, hostedHoldFor, Allocate, hostedSettle at 4x the baseline, SetHostedLimits owner only with the roster, revision and audit in the transaction) and its tests; 46013/20214. Its coordinator ruling: a limit counts only while its setting owner is a current owner (defaults otherwise, checked in the admission transaction) and TestOwnerRaisesLimitRevoked; 46022/20284. Its review round 1: Allocate returns nothing for an empty or reversed span before widening, and its assertions; 46025/20290. Hosted slice 2 Task 21: placement on hosted VMs (placeHosted before the checks early return, its five rules), the bound runner's fits, Authorize by job identity, the hosted offline rule and withdrawal exemption, the hosted pack at dispatch, the step-terminal hook, and the dispatcher's store methods (HostedLive, HostedSweep, HostedLaunching with relaunch, HostedLaunched, HostedAdmitted, HostedFailed, HostedStopped, HostedNeverLaunched, HostedReplaces, PlaceHosted; end, settle, revoke, step moved on) in hosted_run.go, and hosted_place_test.go; 46665/20804. Task 21 review round 1: abandoned-intent evidence waits for the job's lifetime, the job keeps its lifetime and first running sight, admission takes the placing transaction's step attempt, provider-valid attempt IDs, HostedRunning, and the Retry, replacement-runner, cancelled-task and stopping-VM tests; 46709/20937. Its review round 2: TestHostedReplacesNeedsProof; 46709/20971. Task 22: hosted_enrol.go (the enrolment and renewal store steps inside the instance's write transaction: HostedClaimCode, HostedEnrolAdmit, HostedEnrolBind, HostedRunnerJob, HostedNewChallenge, HostedUseChallenge; hostedAdmitted shared with HostedAdmitted); its tests drive it through the instance's routes (internal/equipo); 46848/20971. |
| perf GET /api/v1/questions/{id} skip Thin v1 person API: bearer-only JSON for devices; the browser reads questions on /tasks/{id}. |
| perf GET /api/v1/steps/{id}/log skip Thin v1 person API: bearer-only JSON for devices; the browser shows the log tail on /tasks/{id}. |
| perf GET /api/v1/connections/preference skip Connections slice 1 person API: bearer-only JSON for devices; the browser shows the preference on /conversation/connections. |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index e8f8b001..c4b5bed9 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -1692,3 +1692,26 @@ Mutation: |
| - **316** the proof check removed from `HostedReplaces` (the `prior.provenErr()` block deleted). `CGO_ENABLED=0 go test ./internal/equipo/chat -run TestHostedReplacesNeedsProof -count=1`: exit 1, `hosted_place_test.go:653: predecessor with evidence that does not hold: "" <nil>, want ErrHostedNoProof`. Restored from a copy; `cmp` identical. |
| Green: the brief's command passes, as does the whole chat package. `make migration-check budget build vet` exits 0. |
| + |
| +## Task 22 |
| + |
| +Hosted enrolment, challenge and renewal routes on the instance. |
| + |
| +- `POST /api/hosted/enrol` (`wire.HostedEnrolRequest`), public: `personapi.Dispatcher`'s allowlist gains that one path (cookies, a bearer and another origin are refused there or by `deviceRequest`). `Store.HostedEnrol`: transaction 1 counts the request against BeginEnrolment's limits (`hosted_enrol:<instance>` 60 a minute, `hosted_machine:<instance>:<key hash>` 5 in 10 minutes; a refused guess keeps its count) and uses the code (`chat.Store.HostedClaimCode`: the job enrolling, the code unused, before `code_expires_at`, for the request's launch, and within `HostedEnrolTimeout` (2 min) of `running_seen_at` when the dispatcher has seen the VM running, the window the controller's proxy code keeps). The admission record is read outside any transaction through the injected `hostedrun.Admitter`. Transaction 2: the person is a current member (`currentRunnerMember`), the record is kept (`hostedAdmitted`, shared with `HostedAdmitted`) and must admit the VM (`HostedEnrolAdmit`: state `running`, the record's VM and the job's VM equal to the request's, `CertValid`, the job's epoch, the job's launch); a machine key no runner holds; the worker runner row (role `worker`, label the VM reference, no device code), the binding (`HostedEnrolBind`, the existing `hostedEnrolled` move, with the machine key in base64url), and a credential of an hour capped at the job's deadline. The answer is `runnerproto.HostedEnrolResponse{Credential, Epoch, Deadline}`; the deadline is `launch_by + lifetime` (the provider ends any VM of the attempt by then). A refusing record is committed (`cert_valid` false) and the enrolment refused; the code stays used, so a refused or failed enrolment ends in the dispatcher's enrol timeout. |
| +- `POST /api/runner/v2/hosted/challenge` and `/hosted/renew` on the runner protocol's router (so the Dispatcher's runner lane takes them), behind `RequireRunner`. Challenge: no body; the credential re-checked in the transaction (`runnerPrincipalAt`, roster included), the runner bound to an enrolled job with a valid certificate before its deadline (`hostedLiveJob`), limits `hosted_challenge:<instance>` 60 a minute and `hosted_runner:<instance>:<runner>` 5 in 10 minutes, a 32-byte nonce for 60 s stored as its SHA-256 (`HostedNewChallenge`). Renew: the request names the bearer's runner and the job's current epoch, the Ed25519 signature over `wire.HostedRenewMessage` verifies with the job's stored machine key, then the challenge is used (`HostedUseChallenge`: the runner's, unused, unexpired) and the next credential issued (an hour, capped at the deadline). |
| +- `mintRunnerCredential(tx, runner, now, lifetime, limit)`; `deviceCredential` keeps the 30-day credential for enrolment and rotation. |
| +- `hostedrun.Admitter` moved to `admitter.go`; `Dispatcher.Admitter()` now maps the controller's signed `absent`, `forbidden` and `not_found` answers to `hostedrun.ErrNotAdmitted` (403 to the VM); any other error is 503, which the runner retries. `TestAdmitterMapsRefusals` covers the mapping. |
| +- The routes exist only with `EQUIPO_HOSTED_RUNNERS=1` and an admission reader (`Store.hostedAdmitter`, set from the dispatcher where it runs). |
| + |
| +RED: with the test file written first, `CGO_ENABLED=0 go test ./internal/equipo -run 'TestEnrol|TestRenew|TestHostedCredential' -count=1` failed to build (`r.s.hostedAdmitter undefined`); with only the store field added, every test failed on its assertion (`enrol: 403 cross-origin form submission refused`; `Start: hosted: not enrolled with the instance: the instance answered 403`). |
| + |
| +Green: the brief's command passes (all ten tests, 6.2 s). `TestEnrolEndToEndHostedStart`: the runner's real `hosted.Start` redeems through `proxytest`'s proxy and fake controller (all on 127.0.0.1) and enrols against this route of the whole application; the session's own HTTP client then gets a challenge and renews through the proxy. Also passing: `./internal/equipo/personapi`, `./internal/equipo/hostedrun` (14.5 s), `./internal/equipo/setup`, `./internal/equipo/chat -run 'TestHosted|...'`, `./internal/hostedclient -run TestOnlyHostedrunImportsHostedClient`, `./internal/equipotest -run 'TestRunnerAppCSRF|Enrol|Rotat|Credential'`, `./internal/equipo -run 'Runner|Rotat|Enrol|Credential|Machine|Hosted|Copy|Route|Perf|CSRF'`. `make migration-check budget build vet` exits 0. |
| + |
| +Budgets raised with reasons: `internal/equipo` 24867 to 25248 source and a test record of 8563 (the new tests drive the unexported store and router, so they sit beside them); `internal/equipo/chat` 46709 to 46848 source. |
| + |
| +Mutations (each through the Edit tool, then restored and the brief's command run green again): |
| +- **317** the VMRef comparison skipped (`string(a.VMRef) == vmRef && j.VMRef == vmRef` removed from `HostedEnrolAdmit`). `CGO_ENABLED=0 go test ./internal/equipo -run TestEnrolRefusesReplayAndWrongVM -count=1`: exit 1, `hosted_enrol_test.go:335: the right code from another VM: 200 {"credential":{...,"role":"worker",...},"deadline":"2026-12-01T11:35:00Z","epoch":2}`. Restored. |
| +- **318** a used nonce accepted (`used_at IS NULL` dropped from `HostedUseChallenge`). `... -run TestRenewNonceSingleUse`: exit 1, `hosted_enrol_test.go:514: the same nonce again: 200 {"credential":...}`. Restored. |
| +- **319** (extra) the deadline cap ignored in `mintRunnerCredential`. `... -run TestHostedCredentialCappedAtDeadline`: exit 1, `hosted_enrol_test.go:560: credential expires 2026-12-01 11:00:00 +0000 UTC, want 2026-12-01 10:30:00 +0000 UTC`. Restored. |
| +- **320** (extra) `/api/hosted/enrol` dropped from the public allowlist. `... -run TestEnrolRouteIsPublicNotCSRF`: exit 1, `hosted_enrol_test.go:424: with a browser cookie: 403 cross-origin form submission refused`. Restored. |
| +- **321** (extra) the roster check in transaction 2 skipped. `... -run TestEnrolRemovedPersonRefused`: exit 1, `hosted_enrol_test.go:408: a removed person's job: 200 {"credential":...}`. Restored. |
diff --git a/internal/equipo/app.go b/internal/equipo/app.go| index 30d099ca..5f035edf 100644 |
| --- a/internal/equipo/app.go |
| +++ b/internal/equipo/app.go |
| @@ -292,6 +292,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| logger.Error("hosted_dispatcher_off", "err", e) |
| } else { |
| a.hosted = hd |
| + store.hostedAdmitter = hd.Admitter() |
| store.Chat().SetHostedRunners(true) |
| } |
| } |
| @@ -344,6 +345,7 @@ func RouterWithStore(d *db.DB, cfg Config, mailer mail.Sender, logger *slog.Logg |
| a.Get("/api/team", teamprobe.Handler(cfg.Home, store.db.G)) |
| a.Post("/api/enrolments", a.beginEnrolment) |
| a.Post("/api/enrolments/token", a.exchangeEnrolment) |
| + a.hostedEnrolRoutes(runner) |
| a.Mount("/api/runner/v2", runner) |
| a.Get(wire.StreamPath, a.store.RunnerStreamHandler(a.logger).ServeHTTP) |
| a.Get("/github/connect/manifest", a.githubManifest) |
diff --git a/internal/equipo/chat/hosted_enrol.go b/internal/equipo/chat/hosted_enrol.go| new file mode 100644 |
| index 00000000..5f40b717 |
| --- /dev/null |
| +++ b/internal/equipo/chat/hosted_enrol.go |
| @@ -0,0 +1,131 @@ |
| +package chat |
| + |
| +import ( |
| + "context" |
| + "crypto/sha256" |
| + "encoding/hex" |
| + "fmt" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// A hosted VM's enrolment and its runner's renewals (hosted runners slice |
| +// 2, Task 22), each inside the instance's write transaction tx, which |
| +// also holds the runner and credential rows (package equipo). A refusal |
| +// is ErrForbidden; any other error is a lookup or write failure. |
| + |
| +// hostedRunning is the controller's state for a VM that is running. |
| +const hostedRunning = "running" |
| + |
| +// hostedTx is a txn over the caller's transaction. |
| +func (s *Store) hostedTx(tx *gorm.DB) *txn { |
| + return &txn{s: s, ctx: context.Background(), db: tx, touched: map[string]bool{}} |
| +} |
| + |
| +// HostedClaimCode uses the instance code code for launchID's job, at now: |
| +// the job must be enrolling, its code unused and unexpired, and within |
| +// HostedEnrolTimeout of its VM first being seen running (the controller's |
| +// proxy code keeps the same window). The code is used even if the |
| +// enrolment goes no further. |
| +func (s *Store) HostedClaimCode(tx *gorm.DB, code, launchID string, now time.Time) (HostedJob, error) { |
| + t := s.hostedTx(tx) |
| + if checkCode(code) != nil || launchID == "" { |
| + return HostedJob{}, ErrForbidden |
| + } |
| + var rows []HostedJob |
| + if err := tx.Where("code_hash = ?", codeHash(code)).Limit(1).Find(&rows).Error; err != nil { |
| + return HostedJob{}, err |
| + } |
| + if len(rows) == 0 { |
| + return HostedJob{}, ErrForbidden |
| + } |
| + j := rows[0] |
| + switch { |
| + case j.State != HostedJobEnrolling, j.CodeUsedAt != nil, j.LaunchID != launchID, |
| + j.CodeExpiresAt == nil || !now.Before(*j.CodeExpiresAt), |
| + j.RunningSeenAt != nil && !now.Before(j.RunningSeenAt.Add(HostedEnrolTimeout)): |
| + return HostedJob{}, ErrForbidden |
| + } |
| + used := now.UTC() |
| + res := tx.Model(&HostedJob{}).Where("attempt_id = ? AND state = ? AND code_used_at IS NULL AND revision = ?", j.AttemptID, HostedJobEnrolling, j.Revision). |
| + Updates(map[string]any{"code_used_at": used, "revision": j.Revision + 1}) |
| + if res.Error != nil { |
| + return HostedJob{}, res.Error |
| + } |
| + if res.RowsAffected != 1 { |
| + return HostedJob{}, ErrForbidden |
| + } |
| + j.CodeUsedAt, j.Revision = &used, j.Revision+1 |
| + return j, t.s.authority.Audit(tx, "system", "hosted.job", j.AttemptID+":code_used") |
| +} |
| + |
| +// HostedEnrolAdmit records the controller's admission record a for the |
| +// enrolling job attempt, asked at at, and reports whether it admits the |
| +// VM vmRef of launch launchID: the job is enrolling with its code used |
| +// and no runner yet; a shows its VM running, at the job's VM (the one |
| +// enrolling), with a valid certificate, at the job's epoch. The record is |
| +// kept either way. |
| +func (s *Store) HostedEnrolAdmit(tx *gorm.DB, attempt, launchID, vmRef string, a hostedwire.AdmissionView, at time.Time) (HostedJob, bool, error) { |
| + t := s.hostedTx(tx) |
| + var j HostedJob |
| + if err := tx.Where("attempt_id = ?", attempt).First(&j).Error; err != nil { |
| + return HostedJob{}, false, err |
| + } |
| + if j.State != HostedJobEnrolling || j.CodeUsedAt == nil || j.RunnerID != "" || j.LaunchID != launchID { |
| + return j, false, nil |
| + } |
| + valid, err := t.hostedAdmitted(j, a, at) |
| + if err != nil { |
| + return j, false, err |
| + } |
| + ok := valid && a.State == hostedRunning && string(a.VMRef) == vmRef && j.VMRef == vmRef && a.CertValid && a.Epoch == j.Epoch |
| + return j, ok, nil |
| +} |
| + |
| +// HostedEnrolBind binds the enrolling job attempt to the worker runner |
| +// runnerID its VM enrolled as, with the machine key (base64url) that |
| +// signs its renewals. |
| +func (s *Store) HostedEnrolBind(tx *gorm.DB, attempt, runnerID, machineKey string) error { |
| + return s.hostedTx(tx).hostedEnrolled(attempt, runnerID, machineKey) |
| +} |
| + |
| +// HostedRunnerJob is the job runnerID is bound to, whatever its state |
| +// (found false for a runner that is not hosted). |
| +func (s *Store) HostedRunnerJob(tx *gorm.DB, runnerID string) (HostedJob, bool, error) { |
| + return s.hostedTx(tx).hostedJobForRunner(runnerID) |
| +} |
| + |
| +// hostedNonceHash is what hosted_challenges keeps of a nonce. |
| +func hostedNonceHash(nonce []byte) string { |
| + sum := sha256.Sum256(nonce) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| + |
| +// HostedNewChallenge records a renewal challenge for runnerID: nonce's |
| +// hash, single use, until expires. |
| +func (s *Store) HostedNewChallenge(tx *gorm.DB, runnerID string, nonce []byte, expires time.Time) error { |
| + if runnerID == "" || len(nonce) == 0 || expires.IsZero() { |
| + return fmt.Errorf("%w: challenge", ErrInvalid) |
| + } |
| + return tx.Create(&hostedChallengeRecord{RunnerID: runnerID, NonceHash: hostedNonceHash(nonce), ExpiresAt: expires.UTC()}).Error |
| +} |
| + |
| +// HostedUseChallenge uses runnerID's challenge for nonce at now: it must |
| +// be the runner's, unused and unexpired. Used once, it never renews |
| +// again. |
| +func (s *Store) HostedUseChallenge(tx *gorm.DB, runnerID string, nonce []byte, now time.Time) error { |
| + if runnerID == "" || len(nonce) == 0 { |
| + return ErrForbidden |
| + } |
| + res := tx.Model(&hostedChallengeRecord{}).Where("nonce_hash = ? AND runner_id = ? AND used_at IS NULL AND expires_at > ?", hostedNonceHash(nonce), runnerID, now.UTC()). |
| + Update("used_at", now.UTC()) |
| + if res.Error != nil { |
| + return res.Error |
| + } |
| + if res.RowsAffected != 1 { |
| + return ErrForbidden |
| + } |
| + return nil |
| +} |
diff --git a/internal/equipo/chat/hosted_run.go b/internal/equipo/chat/hosted_run.go| index feb09c30..7ab0c422 100644 |
| --- a/internal/equipo/chat/hosted_run.go |
| +++ b/internal/equipo/chat/hosted_run.go |
| @@ -325,25 +325,33 @@ func (s *Store) HostedAdmitted(ctx context.Context, attempt string, a hostedwire |
| if err := t.db.Where("attempt_id = ?", attempt).First(&j).Error; err != nil { |
| return err |
| } |
| - if a.AttemptID != attempt || !j.Live() || j.VMRef == "" || at.IsZero() { |
| - return fmt.Errorf("%w: admission for %s", ErrHostedTransition, attempt) |
| - } |
| - valid := a.CertValid && a.LaunchID == j.LaunchID && string(a.VMRef) == j.VMRef && a.Epoch == j.Epoch && a.CertDigest != "" && |
| - (j.CertDigest == "" || j.CertDigest == a.CertDigest) |
| - digest := j.CertDigest |
| - if digest == "" { |
| - digest = a.CertDigest |
| - } |
| - when := at.UTC() |
| - res := t.db.Model(&HostedJob{}).Where("attempt_id = ? AND (cert_checked_at IS NULL OR cert_checked_at <= ?)", attempt, when). |
| - Updates(map[string]any{"cert_digest": digest, "cert_valid": valid, "cert_checked_at": when}) |
| - if res.Error != nil || res.RowsAffected == 0 || valid == j.CertValid { |
| - return res.Error |
| - } |
| - return t.s.authority.Audit(t.db, "system", "hosted.job", fmt.Sprintf("%s:cert_valid:%t", attempt, valid)) |
| + _, err := t.hostedAdmitted(j, a, at) |
| + return err |
| }) |
| } |
| +// hostedAdmitted records a for the live job j (HostedAdmitted) and |
| +// reports whether it is valid for j. |
| +func (t *txn) hostedAdmitted(j HostedJob, a hostedwire.AdmissionView, at time.Time) (bool, error) { |
| + attempt := j.AttemptID |
| + if a.AttemptID != attempt || !j.Live() || j.VMRef == "" || at.IsZero() { |
| + return false, fmt.Errorf("%w: admission for %s", ErrHostedTransition, attempt) |
| + } |
| + valid := a.CertValid && a.LaunchID == j.LaunchID && string(a.VMRef) == j.VMRef && a.Epoch == j.Epoch && a.CertDigest != "" && |
| + (j.CertDigest == "" || j.CertDigest == a.CertDigest) |
| + digest := j.CertDigest |
| + if digest == "" { |
| + digest = a.CertDigest |
| + } |
| + when := at.UTC() |
| + res := t.db.Model(&HostedJob{}).Where("attempt_id = ? AND (cert_checked_at IS NULL OR cert_checked_at <= ?)", attempt, when). |
| + Updates(map[string]any{"cert_digest": digest, "cert_valid": valid, "cert_checked_at": when}) |
| + if res.Error != nil || res.RowsAffected == 0 || valid == j.CertValid { |
| + return valid, res.Error |
| + } |
| + return valid, t.s.authority.Audit(t.db, "system", "hosted.job", fmt.Sprintf("%s:cert_valid:%t", attempt, valid)) |
| +} |
| + |
| // HostedRunning records when the dispatcher first saw an enrolling job's |
| // VM running (at, on the instance's clock); a later observation changes |
| // nothing. The enrolment window runs from it. |
diff --git a/internal/equipo/enrolment.go b/internal/equipo/enrolment.go| index 51b9ee14..52af65ca 100644 |
| --- a/internal/equipo/enrolment.go |
| +++ b/internal/equipo/enrolment.go |
| @@ -94,7 +94,7 @@ func (s *Store) enrolments() *setup.Enrolments { |
| return true, err |
| }, SaveResult: func(tx *gorm.DB, ctx context.Context, out Runner) error { |
| return personapi.SaveResult(tx, ctx, out, ErrConflict) |
| - }, 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, NeedsPrimary: ErrRunnerNeedsPrimary} |
| + }, Write: s.write, Now: s.runnerClock.Now, Instance: runnerInstance, Rate: runnerRateAt, Secret: runnerSecret, Hash: runnerHash, Member: currentRunnerMember, Audit: appendAudit, Error: storeError, Runner: runnerAt, Mint: deviceCredential, Invalid: ErrInvalid, Forbidden: ErrForbidden, Conflict: ErrConflict, RunnerRateLimited: ErrRunnerRateLimited, EnrolmentPending: ErrEnrolmentPending, NeedsPrimary: ErrRunnerNeedsPrimary} |
| } |
| func (s *Store) BeginEnrolment(ctx context.Context, key, label string, workerOnly ...bool) (runnerproto.DeviceCode, error) { |
| return s.enrolments().BeginEnrolment(ctx, key, label, workerOnly...) |
diff --git a/internal/equipo/hosted_enrol.go b/internal/equipo/hosted_enrol.go| new file mode 100644 |
| index 00000000..29b5922c |
| --- /dev/null |
| +++ b/internal/equipo/hosted_enrol.go |
| @@ -0,0 +1,356 @@ |
| +package equipo |
| + |
| +import ( |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "encoding/base64" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "mime" |
| + "net/http" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/chat" |
| + "amadan.net/oficina/equipo/internal/equipo/hostedrun" |
| + "amadan.net/oficina/equipo/internal/equipo/setup" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "github.com/go-chi/chi/v5" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// A hosted VM's enrolment and its runner's renewals (hosted runners slice |
| +// 2, Task 22; spec §5). The VM's runner trades its single-use instance |
| +// code for a worker credential bound to its one job, then renews it by |
| +// signing the instance's challenge with the machine key it enrolled. |
| + |
| +const ( |
| + // hostedCredentialLifetime is a hosted runner's credential's, never |
| + // past its job's deadline. |
| + hostedCredentialLifetime = time.Hour |
| + // hostedChallengeLifetime is a renewal challenge's. |
| + hostedChallengeLifetime = time.Minute |
| + // hostedNonceSize is a challenge nonce's size in bytes. |
| + hostedNonceSize = 32 |
| + // maxHostedCode bounds an instance code's text. |
| + maxHostedCode = 64 |
| +) |
| + |
| +// hostedDeadline is the job's deadline: the provider ends any VM of the |
| +// attempt by its launch-by plus its lifetime. A job without both has |
| +// none (ok false) and is issued nothing. |
| +func hostedDeadline(j chat.HostedJob) (time.Time, bool) { |
| + if j.LaunchBy == nil || j.Lifetime <= 0 { |
| + return time.Time{}, false |
| + } |
| + return j.LaunchBy.UTC().Add(j.Lifetime), true |
| +} |
| + |
| +// hostedStoreError is a chat refusal as the runner routes say it, and any |
| +// other error as storeError does. |
| +func hostedStoreError(err error) error { |
| + if errors.Is(err, chat.ErrForbidden) { |
| + return ErrForbidden |
| + } |
| + return storeError(err) |
| +} |
| + |
| +// hostedRate is one of BeginEnrolment's limits. |
| +type hostedRate struct { |
| + key string |
| + period time.Duration |
| + limit int |
| +} |
| + |
| +// hostedRates counts one request against each limit, in tx; allowed is |
| +// false once any is spent. The caller commits the count either way. |
| +func hostedRates(tx *gorm.DB, now time.Time, rates ...hostedRate) (bool, error) { |
| + for _, r := range rates { |
| + allowed, err := runnerRateAt(tx, r.key, now, r.period, r.limit) |
| + if err != nil || !allowed { |
| + return false, err |
| + } |
| + } |
| + return true, nil |
| +} |
| + |
| +// validHostedEnrol: a code of bounded text, a launch ID, a provider VM |
| +// reference and an Ed25519 public key. |
| +func validHostedEnrol(q wire.HostedEnrolRequest) bool { |
| + return q.Code != "" && len(q.Code) <= maxHostedCode && q.LaunchID != "" && len(q.LaunchID) <= hostedwire.MaxLaunchIDLen && |
| + isolatedjob.Ref(q.VMRef).Valid() && len(q.MachinePublicKey) == ed25519.PublicKeySize |
| +} |
| + |
| +// HostedEnrol enrols a hosted VM's runner (POST /api/hosted/enrol). |
| +// Transaction 1 counts the request against BeginEnrolment's limits and |
| +// uses the code (chat.Store.HostedClaimCode). The controller's admission |
| +// record is read outside any transaction. Transaction 2 checks the job's |
| +// person is a current member, records the admission and requires it to |
| +// admit this VM (chat.Store.HostedEnrolAdmit), then creates the worker |
| +// runner bound to the job, with no device code, and issues its first |
| +// credential: an hour, never past the job's deadline. |
| +func (s *Store) HostedEnrol(ctx context.Context, q wire.HostedEnrolRequest) (runnerproto.HostedEnrolResponse, error) { |
| + var none runnerproto.HostedEnrolResponse |
| + if !validHostedEnrol(q) { |
| + return none, ErrInvalid |
| + } |
| + if s.hostedAdmitter == nil { |
| + return none, ErrUnavailable |
| + } |
| + key := base64.RawURLEncoding.EncodeToString(q.MachinePublicKey) |
| + hash := runnerproto.MachineKeyHash(key) |
| + var job chat.HostedJob |
| + 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() |
| + allowed, err := hostedRates(tx, now, hostedRate{"hosted_enrol:" + instance, time.Minute, 60}, |
| + hostedRate{"hosted_machine:" + instance + ":" + hash, 10 * time.Minute, 5}) |
| + if err != nil { |
| + return err |
| + } |
| + if !allowed { |
| + denied = ErrRunnerRateLimited |
| + return nil |
| + } |
| + job, err = s.Chat().HostedClaimCode(tx, q.Code, q.LaunchID, now) |
| + if errors.Is(err, chat.ErrForbidden) { |
| + // The guess's rate count is kept. |
| + denied = ErrForbidden |
| + return nil |
| + } |
| + return hostedStoreError(err) |
| + }) |
| + if err != nil { |
| + return none, err |
| + } |
| + if denied != nil { |
| + return none, denied |
| + } |
| + asked := s.runnerClock.Now().UTC() |
| + a, err := s.hostedAdmitter.Admission(ctx, job.AttemptID) |
| + switch { |
| + case errors.Is(err, hostedrun.ErrNotAdmitted): |
| + return none, ErrForbidden |
| + case err != nil: |
| + return none, fmt.Errorf("%w: hosted admission: %w", ErrUnavailable, err) |
| + } |
| + var result runnerproto.HostedEnrolResponse |
| + err = s.write(ctx, func(tx *gorm.DB) error { |
| + if _, err := currentRunnerMember(tx, job.Person); err != nil { |
| + return err |
| + } |
| + instance, err := runnerInstance(tx) |
| + if err != nil { |
| + return err |
| + } |
| + now := s.runnerClock.Now().UTC() |
| + j, admitted, err := s.Chat().HostedEnrolAdmit(tx, job.AttemptID, q.LaunchID, q.VMRef, a, asked) |
| + if err != nil { |
| + return hostedStoreError(err) |
| + } |
| + deadline, ok := hostedDeadline(j) |
| + if !admitted || !ok || !now.Before(deadline) { |
| + // The admission record is kept; the job enrols nothing. |
| + denied = ErrForbidden |
| + return nil |
| + } |
| + var existing int64 |
| + if err := tx.Model(&runnerRecord{}).Where("instance_id = ? AND machine_key_hash = ?", instance, hash).Count(&existing).Error; err != nil { |
| + return storeError(err) |
| + } |
| + if existing != 0 { |
| + return ErrForbidden |
| + } |
| + runner := runnerRecord{Runner: setup.Runner{ID: rand.Text(), Person: j.Person, MachineKeyHash: hash, Label: j.VMRef, Revision: 1, Role: wire.RoleWorker}, InstanceID: instance} |
| + if err := tx.Create(&runner).Error; err != nil { |
| + return storeError(err) |
| + } |
| + if err := s.Chat().HostedEnrolBind(tx, j.AttemptID, runner.ID, key); err != nil { |
| + return hostedStoreError(err) |
| + } |
| + cred, err := mintRunnerCredential(tx, runner, now, hostedCredentialLifetime, deadline) |
| + if err != nil { |
| + return err |
| + } |
| + result = runnerproto.HostedEnrolResponse{Credential: cred, Epoch: j.Epoch, Deadline: deadline} |
| + return appendAudit(tx, Actor{Address: "device"}, "runner.hosted.enrol", runner.ID) |
| + }) |
| + if err != nil { |
| + return none, err |
| + } |
| + if denied != nil { |
| + return none, denied |
| + } |
| + return result, nil |
| +} |
| + |
| +// hostedLiveJob is the job p's runner is bound to, at now: the runner's |
| +// credential and its person current, the job enrolled with a valid |
| +// certificate, before its deadline. |
| +func (s *Store) hostedLiveJob(tx *gorm.DB, p RunnerPrincipal, now time.Time) (runnerRecord, chat.HostedJob, time.Time, error) { |
| + runner, err := runnerPrincipalAt(tx, p, now) |
| + if err != nil { |
| + return runner, chat.HostedJob{}, time.Time{}, err |
| + } |
| + j, bound, err := s.Chat().HostedRunnerJob(tx, runner.ID) |
| + if err != nil { |
| + return runner, j, time.Time{}, hostedStoreError(err) |
| + } |
| + deadline, ok := hostedDeadline(j) |
| + if !bound || j.State != chat.HostedJobEnrolled || !j.CertValid || !ok || !now.Before(deadline) { |
| + return runner, j, time.Time{}, ErrForbidden |
| + } |
| + return runner, j, deadline, nil |
| +} |
| + |
| +// HostedChallenge gives p's hosted runner a renewal challenge (POST |
| +// /api/runner/v2/hosted/challenge): a nonce valid for a minute, kept |
| +// hashed, within BeginEnrolment's limits. |
| +func (s *Store) HostedChallenge(ctx context.Context, p RunnerPrincipal) (wire.HostedChallenge, error) { |
| + var result wire.HostedChallenge |
| + var denied error |
| + err := s.write(ctx, func(tx *gorm.DB) error { |
| + now := s.runnerClock.Now().UTC() |
| + runner, _, _, err := s.hostedLiveJob(tx, p, now) |
| + if err != nil { |
| + return err |
| + } |
| + allowed, err := hostedRates(tx, now, hostedRate{"hosted_challenge:" + runner.InstanceID, time.Minute, 60}, |
| + hostedRate{"hosted_runner:" + runner.InstanceID + ":" + runner.ID, 10 * time.Minute, 5}) |
| + if err != nil { |
| + return err |
| + } |
| + if !allowed { |
| + denied = ErrRunnerRateLimited |
| + return nil |
| + } |
| + nonce := make([]byte, hostedNonceSize) |
| + if _, err := rand.Read(nonce); err != nil { |
| + return err |
| + } |
| + expires := now.Add(hostedChallengeLifetime) |
| + if err := s.Chat().HostedNewChallenge(tx, runner.ID, nonce, expires); err != nil { |
| + return storeError(err) |
| + } |
| + result = wire.HostedChallenge{Nonce: nonce, ExpiresAt: expires} |
| + return appendAudit(tx, Actor{Address: runner.Person}, "runner.hosted.challenge", runner.ID) |
| + }) |
| + if err != nil { |
| + return wire.HostedChallenge{}, err |
| + } |
| + if denied != nil { |
| + return wire.HostedChallenge{}, denied |
| + } |
| + return result, nil |
| +} |
| + |
| +// HostedRenew issues p's hosted runner its next credential (POST |
| +// /api/runner/v2/hosted/renew): q names p's runner and the job's current |
| +// epoch, and carries an unused, unexpired challenge of that runner's |
| +// signed by the machine key it enrolled with; the job is live. The |
| +// challenge is used and the credential lasts an hour, never past the |
| +// job's deadline. |
| +func (s *Store) HostedRenew(ctx context.Context, p RunnerPrincipal, q wire.HostedRenewRequest) (runnerproto.HostedEnrolResponse, error) { |
| + var result runnerproto.HostedEnrolResponse |
| + if len(q.Nonce) != hostedNonceSize || len(q.Signature) != ed25519.SignatureSize || q.RunnerID == "" { |
| + return result, ErrInvalid |
| + } |
| + if q.RunnerID != p.RunnerID { |
| + return result, ErrForbidden |
| + } |
| + err := s.write(ctx, func(tx *gorm.DB) error { |
| + now := s.runnerClock.Now().UTC() |
| + runner, j, deadline, err := s.hostedLiveJob(tx, p, now) |
| + if err != nil { |
| + return err |
| + } |
| + pub, err := runnerproto.DecodeBytes(j.MachinePublicKey, ed25519.PublicKeySize) |
| + if err != nil || q.Epoch != j.Epoch || runnerproto.MachineKeyHash(j.MachinePublicKey) != runner.MachineKeyHash || |
| + !ed25519.Verify(pub, wire.HostedRenewMessage(runner.ID, q.Epoch, q.Nonce), q.Signature) { |
| + return ErrForbidden |
| + } |
| + if err := s.Chat().HostedUseChallenge(tx, runner.ID, q.Nonce, now); err != nil { |
| + return hostedStoreError(err) |
| + } |
| + cred, err := mintRunnerCredential(tx, runner, now, hostedCredentialLifetime, deadline) |
| + if err != nil { |
| + return err |
| + } |
| + result = runnerproto.HostedEnrolResponse{Credential: cred, Epoch: j.Epoch, Deadline: deadline} |
| + return appendAudit(tx, Actor{Address: runner.Person}, "runner.hosted.renew", runner.ID) |
| + }) |
| + if err != nil { |
| + return runnerproto.HostedEnrolResponse{}, err |
| + } |
| + return result, nil |
| +} |
| + |
| +// hostedEnrolRoutes serves the enrolment on the application's router and |
| +// the challenge and renewal on the runner protocol's (mounted at |
| +// /api/runner/v2), only with EQUIPO_HOSTED_RUNNERS=1 and an admission |
| +// reader: the instance does nothing hosted otherwise. |
| +func (a *application) hostedEnrolRoutes(runner chi.Router) { |
| + if !a.hostedRunners || a.store.hostedAdmitter == nil { |
| + return |
| + } |
| + a.Post("/api/hosted/enrol", a.hostedEnrol) |
| + runner.With(a.RequireRunner).Post("/hosted/challenge", a.hostedChallenge) |
| + runner.With(a.RequireRunner).Post("/hosted/renew", a.hostedRenew) |
| +} |
| + |
| +// hostedEnrol is POST /api/hosted/enrol: public (personapi.Dispatcher's |
| +// allowlist), no cookie, no bearer. |
| +func (a *application) hostedEnrol(w http.ResponseWriter, r *http.Request) { |
| + var input wire.HostedEnrolRequest |
| + if !deviceRequest(w, r, &input) { |
| + return |
| + } |
| + result, err := a.store.HostedEnrol(r.Context(), input) |
| + if err != nil { |
| + a.deviceFailure(w, r, err) |
| + return |
| + } |
| + runnerJSON(w, http.StatusOK, result) |
| +} |
| + |
| +// hostedChallenge is POST /api/runner/v2/hosted/challenge, with the |
| +// runner's bearer (RequireRunner) and no body. |
| +func (a *application) hostedChallenge(w http.ResponseWriter, r *http.Request) { |
| + p, _ := RunnerFrom(r) |
| + if n, _ := io.ReadFull(io.LimitReader(r.Body, 1), make([]byte, 1)); n != 0 { |
| + runnerFailure(w, ErrInvalid) |
| + return |
| + } |
| + result, err := a.store.HostedChallenge(r.Context(), p) |
| + if err != nil { |
| + a.deviceFailure(w, r, err) |
| + return |
| + } |
| + runnerJSON(w, http.StatusOK, result) |
| +} |
| + |
| +// hostedRenew is POST /api/runner/v2/hosted/renew, with the runner's |
| +// bearer (RequireRunner) and a wire.HostedRenewRequest. |
| +func (a *application) hostedRenew(w http.ResponseWriter, r *http.Request) { |
| + p, _ := RunnerFrom(r) |
| + var input wire.HostedRenewRequest |
| + content, _, err := mime.ParseMediaType(r.Header.Get("Content-Type")) |
| + if err != nil || content != "application/json" || runnerproto.Decode(r.Body, &input) != nil { |
| + runnerFailure(w, ErrInvalid) |
| + return |
| + } |
| + result, err := a.store.HostedRenew(r.Context(), p, input) |
| + if err != nil { |
| + a.deviceFailure(w, r, err) |
| + return |
| + } |
| + runnerJSON(w, http.StatusOK, result) |
| +} |
diff --git a/internal/equipo/hosted_enrol_test.go b/internal/equipo/hosted_enrol_test.go| new file mode 100644 |
| index 00000000..cf7dc7b4 |
| --- /dev/null |
| +++ b/internal/equipo/hosted_enrol_test.go |
| @@ -0,0 +1,640 @@ |
| +package equipo |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ed25519" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "crypto/x509" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "encoding/pem" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/netip" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/chat" |
| + "amadan.net/oficina/equipo/internal/equipo/hostedrun" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| + "amadan.net/oficina/equipo/internal/hostedproxy/proxytest" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| + "amadan.net/oficina/equipo/internal/runner/hosted" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/dbtest" |
| + "gorm.io/gorm" |
| +) |
| + |
| +// hostedTestCode is a well-formed instance code (32 bytes, base64url), the |
| +// one the runner tests' bootstrap carries: the first job's. |
| +const hostedTestCode = "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIA" |
| + |
| +const hostedOwner = "owner@example.com" |
| + |
| +var hostedNow = time.Date(2026, 12, 1, 10, 0, 0, 0, time.UTC) |
| + |
| +// fakeAdmitter is the controller's admission records as the enrolment |
| +// reads them, by attempt. |
| +type fakeAdmitter struct { |
| + mu sync.Mutex |
| + views map[string]hostedwire.AdmissionView |
| + errs map[string]error |
| + calls int |
| +} |
| + |
| +func (f *fakeAdmitter) Admission(_ context.Context, attempt string) (hostedwire.AdmissionView, error) { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + f.calls++ |
| + if err := f.errs[attempt]; err != nil { |
| + return hostedwire.AdmissionView{}, err |
| + } |
| + v, ok := f.views[attempt] |
| + if !ok { |
| + return hostedwire.AdmissionView{}, hostedrun.ErrNotAdmitted |
| + } |
| + return v, nil |
| +} |
| + |
| +// hostedRig is the whole application over a fresh database with hosted |
| +// runners on, one hosted job waiting to enrol (more with vm), and a fake |
| +// controller's admission record for each. |
| +type hostedRig struct { |
| + s *Store |
| + h http.Handler |
| + clock *team.FakeClock |
| + adm *fakeAdmitter |
| + // The job this rig's requests are for, its instance code and its |
| + // VM's machine key. |
| + job chat.HostedJob |
| + code string |
| + machine ed25519.PrivateKey |
| +} |
| + |
| +// hostedJobOpts adjusts a job before it is stored. |
| +type hostedJobOpts func(*chat.HostedJob) |
| + |
| +func newHostedRig(t *testing.T, now time.Time, opts ...hostedJobOpts) *hostedRig { |
| + t.Helper() |
| + schema := dbtest.FromSet(BootSchema) |
| + t.Cleanup(schema.Remove) |
| + d, err := db.Open(schema.Path(t), slog.New(slog.NewTextHandler(io.Discard, nil))) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + r := &hostedRig{s: NewStore(d), clock: team.NewFakeClock(now), adm: &fakeAdmitter{views: map[string]hostedwire.AdmissionView{}, errs: map[string]error{}}} |
| + r.s.runnerClock = r.clock |
| + r.s.hostedAdmitter = r.adm |
| + r.h = hostedApp(t, r.s, true) |
| + return r.vm(t, 0, opts...) |
| +} |
| + |
| +// hostedApp is the whole application over s, with or without |
| +// EQUIPO_HOSTED_RUNNERS=1. |
| +func hostedApp(t *testing.T, s *Store, on bool) http.Handler { |
| + t.Helper() |
| + env := map[string]string{"EQUIPO_ORIGIN": "https://equipo.example", "EQUIPO_INSTANCE_KEY": "hosted-test-key", "CARLOS_MAIL": "submit", "EQUIPO_OWNERS": hostedOwner} |
| + if on { |
| + env["EQUIPO_HOSTED_RUNNERS"] = "1" |
| + } |
| + cfg, err := LoadConfig(func(k string) string { return env[k] }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + router, err := RouterWithStore(s.db, cfg, agentMail{}, nil, s) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return Mux(router) |
| +} |
| + |
| +// vm adds job n (0 is the first: launch l-1, VM vm-1, epoch 2, the |
| +// runner tests' code), enrolling, with its own code, VM, launch and |
| +// machine key, and a valid admission record for it; the returned rig's |
| +// requests are for it. |
| +func (r *hostedRig) vm(t *testing.T, n int, opts ...hostedJobOpts) *hostedRig { |
| + t.Helper() |
| + now := r.clock.Now() |
| + v := *r |
| + v.code = hostedTestCode |
| + launch, ref := proxytest.LaunchID, string(proxytest.VMRef) |
| + if n > 0 { |
| + v.code = base64.RawURLEncoding.EncodeToString(bytes.Repeat([]byte{byte(n)}, 32)) |
| + launch, ref = fmt.Sprintf("l-%d", n+1), fmt.Sprintf("vm-%d", n+1) |
| + } |
| + sum := sha256.Sum256([]byte(v.code)) |
| + at, by, expires := now.Add(-5*time.Minute), now.Add(5*time.Minute), now.Add(15*time.Minute) |
| + v.job = chat.HostedJob{AttemptID: fmt.Sprintf("hj-test-%d", n), StepID: fmt.Sprintf("st-%d", n), StepAttempt: 1, TaskID: "tk-1", Project: "p-1", |
| + Person: hostedOwner, Size: isolatedjob.SizeLarge, Lifetime: chat.HostedChecksLifetime, State: chat.HostedJobEnrolling, LaunchID: launch, |
| + VMRef: ref, Epoch: proxytest.Epoch, LaunchBy: &by, CertDigest: "cd", CertValid: true, |
| + CodeHash: hex.EncodeToString(sum[:]), CodeExpiresAt: &expires, AdmittedAt: &at, Revision: 1} |
| + for _, o := range opts { |
| + o(&v.job) |
| + } |
| + v.rawWrite(t, func(tx *gorm.DB) error { return tx.Create(&v.job).Error }) |
| + v.setView(func(a *hostedwire.AdmissionView) { |
| + *a = hostedwire.AdmissionView{AttemptID: v.job.AttemptID, LaunchID: v.job.LaunchID, State: "running", VMRef: isolatedjob.Ref(v.job.VMRef), |
| + Epoch: v.job.Epoch, CertDigest: "cd", CertValid: true} |
| + }) |
| + _, v.machine, _ = ed25519.GenerateKey(rand.Reader) |
| + return &v |
| +} |
| + |
| +// setView changes the controller's admission record for the rig's job. |
| +func (r *hostedRig) setView(fn func(*hostedwire.AdmissionView)) { |
| + r.adm.mu.Lock() |
| + defer r.adm.mu.Unlock() |
| + v := r.adm.views[r.job.AttemptID] |
| + fn(&v) |
| + r.adm.views[r.job.AttemptID] = v |
| +} |
| + |
| +func (r *hostedRig) setErr(err error) { |
| + r.adm.mu.Lock() |
| + defer r.adm.mu.Unlock() |
| + r.adm.errs[r.job.AttemptID] = err |
| +} |
| + |
| +func (r *hostedRig) rawWrite(t *testing.T, fn func(*gorm.DB) error) { |
| + t.Helper() |
| + if err := r.s.write(context.Background(), fn); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
| + |
| +// post sends a request through the whole application. |
| +func (r *hostedRig) post(path, body, bearer, cookie string) *httptest.ResponseRecorder { |
| + var rd io.Reader |
| + if body != "" { |
| + rd = strings.NewReader(body) |
| + } |
| + q := httptest.NewRequest(http.MethodPost, "https://equipo.example"+path, rd) |
| + if body != "" { |
| + q.Header.Set("Content-Type", "application/json") |
| + } |
| + if bearer != "" { |
| + q.Header.Set("Authorization", "Bearer "+bearer) |
| + } |
| + if cookie != "" { |
| + q.Header.Set("Cookie", cookie) |
| + } |
| + w := httptest.NewRecorder() |
| + r.h.ServeHTTP(w, q) |
| + return w |
| +} |
| + |
| +func (r *hostedRig) enrolBody(code, vm string) string { |
| + raw, _ := json.Marshal(wire.HostedEnrolRequest{Code: code, LaunchID: r.job.LaunchID, VMRef: vm, MachinePublicKey: r.machine.Public().(ed25519.PublicKey)}) |
| + return string(raw) |
| +} |
| + |
| +// enrolling is the rig's VM's own enrolment request. |
| +func (r *hostedRig) enrolling() *httptest.ResponseRecorder { |
| + return r.post("/api/hosted/enrol", r.enrolBody(r.code, r.job.VMRef), "", "") |
| +} |
| + |
| +// enrol enrols the rig's VM and wants a credential. |
| +func (r *hostedRig) enrol(t *testing.T) runnerproto.HostedEnrolResponse { |
| + t.Helper() |
| + w := r.enrolling() |
| + if w.Code != http.StatusOK { |
| + t.Fatalf("enrol: %d %s", w.Code, w.Body) |
| + } |
| + var out runnerproto.HostedEnrolResponse |
| + if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + return out |
| +} |
| + |
| +// refused wants a runner refusal (403 form.forbidden). |
| +func refused(t *testing.T, what string, w *httptest.ResponseRecorder) { |
| + t.Helper() |
| + if w.Code != http.StatusForbidden || !strings.Contains(w.Body.String(), "form.forbidden") { |
| + t.Fatalf("%s: %d %s, want a refusal", what, w.Code, w.Body) |
| + } |
| +} |
| + |
| +func (r *hostedRig) challenge(t *testing.T, bearer string) wire.HostedChallenge { |
| + t.Helper() |
| + w := r.post("/api/runner/v2/hosted/challenge", "", bearer, "") |
| + if w.Code != http.StatusOK { |
| + t.Fatalf("challenge: %d %s", w.Code, w.Body) |
| + } |
| + var ch wire.HostedChallenge |
| + if err := json.Unmarshal(w.Body.Bytes(), &ch); err != nil || len(ch.Nonce) != 32 { |
| + t.Fatalf("challenge %s: %v", w.Body, err) |
| + } |
| + return ch |
| +} |
| + |
| +func (r *hostedRig) renewBody(runner string, epoch int64, nonce []byte) string { |
| + sig := ed25519.Sign(r.machine, wire.HostedRenewMessage(runner, epoch, nonce)) |
| + raw, _ := json.Marshal(wire.HostedRenewRequest{RunnerID: runner, Epoch: epoch, Nonce: nonce, Signature: sig}) |
| + return string(raw) |
| +} |
| + |
| +func (r *hostedRig) renew(t *testing.T, cred runnerproto.RunnerCredential) runnerproto.HostedEnrolResponse { |
| + t.Helper() |
| + ch := r.challenge(t, cred.Token) |
| + w := r.post("/api/runner/v2/hosted/renew", r.renewBody(cred.RunnerID, r.job.Epoch, ch.Nonce), cred.Token, "") |
| + if w.Code != http.StatusOK { |
| + t.Fatalf("renew: %d %s", w.Code, w.Body) |
| + } |
| + var out runnerproto.HostedEnrolResponse |
| + if err := json.Unmarshal(w.Body.Bytes(), &out); err != nil { |
| + t.Fatal(err) |
| + } |
| + return out |
| +} |
| + |
| +func (r *hostedRig) jobRow(t *testing.T) chat.HostedJob { |
| + t.Helper() |
| + var j chat.HostedJob |
| + r.rawWrite(t, func(tx *gorm.DB) error { return tx.Where("attempt_id = ?", r.job.AttemptID).First(&j).Error }) |
| + return j |
| +} |
| + |
| +func (r *hostedRig) setJob(t *testing.T, cols map[string]any) { |
| + t.Helper() |
| + r.rawWrite(t, func(tx *gorm.DB) error { |
| + return tx.Model(&chat.HostedJob{}).Where("attempt_id = ?", r.job.AttemptID).Updates(cols).Error |
| + }) |
| +} |
| + |
| +func (r *hostedRig) runnerCount(t *testing.T) int64 { |
| + t.Helper() |
| + var n int64 |
| + r.rawWrite(t, func(tx *gorm.DB) error { return tx.Model(&runnerRecord{}).Count(&n).Error }) |
| + return n |
| +} |
| + |
| +// notEnrolled wants the rig's job still enrolling, with no runner. |
| +func (r *hostedRig) notEnrolled(t *testing.T) { |
| + t.Helper() |
| + if j := r.jobRow(t); j.State != chat.HostedJobEnrolling || j.RunnerID != "" { |
| + t.Fatalf("job %s: %s runner %q, want enrolling with none", j.AttemptID, j.State, j.RunnerID) |
| + } |
| +} |
| + |
| +// wantCredential checks an answer as the runner does, and that it names |
| +// the job's worker runner. |
| +func (r *hostedRig) wantCredential(t *testing.T, out runnerproto.HostedEnrolResponse, expires time.Time) { |
| + t.Helper() |
| + c := out.Credential |
| + deadline := r.job.LaunchBy.Add(r.job.Lifetime) |
| + if c.Token == "" || c.Role != wire.RoleWorker || c.Person != hostedOwner || out.Epoch != r.job.Epoch || !out.Deadline.Equal(deadline) { |
| + t.Fatalf("credential %+v epoch %d deadline %v; want a worker credential for %s at epoch %d, deadline %v", c, out.Epoch, out.Deadline, hostedOwner, r.job.Epoch, deadline) |
| + } |
| + if !c.ExpiresAt.Equal(expires) { |
| + t.Fatalf("credential expires %v, want %v", c.ExpiresAt, expires) |
| + } |
| + if c.ExpiresAt.After(out.Deadline) { |
| + t.Fatalf("credential expires %v, past the deadline %v", c.ExpiresAt, out.Deadline) |
| + } |
| + p, err := r.s.AuthenticateRunner(context.Background(), c.Token) |
| + if err != nil || p.RunnerID != c.RunnerID { |
| + t.Fatalf("the credential does not authenticate its runner: %+v %v", p, err) |
| + } |
| + if j := r.jobRow(t); j.RunnerID != c.RunnerID || j.State != chat.HostedJobEnrolled { |
| + t.Fatalf("job %s runner %q, want enrolled as %s", j.State, j.RunnerID, c.RunnerID) |
| + } |
| +} |
| + |
| +// TestEnrolRefusesReplayAndWrongVM: the code enrols once; the right code |
| +// for another VM, another code, an expired code and a code past the |
| +// enrolment window enrol nothing. |
| +func TestEnrolRefusesReplayAndWrongVM(t *testing.T) { |
| + r := newHostedRig(t, hostedNow) |
| + out := r.enrol(t) |
| + r.wantCredential(t, out, hostedNow.Add(time.Hour)) |
| + if j := r.jobRow(t); j.CodeUsedAt == nil || j.MachinePublicKey != base64.RawURLEncoding.EncodeToString(r.machine.Public().(ed25519.PublicKey)) { |
| + t.Fatalf("job after enrolment: code used %v, machine key %q", j.CodeUsedAt, j.MachinePublicKey) |
| + } |
| + refused(t, "the same enrolment again", r.enrolling()) |
| + if n := r.runnerCount(t); n != 1 { |
| + t.Fatalf("%d runners, want 1", n) |
| + } |
| + |
| + wrongVM := r.vm(t, 1) |
| + refused(t, "the right code from another VM", wrongVM.post("/api/hosted/enrol", wrongVM.enrolBody(wrongVM.code, "vm-other"), "", "")) |
| + wrongVM.notEnrolled(t) |
| + |
| + calls := r.adm.calls |
| + other := r.vm(t, 2) |
| + refused(t, "another code", other.post("/api/hosted/enrol", other.enrolBody("JJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJJA", other.job.VMRef), "", "")) |
| + if r.adm.calls != calls { |
| + t.Fatal("the controller was asked about a code that matched nothing") |
| + } |
| + other.notEnrolled(t) |
| + |
| + seen := hostedNow.Add(-chat.HostedEnrolTimeout) |
| + refused(t, "a code two minutes after its VM was seen running", r.vm(t, 3, func(j *chat.HostedJob) { j.RunningSeenAt = &seen }).enrolling()) |
| + refused(t, "a stopping job's code", r.vm(t, 4, func(j *chat.HostedJob) { j.State = chat.HostedJobStopping }).enrolling()) |
| + expired := r.vm(t, 5) |
| + r.clock.Advance(15 * time.Minute) |
| + refused(t, "an expired code", expired.enrolling()) |
| + if n := r.runnerCount(t); n != 1 { |
| + t.Fatalf("%d runners, want 1", n) |
| + } |
| +} |
| + |
| +// TestEnrolNeedsCertifiedAdmission: the controller's record must show the |
| +// VM running, certified, at the job's epoch; an absent record or a |
| +// refusal enrols nothing, and a controller that cannot answer is a |
| +// temporary failure. The refusing record is kept. |
| +func TestEnrolNeedsCertifiedAdmission(t *testing.T) { |
| + r := newHostedRig(t, hostedNow) |
| + for i, tc := range []struct { |
| + name string |
| + view func(*hostedwire.AdmissionView) |
| + err error |
| + status int |
| + }{ |
| + {"certificate not valid", func(v *hostedwire.AdmissionView) { v.CertValid = false }, nil, http.StatusForbidden}, |
| + {"not running", func(v *hostedwire.AdmissionView) { v.State = "stopping" }, nil, http.StatusForbidden}, |
| + {"another epoch", func(v *hostedwire.AdmissionView) { v.Epoch++ }, nil, http.StatusForbidden}, |
| + {"another VM", func(v *hostedwire.AdmissionView) { v.VMRef = "vm-other" }, nil, http.StatusForbidden}, |
| + {"another launch", func(v *hostedwire.AdmissionView) { v.LaunchID = "l-other" }, nil, http.StatusForbidden}, |
| + {"absent or refused", nil, hostedrun.ErrNotAdmitted, http.StatusForbidden}, |
| + {"controller unreachable", nil, errors.New("connection refused"), http.StatusServiceUnavailable}, |
| + } { |
| + v := r.vm(t, i+1) |
| + if tc.view != nil { |
| + v.setView(tc.view) |
| + } |
| + v.setErr(tc.err) |
| + if w := v.enrolling(); w.Code != tc.status { |
| + t.Fatalf("%s: enrol %d %s, want %d", tc.name, w.Code, w.Body, tc.status) |
| + } |
| + v.notEnrolled(t) |
| + if tc.name == "certificate not valid" { |
| + if j := v.jobRow(t); j.CertValid || j.CertCheckedAt == nil { |
| + t.Fatalf("the refusing admission was not recorded: valid %t checked %v", j.CertValid, j.CertCheckedAt) |
| + } |
| + } |
| + } |
| + if n := r.runnerCount(t); n != 0 { |
| + t.Fatalf("%d runners, want 0", n) |
| + } |
| + r.wantCredential(t, r.enrol(t), hostedNow.Add(time.Hour)) |
| +} |
| + |
| +// TestEnrolRemovedPersonRefused: a job whose person is no longer a current |
| +// member enrols nothing, and a removal ends a hosted runner's renewals. |
| +func TestEnrolRemovedPersonRefused(t *testing.T) { |
| + r := newHostedRig(t, hostedNow) |
| + out := r.enrol(t) |
| + ch := r.challenge(t, out.Credential.Token) |
| + r.rawWrite(t, func(tx *gorm.DB) error { |
| + return tx.Exec("UPDATE members SET active = 0 WHERE address = ?", hostedOwner).Error |
| + }) |
| + v := r.vm(t, 1) |
| + refused(t, "a removed person's job", v.enrolling()) |
| + v.notEnrolled(t) |
| + refused(t, "a removed person's renewal", r.post("/api/runner/v2/hosted/renew", r.renewBody(out.Credential.RunnerID, r.job.Epoch, ch.Nonce), out.Credential.Token, "")) |
| + refused(t, "a removed person's challenge", r.post("/api/runner/v2/hosted/challenge", "", out.Credential.Token, "")) |
| + if n := r.runnerCount(t); n != 1 { |
| + t.Fatalf("%d runners, want 1", n) |
| + } |
| +} |
| + |
| +// TestEnrolRouteIsPublicNotCSRF: the enrolment is a public machine route, |
| +// served through the whole application without a session or a CSRF |
| +// token, refusing cookies, a bearer and another origin; without hosted |
| +// runners on, none of the hosted routes is served. |
| +func TestEnrolRouteIsPublicNotCSRF(t *testing.T) { |
| + r := newHostedRig(t, hostedNow) |
| + body := r.enrolBody(r.code, r.job.VMRef) |
| + refused(t, "with a browser cookie", r.post("/api/hosted/enrol", body, "", "rastrillo_session=browser")) |
| + refused(t, "with a bearer", r.post("/api/hosted/enrol", body, "some-token", "")) |
| + q := httptest.NewRequest(http.MethodPost, "https://equipo.example/api/hosted/enrol", strings.NewReader(body)) |
| + q.Header.Set("Content-Type", "application/json") |
| + q.Header.Set("Origin", "https://other.example") |
| + w := httptest.NewRecorder() |
| + r.h.ServeHTTP(w, q) |
| + refused(t, "from another origin", w) |
| + if w := r.post("/api/hosted/enrol", "{", "", ""); w.Code != http.StatusUnprocessableEntity { |
| + t.Fatalf("a malformed enrolment: %d %s, want 422 from the handler", w.Code, w.Body) |
| + } |
| + r.notEnrolled(t) |
| + // No session, no CSRF token, no Origin: a machine's request. |
| + r.wantCredential(t, r.enrol(t), hostedNow.Add(time.Hour)) |
| + // Only the enrolment is public: the runner's routes are not under |
| + // /api/hosted. |
| + for _, p := range []string{"/api/hosted/challenge", "/api/hosted/renew"} { |
| + if w := r.post(p, "{}", "", ""); w.Code == http.StatusOK { |
| + t.Fatalf("%s served: %d %s", p, w.Code, w.Body) |
| + } |
| + } |
| + |
| + // Without hosted runners the instance serves none of the routes. |
| + v := r.vm(t, 1) |
| + off := hostedApp(t, r.s, false) |
| + for _, p := range []string{"/api/hosted/enrol", "/api/runner/v2/hosted/challenge", "/api/runner/v2/hosted/renew"} { |
| + q := httptest.NewRequest(http.MethodPost, "https://equipo.example"+p, strings.NewReader(v.enrolBody(v.code, v.job.VMRef))) |
| + q.Header.Set("Content-Type", "application/json") |
| + w := httptest.NewRecorder() |
| + off.ServeHTTP(w, q) |
| + // Not a route: the browser lane answers (signed out). |
| + if w.Code == http.StatusOK || strings.Contains(w.Body.String(), "credential") || strings.Contains(w.Body.String(), "nonce") { |
| + t.Fatalf("%s without hosted runners: %d %s, want it not served", p, w.Code, w.Body) |
| + } |
| + } |
| + v.notEnrolled(t) |
| +} |
| + |
| +// TestRenewThroughFullMiddleware: challenge and renew through the whole |
| +// application with the runner's bearer; a browser cookie or no bearer is |
| +// refused on both. |
| +func TestRenewThroughFullMiddleware(t *testing.T) { |
| + r := newHostedRig(t, hostedNow) |
| + out := r.enrol(t) |
| + tok := out.Credential.Token |
| + for _, p := range []string{"/api/runner/v2/hosted/challenge", "/api/runner/v2/hosted/renew"} { |
| + body := "" |
| + if strings.HasSuffix(p, "renew") { |
| + body = r.renewBody(out.Credential.RunnerID, r.job.Epoch, make([]byte, 32)) |
| + } |
| + refused(t, p+" with no bearer", r.post(p, body, "", "")) |
| + refused(t, p+" with a cookie", r.post(p, body, "", "rastrillo_session=browser")) |
| + refused(t, p+" with a bearer and a cookie", r.post(p, body, tok, "rastrillo_session=browser")) |
| + refused(t, p+" with another bearer", r.post(p, body, runnerSecret(), "")) |
| + } |
| + ch := r.challenge(t, tok) |
| + if want := hostedNow.Add(time.Minute); !ch.ExpiresAt.Equal(want) { |
| + t.Fatalf("challenge expires %v, want %v", ch.ExpiresAt, want) |
| + } |
| + if w := r.post("/api/runner/v2/hosted/challenge", "{}", tok, ""); w.Code != http.StatusUnprocessableEntity { |
| + t.Fatalf("a challenge with a body: %d %s, want 422", w.Code, w.Body) |
| + } |
| + r.clock.Advance(30 * time.Minute) |
| + refused(t, "a challenge past its minute", r.post("/api/runner/v2/hosted/renew", r.renewBody(out.Credential.RunnerID, r.job.Epoch, ch.Nonce), tok, "")) |
| + next := r.renew(t, out.Credential) |
| + r.wantCredential(t, next, r.clock.Now().Add(time.Hour)) |
| + if next.Credential.RunnerID != out.Credential.RunnerID || next.Credential.Token == tok { |
| + t.Fatalf("renewal %+v, want a new bearer for runner %s", next.Credential, out.Credential.RunnerID) |
| + } |
| + // The renewed bearer renews in turn; a signature by another key, or |
| + // a renewal naming another runner, does not. |
| + ch = r.challenge(t, next.Credential.Token) |
| + _, other, _ := ed25519.GenerateKey(rand.Reader) |
| + sig := ed25519.Sign(other, wire.HostedRenewMessage(next.Credential.RunnerID, r.job.Epoch, ch.Nonce)) |
| + raw, _ := json.Marshal(wire.HostedRenewRequest{RunnerID: next.Credential.RunnerID, Epoch: r.job.Epoch, Nonce: ch.Nonce, Signature: sig}) |
| + refused(t, "another key's signature", r.post("/api/runner/v2/hosted/renew", string(raw), next.Credential.Token, "")) |
| + refused(t, "another runner's renewal", r.post("/api/runner/v2/hosted/renew", r.renewBody("r-other", r.job.Epoch, ch.Nonce), next.Credential.Token, "")) |
| + r.wantCredential(t, r.renew(t, next.Credential), r.clock.Now().Add(time.Hour)) |
| +} |
| + |
| +// TestRenewNonceSingleUse: a challenge renews once, and only the runner |
| +// it was given to. |
| +func TestRenewNonceSingleUse(t *testing.T) { |
| + r := newHostedRig(t, hostedNow) |
| + out := r.enrol(t) |
| + ch := r.challenge(t, out.Credential.Token) |
| + body := r.renewBody(out.Credential.RunnerID, r.job.Epoch, ch.Nonce) |
| + if w := r.post("/api/runner/v2/hosted/renew", body, out.Credential.Token, ""); w.Code != http.StatusOK { |
| + t.Fatalf("first renewal: %d %s", w.Code, w.Body) |
| + } |
| + refused(t, "the same nonce again", r.post("/api/runner/v2/hosted/renew", body, out.Credential.Token, "")) |
| + refused(t, "a nonce the instance never gave", r.post("/api/runner/v2/hosted/renew", r.renewBody(out.Credential.RunnerID, r.job.Epoch, make([]byte, 32)), out.Credential.Token, "")) |
| + v := r.vm(t, 1) |
| + vo := v.enrol(t) |
| + ch = r.challenge(t, out.Credential.Token) |
| + refused(t, "another runner's nonce", v.post("/api/runner/v2/hosted/renew", v.renewBody(vo.Credential.RunnerID, v.job.Epoch, ch.Nonce), vo.Credential.Token, "")) |
| +} |
| + |
| +// TestRenewOldEpochRefused: a renewal signed for an epoch that is not the |
| +// job's current one is refused, before and after the epoch moves. |
| +func TestRenewOldEpochRefused(t *testing.T) { |
| + r := newHostedRig(t, hostedNow) |
| + out := r.enrol(t) |
| + ch := r.challenge(t, out.Credential.Token) |
| + refused(t, "the epoch before", r.post("/api/runner/v2/hosted/renew", r.renewBody(out.Credential.RunnerID, r.job.Epoch-1, ch.Nonce), out.Credential.Token, "")) |
| + r.setJob(t, map[string]any{"epoch": r.job.Epoch + 1}) |
| + refused(t, "the epoch the VM enrolled at, once it moved", r.post("/api/runner/v2/hosted/renew", r.renewBody(out.Credential.RunnerID, r.job.Epoch, ch.Nonce), out.Credential.Token, "")) |
| +} |
| + |
| +// TestRenewAfterStopRefused: a job that is stopping, or whose certificate |
| +// is no longer valid, renews nothing. |
| +func TestRenewAfterStopRefused(t *testing.T) { |
| + r := newHostedRig(t, hostedNow) |
| + for i, set := range []map[string]any{{"state": chat.HostedJobStopping}, {"cert_valid": false}} { |
| + v := r.vm(t, i+1) |
| + out := v.enrol(t) |
| + ch := v.challenge(t, out.Credential.Token) |
| + v.setJob(t, set) |
| + refused(t, fmt.Sprintf("a renewal after %v", set), v.post("/api/runner/v2/hosted/renew", v.renewBody(out.Credential.RunnerID, v.job.Epoch, ch.Nonce), out.Credential.Token, "")) |
| + refused(t, fmt.Sprintf("a challenge after %v", set), v.post("/api/runner/v2/hosted/challenge", "", out.Credential.Token, "")) |
| + } |
| +} |
| + |
| +// TestHostedCredentialCappedAtDeadline: a credential lasts an hour and |
| +// never past the job's deadline (launch-by plus lifetime), at enrolment |
| +// and at renewal; at the deadline nothing is issued. |
| +func TestHostedCredentialCappedAtDeadline(t *testing.T) { |
| + // The deadline is 30 minutes from now. |
| + by := hostedNow.Add(30*time.Minute - chat.HostedChecksLifetime) |
| + r := newHostedRig(t, hostedNow, func(j *chat.HostedJob) { j.LaunchBy = &by }) |
| + deadline := by.Add(chat.HostedChecksLifetime) |
| + late := hostedNow.Add(-chat.HostedChecksLifetime) |
| + past := r.vm(t, 1, func(j *chat.HostedJob) { j.LaunchBy = &late }) |
| + refused(t, "an enrolment at the deadline", past.enrolling()) |
| + past.notEnrolled(t) |
| + out := r.enrol(t) |
| + r.wantCredential(t, out, deadline) |
| + r.clock.Advance(20 * time.Minute) |
| + r.wantCredential(t, r.renew(t, out.Credential), deadline) |
| + ch := r.challenge(t, out.Credential.Token) |
| + r.clock.Advance(10 * time.Minute) |
| + refused(t, "a renewal at the deadline", r.post("/api/runner/v2/hosted/renew", r.renewBody(out.Credential.RunnerID, r.job.Epoch, ch.Nonce), out.Credential.Token, "")) |
| +} |
| + |
| +// TestEnrolEndToEndHostedStart: the runner's hosted.Start, through the |
| +// test proxy and its controller on 127.0.0.1, enrols against the real |
| +// enrolment route of the whole application, and the session's own HTTP |
| +// client renews its bearer through the real challenge and renewal routes. |
| +func TestEnrolEndToEndHostedStart(t *testing.T) { |
| + h := proxytest.New(t) |
| + r := newHostedRig(t, time.Now().UTC()) |
| + for _, p := range []string{"/api/hosted/enrol", "/api/runner/v2/hosted/challenge", "/api/runner/v2/hosted/renew"} { |
| + h.Handle(p, r.h.ServeHTTP) |
| + } |
| + b := hostedwire.BootstrapV2{Version: hostedwire.BootstrapV2Version, Purpose: hostedwire.PurposeChecks, |
| + LaunchID: proxytest.LaunchID, AttemptID: proxytest.AttemptID, InstanceCode: hostedTestCode, ProxyCode: proxytest.ProxyCode, |
| + Proxies: []netip.AddrPort{h.Proxy.EgressAddr()}, ProxyBoot: []netip.AddrPort{h.Proxy.BootAddr()}, ProxyCAPin: h.InterceptPin, |
| + Services: []hostedwire.Service{{Host: proxytest.Host, Port: 443, Class: hostedwire.ServiceInstance}}} |
| + state := t.TempDir() |
| + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| + defer cancel() |
| + s, err := hosted.Start(ctx, b, proxytest.VMRef, state) |
| + if err != nil { |
| + t.Fatalf("Start: %v", err) |
| + } |
| + defer s.HTTPClient().CloseIdleConnections() |
| + p, err := r.s.AuthenticateRunner(ctx, s.Token()) |
| + if err != nil { |
| + t.Fatalf("the session's bearer: %v", err) |
| + } |
| + if j := r.jobRow(t); j.State != chat.HostedJobEnrolled || j.RunnerID != p.RunnerID { |
| + t.Fatalf("job %s runner %q, want enrolled as %s", j.State, j.RunnerID, p.RunnerID) |
| + } |
| + raw, err := os.ReadFile(filepath.Join(state, hosted.MachineKeyFile)) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + blk, _ := pem.Decode(raw) |
| + if blk == nil { |
| + t.Fatal("the machine key is not PEM") |
| + } |
| + key, err := x509.ParsePKCS8PrivateKey(blk.Bytes) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + r.machine = key.(ed25519.PrivateKey) |
| + call := func(path string, body []byte) (int, []byte) { |
| + t.Helper() |
| + var rd io.Reader |
| + if body != nil { |
| + rd = bytes.NewReader(body) |
| + } |
| + q, _ := http.NewRequestWithContext(ctx, http.MethodPost, s.Origin()+path, rd) |
| + if body != nil { |
| + q.Header.Set("Content-Type", "application/json") |
| + } |
| + q.Header.Set("Authorization", "Bearer "+s.Token()) |
| + resp, err := s.HTTPClient().Do(q) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer resp.Body.Close() |
| + out, _ := io.ReadAll(resp.Body) |
| + return resp.StatusCode, out |
| + } |
| + status, out := call("/api/runner/v2/hosted/challenge", nil) |
| + var ch wire.HostedChallenge |
| + if status != http.StatusOK || json.Unmarshal(out, &ch) != nil { |
| + t.Fatalf("challenge through the proxy: %d %s", status, out) |
| + } |
| + status, out = call("/api/runner/v2/hosted/renew", []byte(r.renewBody(p.RunnerID, r.job.Epoch, ch.Nonce))) |
| + var next runnerproto.HostedEnrolResponse |
| + if status != http.StatusOK || json.Unmarshal(out, &next) != nil { |
| + t.Fatalf("renewal through the proxy: %d %s", status, out) |
| + } |
| + r.wantCredential(t, next, r.clock.Now().Add(time.Hour)) |
| +} |
diff --git a/internal/equipo/hostedrun/admitter.go b/internal/equipo/hostedrun/admitter.go| new file mode 100644 |
| index 00000000..49a61cd2 |
| --- /dev/null |
| +++ b/internal/equipo/hostedrun/admitter.go |
| @@ -0,0 +1,38 @@ |
| +package hostedrun |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedclient" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| +) |
| + |
| +// Admitter reads an attempt's admission record for a hosted VM's |
| +// enrolment (Task 22). The dispatcher's is over hostedclient and is |
| +// injected into the instance's enrolment, so only this package imports |
| +// hostedclient. A controller that has no record of the attempt, or |
| +// refuses to show it, answers ErrNotAdmitted; any other error is the |
| +// controller not answering. |
| +type Admitter interface { |
| + Admission(ctx context.Context, attempt string) (hostedwire.AdmissionView, error) |
| +} |
| + |
| +// ErrNotAdmitted is the controller's signed answer that it holds no |
| +// admission record for the attempt (absent), or a refusal to show one. |
| +var ErrNotAdmitted = errors.New("hostedrun: the controller admits no VM for the attempt") |
| + |
| +// admitter is an Admitter over the dispatcher's controller. |
| +type admitter struct{ c Controller } |
| + |
| +func (a admitter) Admission(ctx context.Context, attempt string) (hostedwire.AdmissionView, error) { |
| + v, err := a.c.Admission(ctx, attempt) |
| + if errors.Is(err, hostedclient.ErrAbsent) || errors.Is(err, hostedclient.ErrForbidden) || errors.Is(err, hostedclient.ErrNotFound) { |
| + return hostedwire.AdmissionView{}, fmt.Errorf("%w: %w", ErrNotAdmitted, err) |
| + } |
| + return v, err |
| +} |
| + |
| +// Admitter is the dispatcher's controller as the enrolment reads it. |
| +func (d *Dispatcher) Admitter() Admitter { return admitter{d.Client} } |
diff --git a/internal/equipo/hostedrun/admitter_test.go b/internal/equipo/hostedrun/admitter_test.go| new file mode 100644 |
| index 00000000..b275f0df |
| --- /dev/null |
| +++ b/internal/equipo/hostedrun/admitter_test.go |
| @@ -0,0 +1,51 @@ |
| +package hostedrun |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedclient" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| +) |
| + |
| +// admissionOnly is a Controller whose Admission answers view or err. |
| +type admissionOnly struct { |
| + Controller |
| + view hostedwire.AdmissionView |
| + err error |
| +} |
| + |
| +func (a admissionOnly) Admission(context.Context, string) (hostedwire.AdmissionView, error) { |
| + return a.view, a.err |
| +} |
| + |
| +// TestAdmitterMapsRefusals: the enrolment's admission reader says |
| +// ErrNotAdmitted for the controller's signed absent and forbidden |
| +// answers, passes any other failure through as it is, and a record |
| +// unchanged. |
| +func TestAdmitterMapsRefusals(t *testing.T) { |
| + ctx := context.Background() |
| + view := hostedwire.AdmissionView{AttemptID: "a-1", State: "running", CertValid: true} |
| + for _, tc := range []struct { |
| + err error |
| + notAdmitted bool |
| + }{ |
| + {fmt.Errorf("absent: %w", hostedclient.ErrAbsent), true}, |
| + {fmt.Errorf("refused: %w", hostedclient.ErrForbidden), true}, |
| + {fmt.Errorf("not found: %w", hostedclient.ErrNotFound), true}, |
| + {fmt.Errorf("lost: %w", hostedclient.ErrTransport), false}, |
| + {fmt.Errorf("forged: %w", hostedclient.ErrUnverified), false}, |
| + } { |
| + d := &Dispatcher{Client: admissionOnly{err: tc.err}} |
| + _, err := d.Admitter().Admission(ctx, "a-1") |
| + if errors.Is(err, ErrNotAdmitted) != tc.notAdmitted || !errors.Is(err, tc.err) { |
| + t.Errorf("%v read as %v (not admitted %t)", tc.err, err, tc.notAdmitted) |
| + } |
| + } |
| + d := &Dispatcher{Client: admissionOnly{view: view}} |
| + if got, err := d.Admitter().Admission(ctx, "a-1"); err != nil || got != view { |
| + t.Fatalf("a record read as %+v %v", got, err) |
| + } |
| +} |
diff --git a/internal/equipo/hostedrun/dispatcher.go b/internal/equipo/hostedrun/dispatcher.go| index 2d7a9238..25a37eed 100644 |
| --- a/internal/equipo/hostedrun/dispatcher.go |
| +++ b/internal/equipo/hostedrun/dispatcher.go |
| @@ -44,13 +44,6 @@ type Controller interface { |
| Stop(ctx context.Context, attempt, reason string) (hostedwire.StopProof, error) |
| } |
| -// Admitter reads an attempt's admission record (hosted enrolment, Task |
| -// 22): implemented here over hostedclient and injected, so only this |
| -// package imports hostedclient. |
| -type Admitter interface { |
| - Admission(ctx context.Context, attempt string) (hostedwire.AdmissionView, error) |
| -} |
| - |
| // Every is how often the dispatcher makes a pass. |
| const Every = 10 * time.Second |
| @@ -479,7 +472,3 @@ func New(store *chat.Store, cfg Config, log *slog.Logger) (*Dispatcher, error) { |
| } |
| return &Dispatcher{Store: store, Client: client, Clock: time.Now, Image: image, Account: cfg.Account, Log: log}, nil |
| } |
| - |
| -// Admitter is the dispatcher's controller as Task 22's enrolment reads |
| -// it. |
| -func (d *Dispatcher) Admitter() Admitter { return d.Client } |
diff --git a/internal/equipo/personapi/auth.go b/internal/equipo/personapi/auth.go| index 7697fc07..ddd709a5 100644 |
| --- a/internal/equipo/personapi/auth.go |
| +++ b/internal/equipo/personapi/auth.go |
| @@ -98,7 +98,9 @@ func Dispatcher(origin string, runner, person chi.Routes, refuseRunner func(http |
| } |
| protocol := registered(r, runner, "/api/runner/v2") |
| personRoute := registered(r, person, "/api/v1") |
| - public := r.Method == "POST" && (r.URL.Path == "/api/enrolments" || r.URL.Path == "/api/enrolments/token") |
| + // A hosted VM's enrolment is public too; its renewals are runner |
| + // routes, under /api/runner/v2. |
| + public := r.Method == "POST" && (r.URL.Path == "/api/enrolments" || r.URL.Path == "/api/enrolments/token" || r.URL.Path == "/api/hosted/enrol") |
| // The runner stream authenticates its own bearer before upgrading. |
| stream := r.Method == "GET" && r.URL.Path == "/api/runner/stream" |
| if personRoute { |
diff --git a/internal/equipo/runner_rotation.go b/internal/equipo/runner_rotation.go| index 6aebae5f..bf2e8d7d 100644 |
| --- a/internal/equipo/runner_rotation.go |
| +++ b/internal/equipo/runner_rotation.go |
| @@ -35,7 +35,7 @@ func (e *Execution) rotateContained(tx *gorm.DB, a runnerAssignment, q RunnerReq |
| } |
| rotation := runnerRotation{RunnerID: a.RunnerID, AssignmentID: a.ID, RequestID: q.RequestID, State: "cleanup_only"} |
| if live { |
| - credential, err := mintRunnerCredential(tx, runner, now) |
| + credential, err := deviceCredential(tx, runner, now) |
| if err != nil { |
| return result, err |
| } |
diff --git a/internal/equipo/runners.go b/internal/equipo/runners.go| index e461c2d6..66b5ddb5 100644 |
| --- a/internal/equipo/runners.go |
| +++ b/internal/equipo/runners.go |
| @@ -31,9 +31,28 @@ func runnerAt(tx *gorm.DB, instance, id string) (runnerRecord, error) { |
| return runner, nil |
| } |
| -func mintRunnerCredential(tx *gorm.DB, runner runnerRecord, now time.Time) (runnerproto.RunnerCredential, error) { |
| +// runnerCredentialLifetime is an enrolled machine's credential's; a |
| +// hosted runner's lasts hostedCredentialLifetime, capped at its job's |
| +// deadline. |
| +const runnerCredentialLifetime = 30 * 24 * time.Hour |
| + |
| +// deviceCredential is a machine's credential at enrolment or rotation. |
| +func deviceCredential(tx *gorm.DB, runner runnerRecord, now time.Time) (runnerproto.RunnerCredential, error) { |
| + return mintRunnerCredential(tx, runner, now, runnerCredentialLifetime, time.Time{}) |
| +} |
| + |
| +// mintRunnerCredential issues runner a credential valid for lifetime from |
| +// now and, when limit is set, never past limit. |
| +func mintRunnerCredential(tx *gorm.DB, runner runnerRecord, now time.Time, lifetime time.Duration, limit time.Time) (runnerproto.RunnerCredential, error) { |
| + expires := now.Add(lifetime) |
| + if !limit.IsZero() && expires.After(limit) { |
| + expires = limit |
| + } |
| + if lifetime <= 0 || !expires.After(now) { |
| + return runnerproto.RunnerCredential{}, ErrForbidden |
| + } |
| token := runnerSecret() |
| - record := runnerCredentialRecord{ID: rand.Text(), RunnerID: runner.ID, InstanceID: runner.InstanceID, Audience: runnerproto.RunnerAudience, Person: runner.Person, MachineKeyHash: runner.MachineKeyHash, TokenHash: runnerHash(runnerproto.RunnerAudience, token), ExpiresAt: now.Add(30 * 24 * time.Hour)} |
| + record := runnerCredentialRecord{ID: rand.Text(), RunnerID: runner.ID, InstanceID: runner.InstanceID, Audience: runnerproto.RunnerAudience, Person: runner.Person, MachineKeyHash: runner.MachineKeyHash, TokenHash: runnerHash(runnerproto.RunnerAudience, token), ExpiresAt: expires} |
| if err := tx.Create(&record).Error; err != nil { |
| return runnerproto.RunnerCredential{}, storeError(err) |
| } |
| @@ -115,7 +134,7 @@ func (s *Store) RotateRunnerCredential(ctx context.Context, token string) (runne |
| if updated.RowsAffected != 1 { |
| return ErrConflict |
| } |
| - result, err = mintRunnerCredential(tx, runner, now) |
| + result, err = deviceCredential(tx, runner, now) |
| if err != nil { |
| return err |
| } |
diff --git a/internal/equipo/store.go b/internal/equipo/store.go| index c0f7836d..1fe5c005 100644 |
| --- a/internal/equipo/store.go |
| +++ b/internal/equipo/store.go |
| @@ -2,6 +2,7 @@ package equipo |
| import ( |
| "amadan.net/oficina/equipo/internal/equipo/github" |
| + "amadan.net/oficina/equipo/internal/equipo/hostedrun" |
| "amadan.net/oficina/equipo/internal/release" |
| "amadan.net/rastrillo/rastrillo/sessions" |
| "context" |
| @@ -92,6 +93,9 @@ type Store struct { |
| // oficinaPause is a test's pause inside oficinaCatchUp. |
| oficinaPause func() |
| assist *assist.Registry |
| + // hostedAdmitter reads the controller's admission record for a hosted |
| + // VM's enrolment: the hosted dispatcher's, set only where it runs. |
| + hostedAdmitter hostedrun.Admitter |
| } |
| type StoreOption func(*Store) |