hostedtest: whole-chain hosted checks and failure drills
Task 30: internal/hostedtest (build tag hostedchain) runs the instance, the controller over the provider fake, two proxies, a primary and each VM's vm-init hooks and real equipo-runner, checks in real bubblewrap, with proxy, controller, VM, orphan and certificate drills. Lane .amadan/ci.d/17-hosted-chain runs make hosted-chain-test. Two defects the drills found, fixed red-first: - equipo-runner hosted-run gave containment the scratch root holding the worker's attempt trees, so every hosted gate was refused; it now has its own root. - decision S2-3 was not built: an enrolled job whose admission could not be refreshed for the feed lifetime now fails hosted_unavailable and is retried once after the stop proof.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
12 files changed,
+1,746
−8
.amadan/ci.d/17-hosted-chain+7 −0.rastrillo/budgets.txt+1 −0Makefile+16 −2cmd/equipo-runner/hosted.go+6 −3docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+22 −0internal/equipo/hostedrun/controller_test.go+35 −0internal/equipo/hostedrun/dispatcher.go+12 −1internal/hostedtest/chain.go+1,097 −0internal/hostedtest/chain_test.go+400 −0internal/hostedtest/doc.go+8 −0internal/thintest/instance.go+44 −2internal/vminit/chain.go+98 −0
diff --git a/.amadan/ci.d/17-hosted-chain b/.amadan/ci.d/17-hosted-chain| new file mode 100755 |
| index 00000000..26052a81 |
| --- /dev/null |
| +++ b/.amadan/ci.d/17-hosted-chain |
| @@ -0,0 +1,7 @@ |
| +#!/bin/sh |
| +# Hosted checks end to end on one machine (internal/hostedtest): the |
| +# instance, the controller over the provider fake, two proxies, a |
| +# primary and each VM's hosted runner, its checks in the exact |
| +# bubblewrap build, then the failure drills. About two minutes after the |
| +# compile step; no AWS call and no credentials. |
| +exec "$(dirname "$0")/../../scripts/ci-box.py" run make hosted-chain-test |
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 8712dedf..79e05513 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -14,6 +14,7 @@ perf GET /* skip Unknown private paths render 404; this fallback contains no scr |
| time internal/equipo/team 60s Plan 3 loaded CI measured 45.985s; niced serial reruns measured 18.079s and 22.031s. Keep migration, recovery, accounting and concurrency assertions; 60s leaves 30 percent headroom above loaded CI. |
| 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. |
| +time internal/hostedtest 300s Hosted slice 2 Task 30 (build tag hostedchain, make hosted-chain-test, its own CI lane): the whole hosted chain in one process (instance, controller, two proxies, a primary) and a real equipo-runner per VM, built at TestMain, its checks in real bubblewrap; eight tests, the drills waiting out gates, stop proofs and retried VMs; measured 128s on a 16 CPU docs-t1 under load 84; 300s covers a loaded CI runner. |
| size internal/equipo 25562 9319 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. Task 22 review 1: the controller's deadline in the credential cap, and tests for a stale admission after a newer refusal, the first sighting and its window, code single use alone and the controller's deadline; 25256/8669. Review 2: a renewal reads the controller's admission record first, outside the transaction, and is capped by its current deadline; its tests (a deadline moved earlier after launch, the controller away or without a record); 25304/8724. Review 3: enrolment tests for a deadline moved earlier before enrolment and one already passed; 25304/8741. Task 25: what the person sees of hosted work: the checks line and timeline for a hosted wait and for each hosted limit (hostedWaitLine), the hosted reasons' words on the checks line and the merge decision, the Usage page's Hosted machines block (unknown, never zero, when unread), the owner's per-person limit editor (form, parsing, save route, the members it lists) and nineteen pending keys; hosted_views_test.go drives the store through the production wiring; 25478/9069. Task 25 review round 1: the limit save keeps a stored figure submitted as shown (hostedLimitsFrom), refuses limits below one checks run in their own words (hosted.limits.too_low), and handler tests for the Usage block and the save (flag, unknown totals, session actor, target, revision, member); 25524/9235. Task 26: runner_update_needed waits for the runner's update on the pause line (tooOld) and its pending work.reason words; 25525/9235. Task 27: checkpoint_key.go, a runner's machine public key for pack receipts (chat.Authority.RunnerMachineKey: runner rows keep only the key's hash, so the key comes from the runner's exchanged enrolment and must hash to it), wired in chat_wiring.go, and checkpoint_key_test.go; 25562/9312. Task 27 review 1: an enrolment whose stored hash matches the runner beside another key's bytes; 25562/9319. |
| size internal/wire 9962 - 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. Task 23: SendPackCommand.Deps, refused below ProtocolHostedRunners; 9902. Task 26: ReasonRunnerUpdateNeeded registered in StepReasons, and ProtocolHostedRunners documented as marking Research's quoting; 9912. Task 27: checkpoint.go, the Checkpoint and PackReceipt types slice 4 sends, the notes bounds, ValidPackDigest and PackReceiptMessage (the receipt's domain-separated signed message); no frame; 9962. |
diff --git a/Makefile b/Makefile| index 45a1ebd4..9bfdbe99 100644 |
| --- a/Makefile |
| +++ b/Makefile |
| @@ -27,7 +27,7 @@ RUNNER_RELEASE_DIR = releases/equipo-runner-linux-amd64-$(RELEASE_VERSION) |
| # and a suite running beside it would be measured too. |
| .NOTPARALLEL: |
| -.PHONY: build release test test-lane ci-shard ci-compile lanes-check test-quarantine vet fmt-check staticcheck govulncheck gitleaks budget perf migration-check runner-adapter-test runner-namespace-test runner-host runner-dead-references hosted-image-check hosted-infra-check ci |
| +.PHONY: build release test test-lane ci-shard ci-compile lanes-check test-quarantine vet fmt-check staticcheck govulncheck gitleaks budget perf migration-check runner-adapter-test runner-namespace-test runner-host runner-dead-references hosted-image-check hosted-infra-check hosted-chain-test ci |
| RASTRILLO := go run amadan.net/rastrillo/rastrillo/cmd/rastrillo |
| @@ -265,6 +265,20 @@ hosted-infra-check: |
| $(HOSTED_TOFU) -chdir=infra/hosted/$$r test -no-color; \ |
| done |
| +# hosted-chain-test is hosted runners slice 2's whole chain on one |
| +# machine (internal/hostedtest, build tag hostedchain): an instance, the |
| +# controller over the in-memory provider fake, two proxies, a primary, |
| +# and each VM's root init and hosted runner, whose checks run in the |
| +# exact bubblewrap build; then the failure drills (a proxy, the |
| +# controller and a VM lost mid-step, an orphan VM, a certificate |
| +# withdrawn). TMPDIR is a fresh directory on disk under HOME, removed |
| +# after: the namespaces' socket paths must stay short. No AWS call. |
| +# .amadan/ci.d/17-hosted-chain runs it on CI. |
| +hosted-chain-test: |
| + @test "$$(/usr/bin/bwrap --version)" = "bubblewrap 0.11.0" |
| + @t=$$(mktemp -d "$$HOME/.hc.XXXXXX") && trap 'rm -rf "$$t"' EXIT && \ |
| + TMPDIR="$$t" CGO_ENABLED=0 go test -tags hostedchain ./internal/hostedtest -count=1 |
| + |
| # Rastrillo v0.30.0's CLI assumes a single internal app directory. The |
| # runner protocol is a second package, so call the same dump.Compute API |
| # from the app test instead of using CLI package discovery. |
| @@ -301,7 +315,7 @@ runner-host: runner-adapter-test runner-namespace-test |
| # fails the build the moment models.go and migrations/ disagree, |
| # instead of at boot on whatever machine notices next. If the app |
| # declares manifest resources, also add: rastrillo generate --check |
| -ci: copy-release-check runner-dead-references lanes-check build vet fmt-check spacing staticcheck govulncheck gitleaks hosted-image-check hosted-infra-check budget test test-quarantine runner-host migration-check perf |
| +ci: copy-release-check runner-dead-references lanes-check build vet fmt-check spacing staticcheck govulncheck gitleaks hosted-image-check hosted-infra-check hosted-chain-test budget test test-quarantine runner-host migration-check perf |
| .PHONY: copy-release-check direct-release-check release-runner runner-prerequisites |
| copy-release-check: |
diff --git a/cmd/equipo-runner/hosted.go b/cmd/equipo-runner/hosted.go| index 5ddfa832..92d1d268 100644 |
| --- a/cmd/equipo-runner/hosted.go |
| +++ b/cmd/equipo-runner/hosted.go |
| @@ -92,13 +92,16 @@ func serveChecks(ctx context.Context, s *hosted.Session, state string, logger *s |
| } |
| c := runner.Config{Origin: s.Origin(), StateDir: filepath.Join(state, "runner"), ScratchRoot: filepath.Join(state, "scratch"), |
| WorkspaceRoot: filepath.Join(state, "work"), GitPath: hostedGit, Executable: self, GoRoot: linuxworker.GoRoot, BwrapPath: linuxworker.Bwrap} |
| - deps := filepath.Join(state, "deps") |
| - for _, d := range []string{c.ScratchRoot, c.WorkspaceRoot, deps} { |
| + // The containment manager's own root lies apart from the scratch |
| + // root, where the worker keeps each attempt's tree (thin's |
| + // worker-steps): containment refuses a workspace inside its root. |
| + deps, namespaces := filepath.Join(state, "deps"), filepath.Join(state, "ns") |
| + for _, d := range []string{c.ScratchRoot, c.WorkspaceRoot, deps, namespaces} { |
| if err := os.MkdirAll(d, 0o700); err != nil { |
| return err |
| } |
| } |
| - m, err := containment.New(containment.Config{Binary: linuxworker.Bwrap, RunnerBinary: self, ScratchRoot: c.ScratchRoot}) |
| + m, err := containment.New(containment.Config{Binary: linuxworker.Bwrap, RunnerBinary: self, ScratchRoot: namespaces}) |
| if err != nil { |
| return err |
| } |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index fe56111f..069ea00f 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -2797,3 +2797,25 @@ Results of the full re-run of M1 to M36 under `CGO_ENABLED=0`. Every mutation fa |
| - M34: exit 1 | FAIL: test_digest_enforcement_altered_refused (__main__.UserData.test_digest_enforcement_altered_refused) / AssertionError: [] is not true : the plan was accepted | restored, SHA-256 identical |
| - M35: exit 1 | assemble_test.go:317: repeated: 4 downloads before the refusal (hostedimage: input pkgs/git-core-2.47.1-1.amzn2023.x86_64.rpm has SHA-256 e3d7a28a2d9eacd388106bb38690a17b50380681d7e41922898aed6b4b782a / --- FAIL: TestAssembleRefusesBadPackagesBeforeFetching (0.01s) | restored, SHA-256 identical |
| - M36: exit 1 | FAIL: test_template_outside_the_modules_refused (__main__.UserData.test_template_outside_the_modules_refused) / AssertionError: "not a module's cloud-init template" not found in "module.controller.aws_instance.controller user_data: cannot be proven: the template interpolates 'type.name.attr', which this checker | restored, SHA-256 identical |
| + |
| +## Task 30 |
| + |
| +The whole hosted chain on one machine: `internal/hostedtest` (build tag `hostedchain`), `make hosted-chain-test`, CI lane `.amadan/ci.d/17-hosted-chain`, time record 300s. No AWS call: the controller runs over the in-memory `isolatedjob` fake, whose launches boot vm-init's own hook code in the test process (`vminit.ChainHooks`, a `linux && hostedchain` file: the unprivileged seam for ownership, account and fork only) and post `/run` with the launch's BootstrapV2; the runner is the real `equipo-runner hosted-run`, built at TestMain, its checks in `/usr/bin/bwrap` 0.11.0. Clocks: the proxies' monotonic clock, the instance's and the controller's can be moved forward (feed expiry, launch window, orphan grace); everything else is real time. thintest gained `HostedRunners`, `Hosted`, `Clock` and `ServeTLS`. |
| + |
| +RED, the chain over the code as it stood (542acf39): |
| +`TMPDIR=$(mktemp -d ~/.hcXXXX) go test -tags hostedchain ./internal/hostedtest -count=1` |
| +- `TestChainHostedCheckPasses`: `step {State:done ... Reason:checks_unavailable Checks:cannot_run ChecksSandbox:bubblewrap}`. DEFECT 1 (Task 17's `serveChecks`): the containment manager's scratch root was the runner's `ScratchRoot`, where thin's worker keeps each attempt's tree (`worker-steps`); containment refuses a workspace inside its own root (`namespace_mount_rejected`), so every hosted gate ended checks_unavailable. Fixed: the manager gets its own root, `<state>/ns`. |
| +- `TestChainKillControllerMidStep`: the proxies closed the VM's sockets at feed expiry (`stale_feed`), then the VM reconnected once the controller was back and its result was certified on the same VM: one job, no `hosted_unavailable`. DEFECT 2 (decision S2-3 not built): nothing failed a job whose VM had lost its tunnels. Fixed in `hostedrun.Dispatcher.watch`: an enrolled job whose admission refresh fails `FeedLost` (5 min, `ctlproxy.FeedLifetime`) after its latest admission record fails `hosted_unavailable`; its stop waits for the controller's proof, then the step is retried once. Unit test `TestControllerLostFailsEnrolledJob` (hostedrun). |
| + |
| +GREEN: `make hosted-chain-test`: ok 108.6s (8 tests; 128s under load 84 earlier). `go test ./internal/equipo/hostedrun -count=1` ok 24.8s; `go test ./internal/vminit` ok; `go test ./cmd/equipo-runner -run Hosted` ok; `make budget build vet lanes-check` ok. |
| + |
| +Mutation checks (each applied alone, the named test run, the file restored byte for byte; chain tests through `hcrun.sh`, a short TMPDIR under $HOME): |
| +- M1 `cmd/equipo-runner/hosted.go`: containment `ScratchRoot: c.ScratchRoot` again. `TestChainHostedCheckPasses`: exit 1 | chain_test.go:169: step {State:done ... Reason:checks_unavailable Checks:cannot_run ...} | restored. |
| +- M2 `hostedrun/dispatcher.go`: the FeedLost rule disabled (`if false && ...`). `TestControllerLostFailsEnrolledJob`: exit 1 | controller_test.go:200: the feed expired and the job is enrolled "" | restored. `TestChainKillControllerMidStep`: exit 1 | chain_test.go:308: the job failing hosted_unavailable: not within 30s | restored. |
| +- M2b the rule's bound moved earlier (`FeedLost - 2*Every`). `TestControllerLostFailsEnrolledJob`: exit 1 | controller_test.go:195: failed 4m40s into the outage: stopping "hosted_unavailable" | restored. |
| +- M3 `runner/hosted/transport.go`: dial only the first proxy (`d.proxies[:1]`). `TestChainKillProxyMidStep`: exit 1 | chain_test.go:279: the step ended and its VMs stopped with proof: not within 3m0s | restored. (A first version of this drill picked the proxy to kill from a log line written only when a tunnel closes, killed the idle proxy and survived this mutation; the drill now kills the bootstrap's first proxy and checks it carried the link.) |
| +- M4 `hostedrun/dispatcher.go`: a stopping or stopped admission no longer fails the job (`case ctlAbandoned:` only). `TestChainStopVMMidStep`: exit 1 | chain_test.go:339: the step ended and its VMs stopped with proof: not within 2m0s | restored. |
| +- M5 `hostedctl/reaper.go`: the orphan grace never over (`false && c.graceOver(...)`). `TestChainOrphanVM`: exit 1 | chain_test.go:359: the orphan stopped: not within 30s | restored. |
| +- M6 `chat/hosted_results.go`: hostedCertified ignores the job's and the record's CertValid. `TestChainCertWithdrawnMidStep`: exit 1 | chain_test.go:380: jobs [{... State:ended ...}] (the withdrawn VM's result kept) | restored. |
| +- M7 `chat/hosted_results.go`: deps_new_module no longer presented as needs_network. `TestChainNewModule`: exit 1 | chain_test.go:228: the person sees "deps_new_module", not needs_network | restored. |
| +- M8 `chat/hosted_results.go`: hostedCertified never certifies. `TestChainFailingCheck`: exit 1 | chain_test.go:193: step {State:done ... Reason:hosted_unavailable Checks:cannot_run ...} | restored. |
diff --git a/internal/equipo/hostedrun/controller_test.go b/internal/equipo/hostedrun/controller_test.go| index 592df97f..76d755bb 100644 |
| --- a/internal/equipo/hostedrun/controller_test.go |
| +++ b/internal/equipo/hostedrun/controller_test.go |
| @@ -16,6 +16,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/hostedctl" |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest" |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlegress" |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy" |
| "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy/ctlproxytest" |
| "amadan.net/oficina/equipo/internal/hostedwire" |
| "amadan.net/oficina/equipo/internal/isolatedjob" |
| @@ -165,3 +166,37 @@ func TestEnrolTimeoutAdmissionOutage(t *testing.T) { |
| t.Fatalf("window closed with the controller unreachable: %s %q", got.State, got.StopReason) |
| } |
| } |
| + |
| +// TestControllerLostFailsEnrolledJob (decision S2-3): with the controller |
| +// unreachable, an enrolled job's VM keeps its tunnels only until the |
| +// proxies' feed expires. Once the job's latest admission record is |
| +// FeedLost old the job fails hosted_unavailable (its step is retried once |
| +// after the stop proof); a shorter outage changes nothing. |
| +func TestControllerLostFailsEnrolledJob(t *testing.T) { |
| + if FeedLost != ctlproxy.FeedLifetime { |
| + t.Fatalf("FeedLost %v is not the proxies' feed lifetime %v", FeedLost, ctlproxy.FeedLifetime) |
| + } |
| + r := newRig(t, nil) |
| + j := r.enrolling() |
| + if !r.enrol(j.AttemptID, "H1") { |
| + t.Fatal("the VM did not enrol") |
| + } |
| + r.passes(Every) |
| + checked := r.job(j.AttemptID).CertCheckedAt |
| + if checked == nil { |
| + t.Fatal("no admission record after enrolment") |
| + } |
| + r.ctl.mu.Lock() |
| + r.ctl.down = true |
| + r.ctl.mu.Unlock() |
| + for r.now.Add(Every).Before(checked.Add(FeedLost)) { |
| + r.passes(Every) |
| + if got := r.job(j.AttemptID); got.State != chat.HostedJobEnrolled { |
| + t.Fatalf("failed %v into the outage: %s %q", r.now.Sub(*checked), got.State, got.StopReason) |
| + } |
| + } |
| + r.passes(2 * Every) |
| + if got := r.job(j.AttemptID); got.State != chat.HostedJobStopping || got.StopReason != wire.ReasonHostedUnavailable { |
| + t.Fatalf("the feed expired and the job is %s %q", got.State, got.StopReason) |
| + } |
| +} |
diff --git a/internal/equipo/hostedrun/dispatcher.go b/internal/equipo/hostedrun/dispatcher.go| index a34b847e..ba5b876c 100644 |
| --- a/internal/equipo/hostedrun/dispatcher.go |
| +++ b/internal/equipo/hostedrun/dispatcher.go |
| @@ -47,6 +47,12 @@ type Controller interface { |
| // Every is how often the dispatcher makes a pass. |
| const Every = 10 * time.Second |
| +// FeedLost is how long the proxies act on the controller's last feed |
| +// (ctlproxy.FeedLifetime, decision S2-3). An enrolled job whose latest |
| +// admission record is this old, the controller unreachable since, has |
| +// had its VM's tunnels closed: it fails hosted_unavailable. |
| +const FeedLost = 5 * time.Minute |
| + |
| // A launch the controller did not take, or an intent it has not yet |
| // given a VM (a throttle), is tried again after a wait that doubles from |
| // BackoffMin to BackoffMax. |
| @@ -267,7 +273,9 @@ func (d *Dispatcher) launch(ctx context.Context, j chat.HostedJob, by time.Time) |
| // controller's check). A VM the controller reports gone fails the job. An |
| // enrolling VM first seen running chat.HostedEnrolTimeout ago (kept on |
| // the job, so a restart or a controller outage does not extend it) is |
| -// stopped, whether or not this refresh succeeds. |
| +// stopped, whether or not this refresh succeeds. An enrolled job whose |
| +// refresh fails FeedLost after its latest admission record fails |
| +// hosted_unavailable: the proxies have closed its VM's tunnels. |
| func (d *Dispatcher) watch(ctx context.Context, j chat.HostedJob) error { |
| asked := d.now() |
| if j.State == chat.HostedJobEnrolling && j.RunningSeenAt != nil && !asked.Before(j.RunningSeenAt.Add(chat.HostedEnrolTimeout)) { |
| @@ -276,6 +284,9 @@ func (d *Dispatcher) watch(ctx context.Context, j chat.HostedJob) error { |
| a, err := d.Client.Admission(ctx, j.AttemptID) |
| if err != nil { |
| d.log().Warn("hosted_admission_failed", "attempt", j.AttemptID, "err", err) |
| + if j.State == chat.HostedJobEnrolled && j.CertCheckedAt != nil && !asked.Before(j.CertCheckedAt.Add(FeedLost)) { |
| + return d.Store.HostedFailed(ctx, j.AttemptID, wire.ReasonHostedUnavailable) |
| + } |
| return nil |
| } |
| if err := d.Store.HostedAdmitted(ctx, j.AttemptID, a, asked); err != nil { |
diff --git a/internal/hostedtest/chain.go b/internal/hostedtest/chain.go| new file mode 100644 |
| index 00000000..0aea7c84 |
| --- /dev/null |
| +++ b/internal/hostedtest/chain.go |
| @@ -0,0 +1,1097 @@ |
| +//go:build linux && hostedchain |
| + |
| +package hostedtest |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ecdsa" |
| + "crypto/ed25519" |
| + "crypto/elliptic" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "crypto/x509/pkix" |
| + "encoding/base64" |
| + "encoding/hex" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + stdlog "log" |
| + "log/slog" |
| + "math/big" |
| + "net" |
| + "net/http" |
| + "net/netip" |
| + "net/url" |
| + "os" |
| + "os/exec" |
| + "path/filepath" |
| + "strings" |
| + "sync" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/chat" |
| + "amadan.net/oficina/equipo/internal/equipo/hostedrun" |
| + "amadan.net/oficina/equipo/internal/hostedclient" |
| + "amadan.net/oficina/equipo/internal/hostedctl" |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlcert" |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest" |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlegress" |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy/ctlproxytest" |
| + "amadan.net/oficina/equipo/internal/hostedproxy" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| + "amadan.net/oficina/equipo/internal/runner" |
| + "amadan.net/oficina/equipo/internal/runner/forge" |
| + "amadan.net/oficina/equipo/internal/runner/thin" |
| + "amadan.net/oficina/equipo/internal/runner/workspace" |
| + "amadan.net/oficina/equipo/internal/thintest" |
| + "amadan.net/oficina/equipo/internal/vminit" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "amadan.net/oficina/equipo/internal/wire/forgekey" |
| +) |
| + |
| +// The instance's service host, the public address the proxies' resolver |
| +// gives it (their dialer sends it to the instance's TLS listener on |
| +// 127.0.0.1), the image every checks launch names, and the project. |
| +const ( |
| + InstanceHost = "instance.example.test" |
| + instanceAddr = "203.0.113.10" |
| + Image = isolatedjob.ImageDigest("sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc") |
| + Repo = "amadan.net/oficina/sample" |
| + Project = "p1" |
| + Owner = thintest.Owner |
| + instanceKey = hostedwire.KeyID("inst-1") |
| +) |
| + |
| +// Every is the pace of the harness's loops: the provider's lifecycle |
| +// tick, the proxies' feed polls, placement and the dispatcher's passes |
| +// (each in place of its 10 to 30 s production pace), and the |
| +// controller's reaper pass. |
| +const Every = 200 * time.Millisecond |
| + |
| +// RunnerBinary is equipo-runner built for the chain (TestMain sets it): |
| +// the hosted VMs run it as vm-init starts it. |
| +var RunnerBinary string |
| + |
| +// BuildRunner builds cmd/equipo-runner into dir and returns its path. |
| +func BuildRunner(dir string) (string, error) { |
| + out := filepath.Join(dir, "equipo-runner") |
| + cmd := exec.Command("go", "build", "-o", out, "amadan.net/oficina/equipo/cmd/equipo-runner") |
| + cmd.Env = append(os.Environ(), "CGO_ENABLED=0") |
| + if b, err := cmd.CombinedOutput(); err != nil { |
| + return "", fmt.Errorf("building equipo-runner: %v: %s", err, b) |
| + } |
| + return out, nil |
| +} |
| + |
| +// Clock is real time that a test can move forward: Mono always, Wall |
| +// too when made with NewClock(true). After fires on real time or on a |
| +// Forward past it, whichever comes first. |
| +type Clock struct { |
| + start time.Time |
| + wall bool |
| + mu sync.Mutex |
| + off time.Duration |
| + waiters []*waiter |
| +} |
| + |
| +type waiter struct { |
| + at time.Duration |
| + ch chan time.Time |
| + once sync.Once |
| +} |
| + |
| +func (w *waiter) fire(t time.Time) { w.once.Do(func() { w.ch <- t }) } |
| + |
| +// NewClock starts a clock at real time; wall says whether Forward moves |
| +// Wall as well as Mono. |
| +func NewClock(wall bool) *Clock { return &Clock{start: time.Now(), wall: wall} } |
| + |
| +func (c *Clock) offset() time.Duration { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + return c.off |
| +} |
| + |
| +// Wall is the real wall time, moved by Forward when the clock moves it. |
| +func (c *Clock) Wall() time.Time { |
| + if !c.wall { |
| + return time.Now() |
| + } |
| + return time.Now().Add(c.offset()) |
| +} |
| + |
| +// Now is Wall in UTC (the instance's clock). |
| +func (c *Clock) Now() time.Time { return c.Wall().UTC() } |
| + |
| +// Mono is the time since the clock started, moved by Forward. |
| +func (c *Clock) Mono() time.Duration { return time.Since(c.start) + c.offset() } |
| + |
| +// After fires once Mono has moved on by d. |
| +func (c *Clock) After(d time.Duration) <-chan time.Time { |
| + w := &waiter{at: c.Mono() + d, ch: make(chan time.Time, 1)} |
| + if d <= 0 { |
| + w.fire(c.Wall()) |
| + return w.ch |
| + } |
| + c.mu.Lock() |
| + c.waiters = append(c.waiters, w) |
| + c.mu.Unlock() |
| + time.AfterFunc(d, func() { w.fire(c.Wall()) }) |
| + return w.ch |
| +} |
| + |
| +// Forward moves the clock on by d and fires every timer now due. |
| +func (c *Clock) Forward(d time.Duration) { |
| + c.mu.Lock() |
| + c.off += d |
| + mono := time.Since(c.start) + c.off |
| + kept := c.waiters[:0] |
| + var due []*waiter |
| + for _, w := range c.waiters { |
| + if w.at <= mono { |
| + due = append(due, w) |
| + continue |
| + } |
| + kept = append(kept, w) |
| + } |
| + c.waiters = kept |
| + c.mu.Unlock() |
| + for _, w := range due { |
| + w.fire(c.Wall()) |
| + } |
| +} |
| + |
| +// Buffer is a log many goroutines write. |
| +type Buffer struct { |
| + mu sync.Mutex |
| + buf bytes.Buffer |
| +} |
| + |
| +func (b *Buffer) Write(p []byte) (int, error) { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + return b.buf.Write(p) |
| +} |
| + |
| +func (b *Buffer) String() string { |
| + b.mu.Lock() |
| + defer b.mu.Unlock() |
| + return b.buf.String() |
| +} |
| + |
| +// Chain is the whole hosted chain on 127.0.0.1. |
| +type Chain struct { |
| + t *testing.T |
| + Root string |
| + ctx context.Context |
| + |
| + // The instance, its hosted dispatcher, and the clock both read. |
| + Inst *thintest.Instance |
| + Disp *hostedrun.Dispatcher |
| + InstClock *Clock |
| + instTLS string |
| + |
| + // The controller (Kill and Start), its certificate set, the provider |
| + // fake under it with each VM's root init, and their clock. |
| + ctl *controller |
| + ctlAddr string |
| + ctlCert tls.Certificate |
| + ctlKey ed25519.PrivateKey |
| + keys map[hostedwire.KeyID]hostedwire.VerifyKey |
| + ctlCfg hostedctl.Config |
| + Certs *ctlcert.Set |
| + Fake *isolatedjob.Fake |
| + Prov *Provider |
| + CtlClock *Clock |
| + CtlLog *Buffer |
| + |
| + // The two proxies and their clock (Mono only: their leaves are |
| + // checked by the runner against real wall time). |
| + Proxies [2]*Proxy |
| + ProxyClock *Clock |
| + |
| + // The person's primary runner and the forge repository it reads. |
| + forgeDir string |
| + primary func() |
| + PrimaryID string |
| + |
| + // The base and candidate commits of the repository's change. |
| + Base, Candidate string |
| + |
| + loopMu sync.Mutex // held by each harness loop pass |
| + paused bool |
| +} |
| + |
| +// Proxy is one egress proxy of the chain. |
| +type Proxy struct { |
| + *hostedproxy.Server |
| + // Log is the proxy's decision log. |
| + Log *Buffer |
| + mu sync.Mutex |
| + dead bool |
| +} |
| + |
| +// Alive reports whether the proxy still runs. |
| +func (p *Proxy) Alive() bool { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + return !p.dead |
| +} |
| + |
| +// Kill stops the proxy and closes every tunnel through it. |
| +func (p *Proxy) Kill() { |
| + p.mu.Lock() |
| + p.dead = true |
| + p.mu.Unlock() |
| + _ = p.Close() |
| +} |
| + |
| +// Files are the repository's files: base, and the candidate's changes. |
| +type Files struct { |
| + Base, Candidate map[string]string |
| +} |
| + |
| +// New starts the chain with the repository's base and candidate commits |
| +// on the forge and the setting "Run checks in a hosted VM" still off. |
| +func New(t *testing.T, repo Files) *Chain { |
| + t.Helper() |
| + if RunnerBinary == "" { |
| + t.Fatal("hostedtest: TestMain must build the runner (BuildRunner)") |
| + } |
| + if _, err := os.Stat(LinuxBwrap); err != nil { |
| + t.Skipf("the hosted runner needs bubblewrap at %s", LinuxBwrap) |
| + } |
| + root, err := os.MkdirTemp("", "hc") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + ch := &Chain{t: t, Root: root, ctx: ctx, InstClock: NewClock(true), CtlClock: NewClock(true), ProxyClock: NewClock(false), |
| + CtlLog: &Buffer{}} |
| + t.Cleanup(func() { |
| + cancel() |
| + _ = os.RemoveAll(root) |
| + }) |
| + ch.Base, ch.Candidate = ch.makeRepo(repo) |
| + |
| + // Keys and certificates: the controller's TLS (pinned) and signing |
| + // keys, the instance's and each proxy's signing key, the origin CA |
| + // that signs the instance's certificate (the proxies' OriginRoots), |
| + // and the intercept CA the VMs pin. |
| + ch.ctlCert = selfSigned(t, "controller", net.ParseIP("127.0.0.1")) |
| + _, ch.ctlKey, _ = ed25519.GenerateKey(rand.Reader) |
| + instSeed := make([]byte, ed25519.SeedSize) |
| + _, _ = rand.Read(instSeed) |
| + instKey := ed25519.NewKeyFromSeed(instSeed) |
| + ch.keys = map[hostedwire.KeyID]hostedwire.VerifyKey{instanceKey: {Public: instKey.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance}} |
| + originKey, originCA := newCA(t, "origin CA") |
| + originPool := x509.NewCertPool() |
| + originPool.AddCert(originCA) |
| + icKey, ic := newCA(t, "intercept CA") |
| + icPin := sha256.Sum256(ic.RawSubjectPublicKeyInfo) |
| + |
| + // The controller's address first: the proxies name it. |
| + l, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ch.ctlAddr = l.Addr().String() |
| + l.Close() |
| + |
| + // The instance, served over TLS for the proxies. |
| + t.Setenv(hostedclient.FlagEnv, "1") |
| + hcfg := hostedrun.Config{Controller: "https://" + ch.ctlAddr, TLSPin: spkiPin(ch.ctlCert.Leaf), |
| + ControllerKey: base64.StdEncoding.EncodeToString(ch.ctlKey.Public().(ed25519.PublicKey)), KeyID: string(instanceKey), |
| + Key: base64.StdEncoding.EncodeToString(instSeed), Image: string(Image), Account: "chain"} |
| + ch.Inst = thintest.StartInstanceWith(t, func(i *thintest.Instance) { i.HostedRunners, i.Hosted, i.Clock = true, hcfg, ch.InstClock }) |
| + ch.instTLS = ch.Inst.ServeTLS(t, issueServer(t, originKey, originCA, InstanceHost)) |
| + if ch.Disp, err = hostedrun.New(ch.Inst.Store.Chat(), hcfg, slog.New(slog.NewTextHandler(ch.CtlLog, nil)).With("side", "dispatcher")); err != nil { |
| + t.Fatal(err) |
| + } |
| + ch.Disp.Clock = ch.InstClock.Now |
| + |
| + // The proxies. |
| + for i := range ch.Proxies { |
| + pub, key, _ := ed25519.GenerateKey(rand.Reader) |
| + id := hostedwire.KeyID(fmt.Sprintf("proxy-%d", i)) |
| + plog := &Buffer{} |
| + ch.keys[id] = hostedwire.VerifyKey{Public: pub, Role: hostedwire.RoleProxy} |
| + srv, err := hostedproxy.NewServer(hostedproxy.Config{ |
| + Egress: netip.MustParseAddrPort("127.0.0.1:0"), Boot: netip.MustParseAddrPort("127.0.0.1:0"), |
| + ControllerURL: "https://" + ch.ctlAddr, ControllerKey: ch.ctlKey.Public().(ed25519.PublicKey), |
| + ControllerTLSPin: spkiPin(ch.ctlCert.Leaf), KeyID: id, Key: key, |
| + ClientCA: ctlproxytest.CA().Pool(), InterceptCA: tls.Certificate{Certificate: [][]byte{ic.Raw}, PrivateKey: icKey, Leaf: ic}, |
| + OriginRoots: originPool, Log: plog, Clock: ch.ProxyClock, Resolver: resolver{}, |
| + DialOrigin: func(ctx context.Context, network, addr string) (net.Conn, error) { |
| + if addr != instanceAddr+":443" { |
| + return nil, fmt.Errorf("hostedtest: no origin at %s", addr) |
| + } |
| + var d net.Dialer |
| + return d.DialContext(ctx, network, ch.instTLS) |
| + }, |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := srv.Start(ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + p := &Proxy{Server: srv, Log: plog} |
| + t.Cleanup(p.Kill) |
| + ch.Proxies[i] = p |
| + } |
| + |
| + // The controller over the provider fake. |
| + ch.Certs = ctlcerttest.Set(ctlcerttest.Cert(Image, InstanceHost)) |
| + ch.Fake = isolatedjob.NewFake(ch.CtlClock, isolatedjob.SpikeLimits()) |
| + ch.Prov = &Provider{Fake: ch.Fake, ch: ch, vms: map[isolatedjob.Ref]*VM{}} |
| + t.Cleanup(ch.Prov.close) |
| + ch.ctlCfg = hostedctl.Config{Enabled: true, Certs: ch.Certs, ProxyCA: ctlproxytest.CA(), ProxyCodeKey: ctlproxytest.CodeKey(), |
| + ProviderNamespace: "chain", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" }, |
| + Manifest: ctlegress.Manifest{ |
| + Services: map[string]hostedwire.Service{"instance": {Host: InstanceHost, Port: 443, Class: hostedwire.ServiceInstance}}, |
| + Proxies: []netip.AddrPort{ch.Proxies[0].EgressAddr(), ch.Proxies[1].EgressAddr()}, |
| + ProxyBoot: []netip.AddrPort{ch.Proxies[0].BootAddr(), ch.Proxies[1].BootAddr()}, |
| + ProxyCAPin: hex.EncodeToString(icPin[:]), |
| + }} |
| + ch.StartController() |
| + t.Cleanup(ch.KillController) |
| + |
| + ch.startPrimary() |
| + go ch.loop() |
| + // Registered last, so it runs first: everything is still up. |
| + t.Cleanup(func() { |
| + if t.Failed() { |
| + ch.dumpLogs() |
| + } |
| + }) |
| + return ch |
| +} |
| + |
| +// loop is the harness's pace: the provider's lifecycle, the proxies' |
| +// polls, placement and a dispatcher pass, every Every. |
| +func (ch *Chain) loop() { |
| + tick := time.NewTicker(Every) |
| + defer tick.Stop() |
| + for { |
| + select { |
| + case <-ch.ctx.Done(): |
| + return |
| + case <-tick.C: |
| + } |
| + ch.loopMu.Lock() |
| + if !ch.paused { |
| + ch.Prov.Tick() |
| + for _, p := range ch.Proxies { |
| + if p.Alive() { |
| + _ = p.Poll(ch.ctx) |
| + } |
| + } |
| + if err := ch.Inst.Store.Chat().Place(ch.ctx); err != nil && ch.ctx.Err() == nil { |
| + fmt.Fprintf(ch.CtlLog, "place: %v\n", err) |
| + } |
| + if err := ch.Disp.Pass(ch.ctx); err != nil && ch.ctx.Err() == nil { |
| + fmt.Fprintf(ch.CtlLog, "dispatcher pass: %v\n", err) |
| + } |
| + } |
| + ch.loopMu.Unlock() |
| + } |
| +} |
| + |
| +// Pause holds the harness's loops (between passes) until resume is |
| +// called. |
| +func (ch *Chain) Pause() (resume func()) { |
| + ch.loopMu.Lock() |
| + ch.paused = true |
| + ch.loopMu.Unlock() |
| + return func() { |
| + ch.loopMu.Lock() |
| + ch.paused = false |
| + ch.loopMu.Unlock() |
| + } |
| +} |
| + |
| +// controller is one controller process: its store, its API over TLS on |
| +// the chain's controller address, and its reaper loop. |
| +type controller struct { |
| + c *hostedctl.Controller |
| + store *hostedctl.Store |
| + srv *http.Server |
| + cancel context.CancelFunc |
| + done chan struct{} |
| +} |
| + |
| +type alerter struct{ log io.Writer } |
| + |
| +func (a alerter) Alert(_ context.Context, al hostedctl.Alert) error { |
| + fmt.Fprintf(a.log, "alert %s: %s\n", al.Kind, al.Detail) |
| + return nil |
| +} |
| + |
| +// StartController starts a controller process on the chain's database |
| +// and address, as a restart does. |
| +func (ch *Chain) StartController() { |
| + t := ch.t |
| + t.Helper() |
| + store, err := hostedctl.Open(ch.ctx, filepath.Join(ch.Root, "controller.db"), ch.CtlClock) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c, err := hostedctl.New(ch.ctlCfg, hostedctl.Deps{Store: store, Runner: ch.Prov, Auditor: ch.Fake, Alerter: alerter{ch.CtlLog}, |
| + Log: slog.New(slog.NewTextHandler(ch.CtlLog, nil)).With("side", "controller")}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := c.RunAudit(ch.ctx); err != nil { |
| + t.Fatal(err) |
| + } |
| + h, err := c.Handler(hostedctl.HandlerConfig{Keys: ch.keys, Signing: ch.ctlKey, Wall: time.Now}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + var l net.Listener |
| + for range 100 { |
| + if l, err = net.Listen("tcp", ch.ctlAddr); err == nil { |
| + break |
| + } |
| + time.Sleep(20 * time.Millisecond) |
| + } |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + srv := &http.Server{Handler: h, ReadHeaderTimeout: 5 * time.Second, ErrorLog: stdlog.New(io.Discard, "", 0), |
| + TLSConfig: &tls.Config{Certificates: []tls.Certificate{ch.ctlCert}, NextProtos: []string{"http/1.1"}}} |
| + go srv.ServeTLS(l, "", "") |
| + ctx, cancel := context.WithCancel(ch.ctx) |
| + k := &controller{c: c, store: store, srv: srv, cancel: cancel, done: make(chan struct{})} |
| + go func() { |
| + defer close(k.done) |
| + _ = c.Loop(ctx, Every) |
| + }() |
| + ch.ctl = k |
| +} |
| + |
| +// KillController stops the controller process at once: its listener and |
| +// every connection close, and its reaper stops. |
| +func (ch *Chain) KillController() { |
| + k := ch.ctl |
| + if k == nil { |
| + return |
| + } |
| + ch.ctl = nil |
| + _ = k.srv.Close() |
| + k.cancel() |
| + <-k.done |
| + _ = k.store.Close() |
| +} |
| + |
| +// Controller is the running controller, nil while it is killed. |
| +func (ch *Chain) Controller() *hostedctl.Controller { |
| + if ch.ctl == nil { |
| + return nil |
| + } |
| + return ch.ctl.c |
| +} |
| + |
| +// Provider is the provider fake as the controller uses it: each VM it |
| +// launches boots vm-init's hook server in this process, which is sent |
| +// the launch's bootstrap on /run and starts the hosted runner; a stop |
| +// sends /terminate. |
| +type Provider struct { |
| + *isolatedjob.Fake |
| + ch *Chain |
| + mu sync.Mutex |
| + vms map[isolatedjob.Ref]*VM |
| + next int |
| +} |
| + |
| +// VM is one VM's root init and runner. |
| +type VM struct { |
| + Ref isolatedjob.Ref |
| + Dir string |
| + hooks *vminit.ChainVM |
| + srv *http.Server |
| + url string |
| + log *os.File |
| + // RunStatus is /run's answer, once it came. |
| + mu sync.Mutex |
| + runStatus int |
| + runBody string |
| + ended bool |
| +} |
| + |
| +// Launch launches as the fake does; a VM it makes for the first time |
| +// boots. |
| +func (p *Provider) Launch(ctx context.Context, s isolatedjob.LaunchSpec) (isolatedjob.Ref, error) { |
| + ref, err := p.Fake.Launch(ctx, s) |
| + if err != nil { |
| + return ref, err |
| + } |
| + p.mu.Lock() |
| + _, seen := p.vms[ref] |
| + p.mu.Unlock() |
| + if !seen { |
| + if err := p.boot(ref, s.Bootstrap); err != nil { |
| + return "", err |
| + } |
| + } |
| + return ref, nil |
| +} |
| + |
| +// Stop stops as the fake does, and ends the VM's runner. |
| +func (p *Provider) Stop(ctx context.Context, ref isolatedjob.Ref, reason string) error { |
| + err := p.Fake.Stop(ctx, ref, reason) |
| + if err == nil { |
| + p.terminate(ref) |
| + } |
| + return err |
| +} |
| + |
| +// Tick moves the fake's VMs on; a VM the provider stopped by itself (its |
| +// lifetime) has its runner ended too. |
| +func (p *Provider) Tick() { |
| + p.Fake.Tick() |
| + jobs, err := p.Fake.List(context.Background()) |
| + if err != nil { |
| + return |
| + } |
| + for _, j := range jobs { |
| + if j.State == isolatedjob.StateStopping || j.State == isolatedjob.StateStopped { |
| + p.terminate(j.Ref) |
| + } |
| + } |
| +} |
| + |
| +// VM is the VM for ref, or nil. |
| +func (p *Provider) VM(ref isolatedjob.Ref) *VM { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + return p.vms[ref] |
| +} |
| + |
| +func (p *Provider) boot(ref isolatedjob.Ref, bootstrap []byte) error { |
| + p.mu.Lock() |
| + p.next++ |
| + dir := filepath.Join(p.ch.Root, fmt.Sprintf("v%d", p.next)) |
| + p.mu.Unlock() |
| + state, home := filepath.Join(dir, "s"), filepath.Join(dir, "h") |
| + for _, d := range []string{state, home} { |
| + if err := os.MkdirAll(d, 0o700); err != nil { |
| + return err |
| + } |
| + } |
| + policy := filepath.Join(dir, "policy.json") |
| + if err := os.WriteFile(policy, []byte(`{"policy":"bwrap"}`), 0o644); err != nil { |
| + return err |
| + } |
| + logFile, err := os.Create(filepath.Join(dir, "vm.log")) |
| + if err != nil { |
| + return err |
| + } |
| + l, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + return err |
| + } |
| + cfg := vminit.Config{HookAddr: l.Addr().(*net.TCPAddr).AddrPort(), RunnerUser: "equipo", RunnerBinary: RunnerBinary, |
| + StateDir: state, ResultsDir: filepath.Join(dir, "r"), PolicyFiles: []string{policy}} |
| + var logMu sync.Mutex |
| + hooks, err := vminit.ChainHooks(cfg, home, logFile, func(format string, a ...any) { |
| + logMu.Lock() |
| + defer logMu.Unlock() |
| + fmt.Fprintf(logFile, format+"\n", a...) |
| + }) |
| + if err != nil { |
| + l.Close() |
| + return err |
| + } |
| + vm := &VM{Ref: ref, Dir: dir, hooks: hooks, url: "http://" + l.Addr().String(), log: logFile, |
| + srv: &http.Server{Handler: hooks, ReadHeaderTimeout: 5 * time.Second}} |
| + go vm.srv.Serve(l) |
| + p.mu.Lock() |
| + p.vms[ref] = vm |
| + p.mu.Unlock() |
| + body, _ := json.Marshal(map[string]string{"microvmId": string(ref), "runHookPayload": string(bootstrap)}) |
| + go func() { |
| + status, out := vm.post("run", body) |
| + vm.mu.Lock() |
| + vm.runStatus, vm.runBody = status, out |
| + vm.mu.Unlock() |
| + }() |
| + return nil |
| +} |
| + |
| +// post sends one lifecycle hook and returns its status and body. |
| +func (vm *VM) post(hook string, body []byte) (int, string) { |
| + resp, err := http.Post(vm.url+"/aws/lambda-microvms/runtime/v1/"+hook, "application/json", bytes.NewReader(body)) |
| + if err != nil { |
| + return 0, err.Error() |
| + } |
| + defer resp.Body.Close() |
| + out, _ := io.ReadAll(resp.Body) |
| + return resp.StatusCode, strings.TrimSpace(string(out)) |
| +} |
| + |
| +// Run is /run's answer: 0 until it came. |
| +func (vm *VM) Run() (int, string) { |
| + vm.mu.Lock() |
| + defer vm.mu.Unlock() |
| + return vm.runStatus, vm.runBody |
| +} |
| + |
| +// RunnerPID is the VM's runner's pid while it runs. |
| +func (vm *VM) RunnerPID() int { return vm.hooks.RunnerPID() } |
| + |
| +// Gating reports whether a checks gate has started in the VM: its |
| +// runner's containment manager has recorded a namespace. |
| +func (vm *VM) Gating() bool { |
| + entries, _ := os.ReadDir(filepath.Join(vm.Dir, "s", "ns")) |
| + return len(entries) > 0 |
| +} |
| + |
| +// Log is everything the VM's root init and runner wrote. |
| +func (vm *VM) Log() string { |
| + b, _ := os.ReadFile(filepath.Join(vm.Dir, "vm.log")) |
| + return string(b) |
| +} |
| + |
| +// terminate sends /terminate once and waits for the runner to end; a |
| +// runner still there after 20 s is killed. |
| +func (p *Provider) terminate(ref isolatedjob.Ref) { |
| + vm := p.VM(ref) |
| + if vm == nil { |
| + return |
| + } |
| + vm.mu.Lock() |
| + if vm.ended { |
| + vm.mu.Unlock() |
| + return |
| + } |
| + vm.ended = true |
| + vm.mu.Unlock() |
| + vm.post("terminate", nil) |
| + for end := time.Now().Add(20 * time.Second); time.Now().Before(end); time.Sleep(50 * time.Millisecond) { |
| + if vm.RunnerPID() == 0 { |
| + break |
| + } |
| + } |
| + if pid := vm.RunnerPID(); pid > 0 { |
| + _ = syscall.Kill(-pid, syscall.SIGKILL) |
| + } |
| + _ = vm.srv.Close() |
| +} |
| + |
| +// close ends every VM's runner. |
| +func (p *Provider) close() { |
| + p.mu.Lock() |
| + vms := make([]*VM, 0, len(p.vms)) |
| + for _, vm := range p.vms { |
| + vms = append(vms, vm) |
| + } |
| + p.mu.Unlock() |
| + for _, vm := range vms { |
| + if pid := vm.RunnerPID(); pid > 0 { |
| + _ = syscall.Kill(-pid, syscall.SIGKILL) |
| + } |
| + for end := time.Now().Add(5 * time.Second); vm.RunnerPID() > 0 && time.Now().Before(end); time.Sleep(20 * time.Millisecond) { |
| + } |
| + _ = vm.srv.Close() |
| + _ = vm.log.Close() |
| + } |
| +} |
| + |
| +// VMs is every VM booted so far, in launch order. |
| +func (p *Provider) VMs() []*VM { |
| + p.mu.Lock() |
| + defer p.mu.Unlock() |
| + out := make([]*VM, 0, len(p.vms)) |
| + for _, vm := range p.vms { |
| + out = append(out, vm) |
| + } |
| + for i := 1; i < len(out); i++ { |
| + for j := i; j > 0 && out[j].Dir < out[j-1].Dir; j-- { |
| + out[j], out[j-1] = out[j-1], out[j] |
| + } |
| + } |
| + return out |
| +} |
| + |
| +// LinuxBwrap is where the hosted image and this machine keep bubblewrap. |
| +const LinuxBwrap = "/usr/bin/bwrap" |
| + |
| +// localForge is the person's forge as their primary sees it: the one |
| +// repository, a bare repository on disk. |
| +type localForge struct { |
| + thin.Forge |
| + dir string |
| +} |
| + |
| +func (f localForge) Host() string { return forgekey.Hub } |
| +func (f localForge) Repos() []string { return []string{Repo} } |
| +func (f localForge) Reachable(context.Context) []string { return []string{Repo} } |
| +func (f localForge) CreateIn(context.Context) []string { return nil } |
| +func (f localForge) Agent() string { return "equipo-test" } |
| +func (f localForge) Recheck() {} |
| +func (f localForge) Exists(context.Context, string) (bool, error) { return true, nil } |
| +func (f localForge) Create(context.Context, string) error { return thin.ErrNoCreate } |
| +func (f localForge) Remote(_ context.Context, repo string, _ thin.Use) (workspace.Remote, error) { |
| + if repo != Repo { |
| + return workspace.Remote{}, errors.New("hostedtest: no such repository") |
| + } |
| + return workspace.Remote{URL: f.dir}, nil |
| +} |
| +func (f localForge) Propose(context.Context, thin.Proposal) (thin.ProposalRef, error) { |
| + return thin.ProposalRef{}, errors.New("hostedtest: no proposals") |
| +} |
| +func (f localForge) Merge(context.Context, string, string, forge.MergeRequest) (forge.MergeResult, error) { |
| + return forge.MergeResult{}, errors.New("hostedtest: no merges") |
| +} |
| + |
| +// git runs git in dir with a fixed identity and no user config. |
| +func git(t *testing.T, dir string, args ...string) string { |
| + t.Helper() |
| + cmd := exec.Command("/usr/bin/git", args...) |
| + cmd.Dir = dir |
| + cmd.Env = append(os.Environ(), "GIT_CONFIG_GLOBAL=/dev/null", "GIT_AUTHOR_NAME=t", "GIT_AUTHOR_EMAIL=t@example.com", "GIT_COMMITTER_NAME=t", "GIT_COMMITTER_EMAIL=t@example.com") |
| + out, err := cmd.CombinedOutput() |
| + if err != nil { |
| + t.Fatalf("git %v: %v %s", args, err, out) |
| + } |
| + return strings.TrimSpace(string(out)) |
| +} |
| + |
| +// makeRepo makes the forge's bare repository: main at the base, and the |
| +// task's branch at the candidate. |
| +func (ch *Chain) makeRepo(f Files) (base, candidate string) { |
| + t := ch.t |
| + seed := filepath.Join(ch.Root, "seed") |
| + git(t, ch.Root, "init", "-q", "-b", "main", seed) |
| + write := func(files map[string]string) { |
| + for name, body := range files { |
| + p := filepath.Join(seed, name) |
| + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + git(t, seed, "add", "-A") |
| + } |
| + write(f.Base) |
| + git(t, seed, "commit", "-q", "--allow-empty", "-m", "base") |
| + base = git(t, seed, "rev-parse", "HEAD") |
| + git(t, seed, "checkout", "-q", "-b", Branch) |
| + write(f.Candidate) |
| + git(t, seed, "commit", "-q", "--allow-empty", "-m", "candidate") |
| + candidate = git(t, seed, "rev-parse", "HEAD") |
| + git(t, seed, "checkout", "-q", "main") |
| + ch.forgeDir = filepath.Join(ch.Root, "forge.git") |
| + git(t, ch.Root, "clone", "-q", "--bare", seed, ch.forgeDir) |
| + return base, candidate |
| +} |
| + |
| +// Commit commits files over the task branch's tip, pushes it to the |
| +// forge and returns the new commit. |
| +func (ch *Chain) Commit(files map[string]string) string { |
| + t := ch.t |
| + t.Helper() |
| + seed := filepath.Join(ch.Root, "seed") |
| + git(t, seed, "checkout", "-q", Branch) |
| + for name, body := range files { |
| + if err := os.WriteFile(filepath.Join(seed, name), []byte(body), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + git(t, seed, "add", "-A") |
| + git(t, seed, "commit", "-q", "-m", "candidate again") |
| + sha := git(t, seed, "rev-parse", "HEAD") |
| + git(t, seed, "push", "-q", ch.forgeDir, Branch) |
| + git(t, seed, "checkout", "-q", "main") |
| + return sha |
| +} |
| + |
| +// Branch is the task's branch. |
| +const Branch = "equipo/tk1-change" |
| + |
| +// ModuleCache is the primary's module cache (its checks' own), which |
| +// the dependency bundle is read from. |
| +func (ch *Chain) ModuleCache() string { return filepath.Join(ch.Root, "p", "modules") } |
| + |
| +// startPrimary enrols the owner's primary runner and runs it in this |
| +// process until the test ends. |
| +func (ch *Chain) startPrimary() { |
| + t := ch.t |
| + root := filepath.Join(ch.Root, "p") |
| + dirs := map[string]string{} |
| + for _, d := range []string{"state", "work", "scratch", "modules", "bin", "config", "go", "sessions"} { |
| + dirs[d] = filepath.Join(root, d) |
| + if err := os.MkdirAll(dirs[d], 0o700); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + amadan := filepath.Join(dirs["bin"], "amadan") |
| + if err := os.WriteFile(amadan, []byte("#!/bin/sh\nexit 1\n"), 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + bindings := filepath.Join(dirs["config"], "bindings.json") |
| + if err := os.WriteFile(bindings, []byte("[]"), 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + cred := ch.Inst.EnrolRunner(t) |
| + ch.PrimaryID = cred.RunnerID |
| + if err := thintest.WriteRunnerCredential(dirs["state"], cred); err != nil { |
| + t.Fatal(err) |
| + } |
| + self, err := os.Executable() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg := runner.Config{Origin: ch.Inst.URL, InstanceID: ch.Inst.TeamID, StateDir: dirs["state"], AccountBindingsPath: bindings, |
| + AmadanCredentialPath: filepath.Join(dirs["config"], "amadan.json"), ClaudePath: filepath.Join(dirs["bin"], "claude"), |
| + CodexPath: filepath.Join(dirs["bin"], "codex"), CodexCodeModeHostPath: filepath.Join(dirs["bin"], "codex-host"), |
| + BwrapPath: LinuxBwrap, GoRoot: dirs["go"], ModuleCache: dirs["modules"], GoBinary: filepath.Join(dirs["go"], "bin", "go"), |
| + WorkspaceRoot: dirs["work"], ScratchRoot: dirs["scratch"], GitPath: "/usr/bin/git", AmadanPath: amadan, Executable: self} |
| + ctx, cancel := context.WithCancel(ch.ctx) |
| + connected := make(chan bool, 16) |
| + done := make(chan error, 1) |
| + opts := thin.Options{Version: "test", Logger: slog.New(slog.NewTextHandler(ch.CtlLog, nil)).With("side", "primary"), |
| + Forge: localForge{dir: ch.forgeDir}, NoMoveIn: true, NoCreate: true, MergeEvery: time.Hour, AccountsRoot: filepath.Join(root, "accounts"), |
| + Connected: func(up bool) { |
| + select { |
| + case connected <- up: |
| + default: |
| + } |
| + }} |
| + go func() { done <- thin.Run(ctx, cfg, opts) }() |
| + select { |
| + case up := <-connected: |
| + if !up { |
| + t.Fatal("the primary did not connect") |
| + } |
| + case err := <-done: |
| + t.Fatalf("the primary exited: %v", err) |
| + case <-time.After(30 * time.Second): |
| + t.Fatal("the primary did not connect in time") |
| + } |
| + ch.primary = func() { |
| + cancel() |
| + select { |
| + case <-done: |
| + case <-time.After(30 * time.Second): |
| + } |
| + } |
| + t.Cleanup(ch.primary) |
| +} |
| + |
| +// resolver answers the instance's host with its public test address. |
| +type resolver struct{} |
| + |
| +func (resolver) LookupNetIP(_ context.Context, network, host string) ([]netip.Addr, error) { |
| + if network == "ip" && strings.EqualFold(host, InstanceHost) { |
| + return []netip.Addr{netip.MustParseAddr(instanceAddr)}, nil |
| + } |
| + return nil, fmt.Errorf("lookup %s %s: no such host", network, host) |
| +} |
| + |
| +func spkiPin(c *x509.Certificate) string { |
| + sum := sha256.Sum256(c.RawSubjectPublicKeyInfo) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| + |
| +var serial big.Int |
| + |
| +func nextSerial() *big.Int { |
| + serial.Add(&serial, big.NewInt(1)) |
| + return new(big.Int).Set(&serial) |
| +} |
| + |
| +// newCA is a fresh P-256 CA. |
| +func newCA(t *testing.T, name string) (*ecdsa.PrivateKey, *x509.Certificate) { |
| + t.Helper() |
| + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tmpl := &x509.Certificate{SerialNumber: nextSerial(), Subject: pkix.Name{CommonName: name}, |
| + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(24 * time.Hour), |
| + BasicConstraintsValid: true, IsCA: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature} |
| + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c, _ := x509.ParseCertificate(der) |
| + return key, c |
| +} |
| + |
| +// issueServer is a server certificate for name under the CA. |
| +func issueServer(t *testing.T, caKey *ecdsa.PrivateKey, ca *x509.Certificate, name string) tls.Certificate { |
| + t.Helper() |
| + key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + der, err := x509.CreateCertificate(rand.Reader, &x509.Certificate{SerialNumber: nextSerial(), DNSNames: []string{name}, |
| + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(24 * time.Hour), ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}, |
| + ca, &key.PublicKey, caKey) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c, _ := x509.ParseCertificate(der) |
| + return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key, Leaf: c} |
| +} |
| + |
| +// selfSigned is a self-signed server certificate for ip (the |
| +// controller's: trusted by its pin only). |
| +func selfSigned(t *testing.T, name string, ip net.IP) tls.Certificate { |
| + t.Helper() |
| + key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + tmpl := &x509.Certificate{SerialNumber: nextSerial(), Subject: pkix.Name{CommonName: name}, IPAddresses: []net.IP{ip}, |
| + NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(24 * time.Hour), ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} |
| + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + c, _ := x509.ParseCertificate(der) |
| + return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key, Leaf: c} |
| +} |
| + |
| +// dumpLogs writes every log of the chain into the failed test's output. |
| +func (ch *Chain) dumpLogs() { |
| + t := ch.t |
| + t.Logf("controller, dispatcher and primary log:\n%s", tail(ch.CtlLog.String(), 200)) |
| + for i, p := range ch.Proxies { |
| + t.Logf("proxy %d decision log:\n%s", i, tail(p.Log.String(), 60)) |
| + } |
| + t.Logf("instance log:\n%s", tail(ch.Inst.Logs(), 120)) |
| + for _, q := range []string{"SELECT id, state, coalesce(placement,''), coalesce(runner_id,''), coalesce(reason,''), coalesce(checks,''), attempt, coalesce(log_tail,''), coalesce(output,'') FROM chat_steps", |
| + "SELECT attempt_id, step_id, state, coalesce(stop_reason,''), coalesce(runner_id,''), coalesce(vm_ref,'') FROM hosted_jobs ORDER BY admitted_at"} { |
| + rows, err := ch.Inst.DB.Writer().Query(q) |
| + if err != nil { |
| + t.Logf("%s: %v", q, err) |
| + continue |
| + } |
| + cols, _ := rows.Columns() |
| + for rows.Next() { |
| + vals := make([]any, len(cols)) |
| + ptrs := make([]any, len(cols)) |
| + for i := range vals { |
| + ptrs[i] = &vals[i] |
| + } |
| + _ = rows.Scan(ptrs...) |
| + t.Logf("row %v", vals) |
| + } |
| + rows.Close() |
| + } |
| + for _, vm := range ch.Prov.VMs() { |
| + status, body := vm.Run() |
| + t.Logf("VM %s (/run %d %s):\n%s", vm.Ref, status, body, tail(vm.Log(), 120)) |
| + } |
| +} |
| + |
| +func tail(s string, n int) string { |
| + lines := strings.Split(strings.TrimRight(s, "\n"), "\n") |
| + if len(lines) > n { |
| + lines = lines[len(lines)-n:] |
| + } |
| + return strings.Join(lines, "\n") |
| +} |
| + |
| +// Until polls done every 100 ms for at most d. |
| +func (ch *Chain) Until(d time.Duration, what string, done func() bool) { |
| + ch.t.Helper() |
| + for end := time.Now().Add(d); !done(); time.Sleep(100 * time.Millisecond) { |
| + if time.Now().After(end) { |
| + ch.t.Fatalf("%s: not within %v", what, d) |
| + } |
| + } |
| +} |
| + |
| +// Step is a checks step as the instance holds it. |
| +type Step struct { |
| + State, Placement, RunnerID, Reason, Checks string |
| + ChecksSandbox, BaseChecksSHA, Output string |
| + LogTail string |
| + Attempt int64 |
| +} |
| + |
| +// Step reads step id. |
| +func (ch *Chain) Step(id string) Step { |
| + ch.t.Helper() |
| + var rows []Step |
| + err := ch.Inst.DB.G.Raw("SELECT coalesce(state, '') AS state, coalesce(placement, '') AS placement, coalesce(runner_id, '') AS runner_id, "+ |
| + "coalesce(reason, '') AS reason, coalesce(checks, '') AS checks, coalesce(checks_sandbox, '') AS checks_sandbox, "+ |
| + "coalesce(base_checks_sha, '') AS base_checks_sha, coalesce(output, '') AS output, coalesce(log_tail, '') AS log_tail, attempt FROM chat_steps WHERE id = ?", id).Scan(&rows).Error |
| + if err != nil || len(rows) != 1 { |
| + ch.t.Fatalf("step %s: %d rows, %v", id, len(rows), err) |
| + } |
| + return rows[0] |
| +} |
| + |
| +// Jobs are step id's hosted jobs, in admission order. |
| +func (ch *Chain) Jobs(step string) []chat.HostedJob { |
| + ch.t.Helper() |
| + var rows []chat.HostedJob |
| + if err := ch.Inst.DB.G.Where("step_id = ?", step).Order("admitted_at, rowid").Find(&rows).Error; err != nil { |
| + ch.t.Fatal(err) |
| + } |
| + return rows |
| +} |
| + |
| +// Exec runs one statement on the instance's database. |
| +func (ch *Chain) Exec(q string, args ...any) { |
| + ch.t.Helper() |
| + if _, err := ch.Inst.DB.Writer().Exec(q, args...); err != nil { |
| + ch.t.Fatal(err) |
| + } |
| +} |
| + |
| +// EnableHosted turns "Run checks in a hosted VM" on for the project as |
| +// its owner, through the instance's setting. |
| +func (ch *Chain) EnableHosted() { |
| + t := ch.t |
| + t.Helper() |
| + form := url.Values{"project": {Project}, "hosted_checks": {"on"}, "revision": {"0"}} |
| + req, _ := http.NewRequest(http.MethodPost, ch.Inst.URL+"/settings/hosted", strings.NewReader(form.Encode())) |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + req.Header.Set("Origin", ch.Inst.URL) |
| + req.Header.Set("Sec-Fetch-Site", "same-origin") |
| + req.AddCookie(ch.Inst.Cookie()) |
| + client := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| + resp, err := client.Do(req) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + body, _ := io.ReadAll(resp.Body) |
| + resp.Body.Close() |
| + if resp.StatusCode >= 400 { |
| + t.Fatalf("saving the hosted setting: %d %s", resp.StatusCode, body) |
| + } |
| + var on bool |
| + if err := ch.Inst.DB.Writer().QueryRow("SELECT hosted_checks FROM chat_projects WHERE id = ?", Project).Scan(&on); err != nil || !on { |
| + t.Fatalf("the hosted setting is not on: %v %v", on, err) |
| + } |
| +} |
| + |
| +// AddChecks records task tk in review: its Engineering step done with |
| +// the change (Base to Candidate) pushed, and checks step id queued for |
| +// it, waiting for a runner as a step does when none fitted at its |
| +// creation; the next placement pass places it. |
| +func (ch *Chain) AddChecks(id, tk string) { |
| + now := ch.InstClock.Now() |
| + ch.Exec("INSERT INTO chat_tasks(id, project_id, title, stage, creator, revision, created_at, updated_at, branch, base_sha) VALUES (?, ?, 'Checks', ?, ?, 1, ?, ?, ?, ?)", |
| + tk, Project, wire.StageInReview, Owner, now, now, Branch, ch.Base) |
| + ch.Exec("INSERT INTO chat_steps(id, task_id, idx, person, state, attempt, specialist, base_sha, candidate_sha, pushed, terminated, revision, created_at, updated_at) VALUES (?, ?, 1, ?, ?, 1, ?, ?, ?, 1, 1, 1, ?, ?)", |
| + "eng-"+id, tk, Owner, wire.StepDone, wire.SpecialistEngineering, ch.Base, ch.Candidate, now, now) |
| + ch.Exec("INSERT INTO chat_steps(id, task_id, idx, person, state, attempt, specialist, base_sha, candidate_sha, revision, created_at, updated_at, placement, waiting_since) VALUES (?, ?, 2, ?, ?, 1, ?, ?, ?, 1, ?, ?, ?, ?)", |
| + id, tk, Owner, wire.StepQueued, wire.SpecialistChecks, ch.Base, ch.Candidate, now, now, wire.PlacementWaiting, now) |
| +} |
| + |
| +// AddProject records the project for the repository. |
| +func (ch *Chain) AddProject() { |
| + now := ch.InstClock.Now() |
| + ch.Exec("INSERT INTO chat_projects(id, repo, state, revision, created_at, updated_at) VALUES (?, ?, 'active', 1, ?, ?)", Project, Repo, now, now) |
| +} |
diff --git a/internal/hostedtest/chain_test.go b/internal/hostedtest/chain_test.go| new file mode 100644 |
| index 00000000..ff53dffd |
| --- /dev/null |
| +++ b/internal/hostedtest/chain_test.go |
| @@ -0,0 +1,400 @@ |
| +//go:build linux && hostedchain |
| + |
| +package hostedtest |
| + |
| +import ( |
| + "bytes" |
| + "encoding/json" |
| + "fmt" |
| + "io" |
| + "os" |
| + "path/filepath" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo/chat" |
| + "amadan.net/oficina/equipo/internal/equipo/hostedrun" |
| + "amadan.net/oficina/equipo/internal/hostedctl" |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlcert/ctlcerttest" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| + "amadan.net/oficina/equipo/internal/runner/containment" |
| + "amadan.net/oficina/equipo/internal/runner/depsbundle" |
| + "amadan.net/oficina/equipo/internal/thintest" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "amadan.net/rastrillo/rastrillo/budget" |
| + "golang.org/x/mod/module" |
| + "golang.org/x/mod/sumdb/dirhash" |
| + modzip "golang.org/x/mod/zip" |
| +) |
| + |
| +// TestMain builds equipo-runner for the VMs, and serves as the primary's |
| +// namespace helper. |
| +func TestMain(m *testing.M) { |
| + if len(os.Args) > 1 && os.Args[1] == "__namespace" { |
| + os.Exit(containment.NamespaceMain(os.Args[2:])) |
| + } |
| + dir, err := os.MkdirTemp("", "hcbin") |
| + if err != nil { |
| + fmt.Fprintln(os.Stderr, err) |
| + os.Exit(1) |
| + } |
| + if RunnerBinary, err = BuildRunner(dir); err != nil { |
| + fmt.Fprintln(os.Stderr, err) |
| + os.RemoveAll(dir) |
| + os.Exit(1) |
| + } |
| + code := budget.Main(m) |
| + os.RemoveAll(dir) |
| + thintest.RemoveSchema() |
| + os.Exit(code) |
| +} |
| + |
| +// The repository every test checks: a base gate (.equipo/gates.json and |
| +// make ci) that needs the one module the base pins, read from the staged |
| +// dependency cache, and that fails when fail.txt says so. |
| +const contract = `{"version":1,"files":["budgets.txt"]}` |
| + |
| +var dep = depsbundle.Module{Path: "example.com/m", Version: "v1.0.0"} |
| + |
| +// gate is make ci: the module staged read-only from the bundle, the |
| +// candidate's budget, then sleep.txt's seconds (a drill's window). |
| +const gate = "ci:\n" + |
| + "\t@test -f /opt/go-mod/example.com/m@v1.0.0/m.go && echo staged\n" + |
| + "\t@test \"$$(cat size.txt)\" -le \"$$(cat budgets.txt)\" || { echo over budget; exit 3; }\n" + |
| + "\t@sleep \"$$(cat sleep.txt)\"\n" + |
| + "\t@echo gate done\n" |
| + |
| +// moduleFixture puts dep in cache as the go command keeps it and returns |
| +// its go.sum lines. |
| +func moduleFixture(t *testing.T, cache string) string { |
| + t.Helper() |
| + files := map[string]string{"go.mod": "module example.com/m\n", "m.go": "package m\n"} |
| + src := t.TempDir() |
| + for name, body := range files { |
| + if err := os.WriteFile(filepath.Join(src, name), []byte(body), 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + esc, _ := module.EscapePath(dep.Path) |
| + at := filepath.Join(cache, "cache", "download", filepath.FromSlash(esc), "@v") |
| + if err := os.MkdirAll(at, 0o755); err != nil { |
| + t.Fatal(err) |
| + } |
| + var z bytes.Buffer |
| + if err := modzip.CreateFromDir(&z, module.Version{Path: dep.Path, Version: dep.Version}, src); err != nil { |
| + t.Fatal(err) |
| + } |
| + base := filepath.Join(at, dep.Version) |
| + for ext, data := range map[string][]byte{".zip": z.Bytes(), ".mod": []byte(files["go.mod"]), ".info": []byte(`{"Version":"` + dep.Version + `"}`)} { |
| + if err := os.WriteFile(base+ext, data, 0o644); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + zh, err := dirhash.HashZip(base+".zip", dirhash.Hash1) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + mh, err := dirhash.Hash1([]string{"go.mod"}, func(string) (io.ReadCloser, error) { return io.NopCloser(strings.NewReader(files["go.mod"])), nil }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return fmt.Sprintf("%s %s %s\n%s %s/go.mod %s\n", dep.Path, dep.Version, zh, dep.Path, dep.Version, mh) |
| +} |
| + |
| +// repo is the repository: the base with the gate and the pinned module, |
| +// and the candidate's changes over it. |
| +func repo(sum string, candidate map[string]string) Files { |
| + return Files{ |
| + Base: map[string]string{".equipo/gates.json": contract, "Makefile": gate, "size.txt": "1\n", "budgets.txt": "1\n", "sleep.txt": "0\n", |
| + "go.mod": "module example.com/app\n\ngo 1.26\n\nrequire example.com/m v1.0.0\n", "go.sum": sum}, |
| + Candidate: candidate, |
| + } |
| +} |
| + |
| +// start is a chain over repo with the module in the primary's cache, the |
| +// project added and its hosted setting on. |
| +func start(t *testing.T, candidate map[string]string) *Chain { |
| + t.Helper() |
| + cacheDir := t.TempDir() |
| + sum := moduleFixture(t, cacheDir) |
| + ch := New(t, repo(sum, candidate)) |
| + if err := os.CopyFS(ch.ModuleCache(), os.DirFS(cacheDir)); err != nil { |
| + t.Fatal(err) |
| + } |
| + ch.AddProject() |
| + ch.EnableHosted() |
| + return ch |
| +} |
| + |
| +// ended waits for step id's attempt to end and every one of its hosted |
| +// jobs to end with stop proof, and returns the step and its jobs. |
| +func (ch *Chain) ended(id string, d time.Duration) (Step, []chat.HostedJob) { |
| + ch.t.Helper() |
| + ch.Until(d, "the step ended and its VMs stopped with proof", func() bool { |
| + if !wire.StepTerminal(ch.Step(id).State) { |
| + return false |
| + } |
| + for _, j := range ch.Jobs(id) { |
| + if j.Live() { |
| + return false |
| + } |
| + } |
| + return true |
| + }) |
| + return ch.Step(id), ch.Jobs(id) |
| +} |
| + |
| +// proven fails unless j ended with the controller's stop proof and its |
| +// usage settled. |
| +func proven(t *testing.T, j chat.HostedJob) { |
| + t.Helper() |
| + var p chat.HostedEndProof |
| + if j.StopProofJSON == "" || json.Unmarshal([]byte(j.StopProofJSON), &p) != nil || j.SettledAt == nil { |
| + t.Fatalf("job %s ended %s without proof or settlement: proof %q settled %v", j.AttemptID, j.State, j.StopProofJSON, j.SettledAt) |
| + } |
| +} |
| + |
| +// TestChainHostedCheckPasses: with the setting on, a checks step waits as |
| +// hosted work (waiting_hosted), its VM enrols through a proxy, the |
| +// primary sends the pack and the dependency bundle, the base's gate |
| +// passes in bubblewrap with the staged module, the result is certified |
| +// (sandboxed, base checks trusted), the VM is stopped with proof and the |
| +// usage settled. |
| +func TestChainHostedCheckPasses(t *testing.T) { |
| + ch := start(t, map[string]string{"NEWS": "news\n"}) |
| + ch.AddChecks("s1", "tk1") |
| + ch.Until(30*time.Second, "the step waits as hosted work", func() bool { |
| + s := ch.Step("s1") |
| + return s.Placement == wire.PlacementHosted && len(ch.Jobs("s1")) == 1 |
| + }) |
| + s, jobs := ch.ended("s1", 3*time.Minute) |
| + if s.State != wire.StepDone || s.Checks != wire.ChecksPassed || s.ChecksSandbox != wire.SandboxBubblewrap || s.BaseChecksSHA != ch.Base { |
| + t.Fatalf("step %+v", s) |
| + } |
| + if !strings.Contains(s.Output, "staged") || !strings.Contains(s.Output, "gate done") { |
| + t.Fatalf("the gate did not run over the staged module: %q", s.Output) |
| + } |
| + if len(jobs) != 1 || jobs[0].State != chat.HostedJobEnded { |
| + t.Fatalf("jobs %+v", jobs) |
| + } |
| + proven(t, jobs[0]) |
| +} |
| + |
| +// TestChainFailingCheck: a candidate over its budget fails the base's |
| +// gate in bubblewrap; the failure is certified (sandboxed, the base's |
| +// gate), the VM stopped with proof and the usage settled. |
| +func TestChainFailingCheck(t *testing.T) { |
| + ch := start(t, map[string]string{"size.txt": "2\n"}) |
| + ch.AddChecks("s1", "tk1") |
| + s, jobs := ch.ended("s1", 3*time.Minute) |
| + if s.State != wire.StepDone || s.Checks != wire.ChecksFailed || s.ChecksSandbox != wire.SandboxBubblewrap || s.BaseChecksSHA != "" { |
| + t.Fatalf("step %+v", s) |
| + } |
| + if !strings.Contains(s.Output, "over budget") { |
| + t.Fatalf("the base gate's failure is not in the output: %q", s.Output) |
| + } |
| + if len(jobs) != 1 || jobs[0].State != chat.HostedJobEnded { |
| + t.Fatalf("jobs %+v", jobs) |
| + } |
| + proven(t, jobs[0]) |
| +} |
| + |
| +// TestChainNewModule: a candidate that pins a module the base does not |
| +// is never staged or run: the step ends cannot_run deps_new_module, and |
| +// the person sees needs_network. |
| +func TestChainNewModule(t *testing.T) { |
| + sum := "example.com/n v1.0.0 h1:" + strings.Repeat("A", 43) + "=\nexample.com/n v1.0.0/go.mod h1:" + strings.Repeat("B", 43) + "=\n" |
| + ch := start(t, nil) |
| + // The candidate is made after start: it keeps the base's go.sum lines |
| + // and adds the new module's. |
| + base, err := os.ReadFile(filepath.Join(ch.Root, "seed", "go.sum")) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + ch.Candidate = ch.Commit(map[string]string{"go.mod": "module example.com/app\n\ngo 1.26\n\nrequire (\n\texample.com/m v1.0.0\n\texample.com/n v1.0.0\n)\n", |
| + "go.sum": string(base) + sum}) |
| + ch.AddChecks("s1", "tk1") |
| + s, jobs := ch.ended("s1", 3*time.Minute) |
| + if s.State != wire.StepDone || s.Checks != wire.ChecksCannotRun || s.Reason != wire.ReasonDepsNewModule { |
| + t.Fatalf("step %+v", s) |
| + } |
| + task, err := thintest.NewClient(ch.Inst.URL, ch.Inst.DeviceToken(t)).Task(t.Context(), "tk1") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if task.ChecksReason != "needs_network" { |
| + t.Fatalf("the person sees %q, not needs_network", task.ChecksReason) |
| + } |
| + if len(jobs) != 1 || jobs[0].State != chat.HostedJobEnded { |
| + t.Fatalf("jobs %+v", jobs) |
| + } |
| + proven(t, jobs[0]) |
| +} |
| + |
| +// slow is a candidate whose gate sleeps long enough for a drill. |
| +var slow = map[string]string{"NEWS": "news\n", "sleep.txt": "8\n"} |
| + |
| +// midStep waits until the step's checks run in its first VM (a |
| +// namespace recorded there) and returns that VM. |
| +func (ch *Chain) midStep(id string) *VM { |
| + ch.t.Helper() |
| + var vm *VM |
| + ch.Until(2*time.Minute, "the checks running in the VM", func() bool { |
| + vms := ch.Prov.VMs() |
| + if len(vms) == 0 || ch.Step(id).State != wire.StepRunning { |
| + return false |
| + } |
| + vm = vms[0] |
| + return vm.Gating() |
| + }) |
| + return vm |
| +} |
| + |
| +// passed fails unless s passed, certified. |
| +func passed(t *testing.T, ch *Chain, s Step) { |
| + t.Helper() |
| + if s.State != wire.StepDone || s.Checks != wire.ChecksPassed || s.ChecksSandbox != wire.SandboxBubblewrap || s.BaseChecksSHA != ch.Base { |
| + t.Fatalf("step %+v", s) |
| + } |
| +} |
| + |
| +// TestChainKillProxyMidStep: the proxy the VM's link runs through (the |
| +// first in its bootstrap, which the runner tries first) dies mid-step; |
| +// the runner fails over to the other one, and the step's result arrives |
| +// there, certified, from the same VM. |
| +func TestChainKillProxyMidStep(t *testing.T) { |
| + ch := start(t, slow) |
| + ch.AddChecks("s1", "tk1") |
| + ch.midStep("s1") |
| + if strings.Contains(ch.Proxies[1].Log.String(), `"destination":"instance.example.test:443"`) { |
| + t.Fatalf("the VM reached the instance through the second proxy first:\n%s", ch.Proxies[1].Log.String()) |
| + } |
| + ch.Proxies[0].Kill() |
| + // A tunnel's line is written when it closes: the link's, now. |
| + if !strings.Contains(ch.Proxies[0].Log.String(), `"status":101`) { |
| + t.Fatalf("the killed proxy carried no link:\n%s", ch.Proxies[0].Log.String()) |
| + } |
| + s, jobs := ch.ended("s1", 3*time.Minute) |
| + passed(t, ch, s) |
| + if len(jobs) != 1 || jobs[0].State != chat.HostedJobEnded { |
| + t.Fatalf("jobs %+v", jobs) |
| + } |
| + proven(t, jobs[0]) |
| + // The VM stopped, its link through the second proxy closed. |
| + ch.Until(30*time.Second, "the link through the other proxy", func() bool { return strings.Contains(ch.Proxies[1].Log.String(), `"status":101`) }) |
| +} |
| + |
| +// TestChainKillControllerMidStep: the controller dies mid-step. With no |
| +// fresh feed the proxies close the VM's open sockets at the feed's |
| +// expiry and let nothing through; the step fails hosted_unavailable, |
| +// and once the controller is back the VM is stopped with proof and the |
| +// step retried once, on a new VM, where it passes. |
| +func TestChainKillControllerMidStep(t *testing.T) { |
| + ch := start(t, slow) |
| + ch.AddChecks("s1", "tk1") |
| + ch.midStep("s1") |
| + ch.KillController() |
| + // The feed's lifetime passes, for the proxies and the instance alike. |
| + ch.ProxyClock.Forward(hostedrun.FeedLost + time.Second) |
| + ch.InstClock.Forward(hostedrun.FeedLost + time.Second) |
| + ch.Until(30*time.Second, "the proxies closing the VM's sockets", func() bool { |
| + for _, p := range ch.Proxies { |
| + if strings.Contains(p.Log.String(), "stale_feed") { |
| + return true |
| + } |
| + } |
| + return false |
| + }) |
| + ch.Until(30*time.Second, "the job failing hosted_unavailable", func() bool { |
| + j := ch.Jobs("s1")[0] |
| + return j.State == chat.HostedJobStopping && j.StopReason == wire.ReasonHostedUnavailable |
| + }) |
| + // No proof without the controller: the step waits for it. |
| + time.Sleep(2 * time.Second) |
| + if jobs := ch.Jobs("s1"); len(jobs) != 1 || jobs[0].State != chat.HostedJobStopping { |
| + t.Fatalf("the job ended, or another began, with the controller down: %+v", jobs) |
| + } |
| + ch.StartController() |
| + s, jobs := ch.ended("s1", 4*time.Minute) |
| + passed(t, ch, s) |
| + if len(jobs) != 2 || jobs[0].State != chat.HostedJobFailed || jobs[0].StopReason != wire.ReasonHostedUnavailable || jobs[1].State != chat.HostedJobEnded || jobs[1].RetryOf != jobs[0].AttemptID { |
| + t.Fatalf("jobs %+v", jobs) |
| + } |
| + proven(t, jobs[0]) |
| + proven(t, jobs[1]) |
| +} |
| + |
| +// TestChainStopVMMidStep: the provider stops the VM mid-step; the |
| +// controller's admission record shows it gone, the job ends with proof |
| +// and the step is retried once on a new VM, where it passes. |
| +func TestChainStopVMMidStep(t *testing.T) { |
| + ch := start(t, slow) |
| + ch.AddChecks("s1", "tk1") |
| + vm := ch.midStep("s1") |
| + if err := ch.Prov.Stop(t.Context(), vm.Ref, "provider stopped it"); err != nil { |
| + t.Fatal(err) |
| + } |
| + s, jobs := ch.ended("s1", 2*time.Minute) |
| + passed(t, ch, s) |
| + if len(jobs) != 2 || jobs[0].State != chat.HostedJobFailed || jobs[0].StopReason != wire.ReasonHostedVMLost || jobs[1].State != chat.HostedJobEnded || jobs[1].RetryOf != jobs[0].AttemptID { |
| + t.Fatalf("jobs %+v", jobs) |
| + } |
| + proven(t, jobs[0]) |
| + proven(t, jobs[1]) |
| +} |
| + |
| +// TestChainOrphanVM: a VM no launch asked for runs on the provider; past |
| +// the orphan grace the controller's reaper stops it and alerts. |
| +func TestChainOrphanVM(t *testing.T) { |
| + ch := start(t, nil) |
| + ref := ch.Fake.Plant(isolatedjob.LaunchSpec{AttemptID: "orphan", Image: Image, Size: isolatedjob.SizeLarge}) |
| + ch.Until(10*time.Second, "the reaper seeing the orphan", func() bool { |
| + r, ok := ch.Controller().LastReap() |
| + return ok && r.Report.OrphansSeen == 1 |
| + }) |
| + if live := ch.Fake.LiveByAttempt()["orphan"]; live != 1 { |
| + t.Fatalf("the orphan was stopped within its grace: %d live", live) |
| + } |
| + ch.CtlClock.Forward(hostedctl.OrphanGrace + time.Minute) |
| + ch.Until(30*time.Second, "the orphan stopped", func() bool { return ch.Fake.LiveByAttempt()["orphan"] == 0 }) |
| + if !slices.Contains(ch.Fake.StopsIssued(), ref) { |
| + t.Fatalf("the orphan %s ended without a stop: %v", ref, ch.Fake.StopsIssued()) |
| + } |
| + ch.Until(10*time.Second, "the orphan alert", func() bool { return strings.Contains(ch.CtlLog.String(), "alert "+hostedctl.AlertOrphanStopped) }) |
| +} |
| + |
| +// TestChainCertWithdrawnMidStep: the image's certificate is withdrawn |
| +// while its VM runs checks; the controller's next admission record says |
| +// so, and the VM's result is not certified: not kept, its job stopped |
| +// with proof, and the step does not pass. |
| +func TestChainCertWithdrawnMidStep(t *testing.T) { |
| + ch := start(t, slow) |
| + ch.AddChecks("s1", "tk1") |
| + ch.midStep("s1") |
| + if _, err := ch.Certs.Replace(ctlcerttest.Keys(), nil); err != nil { |
| + t.Fatal(err) |
| + } |
| + ch.Until(4*time.Minute, "the first job ended", func() bool { return !ch.Jobs("s1")[0].Live() }) |
| + jobs := ch.Jobs("s1") |
| + if jobs[0].State != chat.HostedJobFailed || jobs[0].StopReason != "uncertified" { |
| + t.Fatalf("jobs %+v", jobs) |
| + } |
| + proven(t, jobs[0]) |
| + if s := ch.Step("s1"); s.Checks == wire.ChecksPassed || s.ChecksSandbox != "" || s.BaseChecksSHA != "" { |
| + t.Fatalf("an uncertified result was kept: %+v", s) |
| + } |
| + // Placed again once: with no certificate the controller launches |
| + // nothing for it, and once its launch window has passed (the |
| + // instance's clock moved on) the step ends not run, hosted_unavailable. |
| + ch.Until(time.Minute, "the step placed again", func() bool { return len(ch.Jobs("s1")) == 2 }) |
| + ch.InstClock.Forward(chat.HostedLaunchWindow + chat.HostedNeverLaunchedAfter + time.Minute) |
| + s, jobs := ch.ended("s1", 2*time.Minute) |
| + if s.Checks != wire.ChecksCannotRun || s.Reason != wire.ReasonHostedUnavailable || s.ChecksSandbox != "" || s.BaseChecksSHA != "" { |
| + t.Fatalf("step %+v", s) |
| + } |
| + if len(jobs) != 2 || jobs[1].State != chat.HostedJobFailed || len(ch.Prov.VMs()) != 1 { |
| + t.Fatalf("jobs %+v, %d VMs", jobs, len(ch.Prov.VMs())) |
| + } |
| +} |
diff --git a/internal/hostedtest/doc.go b/internal/hostedtest/doc.go| new file mode 100644 |
| index 00000000..cc4dfb7c |
| --- /dev/null |
| +++ b/internal/hostedtest/doc.go |
| @@ -0,0 +1,8 @@ |
| +// Package hostedtest runs the whole hosted checks chain on one machine |
| +// (hosted runners slice 2, Task 30): an Equipo instance, the hosted |
| +// controller over the in-memory provider fake, two egress proxies, a |
| +// person's primary runner, and each VM's root init and hosted runner, |
| +// whose checks run in real bubblewrap. Everything is on 127.0.0.1 and no |
| +// AWS call is made. Its files build only with the hostedchain tag |
| +// (make hosted-chain-test). |
| +package hostedtest |
diff --git a/internal/thintest/instance.go b/internal/thintest/instance.go| index 02e7d601..5b824a09 100644 |
| --- a/internal/thintest/instance.go |
| +++ b/internal/thintest/instance.go |
| @@ -8,6 +8,7 @@ import ( |
| "context" |
| "crypto/ed25519" |
| "crypto/rand" |
| + "crypto/tls" |
| "encoding/base64" |
| "encoding/json" |
| "errors" |
| @@ -25,7 +26,9 @@ import ( |
| "amadan.net/oficina/equipo/internal/equipo" |
| "amadan.net/oficina/equipo/internal/equipo/assist" |
| + "amadan.net/oficina/equipo/internal/equipo/hostedrun" |
| "amadan.net/oficina/equipo/internal/equipo/personapi" |
| + "amadan.net/oficina/equipo/internal/equipo/team" |
| "amadan.net/oficina/equipo/internal/runnerproto" |
| "amadan.net/rastrillo/rastrillo/db" |
| "amadan.net/rastrillo/rastrillo/dbtest" |
| @@ -63,6 +66,15 @@ type Instance struct { |
| // OficinaConnect and OficinaClientID are |
| // EQUIPO_OFICINA_CONNECT_ORIGIN and EQUIPO_OFICINA_CONNECT_CLIENT_ID. |
| OficinaConnect, OficinaClientID string |
| + // HostedRunners is EQUIPO_HOSTED_RUNNERS and Hosted the controller |
| + // connection (hosted runners slice 2), both from the next start. The |
| + // dispatcher is built only with EQUIPO_HOSTED_RUNNERS=1 in the |
| + // environment; this harness never runs it (the caller does). |
| + HostedRunners bool |
| + Hosted hostedrun.Config |
| + // Clock, when set, is the instance's runner clock and its chat |
| + // store's, from the next start. |
| + Clock team.Clock |
| addr string |
| server *http.Server |
| @@ -130,8 +142,11 @@ func (i *Instance) serve(t testing.TB, l net.Listener) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - s := equipo.NewStore(d) |
| - router, err := equipo.RouterWithStore(d, equipo.Config{Origin: i.URL, InstanceKey: "thin-v1-test", AllowLoggedMail: true, ExecutionEnabled: !i.NoExecution, MacEngineering: i.MacEngineering, Owners: []string{Owner}, TestPeople: []string{".invalid"}, AssistantHosts: i.AssistantHosts, OficinaConnectOrigin: i.OficinaConnect, OficinaConnectClientID: i.OficinaClientID}, mail.Logged(i.logger), i.logger, s) |
| + s := equipo.NewStore(d, equipo.WithRunnerClock(i.Clock)) |
| + if i.Clock != nil { |
| + s.Chat().SetClock(i.Clock.Now) |
| + } |
| + router, err := equipo.RouterWithStore(d, equipo.Config{Origin: i.URL, InstanceKey: "thin-v1-test", AllowLoggedMail: true, ExecutionEnabled: !i.NoExecution, MacEngineering: i.MacEngineering, Owners: []string{Owner}, TestPeople: []string{".invalid"}, AssistantHosts: i.AssistantHosts, OficinaConnectOrigin: i.OficinaConnect, OficinaConnectClientID: i.OficinaClientID, HostedRunners: i.HostedRunners, Hosted: i.Hosted}, mail.Logged(i.logger), i.logger, s) |
| if err != nil { |
| t.Fatal(err) |
| } |
| @@ -187,6 +202,33 @@ func (i *Instance) Restart(t testing.TB) { |
| i.serve(t, l) |
| } |
| +// ServeTLS serves the instance, as it runs now and after each Restart, |
| +// over TLS with cert on a second listener on 127.0.0.1, until the test |
| +// ends, and returns its address. A hosted VM's proxy reaches it there. |
| +func (i *Instance) ServeTLS(t testing.TB, cert tls.Certificate) string { |
| + t.Helper() |
| + l, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + srv := &http.Server{ReadHeaderTimeout: 5 * time.Second, TLSConfig: &tls.Config{Certificates: []tls.Certificate{cert}, NextProtos: []string{"http/1.1"}}, |
| + Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + s := i.server |
| + if s == nil { |
| + http.Error(w, "stopped", http.StatusServiceUnavailable) |
| + return |
| + } |
| + s.Handler.ServeHTTP(w, r) |
| + })} |
| + go srv.ServeTLS(l, "", "") |
| + t.Cleanup(func() { |
| + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) |
| + defer cancel() |
| + _ = srv.Shutdown(ctx) |
| + }) |
| + return l.Addr().String() |
| +} |
| + |
| // DeviceToken signs a device in with the person API device flow: begin, |
| // approval by the owner's session, exchange. It returns the bearer. |
| func (i *Instance) DeviceToken(t testing.TB) string { |
diff --git a/internal/vminit/chain.go b/internal/vminit/chain.go| new file mode 100644 |
| index 00000000..30d92927 |
| --- /dev/null |
| +++ b/internal/vminit/chain.go |
| @@ -0,0 +1,98 @@ |
| +//go:build linux && hostedchain |
| + |
| +package vminit |
| + |
| +import ( |
| + "io/fs" |
| + "net/http" |
| + "os" |
| + "runtime" |
| + "syscall" |
| + |
| + "golang.org/x/sys/unix" |
| +) |
| + |
| +// ChainVM is what the whole-chain test (internal/hostedtest, build tag |
| +// hostedchain) needs of a VM's root init in its own, unprivileged |
| +// process: the hook server, and whether its runner still runs. |
| +type ChainVM struct { |
| + http.Handler |
| + h *hooks |
| +} |
| + |
| +// RunnerPID is the runner's pid while it runs, 0 before and after. |
| +func (v *ChainVM) RunnerPID() int { return v.h.runnerPID() } |
| + |
| +// ChainHooks is the hook server for a test that runs the whole hosted |
| +// chain in one process and cannot be root. Everything /run and |
| +// /terminate decide is vm-init's own code; only the privileged actions |
| +// are the calling user's: the runner account is the calling user (home |
| +// home), ownership is not changed, every directory on the results' path |
| +// is taken as root's (with its real type and mode), and the runner starts |
| +// as the calling user in its own process group, with no_new_privs, the |
| +// exact environment /run gives it, and its output in logFile. Only a |
| +// hostedchain build has it. |
| +func ChainHooks(cfg Config, home string, logFile *os.File, logf func(string, ...any)) (*ChainVM, error) { |
| + if err := cfg.check(); err != nil { |
| + return nil, err |
| + } |
| + self, err := os.Executable() |
| + if err != nil { |
| + return nil, err |
| + } |
| + h := newHooks(cfg, system{ |
| + lookup: func(string) (account, error) { return account{UID: os.Getuid(), GID: os.Getgid(), Home: home}, nil }, |
| + chown: func(string, int, int) error { return nil }, |
| + owner: func(path string) (int, int, fs.FileMode, error) { |
| + _, _, mode, err := lstatOwner(path) |
| + return 0, 0, mode, err |
| + }, |
| + start: func(s launchSpec) (int, <-chan struct{}, error) { |
| + // The calling user cannot change its credentials. |
| + s.Sys.Credential = nil |
| + return chainFork(s, logFile) |
| + }, |
| + signal: func(pid int, sig syscall.Signal) error { return syscall.Kill(-pid, sig) }, |
| + net: hostNet{}, |
| + self: self, |
| + resolvConf: os.DevNull, |
| + resolvers: cfg.Resolvers, |
| + logf: logf, |
| + }) |
| + return &ChainVM{Handler: h, h: h}, nil |
| +} |
| + |
| +// chainFork is forkRunner with the output in logFile, waiting for its |
| +// own child only (a test process has other children than the runner). |
| +func chainFork(s launchSpec, logFile *os.File) (int, <-chan struct{}, error) { |
| + null, err := os.Open(os.DevNull) |
| + if err != nil { |
| + return 0, nil, err |
| + } |
| + defer null.Close() |
| + attr := &os.ProcAttr{Dir: s.Dir, Env: s.Env, Files: []*os.File{null, logFile, logFile}, Sys: s.Sys} |
| + type result struct { |
| + p *os.Process |
| + err error |
| + } |
| + done := make(chan result, 1) |
| + go func() { |
| + runtime.LockOSThread() |
| + if err := unix.Prctl(unix.PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0); err != nil { |
| + done <- result{err: err} |
| + return |
| + } |
| + p, err := os.StartProcess(s.Path, s.Args, attr) |
| + done <- result{p, err} |
| + }() |
| + res := <-done |
| + if res.err != nil { |
| + return 0, nil, res.err |
| + } |
| + exited := make(chan struct{}) |
| + go func() { |
| + _, _ = res.p.Wait() |
| + close(exited) |
| + }() |
| + return res.p.Pid, exited, nil |
| +} |