runner: hosted transport through the proxy, bootstrap and enrolment
internal/runner/hosted reads and deletes vm-init's bootstrap, redeems the proxy code (retrying a refused code for up to 3 minutes), enrols with the instance and gives the runner an HTTP client that only goes through the proxies, pinned to the intercept CA at both TLS layers. thin.Link gains TokenSource and HTTPClient; equipo-runner gains hosted-run and hosted-certify, which refuse as not yet wired after Start. The proxy now sends its CA after each leaf so a VM holding only the pin can verify it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
21 files changed,
+1,721
−65
.rastrillo/budgets.txt+1 −1cmd/equipo-runner/hosted.go+58 −0cmd/equipo-runner/hosted_test.go+94 −0cmd/equipo-runner/main.go+5 −0docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md+64 −0internal/hostedproxy/e2e_test.go+1 −1internal/hostedproxy/origin.go+7 −3internal/hostedproxy/proxytest/harness.go+31 −40internal/hostedwire/hosted.go+33 −0internal/runner/hosted/bootstrap.go+187 −0internal/runner/hosted/enrol.go+134 −0internal/runner/hosted/export_test.go+14 −0internal/runner/hosted/hosted_test.go+558 −0internal/runner/hosted/redeem.go+190 −0internal/runner/hosted/transport.go+210 −0internal/runner/thin/link.go+12 −3internal/runner/thin/link_hooks_test.go+101 −0internal/runnerproto/types.go+10 −0internal/vminit/hooks.go+1 −10internal/vminit/init.go+9 −6internal/vminit/init_test.go+1 −1
diff --git a/.rastrillo/budgets.txt b/.rastrillo/budgets.txt| index 0dffab14..76ba2580 100644 |
| --- a/.rastrillo/budgets.txt |
| +++ b/.rastrillo/budgets.txt |
| @@ -39,7 +39,7 @@ time internal/runner/provider 15s Plan 3 CI repair measured 10.346s for the full |
| perf GET /releases/* skip Verified runner release file downloads, not browser GET screens. |
| perf GET /install.sh skip Mac runners: the one-line bootstrap a terminal pipes to sh, not a browser screen. |
| time internal/runner/containment 15s Plan 3 loaded CI measured 10.817s; |
| -size internal/runner/thin 35822 35352 Protocols 31-35, merge credential, publication guards, kept work, scans, 36 lookups; Mac pin, Engineering, asks, F probes, D1, P2, held reports; 38 Design step, renderer; hosted slice 2 Task 11 moved the base-gate checks to checkrun (source down) and pinned the primary and Mac behaviour with tests (test up), and its round 1 fixes added the worker step-engine wiring test; 35822/35352. |
| +size internal/runner/thin 35831 35453 Protocols 31-35, merge credential, publication guards, kept work, scans, 36 lookups; Mac pin, Engineering, asks, F probes, D1, P2, held reports; 38 Design step, renderer; hosted slice 2 Task 11 moved the base-gate checks to checkrun (source down) and pinned the primary and Mac behaviour with tests (test up), and its round 1 fixes added the worker step-engine wiring test; Task 12 added Link.TokenSource and Link.HTTPClient (a hosted runner's bearer is read at each dial and its dial goes through the proxy) and their two tests; 35831/35453. |
| time internal/thintest 240s Thin contract and page tests, the Assistant's and the models' included, share one harness. Measured 202s on a shared 16 CPU box (2026-11-13); CI runs two lanes. |
| time internal/runner/mac 45s Real processes killed and proven gone: groups, sessions, the runner-user sweep, turns, restarts; probes end to end. Measured 29.3s locally. |
| time internal/runner/thin 45s Thin v1 slice 4 review: real git repositories for the merge and squash checks, a stalled fetch, and a 16 MiB candidate streamed through the review diff and the checks pack (about 5s). |
diff --git a/cmd/equipo-runner/hosted.go b/cmd/equipo-runner/hosted.go| new file mode 100644 |
| index 00000000..9259c02c |
| --- /dev/null |
| +++ b/cmd/equipo-runner/hosted.go |
| @@ -0,0 +1,58 @@ |
| +package main |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "log/slog" |
| + "path/filepath" |
| + |
| + "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/runner/hosted" |
| +) |
| + |
| +// startHosted is hosted.Start; tests replace it. |
| +var startHosted = hosted.Start |
| + |
| +// errNotWired is a hosted subcommand whose work has not arrived yet: the |
| +// checks worker loop (Task 17) and the certification probes (Task 13). |
| +var errNotWired = errors.New("equipo-runner: started, but this hosted subcommand is not yet wired") |
| + |
| +// hostedMain runs hosted-run or hosted-certify as vm-init starts it: the |
| +// environment names the bootstrap file (in the state directory) and the |
| +// results directory. It reads and deletes the bootstrap, checks that its |
| +// purpose is the subcommand's, and runs hosted.Start. What follows Start |
| +// is not built yet, so it then refuses. |
| +func hostedMain(ctx context.Context, sub string, errorOutput io.Writer, getenv func(string) string) int { |
| + logger := slog.New(slog.NewTextHandler(errorOutput, nil)) |
| + fail := func(code, variable string, err error) int { |
| + logger.Error("hosted runner", "subcommand", sub, "err", err) |
| + _, _ = fmt.Fprintf(errorOutput, equipo.CopyRunnerDiagnostic, code, variable) |
| + return 1 |
| + } |
| + path, results := getenv(hostedwire.EnvBootstrap), getenv(hostedwire.EnvResults) |
| + if !filepath.IsAbs(path) { |
| + return fail("runner.hosted.bootstrap", hostedwire.EnvBootstrap, errors.New("not an absolute path")) |
| + } |
| + if !filepath.IsAbs(results) { |
| + return fail("runner.hosted.results", hostedwire.EnvResults, errors.New("not an absolute path")) |
| + } |
| + b, vm, err := hosted.ReadBootstrap(path) |
| + if err != nil { |
| + return fail("runner.hosted.bootstrap", hostedwire.EnvBootstrap, err) |
| + } |
| + want := hostedwire.PurposeChecks |
| + if sub == hostedwire.SubcommandCertify { |
| + want = hostedwire.PurposeCertification |
| + } |
| + if b.Purpose != want { |
| + return fail("runner.hosted.purpose", hostedwire.EnvBootstrap, fmt.Errorf("a %s bootstrap for %s", b.Purpose, sub)) |
| + } |
| + if _, err := startHosted(ctx, b, vm, filepath.Dir(path)); err != nil { |
| + return fail("runner.hosted.start", hostedwire.EnvBootstrap, err) |
| + } |
| + logger.Info("hosted runner started", "subcommand", sub, "launch", b.LaunchID, "vm", string(vm)) |
| + return fail("runner.hosted.not_wired", "-", errNotWired) |
| +} |
diff --git a/cmd/equipo-runner/hosted_test.go b/cmd/equipo-runner/hosted_test.go| new file mode 100644 |
| index 00000000..646106b9 |
| --- /dev/null |
| +++ b/cmd/equipo-runner/hosted_test.go |
| @@ -0,0 +1,94 @@ |
| +package main |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "net/netip" |
| + "os" |
| + "path/filepath" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| + "amadan.net/oficina/equipo/internal/runner/hosted" |
| +) |
| + |
| +// hostedBootstrap writes a bootstrap file for purpose into a new state |
| +// directory and returns its path. |
| +func hostedBootstrap(t *testing.T, purpose string) string { |
| + t.Helper() |
| + code := "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIA" |
| + b := hostedwire.BootstrapV2{Version: hostedwire.BootstrapV2Version, Purpose: purpose, LaunchID: "l-1", AttemptID: "a-1", |
| + InstanceCode: code, ProxyCode: code, Proxies: []netip.AddrPort{netip.MustParseAddrPort("127.0.0.1:8443")}, |
| + ProxyBoot: []netip.AddrPort{netip.MustParseAddrPort("127.0.0.1:8444")}, ProxyCAPin: strings.Repeat("ab", 32), |
| + Services: []hostedwire.Service{{Host: "instance.example.test", Port: 443, Class: hostedwire.ServiceInstance}}} |
| + if purpose == hostedwire.PurposeCertification { |
| + b.InstanceCode = "" |
| + } |
| + raw, _ := json.Marshal(hostedwire.RunnerBootstrap{VMRef: "vm-1", Bootstrap: b}) |
| + path := filepath.Join(t.TempDir(), hostedwire.BootstrapFile) |
| + if err := os.WriteFile(path, raw, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + return path |
| +} |
| + |
| +// The hosted subcommands read vm-init's environment and bootstrap and |
| +// run Start; until their work arrives (Tasks 13 and 17) they then refuse |
| +// with "not yet wired", never a silent success. |
| +func TestHostedSubcommandsNotYetWired(t *testing.T) { |
| + defer func(f func(context.Context, hostedwire.BootstrapV2, isolatedjob.Ref, string) (*hosted.Session, error)) { |
| + startHosted = f |
| + }(startHosted) |
| + for sub, purpose := range map[string]string{hostedwire.SubcommandChecks: hostedwire.PurposeChecks, |
| + hostedwire.SubcommandCertify: hostedwire.PurposeCertification} { |
| + path := hostedBootstrap(t, purpose) |
| + env := map[string]string{hostedwire.EnvBootstrap: path, hostedwire.EnvResults: filepath.Join(t.TempDir(), "results")} |
| + var started []string |
| + startHosted = func(_ context.Context, b hostedwire.BootstrapV2, vm isolatedjob.Ref, state string) (*hosted.Session, error) { |
| + started = append(started, b.Purpose+" "+string(vm)+" "+state) |
| + return &hosted.Session{}, nil |
| + } |
| + var out, errOut bytes.Buffer |
| + code := run(context.Background(), []string{sub}, strings.NewReader(""), &out, &errOut, func(k string) string { return env[k] }) |
| + want := purpose + " vm-1 " + filepath.Dir(path) |
| + if code != 1 || len(started) != 1 || started[0] != want || !strings.Contains(errOut.String(), "runner.hosted.not_wired") { |
| + t.Errorf("%s: exit %d, started %q (want %q), stderr %q", sub, code, started, want, errOut.String()) |
| + } |
| + if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) { |
| + t.Errorf("%s: the bootstrap file was left behind", sub) |
| + } |
| + } |
| + // The other purpose's bootstrap, a failed Start and a missing |
| + // environment are refused for what they are, and Start runs only for |
| + // the right purpose. |
| + calls := 0 |
| + startHosted = func(context.Context, hostedwire.BootstrapV2, isolatedjob.Ref, string) (*hosted.Session, error) { |
| + calls++ |
| + return nil, errors.New("redeem refused") |
| + } |
| + for _, tc := range []struct { |
| + sub, purpose, want string |
| + env bool |
| + calls int |
| + }{ |
| + {hostedwire.SubcommandChecks, hostedwire.PurposeCertification, "runner.hosted.purpose", true, 0}, |
| + {hostedwire.SubcommandCertify, hostedwire.PurposeChecks, "runner.hosted.purpose", true, 0}, |
| + {hostedwire.SubcommandChecks, hostedwire.PurposeChecks, "runner.hosted.start", true, 1}, |
| + {hostedwire.SubcommandChecks, hostedwire.PurposeChecks, hostedwire.EnvBootstrap, false, 1}, |
| + } { |
| + path := hostedBootstrap(t, tc.purpose) |
| + env := map[string]string{hostedwire.EnvBootstrap: path, hostedwire.EnvResults: filepath.Join(t.TempDir(), "results")} |
| + if !tc.env { |
| + env = nil |
| + } |
| + var out, errOut bytes.Buffer |
| + code := run(context.Background(), []string{tc.sub}, strings.NewReader(""), &out, &errOut, func(k string) string { return env[k] }) |
| + if code != 1 || calls != tc.calls || !strings.Contains(errOut.String(), tc.want) || strings.Contains(errOut.String(), "not_wired") { |
| + t.Errorf("%s with a %s bootstrap: exit %d, %d starts, stderr %q; want %q", tc.sub, tc.purpose, code, calls, errOut.String(), tc.want) |
| + } |
| + } |
| +} |
diff --git a/cmd/equipo-runner/main.go b/cmd/equipo-runner/main.go| index ce74fe2a..3818d2ed 100644 |
| --- a/cmd/equipo-runner/main.go |
| +++ b/cmd/equipo-runner/main.go |
| @@ -13,6 +13,7 @@ import ( |
| "syscall" |
| "amadan.net/oficina/equipo/internal/equipo" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| "amadan.net/oficina/equipo/internal/release" |
| "amadan.net/oficina/equipo/internal/runner" |
| "amadan.net/oficina/equipo/internal/runner/mac" |
| @@ -63,6 +64,10 @@ func run(ctx context.Context, args []string, input io.Reader, output, errorOutpu |
| } |
| return installRunner(ctx, args[1:], input, output, errorOutput, getenv) |
| } |
| + // A hosted VM's runner, started by vm-init with its own environment. |
| + if len(args) == 1 && (args[0] == hostedwire.SubcommandChecks || args[0] == hostedwire.SubcommandCertify) { |
| + return hostedMain(ctx, args[0], errorOutput, getenv) |
| + } |
| // A Mac's launchd agent passes its environment as a file (launchd has |
| // no EnvironmentFile): run --env-file <path>, probe --env-file <path>. |
| args, envFile, ok := cutEnvFile(args) |
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md| index dbc0b358..6d4d119b 100644 |
| --- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| +++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md |
| @@ -766,3 +766,67 @@ Mutation checks. Each was run from the repository root, outside the agent sandbo |
| Also run (targeted only, as the coordinator asked): |
| - `go test ./internal/runner/gate ./internal/runner/checkrun ./internal/runner/thin -run 'TestPrimaryChecks|TestMacWorker|TestChecks|TestWorker|TestRunnerReasonsAreKnown|TestBaseGate|TestCandidateGate|TestGateDirectory|TestCombinedOutput' -count=1`: ok. thin took 129s under load. |
| - `make budget build vet`: ok. gofmt and `git diff --check`: clean. |
| + |
| +## Task 12 |
| + |
| +The hosted transport through the proxy, the bootstrap and enrolment in the runner. |
| + |
| +- `internal/runner/hosted` (new): `ReadBootstrap(path)` reads vm-init's file and deletes it whether or not it keeps the rules (a file that cannot be deleted is an error). `Start(ctx, b, vm, state)` checks the bootstrap, makes the ECDSA P-256 proxy key, redeems the proxy code at the bootstrap listeners with a CSR that names nothing, checks the certificate (this key, client auth, exactly this launch, attempt and VM; epoch from its URI), then for a checks launch makes the ed25519 machine key and enrols. A certification launch stops after the redemption (it does not enrol). Both keys are PKCS #8 PEM, created with `O_EXCL`, 0600, in the state directory (`hosted-proxy.key`, `hosted-machine.key`). `Session` holds the machine key, proxy key, certificate and bearer (both atomic, for Task 14), epoch and deadline; `HTTPClient()`, `Token()`, `Origin()`. |
| +- Redemption retries a 403 (the controller answers every refusal alike, the not-yet-open window among them), 429 and 5xx, from 1 s doubling to 10 s, until 3 minutes have passed, with a last ask at the end; a connection error moves to the next bootstrap listener; any other answer fails at once. Enrolment retries a lost connection, 429 and 5xx for a minute. |
| +- `NewHTTPClient(proxies, caPin, cert)` is the transport (exported so the harness uses it): `Proxy: nil`, plain dials refused, `DialTLSContext` tries each proxy in order (failover on any error), mutual TLS with the current certificate (sent whatever CAs the proxy names), `CONNECT host:443`, then TLS to the host. At both layers the chain must carry the CA whose SPKI matches the pin, after the leaf, and the leaf must verify for the name with that CA as the only root (no intermediates, never the system roots); ALPN `http/1.1` only; redirects not followed. |
| +- Decisions to confirm: |
| + - **The proxy now sends its CA after each leaf** (`internal/hostedproxy/origin.go`, one line). The bootstrap carries only the CA's pin, and the proxy sent the leaf alone, so a VM had no CA to use as its root. Without this the brief's transport cannot work. Task 6/7 tests are unchanged and pass. |
| + - **The enrol answer** is `runnerproto.HostedEnrolResponse{Credential RunnerCredential; Epoch int64; Deadline time.Time}` (new; nothing defined it). The runner requires a worker role, a header-safe token, a runner ID, an epoch equal to its proxy certificate's, and an expiry in the future and not past the deadline. Task 22 must answer this shape. |
| + - The bootstrap file type (`hostedwire.RunnerBootstrap`, with `Check`) and the launch names (`SubcommandChecks`, `SubcommandCertify`, `EnvBootstrap`, `EnvResults`, `BootstrapFile`) moved to `hostedwire`; vminit's constants are now aliases of them and its one test uses the moved type. |
| + - `proxytest`: `Client(vm)` is now `hosted.NewHTTPClient` through the harness's proxy; `Handle(path, fn)` serves a fake instance route on the service origin; the default launch's code is the new exported `ProxyCode`, a well-formed code (the old `"C"` x 43 fails `BootstrapV2`'s strict base64url check). Task 7's `TestOpenSocketClosesAtCertExpiry` repeated the old literal and now uses `proxytest.ProxyCode`; its assertions are unchanged. |
| +- `internal/runner/thin/link.go`: `Link.TokenSource` (read at each dial; nil keeps `Token`) and `Link.HTTPClient` (passed to `websocket.DialOptions`). Budget: thin 35822/35352 to 35831/35453 (the two hooks and their two tests), record raised with the reason. |
| +- `cmd/equipo-runner`: `hosted-run` and `hosted-certify` read `EQUIPO_HOSTED_BOOTSTRAP` and `EQUIPO_HOSTED_RESULTS` (both absolute), read and delete the bootstrap, refuse a bootstrap of the other purpose, run `hosted.Start` with the bootstrap's directory as the state directory, then exit 1 with diagnostic `runner.hosted.not_wired`. Diagnostics use the existing `CopyRunnerDiagnostic` format with codes; no new copy. |
| +- `TestPathClassCoversRunner` picks up `/api/hosted/enrol` from `internal/runner/hosted/enrol.go` and passes (mutation 75). |
| + |
| +Red: `go vet ./internal/runner/hosted ./internal/runner/thin ./cmd/equipo-runner` at 0e392ff8 with the tests written: `no non-test Go files in .../internal/runner/hosted`; `link_hooks_test.go:76:67: unknown field TokenSource in struct literal of type Link`. |
| + |
| +Green: |
| +- `go test ./internal/runner/hosted ./internal/runner/thin ./internal/hostedproxy -run 'TestLinkReads|TestLinkUses|TestReadBootstrap|TestTransport|TestEnrolSends|TestNoDirectDial|TestRealLink|TestFronting' -count=1`: ok. |
| +- `go test ./internal/runner/hosted ./internal/hostedproxy/... ./internal/vminit ./internal/hostedwire -count=1`: ok (hosted 3.2s, hostedproxy 1.0s). |
| +- `go test ./internal/runner/thin -run '^(TestRunnerContract|TestEnrolledWorkerNeverFallsBack|TestUnknownRoleWaitsForTheInstance|TestLinkReadsTokenEachDial|TestLinkUsesGivenHTTPClient)$' -count=1`: ok. |
| +- `go test ./cmd/equipo-runner ./internal/runnerproto -count=1`: ok. |
| +- `GOOS=darwin GOARCH=arm64 CGO_ENABLED=0 go build ./cmd/equipo-runner`: ok. `make budget build vet`: ok. staticcheck on the changed packages, gofmt and `git diff --check`: clean. |
| + |
| +Mutation checks. Each was applied with the `sed` shown, then the `go test` shown was run with `-count=1`; the file was copied first and restored with `cp`, and `cmp` against the copy was clean after every one. Every run compiled and failed on an assertion. Output is cut. |
| + |
| +70. The link copies the token once (the brief's mutation). |
| + - `sed -i 's/^\tbackoff := time.Second$/\tif l.TokenSource != nil { t0 := l.TokenSource(); l.TokenSource = func() string { return t0 } }\n\tbackoff := time.Second/' internal/runner/thin/link.go` |
| + - `go test ./internal/runner/thin -run '^TestLinkReadsTokenEachDial$'` |
| + - FAIL: `link_hooks_test.go:82: second dial sent "Bearer first", want the source's token at that dial`. Restored. |
| +71. The inner TLS trusts the system roots (the brief's mutation). |
| + - `sed -i 's/d.pin.tlsConfig(host))/\&tls.Config{MinVersion: tls.VersionTLS12, ServerName: host, NextProtos: []string{alpnHTTP11}})/' internal/runner/hosted/transport.go` |
| + - `go test ./internal/runner/hosted -run '^(TestTransportPinsInterceptCA|TestRealLinkThroughProxy)$'` |
| + - FAIL: `hosted_test.go:429: the pinned CA at both layers: 0 "", ... tls: failed to verify certificate: x509: certificate signed by unknown authority`, `hosted_test.go:444: with the proxy's own pin: 0, ...` and `hosted_test.go:512: Start: hosted: not enrolled with the instance: ...`. Restored. |
| +72. Any CA the chain carries is trusted (the pin not compared). |
| + - `sed -i 's/if subtle.ConstantTimeCompare(sum\[:\], p) == 1 {/if subtle.ConstantTimeCompare(sum[:], p) == 1 || true {/' internal/runner/hosted/transport.go` |
| + - `go test ./internal/runner/hosted -run '^TestTransportPinsInterceptCA$'` |
| + - FAIL: `hosted_test.go:429: another CA inside the tunnel: 200 "ok", <nil>, 1 requests reached the tunnel`, `... another CA at the proxy: ...`, `hosted_test.go:438: a proxy whose CA is not the pinned one was trusted`, `hosted_test.go:441: the origin saw 1 requests`, `hosted_test.go:455: the controller got 1 redemptions`. Restored. |
| +73. The proxy sends its leaf without the CA. |
| + - `sed -i 's/Certificate: \[\]\[\]byte{der, ca.cert.Raw}/Certificate: [][]byte{der}/' internal/hostedproxy/origin.go` |
| + - `go test ./internal/runner/hosted -run '^TestRealLinkThroughProxy$'` |
| + - FAIL: `hosted_test.go:512: Start: hosted: proxy code not redeemed: context deadline exceeded (last: ... the peer's chain does not carry the pinned intercept CA)`. Restored. |
| +74. Start does not ask again after a refused code. |
| + - `sed -i 's/return status == http.StatusForbidden || status == http.StatusTooManyRequests/return status == http.StatusTooManyRequests/' internal/runner/hosted/redeem.go` |
| + - `go test ./internal/runner/hosted -run '^TestStartRetriesEarlyRedeem$'` |
| + - FAIL: `hosted_test.go:266: Start did not ask again after a refusal` and `hosted_test.go:284: gave up after 9.8ms and 1 redemptions, want its patience and retries`. Restored. |
| +75. The runner names a hosted path outside the proxy's class (TestPathClassCoversRunner reads `internal/runner/hosted`). |
| + - `sed -i 's|const enrolPath = "/api/hosted/enrol"|const enrolPath = "/api/hosted/enroll"|' internal/runner/hosted/enrol.go` |
| + - `go test ./internal/hostedproxy -run '^TestPathClassCoversRunner$'` |
| + - FAIL: `policy_test.go:467: /api/hosted/enroll (../runner/hosted/enrol.go) is outside the proxy's instance path class`. Restored. |
| +76. ReadBootstrap leaves the file. |
| + - `sed -i 's/if err := os.Remove(path); err != nil {/if err := error(nil); err != nil {/' internal/runner/hosted/bootstrap.go` |
| + - `go test ./internal/runner/hosted -run '^TestReadBootstrapDeletesFile$'` |
| + - FAIL: `hosted_test.go:143: after a read: the bootstrap file is still there (<nil>)` (and after a refusal, after a bad VM ID). Restored. |
| +77. A hosted subcommand exits 0 after Start. |
| + - `sed -i 's/return fail("runner.hosted.not_wired", "-", errNotWired)/_ = errNotWired; return 0/' cmd/equipo-runner/hosted.go` |
| + - `go test ./cmd/equipo-runner -run '^TestHostedSubcommandsNotYetWired$'` |
| + - FAIL: `hosted_test.go:59: hosted-certify: exit 0, started [...]` and `hosted-run: exit 0, ...`. Restored. |
| +78. The CSR names the VM. |
| + - `sed -i 's/\&x509.CertificateRequest{}, key)/\&x509.CertificateRequest{DNSNames: []string{"vm"}}, key)/' internal/runner/hosted/redeem.go` |
| + - `go test ./internal/runner/hosted -run '^TestEnrolSendsVMRefAndKey$'` |
| + - FAIL: `hosted_test.go:235: the CSR names "" [vm] [] [] []; want no identity fields`. Restored. |
diff --git a/internal/hostedproxy/e2e_test.go b/internal/hostedproxy/e2e_test.go| index 5ebc2afa..f5ec306e 100644 |
| --- a/internal/hostedproxy/e2e_test.go |
| +++ b/internal/hostedproxy/e2e_test.go |
| @@ -337,7 +337,7 @@ func TestOpenSocketClosesAtCertExpiry(t *testing.T) { |
| h := proxytest.New(t) |
| const life = 20 * time.Second // the launch deadline caps the certificate, inside one poll interval |
| h.Controller.SetLaunch(proxytest.Launch{LaunchID: proxytest.LaunchID, AttemptID: proxytest.AttemptID, VMRef: proxytest.VMRef, |
| - Epoch: proxytest.Epoch, Code: strings.Repeat("C", len(ctlproxy.CodePlaceholder)), Deadline: h.Clock.Wall().Add(life), |
| + Epoch: proxytest.Epoch, Code: proxytest.ProxyCode, Deadline: h.Clock.Wall().Add(life), |
| Services: []hostedwire.Service{{Host: host, Port: 443, Class: hostedwire.ServiceInstance}}}) |
| vm := h.Redeem(t) |
| if got := vm.Cert.Leaf.NotAfter.Sub(h.Clock.Wall()); got != life { |
diff --git a/internal/hostedproxy/origin.go b/internal/hostedproxy/origin.go| index 9e8c863f..ebe94286 100644 |
| --- a/internal/hostedproxy/origin.go |
| +++ b/internal/hostedproxy/origin.go |
| @@ -28,8 +28,9 @@ const ( |
| ) |
| // interceptCA mints the proxy's server leaves: one for each CONNECT host |
| -// (the inner TLS), and one for each listener's IP address. VMs trust only |
| -// this CA (its SPKI is the bootstrap's ProxyCAPin). |
| +// (the inner TLS), and one for each listener's IP address, each sent with |
| +// the CA after it. VMs trust only this CA (its SPKI is the bootstrap's |
| +// ProxyCAPin). |
| type interceptCA struct { |
| cert *x509.Certificate |
| key crypto.Signer |
| @@ -95,7 +96,10 @@ func (ca *interceptCA) leaf(key string, name func(*x509.Certificate)) (*tls.Cert |
| if err != nil { |
| return nil, err |
| } |
| - l := &tls.Certificate{Certificate: [][]byte{der}, PrivateKey: ca.leafKey, Leaf: c} |
| + // The CA follows the leaf: a VM holds only its pin (the bootstrap's |
| + // ProxyCAPin), so it takes the CA from the chain, checks it against |
| + // the pin, and verifies the leaf with that CA as its only root. |
| + l := &tls.Certificate{Certificate: [][]byte{der, ca.cert.Raw}, PrivateKey: ca.leafKey, Leaf: c} |
| ca.leaves[key] = l |
| return l, nil |
| } |
diff --git a/internal/hostedproxy/proxytest/harness.go b/internal/hostedproxy/proxytest/harness.go| index 62abadf9..28db94d1 100644 |
| --- a/internal/hostedproxy/proxytest/harness.go |
| +++ b/internal/hostedproxy/proxytest/harness.go |
| @@ -41,6 +41,7 @@ import ( |
| "amadan.net/oficina/equipo/internal/hostedproxy" |
| "amadan.net/oficina/equipo/internal/hostedwire" |
| "amadan.net/oficina/equipo/internal/isolatedjob" |
| + "amadan.net/oficina/equipo/internal/runner/hosted" |
| "github.com/coder/websocket" |
| ) |
| @@ -61,6 +62,9 @@ const ( |
| VMRef = isolatedjob.Ref("vm-1") |
| Epoch = 2 |
| ProxyKey = hostedwire.KeyID("proxy-1") |
| + // ProxyCode is the default launch's proxy code: well formed (32 |
| + // bytes, base64url), as a bootstrap must carry it. |
| + ProxyCode = "CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCA" |
| ) |
| // FakeMono is a hostedproxy.Clock tests move by hand. Wall starts at the |
| @@ -715,6 +719,7 @@ type Harness struct { |
| ProxyKey ed25519.PrivateKey |
| t testing.TB |
| + routes sync.Map // path -> http.HandlerFunc on the service origin (Handle) |
| originHits atomic.Int64 |
| otherHits atomic.Int64 |
| part *partition |
| @@ -733,7 +738,7 @@ func New(t testing.TB) *Harness { |
| h.ProxyKey = proxyKey |
| h.Controller = newFakeController(t, h.Clock, proxyPub) |
| h.Controller.SetLaunch(Launch{LaunchID: LaunchID, AttemptID: AttemptID, VMRef: VMRef, Epoch: Epoch, |
| - Code: strings.Repeat("C", len(ctlproxy.CodePlaceholder)), |
| + Code: ProxyCode, |
| Services: []hostedwire.Service{{Host: Host, Port: hostedproxy.ServicePort, Class: hostedwire.ServiceInstance}}}) |
| // The proxy reaches the controller only through the partition, cut |
| // until its own first poll has failed, so the only feed it holds is |
| @@ -741,8 +746,8 @@ func New(t testing.TB) *Harness { |
| h.part = newPartition(t, h.Controller.Addr()) |
| originKey, originCA, originPool := newCA(t, "origin CA") |
| - h.Origin = h.startOrigin(originCA, originKey, Host, &h.originHits) |
| - h.Other = h.startOrigin(originCA, originKey, OtherHost, &h.otherHits) |
| + h.Origin = h.startOrigin(originCA, originKey, Host, &h.originHits, &h.routes) |
| + h.Other = h.startOrigin(originCA, originKey, OtherHost, &h.otherHits, &sync.Map{}) |
| icKey, ic, icPool := newCA(t, "intercept CA") |
| sum := sha256.Sum256(ic.RawSubjectPublicKeyInfo) |
| @@ -797,13 +802,22 @@ func (h *Harness) Partition(cut bool) { h.part.set(cut) } |
| // host's origin. |
| func (h *Harness) Hits() (origin, other int64) { return h.originHits.Load(), h.otherHits.Load() } |
| -// startOrigin is a TLS origin for name on 127.0.0.1: GET |
| -// /api/runner/protocol answers "protocol 39", GET /api/runner/stream is a |
| -// WebSocket echo, anything else answers its method and path. |
| -func (h *Harness) startOrigin(caCert *x509.Certificate, caKey *ecdsa.PrivateKey, name string, hits *atomic.Int64) *httptest.Server { |
| +// Handle serves path on the service host's origin with fn, in place of |
| +// what it answers by default: a fake instance's routes. |
| +func (h *Harness) Handle(path string, fn http.HandlerFunc) { h.routes.Store(path, fn) } |
| + |
| +// startOrigin is a TLS origin for name on 127.0.0.1: a path given to |
| +// routes is served by its handler; otherwise GET /api/runner/protocol |
| +// answers "protocol 39", GET /api/runner/stream is a WebSocket echo, and |
| +// anything else answers its method and path. |
| +func (h *Harness) startOrigin(caCert *x509.Certificate, caKey *ecdsa.PrivateKey, name string, hits *atomic.Int64, routes *sync.Map) *httptest.Server { |
| leaf := issueServer(h.t, caCert, caKey, name) |
| srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| hits.Add(1) |
| + if fn, ok := routes.Load(r.URL.Path); ok { |
| + fn.(http.HandlerFunc)(w, r) |
| + return |
| + } |
| switch r.URL.Path { |
| case "/api/runner/protocol": |
| _, _ = io.WriteString(w, "protocol 39") |
| @@ -905,7 +919,7 @@ func (h *Harness) Redeem(t testing.TB) *VM { |
| t.Helper() |
| key, csr := CSR(t) |
| body, _ := json.Marshal(hostedwire.RedeemRequest{LaunchID: LaunchID, VMRef: VMRef, |
| - ProxyCode: strings.Repeat("C", len(ctlproxy.CodePlaceholder)), CSR: csr}) |
| + ProxyCode: ProxyCode, CSR: csr}) |
| status, out := h.Boot(t, nil, "/redeem", body, nil) |
| if status != http.StatusOK { |
| t.Fatalf("redeem: %d %s", status, out) |
| @@ -1020,39 +1034,16 @@ func (h *Harness) pinned(cs tls.ConnectionState) error { |
| return errors.New("proxytest: the proxy's chain does not end at the pinned intercept CA") |
| } |
| -// Client is the hosted runner's HTTP client as Task 12 builds it, with |
| -// vm's credential: no environment proxy; each connection is mutual TLS to |
| -// the proxy's egress listener, CONNECT host:443, then TLS to host with the |
| -// intercept CA alone as root (SPKI pinned), ServerName host, ALPN |
| -// http/1.1. Redirects are not followed. Task 12 replaces this with the |
| -// runner's own transport. |
| +// Client is the hosted runner's own HTTP client (hosted.NewHTTPClient) |
| +// with vm's credential (nil: none), through this proxy alone, pinned to |
| +// its intercept CA. |
| func (h *Harness) Client(vm *VM) *http.Client { |
| - return &http.Client{ |
| - Transport: &http.Transport{ |
| - Proxy: nil, ForceAttemptHTTP2: false, TLSNextProto: map[string]func(string, *tls.Conn) http.RoundTripper{}, |
| - DialTLSContext: func(ctx context.Context, _, addr string) (net.Conn, error) { |
| - host, port, err := net.SplitHostPort(addr) |
| - if err != nil || port != "443" { |
| - return nil, fmt.Errorf("proxytest: %s is not host:443", addr) |
| - } |
| - c, status, err := h.Connect(ctx, vm, net.JoinHostPort(host, "443")) |
| - if err != nil { |
| - return nil, err |
| - } |
| - if status != http.StatusOK { |
| - return nil, fmt.Errorf("proxytest: CONNECT %s: %d", addr, status) |
| - } |
| - inner := tls.Client(c, &tls.Config{ServerName: host, RootCAs: h.InterceptPool, |
| - NextProtos: []string{hostedproxy.ALPNHTTP11}, MinVersion: tls.VersionTLS12, VerifyConnection: h.pinned}) |
| - if err := inner.HandshakeContext(ctx); err != nil { |
| - c.Close() |
| - return nil, err |
| - } |
| - return inner, nil |
| - }, |
| - }, |
| - CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, |
| - } |
| + return hosted.NewHTTPClient([]netip.AddrPort{h.Proxy.EgressAddr()}, h.InterceptPin, func() *tls.Certificate { |
| + if vm == nil { |
| + return nil |
| + } |
| + return &vm.Cert |
| + }) |
| } |
| // Connect opens mutual TLS to the egress listener with vm's certificate |
diff --git a/internal/hostedwire/hosted.go b/internal/hostedwire/hosted.go| index eec088fd..5a514ca7 100644 |
| --- a/internal/hostedwire/hosted.go |
| +++ b/internal/hostedwire/hosted.go |
| @@ -261,3 +261,36 @@ func (q CertLaunchRequest) Validate() error { |
| } |
| return nil |
| } |
| + |
| +// The hosted runner's launch, shared by vm-init, which starts it, and the |
| +// runner (vm-init is Linux only; the runner also builds for macOS). |
| +const ( |
| + SubcommandChecks = "hosted-run" // purpose "checks" |
| + SubcommandCertify = "hosted-certify" // purpose "certification" |
| + // EnvBootstrap names the runner's bootstrap file (RunnerBootstrap). |
| + EnvBootstrap = "EQUIPO_HOSTED_BOOTSTRAP" |
| + // EnvResults names the directory the root stage's results are in. |
| + EnvResults = "EQUIPO_HOSTED_RESULTS" |
| + // BootstrapFile is the bootstrap file's name in the runner's state |
| + // directory. |
| + BootstrapFile = "bootstrap.json" |
| +) |
| + |
| +// RunnerBootstrap is the file vm-init writes for the runner, at |
| +// EnvBootstrap: the launch's bootstrap and the VM's own ID from the /run |
| +// hook. It is the runner user's, mode 0600, and the runner deletes it |
| +// once read. |
| +type RunnerBootstrap struct { |
| + VMRef isolatedjob.Ref `json:"vm_ref"` |
| + Bootstrap BootstrapV2 `json:"bootstrap"` |
| +} |
| + |
| +// Check is the file's rules: a valid VM ID and a bootstrap Encode would |
| +// write. |
| +func (f RunnerBootstrap) Check() error { |
| + if !f.VMRef.Valid() { |
| + return fmt.Errorf("%w: VM ID", ErrBootstrap) |
| + } |
| + _, err := f.Bootstrap.Encode() |
| + return err |
| +} |
diff --git a/internal/runner/hosted/bootstrap.go b/internal/runner/hosted/bootstrap.go| new file mode 100644 |
| index 00000000..03cedb07 |
| --- /dev/null |
| +++ b/internal/runner/hosted/bootstrap.go |
| @@ -0,0 +1,187 @@ |
| +package hosted |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto" |
| + "crypto/ecdsa" |
| + "crypto/ed25519" |
| + "crypto/elliptic" |
| + "crypto/rand" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "encoding/pem" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "os" |
| + "path/filepath" |
| + "sync/atomic" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| +) |
| + |
| +// The keys' files in the state directory, each 0600. Both keys are made |
| +// in this process and never leave the directory. |
| +const ( |
| + MachineKeyFile = "hosted-machine.key" // ed25519: the instance's challenges |
| + ProxyKeyFile = "hosted-proxy.key" // ECDSA P-256: the proxy client certificate |
| +) |
| + |
| +// maxBootstrapFile bounds the bootstrap file: the bootstrap and its VM ID. |
| +const maxBootstrapFile = 2 * hostedwire.MaxBootstrapBytes |
| + |
| +// ReadBootstrap reads the bootstrap file vm-init left at path |
| +// (hostedwire.RunnerBootstrap) and deletes it, whether or not it keeps |
| +// the rules: the codes it carries are single use and are not left on |
| +// disk. A file that breaks a rule, or one that cannot be deleted, is an |
| +// error. |
| +func ReadBootstrap(path string) (hostedwire.BootstrapV2, isolatedjob.Ref, error) { |
| + var none hostedwire.BootstrapV2 |
| + st, err := os.Lstat(path) |
| + if err != nil { |
| + return none, "", fmt.Errorf("hosted: bootstrap file: %w", err) |
| + } |
| + var raw []byte |
| + if st.Mode().IsRegular() { |
| + if f, err := os.Open(path); err == nil { |
| + raw, err = io.ReadAll(io.LimitReader(f, maxBootstrapFile+1)) |
| + f.Close() |
| + if err != nil { |
| + raw = nil |
| + } |
| + } |
| + } |
| + if err := os.Remove(path); err != nil { |
| + return none, "", fmt.Errorf("hosted: deleting the bootstrap file: %w", err) |
| + } |
| + if !st.Mode().IsRegular() || len(raw) == 0 || len(raw) > maxBootstrapFile { |
| + return none, "", fmt.Errorf("%w: the bootstrap file is not a readable regular file within %d bytes", hostedwire.ErrBootstrap, maxBootstrapFile) |
| + } |
| + var f hostedwire.RunnerBootstrap |
| + if err := hostedwire.DecodeStrict(bytes.NewReader(raw), &f); err != nil { |
| + return none, "", fmt.Errorf("hosted: bootstrap file: %w", err) |
| + } |
| + if err := f.Check(); err != nil { |
| + return none, "", err |
| + } |
| + return f.Bootstrap, f.VMRef, nil |
| +} |
| + |
| +// Session is a hosted runner's standing with the proxy and the instance: |
| +// its machine key, its proxy key and certificate, its bearer, and the |
| +// job's epoch and deadline. The certificate and the bearer are swapped |
| +// atomically as they are renewed. |
| +type Session struct { |
| + launch hostedwire.BootstrapV2 |
| + vm isolatedjob.Ref |
| + origin string |
| + machine ed25519.PrivateKey |
| + |
| + proxyKey *ecdsa.PrivateKey |
| + cert atomic.Pointer[tls.Certificate] |
| + bearer atomic.Pointer[runnerproto.RunnerCredential] |
| + epoch int64 |
| + deadline time.Time |
| + |
| + client *http.Client |
| + boot *http.Client |
| +} |
| + |
| +// HTTPClient is the session's client: every connection goes through the |
| +// proxy with the current certificate (NewHTTPClient). |
| +func (s *Session) HTTPClient() *http.Client { return s.client } |
| + |
| +// Token is the current bearer ("" before enrolment, and for a |
| +// certification launch, which does not enrol). |
| +func (s *Session) Token() string { |
| + if c := s.bearer.Load(); c != nil { |
| + return c.Token |
| + } |
| + return "" |
| +} |
| + |
| +// Origin is the instance's origin, its one host on port 443. |
| +func (s *Session) Origin() string { return s.origin } |
| + |
| +func (s *Session) currentCert() *tls.Certificate { return s.cert.Load() } |
| + |
| +// Start makes the session for b in the state directory state: it makes |
| +// the proxy key and redeems the proxy code for a client certificate |
| +// (retrying while the controller has not yet opened the code's window), |
| +// then, for a checks launch, makes the machine key and enrols with the |
| +// instance through the proxy. A certification launch does not enrol. |
| +func Start(ctx context.Context, b hostedwire.BootstrapV2, vm isolatedjob.Ref, state string) (*Session, error) { |
| + if err := (hostedwire.RunnerBootstrap{VMRef: vm, Bootstrap: b}).Check(); err != nil { |
| + return nil, err |
| + } |
| + origin, err := instanceOrigin(b) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if !filepath.IsAbs(state) { |
| + return nil, errors.New("hosted: the state directory must be an absolute path") |
| + } |
| + proxyKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if err := writeKey(filepath.Join(state, ProxyKeyFile), proxyKey); err != nil { |
| + return nil, err |
| + } |
| + s := &Session{launch: b, vm: vm, origin: origin, proxyKey: proxyKey} |
| + pin := parsePin(b.ProxyCAPin) |
| + s.boot = bootClient(b.ProxyBoot, pin, s.currentCert) |
| + defer s.boot.CloseIdleConnections() |
| + cert, epoch, err := redeem(ctx, s.boot, b, vm, proxyKey) |
| + if err != nil { |
| + return nil, err |
| + } |
| + s.cert.Store(&cert) |
| + s.epoch = epoch |
| + s.client = NewHTTPClient(b.Proxies, b.ProxyCAPin, s.currentCert) |
| + if b.Purpose != hostedwire.PurposeChecks { |
| + return s, nil |
| + } |
| + pub, machine, err := ed25519.GenerateKey(rand.Reader) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if err := writeKey(filepath.Join(state, MachineKeyFile), machine); err != nil { |
| + return nil, err |
| + } |
| + s.machine = machine |
| + r, err := enrol(ctx, s.client, origin, b, vm, pub, epoch) |
| + if err != nil { |
| + return nil, err |
| + } |
| + s.bearer.Store(&r.Credential) |
| + s.deadline = r.Deadline |
| + return s, nil |
| +} |
| + |
| +// writeKey writes key as PKCS #8 PEM to a new file at path, mode 0600. A |
| +// file already there is an error: a key is made once per launch. |
| +func writeKey(path string, key crypto.PrivateKey) error { |
| + der, err := x509.MarshalPKCS8PrivateKey(key) |
| + if err != nil { |
| + return err |
| + } |
| + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) |
| + if err != nil { |
| + return fmt.Errorf("hosted: key file: %w", err) |
| + } |
| + if err := pem.Encode(f, &pem.Block{Type: "PRIVATE KEY", Bytes: der}); err != nil { |
| + f.Close() |
| + return fmt.Errorf("hosted: key file: %w", err) |
| + } |
| + if err := f.Sync(); err != nil { |
| + f.Close() |
| + return fmt.Errorf("hosted: key file: %w", err) |
| + } |
| + return f.Close() |
| +} |
diff --git a/internal/runner/hosted/enrol.go b/internal/runner/hosted/enrol.go| new file mode 100644 |
| index 00000000..a1fb9556 |
| --- /dev/null |
| +++ b/internal/runner/hosted/enrol.go |
| @@ -0,0 +1,134 @@ |
| +package hosted |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ed25519" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net/http" |
| + "strconv" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/wire" |
| +) |
| + |
| +// enrolPath is the instance's public hosted enrolment route (Task 22). |
| +const enrolPath = "/api/hosted/enrol" |
| + |
| +// Enrolment retries a lost connection or a busy instance for up to |
| +// enrolPatience: the instance code lives two minutes from the VM's |
| +// admission. |
| +const ( |
| + enrolPatience = time.Minute |
| + enrolMaxWait = 8 * time.Second |
| + enrolTimeout = 30 * time.Second |
| +) |
| + |
| +// ErrEnrol is an enrolment the instance refused or never answered. |
| +var ErrEnrol = errors.New("hosted: not enrolled with the instance") |
| + |
| +// instanceOrigin is the origin of b's instance service: its one exact |
| +// host on port 443. |
| +func instanceOrigin(b hostedwire.BootstrapV2) (string, error) { |
| + for _, s := range b.Services { |
| + if s.Class != hostedwire.ServiceInstance { |
| + continue |
| + } |
| + if strconv.Itoa(int(s.Port)) != servicePort { |
| + return "", fmt.Errorf("%w: the instance service is on port %d, not %s", ErrTransport, s.Port, servicePort) |
| + } |
| + return "https://" + s.Host, nil |
| + } |
| + return "", fmt.Errorf("%w: the bootstrap names no instance service", ErrTransport) |
| +} |
| + |
| +// enrol sends the instance code, the launch, the VM and the machine key |
| +// to the instance through c, and returns its answer: a worker credential |
| +// for this job, at the epoch of the proxy certificate. |
| +func enrol(ctx context.Context, c *http.Client, origin string, b hostedwire.BootstrapV2, vm isolatedjob.Ref, |
| + machine ed25519.PublicKey, epoch int64) (runnerproto.HostedEnrolResponse, error) { |
| + var none runnerproto.HostedEnrolResponse |
| + body, err := json.Marshal(wire.HostedEnrolRequest{Code: b.InstanceCode, LaunchID: b.LaunchID, VMRef: string(vm), |
| + MachinePublicKey: machine}) |
| + if err != nil { |
| + return none, err |
| + } |
| + giveUp := time.Now().Add(enrolPatience) |
| + wait := time.Second |
| + for { |
| + status, out, err := postEnrol(ctx, c, origin+enrolPath, body) |
| + switch { |
| + case err == nil && status == http.StatusOK: |
| + return acceptCredential(out, epoch) |
| + case err == nil && status != http.StatusTooManyRequests && status < 500: |
| + return none, fmt.Errorf("%w: the instance answered %d", ErrEnrol, status) |
| + case err == nil: |
| + err = fmt.Errorf("the instance answered %d", status) |
| + } |
| + left := time.Until(giveUp) |
| + if left <= 0 { |
| + return none, fmt.Errorf("%w: %w", ErrEnrol, err) |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return none, fmt.Errorf("%w: %w (last: %w)", ErrEnrol, ctx.Err(), err) |
| + case <-time.After(min(wait, left)): |
| + } |
| + wait = min(2*wait, enrolMaxWait) |
| + } |
| +} |
| + |
| +func postEnrol(ctx context.Context, c *http.Client, url string, body []byte) (int, []byte, error) { |
| + ctx, cancel := context.WithTimeout(ctx, enrolTimeout) |
| + defer cancel() |
| + req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body)) |
| + if err != nil { |
| + return 0, nil, err |
| + } |
| + req.Header.Set("Content-Type", "application/json") |
| + resp, err := c.Do(req) |
| + if err != nil { |
| + return 0, nil, err |
| + } |
| + defer resp.Body.Close() |
| + out, err := io.ReadAll(io.LimitReader(resp.Body, 64<<10)) |
| + return resp.StatusCode, out, err |
| +} |
| + |
| +// acceptCredential checks the instance's answer: a worker bearer that |
| +// fits a header, a runner ID, an epoch equal to the proxy certificate's, |
| +// and an expiry in the future and not past the deadline. |
| +func acceptCredential(out []byte, epoch int64) (runnerproto.HostedEnrolResponse, error) { |
| + var r runnerproto.HostedEnrolResponse |
| + if err := json.Unmarshal(out, &r); err != nil { |
| + return r, fmt.Errorf("%w: the answer does not decode", ErrEnrol) |
| + } |
| + cred, now := r.Credential, time.Now() |
| + switch { |
| + case cred.Token == "" || !headerSafe(cred.Token) || cred.RunnerID == "": |
| + return r, fmt.Errorf("%w: the answer has no usable credential", ErrEnrol) |
| + case cred.Role != wire.RoleWorker: |
| + return r, fmt.Errorf("%w: the credential's role is %q, not a worker's", ErrEnrol, cred.Role) |
| + case r.Epoch != epoch: |
| + return r, fmt.Errorf("%w: the credential is for epoch %d, the proxy certificate for %d", ErrEnrol, r.Epoch, epoch) |
| + case !cred.ExpiresAt.After(now) || cred.ExpiresAt.After(r.Deadline): |
| + return r, fmt.Errorf("%w: the credential's expiry is not within the job's deadline", ErrEnrol) |
| + } |
| + return r, nil |
| +} |
| + |
| +// headerSafe: printable ASCII without spaces, as a bearer token is. |
| +func headerSafe(s string) bool { |
| + for i := 0; i < len(s); i++ { |
| + if s[i] <= 0x20 || s[i] > 0x7e { |
| + return false |
| + } |
| + } |
| + return true |
| +} |
diff --git a/internal/runner/hosted/export_test.go b/internal/runner/hosted/export_test.go| new file mode 100644 |
| index 00000000..e469d973 |
| --- /dev/null |
| +++ b/internal/runner/hosted/export_test.go |
| @@ -0,0 +1,14 @@ |
| +package hosted |
| + |
| +import ( |
| + "testing" |
| + "time" |
| +) |
| + |
| +// SetRedeemTiming shortens Start's patience with a refused proxy code, |
| +// and its first wait, for one test. |
| +func SetRedeemTiming(t testing.TB, patience, firstWait time.Duration) { |
| + p, w := redeemPatience, redeemFirstWait |
| + redeemPatience, redeemFirstWait = patience, firstWait |
| + t.Cleanup(func() { redeemPatience, redeemFirstWait = p, w }) |
| +} |
diff --git a/internal/runner/hosted/hosted_test.go b/internal/runner/hosted/hosted_test.go| new file mode 100644 |
| index 00000000..2177316b |
| --- /dev/null |
| +++ b/internal/runner/hosted/hosted_test.go |
| @@ -0,0 +1,558 @@ |
| +package hosted_test |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "crypto/ecdsa" |
| + "crypto/ed25519" |
| + "crypto/elliptic" |
| + "crypto/rand" |
| + "crypto/sha256" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "encoding/hex" |
| + "encoding/json" |
| + "encoding/pem" |
| + "errors" |
| + "io" |
| + "log/slog" |
| + "math/big" |
| + "net" |
| + "net/http" |
| + "net/netip" |
| + "os" |
| + "path/filepath" |
| + "reflect" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedproxy/proxytest" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/runner/hosted" |
| + "amadan.net/oficina/equipo/internal/runner/thin" |
| + "amadan.net/oficina/equipo/internal/runnerproto" |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "amadan.net/rastrillo/rastrillo/budget" |
| + "github.com/coder/websocket" |
| +) |
| + |
| +func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| + |
| +// instanceCode is a well-formed instance code (32 bytes, base64url). |
| +const instanceCode = "IIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIIA" |
| + |
| +// bootstrap is the harness's default launch as vm-init hands it over. |
| +func bootstrap(h *proxytest.Harness) hostedwire.BootstrapV2 { |
| + return hostedwire.BootstrapV2{Version: hostedwire.BootstrapV2Version, Purpose: hostedwire.PurposeChecks, |
| + LaunchID: proxytest.LaunchID, AttemptID: proxytest.AttemptID, InstanceCode: instanceCode, 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}}} |
| +} |
| + |
| +// fakeEnrol is the instance's POST /api/hosted/enrol (Task 22): it |
| +// records each request and answers a worker credential. |
| +type fakeEnrol struct { |
| + mu sync.Mutex |
| + got []wire.HostedEnrolRequest |
| +} |
| + |
| +func (f *fakeEnrol) requests() []wire.HostedEnrolRequest { |
| + f.mu.Lock() |
| + defer f.mu.Unlock() |
| + return append([]wire.HostedEnrolRequest(nil), f.got...) |
| +} |
| + |
| +func enrolOn(h *proxytest.Harness) *fakeEnrol { |
| + f := &fakeEnrol{} |
| + h.Handle("/api/hosted/enrol", func(w http.ResponseWriter, r *http.Request) { |
| + var q wire.HostedEnrolRequest |
| + if r.Method != http.MethodPost || json.NewDecoder(r.Body).Decode(&q) != nil { |
| + http.Error(w, "bad request", http.StatusBadRequest) |
| + return |
| + } |
| + f.mu.Lock() |
| + f.got = append(f.got, q) |
| + f.mu.Unlock() |
| + end := time.Now().Add(time.Hour) |
| + _ = json.NewEncoder(w).Encode(runnerproto.HostedEnrolResponse{ |
| + Credential: runnerproto.RunnerCredential{Version: 1, Token: "bearer-1", TokenType: "Bearer", RunnerID: "r-1", |
| + CredentialID: "c-1", Person: "person@example.com", ExpiresAt: end, Role: wire.RoleWorker}, |
| + Epoch: proxytest.Epoch, Deadline: end}) |
| + }) |
| + return f |
| +} |
| + |
| +func start(t *testing.T, b hostedwire.BootstrapV2, state string) (*hosted.Session, error) { |
| + t.Helper() |
| + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) |
| + defer cancel() |
| + return hosted.Start(ctx, b, proxytest.VMRef, state) |
| +} |
| + |
| +// deadAddr is a loopback address nothing listens on. |
| +func deadAddr(t *testing.T) netip.AddrPort { |
| + t.Helper() |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + a := ln.Addr().(*net.TCPAddr).AddrPort() |
| + ln.Close() |
| + return a |
| +} |
| + |
| +// get fetches url with c and returns the status and body. |
| +func get(c *http.Client, url string) (int, string, error) { |
| + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| + defer cancel() |
| + defer c.CloseIdleConnections() |
| + req, _ := http.NewRequestWithContext(ctx, http.MethodGet, url, nil) |
| + resp, err := c.Do(req) |
| + if err != nil { |
| + return 0, "", err |
| + } |
| + defer resp.Body.Close() |
| + body, _ := io.ReadAll(resp.Body) |
| + return resp.StatusCode, string(body), nil |
| +} |
| + |
| +const protocolURL = "https://" + proxytest.Host + "/api/runner/protocol" |
| + |
| +func TestReadBootstrapDeletesFile(t *testing.T) { |
| + addr := netip.MustParseAddrPort("127.0.0.1:8443") |
| + boot := netip.MustParseAddrPort("127.0.0.1:8444") |
| + b := hostedwire.BootstrapV2{Version: hostedwire.BootstrapV2Version, Purpose: hostedwire.PurposeChecks, LaunchID: "l-1", |
| + AttemptID: "a-1", InstanceCode: instanceCode, ProxyCode: proxytest.ProxyCode, Proxies: []netip.AddrPort{addr}, |
| + ProxyBoot: []netip.AddrPort{boot}, ProxyCAPin: strings.Repeat("ab", 32), |
| + Services: []hostedwire.Service{{Host: "instance.example.test", Port: 443, Class: hostedwire.ServiceInstance}}} |
| + path := filepath.Join(t.TempDir(), hostedwire.BootstrapFile) |
| + write := func(f hostedwire.RunnerBootstrap) { |
| + raw, err := json.Marshal(f) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := os.WriteFile(path, raw, 0o600); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + gone := func(what string) { |
| + if _, err := os.Lstat(path); !errors.Is(err, os.ErrNotExist) { |
| + t.Errorf("%s: the bootstrap file is still there (%v)", what, err) |
| + } |
| + } |
| + write(hostedwire.RunnerBootstrap{VMRef: "vm-1", Bootstrap: b}) |
| + got, vm, err := hosted.ReadBootstrap(path) |
| + if err != nil || vm != "vm-1" || !reflect.DeepEqual(got, b) { |
| + t.Fatalf("ReadBootstrap = %+v, %q, %v; want the file's bootstrap and VM", got, vm, err) |
| + } |
| + gone("after a read") |
| + // A file that breaks a rule is refused, and deleted all the same: its |
| + // codes are not left behind. |
| + bad := b |
| + bad.ProxyCode = "short" |
| + write(hostedwire.RunnerBootstrap{VMRef: "vm-1", Bootstrap: bad}) |
| + if _, _, err := hosted.ReadBootstrap(path); err == nil { |
| + t.Error("a bootstrap with a malformed proxy code was accepted") |
| + } |
| + gone("after a refusal") |
| + write(hostedwire.RunnerBootstrap{VMRef: "vm 1", Bootstrap: b}) |
| + if _, _, err := hosted.ReadBootstrap(path); err == nil { |
| + t.Error("a malformed VM ID was accepted") |
| + } |
| + gone("after a bad VM ID") |
| + if _, _, err := hosted.ReadBootstrap(path); err == nil { |
| + t.Error("a missing file was read") |
| + } |
| +} |
| + |
| +// keyFile reads one of the session's key files, which must be 0600. |
| +func keyFile(t *testing.T, state, name string) any { |
| + t.Helper() |
| + p := filepath.Join(state, name) |
| + st, err := os.Lstat(p) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if st.Mode() != 0o600 { |
| + t.Errorf("%s mode %v, want 0600", name, st.Mode()) |
| + } |
| + raw, _ := os.ReadFile(p) |
| + blk, _ := pem.Decode(raw) |
| + if blk == nil { |
| + t.Fatalf("%s is not PEM", name) |
| + } |
| + k, err := x509.ParsePKCS8PrivateKey(blk.Bytes) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return k |
| +} |
| + |
| +// Start redeems the proxy code with a CSR naming nothing (the controller |
| +// sets the identity), then enrols with the instance code, the VM's ID and |
| +// the machine key; both keys are made here and kept 0600 in the state |
| +// directory. |
| +func TestEnrolSendsVMRefAndKey(t *testing.T) { |
| + h := proxytest.New(t) |
| + f := enrolOn(h) |
| + state := t.TempDir() |
| + s, err := start(t, bootstrap(h), state) |
| + if err != nil { |
| + t.Fatalf("Start: %v", err) |
| + } |
| + got := f.requests() |
| + if len(got) != 1 { |
| + t.Fatalf("%d enrolments, want 1", len(got)) |
| + } |
| + q := got[0] |
| + if q.Code != instanceCode || q.LaunchID != proxytest.LaunchID || q.VMRef != string(proxytest.VMRef) { |
| + t.Errorf("enrolment %+v, want the instance code, launch %s and VM %s", q, proxytest.LaunchID, proxytest.VMRef) |
| + } |
| + machine, ok := keyFile(t, state, hosted.MachineKeyFile).(ed25519.PrivateKey) |
| + if !ok || !machine.Public().(ed25519.PublicKey).Equal(ed25519.PublicKey(q.MachinePublicKey)) { |
| + t.Errorf("enrolment key %x is not the stored ed25519 machine key's", q.MachinePublicKey) |
| + } |
| + proxyKey, ok := keyFile(t, state, hosted.ProxyKeyFile).(*ecdsa.PrivateKey) |
| + if !ok || proxyKey.Curve != elliptic.P256() { |
| + t.Fatalf("proxy key %T, want ECDSA P-256", proxyKey) |
| + } |
| + redeems := h.Controller.Received("POST /v1/proxy/redeem") |
| + if len(redeems) != 1 { |
| + t.Fatalf("%d redemptions, want 1", len(redeems)) |
| + } |
| + var rq hostedwire.RedeemRequest |
| + if err := json.Unmarshal(redeems[0].Body, &rq); err != nil { |
| + t.Fatal(err) |
| + } |
| + csr, err := x509.ParseCertificateRequest(rq.CSR) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if len(csr.Subject.Names) != 0 || len(csr.DNSNames)+len(csr.IPAddresses)+len(csr.URIs)+len(csr.EmailAddresses) != 0 || len(csr.Extensions) != 0 { |
| + t.Errorf("the CSR names %q %v %v %v %v; want no identity fields", csr.Subject, csr.DNSNames, csr.IPAddresses, csr.URIs, csr.EmailAddresses) |
| + } |
| + if pub, ok := csr.PublicKey.(*ecdsa.PublicKey); !ok || !pub.Equal(&proxyKey.PublicKey) { |
| + t.Error("the CSR is not for the stored proxy key") |
| + } |
| + if rq.LaunchID != proxytest.LaunchID || rq.VMRef != proxytest.VMRef || rq.ProxyCode != proxytest.ProxyCode { |
| + t.Errorf("redemption %+v", rq) |
| + } |
| + if s.Token() != "bearer-1" || s.Origin() != "https://"+proxytest.Host { |
| + t.Errorf("session token %q origin %q", s.Token(), s.Origin()) |
| + } |
| +} |
| + |
| +// The controller refuses the proxy code until it has seen the VM running |
| +// (up to a minute after boot): Start keeps asking, with backoff, within |
| +// its patience, and gives up after it. |
| +func TestStartRetriesEarlyRedeem(t *testing.T) { |
| + notYet := func(h *proxytest.Harness, stopped bool) { |
| + h.Controller.SetLaunch(proxytest.Launch{LaunchID: proxytest.LaunchID, AttemptID: proxytest.AttemptID, VMRef: proxytest.VMRef, |
| + Epoch: proxytest.Epoch, Code: proxytest.ProxyCode, Stopped: stopped, |
| + Services: []hostedwire.Service{{Host: proxytest.Host, Port: 443, Class: hostedwire.ServiceInstance}}}) |
| + } |
| + t.Run("opens later", func(t *testing.T) { |
| + hosted.SetRedeemTiming(t, 20*time.Second, 50*time.Millisecond) |
| + h := proxytest.New(t) |
| + f := enrolOn(h) |
| + notYet(h, true) |
| + done := make(chan error, 1) |
| + go func() { _, err := start(t, bootstrap(h), t.TempDir()); done <- err }() |
| + for deadline := time.Now().Add(10 * time.Second); len(h.Controller.Received("POST /v1/proxy/redeem")) < 3; time.Sleep(10 * time.Millisecond) { |
| + if time.Now().After(deadline) { |
| + t.Fatal("Start did not ask again after a refusal") |
| + } |
| + } |
| + notYet(h, false) |
| + if err := <-done; err != nil || len(f.requests()) != 1 { |
| + t.Fatalf("Start after the window opened: %v, %d enrolments", err, len(f.requests())) |
| + } |
| + }) |
| + t.Run("never opens", func(t *testing.T) { |
| + hosted.SetRedeemTiming(t, 1500*time.Millisecond, 50*time.Millisecond) |
| + h := proxytest.New(t) |
| + f := enrolOn(h) |
| + notYet(h, true) |
| + began := time.Now() |
| + if _, err := start(t, bootstrap(h), t.TempDir()); err == nil { |
| + t.Fatal("Start succeeded with the code refused throughout") |
| + } |
| + if took, n := time.Since(began), len(h.Controller.Received("POST /v1/proxy/redeem")); took < time.Second || n < 2 { |
| + t.Errorf("gave up after %v and %d redemptions, want its patience and retries", took, n) |
| + } |
| + if len(f.requests()) != 0 { |
| + t.Error("enrolled without a proxy certificate") |
| + } |
| + }) |
| +} |
| + |
| +// Each connection goes to the first proxy that answers: a dead first |
| +// proxy costs only its dial, for requests and for Start alike. |
| +func TestTransportFailsOver(t *testing.T) { |
| + h := proxytest.New(t) |
| + vm := h.Issue(t, proxytest.LaunchID) |
| + dead := deadAddr(t) |
| + c := hosted.NewHTTPClient([]netip.AddrPort{dead, h.Proxy.EgressAddr()}, h.InterceptPin, func() *tls.Certificate { return &vm.Cert }) |
| + if status, body, err := get(c, protocolURL); err != nil || status != http.StatusOK || body != "protocol 39" { |
| + t.Fatalf("GET through the second proxy = %d %q, %v", status, body, err) |
| + } |
| + f := enrolOn(h) |
| + b := bootstrap(h) |
| + b.Proxies = []netip.AddrPort{dead, h.Proxy.EgressAddr()} |
| + b.ProxyBoot = []netip.AddrPort{dead, h.Proxy.BootAddr()} |
| + s, err := start(t, b, t.TempDir()) |
| + if err != nil || len(f.requests()) != 1 { |
| + t.Fatalf("Start with the first proxy down: %v, %d enrolments", err, len(f.requests())) |
| + } |
| + if status, _, err := get(s.HTTPClient(), protocolURL); err != nil || status != http.StatusOK { |
| + t.Errorf("the session's client = %d, %v", status, err) |
| + } |
| +} |
| + |
| +// testCA is a CA the test controls. |
| +type testCA struct { |
| + key *ecdsa.PrivateKey |
| + cert *x509.Certificate |
| +} |
| + |
| +func newTestCA(t *testing.T) testCA { |
| + k, c := proxytest.NewCA(t) |
| + return testCA{k, c} |
| +} |
| + |
| +func (ca testCA) pin() string { |
| + sum := sha256.Sum256(ca.cert.RawSubjectPublicKeyInfo) |
| + return hex.EncodeToString(sum[:]) |
| +} |
| + |
| +var serial atomic.Int64 |
| + |
| +// leaf is a server certificate for name (an IP or a DNS name) signed by |
| +// ca, sent with chain after it. |
| +func (ca testCA) leaf(t *testing.T, name string, chain ...*x509.Certificate) tls.Certificate { |
| + t.Helper() |
| + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + tmpl := &x509.Certificate{SerialNumber: big.NewInt(serial.Add(1)), NotBefore: time.Now().Add(-time.Hour), |
| + NotAfter: time.Now().Add(time.Hour), ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}} |
| + if ip := net.ParseIP(name); ip != nil { |
| + tmpl.IPAddresses = []net.IP{ip} |
| + } else { |
| + tmpl.DNSNames = []string{name} |
| + } |
| + der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.cert, &key.PublicKey, ca.key) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + out := tls.Certificate{Certificate: [][]byte{der}, PrivateKey: key} |
| + for _, c := range chain { |
| + out.Certificate = append(out.Certificate, c.Raw) |
| + } |
| + return out |
| +} |
| + |
| +// fakeProxy is an egress proxy with chosen certificates: outer for its |
| +// listener, inner for the CONNECT host. It counts the requests that reach |
| +// it inside a tunnel and answers each "ok". |
| +func fakeProxy(t *testing.T, outer, inner tls.Certificate) (netip.AddrPort, *atomic.Int64) { |
| + t.Helper() |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { ln.Close() }) |
| + var requests atomic.Int64 |
| + go func() { |
| + for { |
| + raw, err := ln.Accept() |
| + if err != nil { |
| + return |
| + } |
| + go func() { |
| + defer raw.Close() |
| + _ = raw.SetDeadline(time.Now().Add(10 * time.Second)) |
| + o := tls.Server(raw, &tls.Config{Certificates: []tls.Certificate{outer}, NextProtos: []string{"http/1.1"}, ClientAuth: tls.RequestClientCert}) |
| + br := bufio.NewReader(o) |
| + if req, err := http.ReadRequest(br); err != nil || req.Method != http.MethodConnect { |
| + return |
| + } |
| + _, _ = io.WriteString(o, "HTTP/1.1 200 Connection established\r\n\r\n") |
| + i := tls.Server(&readConn{Conn: o, r: br}, &tls.Config{Certificates: []tls.Certificate{inner}, NextProtos: []string{"http/1.1"}}) |
| + ibr := bufio.NewReader(i) |
| + if _, err := http.ReadRequest(ibr); err != nil { |
| + return |
| + } |
| + requests.Add(1) |
| + _, _ = io.WriteString(i, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nok") |
| + }() |
| + } |
| + }() |
| + return ln.Addr().(*net.TCPAddr).AddrPort(), &requests |
| +} |
| + |
| +type readConn struct { |
| + net.Conn |
| + r *bufio.Reader |
| +} |
| + |
| +func (c *readConn) Read(p []byte) (int, error) { return c.r.Read(p) } |
| + |
| +// Both TLS layers trust the pinned intercept CA alone: a proxy presenting |
| +// another CA, at either layer, or a chain that carries the pinned CA |
| +// after a leaf another CA signed, is refused before any request is sent. |
| +func TestTransportPinsInterceptCA(t *testing.T) { |
| + pinned, other := newTestCA(t), newTestCA(t) |
| + outerOK := pinned.leaf(t, "127.0.0.1", pinned.cert) |
| + innerOK := pinned.leaf(t, proxytest.Host, pinned.cert) |
| + cases := []struct { |
| + name string |
| + outer, inner tls.Certificate |
| + pass bool |
| + }{ |
| + {"the pinned CA at both layers", outerOK, innerOK, true}, |
| + {"another CA inside the tunnel", outerOK, other.leaf(t, proxytest.Host, other.cert), false}, |
| + {"another CA at the proxy", other.leaf(t, "127.0.0.1", other.cert), innerOK, false}, |
| + {"another CA's leaf before the pinned CA, inside", outerOK, other.leaf(t, proxytest.Host, pinned.cert), false}, |
| + {"another CA's leaf before the pinned CA, at the proxy", other.leaf(t, "127.0.0.1", pinned.cert), innerOK, false}, |
| + {"the pinned CA's leaf for another host", outerOK, pinned.leaf(t, proxytest.OtherHost, pinned.cert), false}, |
| + } |
| + for _, tc := range cases { |
| + addr, requests := fakeProxy(t, tc.outer, tc.inner) |
| + c := hosted.NewHTTPClient([]netip.AddrPort{addr}, pinned.pin(), nil) |
| + status, body, err := get(c, protocolURL) |
| + if tc.pass != (err == nil && status == http.StatusOK && body == "ok") || !tc.pass && requests.Load() != 0 { |
| + t.Errorf("%s: %d %q, %v, %d requests reached the tunnel", tc.name, status, body, err, requests.Load()) |
| + } |
| + } |
| + // The real proxy, pinned to another proxy's CA: refused, and the |
| + // origin sees nothing; the same request with its own pin passes. |
| + h, h2 := proxytest.New(t), proxytest.New(t) |
| + vm := h.Issue(t, proxytest.LaunchID) |
| + cert := func() *tls.Certificate { return &vm.Cert } |
| + if _, _, err := get(hosted.NewHTTPClient([]netip.AddrPort{h.Proxy.EgressAddr()}, h2.InterceptPin, cert), protocolURL); err == nil { |
| + t.Error("a proxy whose CA is not the pinned one was trusted") |
| + } |
| + if origin, _ := h.Hits(); origin != 0 { |
| + t.Errorf("the origin saw %d requests", origin) |
| + } |
| + if status, _, err := get(hosted.NewHTTPClient([]netip.AddrPort{h.Proxy.EgressAddr()}, h.InterceptPin, cert), protocolURL); err != nil || status != http.StatusOK { |
| + t.Errorf("with the proxy's own pin: %d, %v", status, err) |
| + } |
| + // And the redemption: a bootstrap listener whose CA is not the |
| + // pinned one never receives the proxy code. |
| + hosted.SetRedeemTiming(t, 300*time.Millisecond, 50*time.Millisecond) |
| + b := bootstrap(h) |
| + b.ProxyCAPin = h2.InterceptPin |
| + if _, err := start(t, b, t.TempDir()); err == nil { |
| + t.Error("Start redeemed through a proxy whose CA is not the pinned one") |
| + } |
| + if n := len(h.Controller.Received("POST /v1/proxy/redeem")); n != 0 { |
| + t.Errorf("the controller got %d redemptions", n) |
| + } |
| +} |
| + |
| +// With both proxies down, nothing reaches the instance any other way: no |
| +// direct dial, no environment proxy, no plain HTTP, no port but 443. |
| +func TestNoDirectDial(t *testing.T) { |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer ln.Close() |
| + var accepted atomic.Int64 |
| + go func() { |
| + for { |
| + c, err := ln.Accept() |
| + if err != nil { |
| + return |
| + } |
| + accepted.Add(1) |
| + c.Close() |
| + } |
| + }() |
| + inst := ln.Addr().String() |
| + for _, v := range []string{"HTTPS_PROXY", "HTTP_PROXY", "ALL_PROXY", "https_proxy", "http_proxy"} { |
| + t.Setenv(v, "http://"+inst) |
| + } |
| + t.Setenv("NO_PROXY", "") |
| + dead1, dead2 := deadAddr(t), deadAddr(t) |
| + c := hosted.NewHTTPClient([]netip.AddrPort{dead1, dead2}, strings.Repeat("ab", 32), nil) |
| + for _, url := range []string{protocolURL, "https://" + inst + "/api/runner/protocol", "http://" + inst + "/api/runner/protocol", |
| + "http://" + proxytest.Host + "/api/runner/protocol"} { |
| + if status, _, err := get(c, url); err == nil { |
| + t.Errorf("GET %s answered %d with both proxies down", url, status) |
| + } |
| + } |
| + hosted.SetRedeemTiming(t, 300*time.Millisecond, 50*time.Millisecond) |
| + b := hostedwire.BootstrapV2{Version: hostedwire.BootstrapV2Version, Purpose: hostedwire.PurposeChecks, LaunchID: "l-1", |
| + AttemptID: "a-1", InstanceCode: instanceCode, ProxyCode: proxytest.ProxyCode, Proxies: []netip.AddrPort{dead1, dead2}, |
| + ProxyBoot: []netip.AddrPort{dead1, dead2}, ProxyCAPin: strings.Repeat("ab", 32), |
| + Services: []hostedwire.Service{{Host: proxytest.Host, Port: 443, Class: hostedwire.ServiceInstance}}} |
| + if _, err := start(t, b, t.TempDir()); err == nil { |
| + t.Error("Start succeeded with both proxies down") |
| + } |
| + if n := accepted.Load(); n != 0 { |
| + t.Errorf("the instance's address was dialled directly %d times", n) |
| + } |
| +} |
| + |
| +// The real Link, given the session's token source and client, reaches a |
| +// fake instance's runner stream through the real proxy over TLS, and the |
| +// proxy logs it as the instance class's stream. |
| +func TestRealLinkThroughProxy(t *testing.T) { |
| + h := proxytest.New(t) |
| + enrolOn(h) |
| + s, err := start(t, bootstrap(h), t.TempDir()) |
| + if err != nil { |
| + t.Fatalf("Start: %v", err) |
| + } |
| + hellos := make(chan string, 4) |
| + h.Handle(wire.StreamPath, func(w http.ResponseWriter, r *http.Request) { |
| + if r.Header.Get("Authorization") != "Bearer "+s.Token() { |
| + http.Error(w, "forbidden", http.StatusForbidden) |
| + return |
| + } |
| + c, err := websocket.Accept(w, r, nil) |
| + if err != nil { |
| + return |
| + } |
| + defer c.CloseNow() |
| + _, msg, err := c.Read(r.Context()) |
| + if err != nil { |
| + return |
| + } |
| + f, _, _ := wire.ParseFrame(msg) |
| + hellos <- f.Type |
| + c.Close(websocket.StatusNormalClosure, "") |
| + }) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + state, err := thin.OpenState(ctx, t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + link := &thin.Link{Origin: s.Origin(), TokenSource: s.Token, HTTPClient: s.HTTPClient(), State: state, Role: wire.RoleWorker, |
| + Logger: slog.New(slog.NewTextHandler(io.Discard, nil)), |
| + Hello: func() wire.Hello { |
| + return wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Versions: map[string]string{"runner": "test"}} |
| + }} |
| + done := make(chan struct{}) |
| + go func() { defer close(done); _ = link.Run(ctx) }() |
| + defer func() { cancel(); <-done; state.Close() }() |
| + select { |
| + case kind := <-hellos: |
| + if kind != wire.FrameHello { |
| + t.Fatalf("the instance's stream got %q first, want the hello", kind) |
| + } |
| + case <-time.After(15 * time.Second): |
| + t.Fatal("the link never reached the instance's stream through the proxy") |
| + } |
| + h.Log.Wait(t, "the stream through the proxy", 0, func(l proxytest.LogLine) bool { |
| + return l.Method == http.MethodGet && l.PathClass == hostedwire.ServiceInstance && l.Decision == "allow" && |
| + l.VM == string(proxytest.VMRef) && l.Status == http.StatusSwitchingProtocols |
| + }) |
| +} |
diff --git a/internal/runner/hosted/redeem.go b/internal/runner/hosted/redeem.go| new file mode 100644 |
| index 00000000..11565711 |
| --- /dev/null |
| +++ b/internal/runner/hosted/redeem.go |
| @@ -0,0 +1,190 @@ |
| +package hosted |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "crypto/ecdsa" |
| + "crypto/rand" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "net" |
| + "net/http" |
| + "net/netip" |
| + "slices" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy" |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| + "amadan.net/oficina/equipo/internal/isolatedjob" |
| +) |
| + |
| +// The controller opens the proxy code's window only at the first refresh |
| +// that sees the VM running, up to a minute after boot, and refuses the |
| +// code until then. Start asks again with backoff, from redeemFirstWait |
| +// doubling to redeemMaxWait, until redeemPatience has passed (a last ask |
| +// at its end). |
| +var ( |
| + redeemPatience = 3 * time.Minute |
| + redeemFirstWait = time.Second |
| +) |
| + |
| +const ( |
| + redeemMaxWait = 10 * time.Second |
| + // bootTimeout bounds one call to a bootstrap listener. |
| + bootTimeout = 30 * time.Second |
| +) |
| + |
| +// ErrRedeem is a proxy code Start could not trade for a certificate. |
| +var ErrRedeem = errors.New("hosted: proxy code not redeemed") |
| + |
| +// bootClient calls the proxies' bootstrap listeners: server TLS pinned to |
| +// the intercept CA, the current client certificate when there is one, and |
| +// no address but the bootstrap's. |
| +func bootClient(boot []netip.AddrPort, pin pinnedCA, cert func() *tls.Certificate) *http.Client { |
| + d := &proxyDialer{pin: pin, cert: cert} |
| + dial := func(ctx context.Context, _, addr string) (net.Conn, error) { |
| + ap, err := netip.ParseAddrPort(addr) |
| + if err != nil || !slices.Contains(boot, ap) { |
| + return nil, fmt.Errorf("%w: %q is not a bootstrap listener", ErrTransport, addr) |
| + } |
| + var nd net.Dialer |
| + raw, err := nd.DialContext(ctx, "tcp", addr) |
| + if err != nil { |
| + return nil, err |
| + } |
| + cfg := pin.tlsConfig(ap.Addr().String()) |
| + cfg.GetClientCertificate = d.clientCert |
| + c := tls.Client(raw, cfg) |
| + if err := c.HandshakeContext(ctx); err != nil { |
| + raw.Close() |
| + return nil, err |
| + } |
| + return c, nil |
| + } |
| + return &http.Client{ |
| + Transport: &http.Transport{Proxy: nil, DialTLSContext: dial, |
| + DialContext: func(context.Context, string, string) (net.Conn, error) { return nil, errPlainDial }, |
| + TLSNextProto: map[string]func(string, *tls.Conn) http.RoundTripper{}, ResponseHeaderTimeout: bootTimeout}, |
| + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, |
| + } |
| +} |
| + |
| +// postBoot posts body to path on one bootstrap listener and returns the |
| +// status and the answer. |
| +func postBoot(ctx context.Context, c *http.Client, boot netip.AddrPort, path string, body []byte) (int, []byte, error) { |
| + ctx, cancel := context.WithTimeout(ctx, bootTimeout) |
| + defer cancel() |
| + req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://"+boot.String()+path, bytes.NewReader(body)) |
| + if err != nil { |
| + return 0, nil, err |
| + } |
| + req.Header.Set("Content-Type", "application/json") |
| + resp, err := c.Do(req) |
| + if err != nil { |
| + return 0, nil, err |
| + } |
| + defer resp.Body.Close() |
| + out, err := io.ReadAll(io.LimitReader(resp.Body, hostedwire.MaxBody+1)) |
| + if err != nil { |
| + return 0, nil, err |
| + } |
| + if len(out) > hostedwire.MaxBody { |
| + return 0, nil, errors.New("the answer is too large") |
| + } |
| + return resp.StatusCode, out, nil |
| +} |
| + |
| +// retryable: an answer that may change if asked again. The controller |
| +// answers every refusal alike (403), the code not yet valid among them; |
| +// 429 and 5xx are a busy or unreachable controller. Anything else (a 400 |
| +// for a malformed request) will not change. |
| +func retryable(status int) bool { |
| + return status == http.StatusForbidden || status == http.StatusTooManyRequests || status >= 500 |
| +} |
| + |
| +// csrFor is a certificate request for key that names nothing: the |
| +// controller sets the certificate's only name, the launch URI. |
| +func csrFor(key *ecdsa.PrivateKey) ([]byte, error) { |
| + return x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{}, key) |
| +} |
| + |
| +// redeem trades b's proxy code for a client certificate for key, asking |
| +// each bootstrap listener in turn, and again within redeemPatience while |
| +// the answer may change. It returns the certificate and the epoch it |
| +// names. |
| +func redeem(ctx context.Context, c *http.Client, b hostedwire.BootstrapV2, vm isolatedjob.Ref, key *ecdsa.PrivateKey) (tls.Certificate, int64, error) { |
| + csr, err := csrFor(key) |
| + if err != nil { |
| + return tls.Certificate{}, 0, fmt.Errorf("%w: certificate request: %w", ErrRedeem, err) |
| + } |
| + body, err := json.Marshal(hostedwire.RedeemRequest{LaunchID: b.LaunchID, VMRef: vm, ProxyCode: b.ProxyCode, CSR: csr}) |
| + if err != nil { |
| + return tls.Certificate{}, 0, err |
| + } |
| + giveUp := time.Now().Add(redeemPatience) |
| + wait := redeemFirstWait |
| + var last error |
| + for { |
| + for _, boot := range b.ProxyBoot { |
| + status, out, err := postBoot(ctx, c, boot, "/redeem", body) |
| + switch { |
| + case err != nil: |
| + last = fmt.Errorf("bootstrap listener %s: %w", boot, err) |
| + continue // the next proxy |
| + case status == http.StatusOK: |
| + return acceptCert(out, b, vm, key) |
| + } |
| + var e hostedwire.ErrorResponse |
| + _ = json.Unmarshal(out, &e) |
| + last = fmt.Errorf("bootstrap listener %s answered %d %q", boot, status, e.Code) |
| + if !retryable(status) { |
| + return tls.Certificate{}, 0, fmt.Errorf("%w: %w", ErrRedeem, last) |
| + } |
| + break // both proxies ask the same controller |
| + } |
| + left := time.Until(giveUp) |
| + if left <= 0 { |
| + return tls.Certificate{}, 0, fmt.Errorf("%w after %v: %w", ErrRedeem, redeemPatience, last) |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return tls.Certificate{}, 0, fmt.Errorf("%w: %w (last: %w)", ErrRedeem, ctx.Err(), last) |
| + case <-time.After(min(wait, left)): |
| + } |
| + wait = min(2*wait, redeemMaxWait) |
| + } |
| +} |
| + |
| +// acceptCert checks the controller's answer: a client certificate, valid |
| +// now, for key, naming exactly b's launch and attempt and vm. |
| +func acceptCert(out []byte, b hostedwire.BootstrapV2, vm isolatedjob.Ref, key *ecdsa.PrivateKey) (tls.Certificate, int64, error) { |
| + bad := func(what string) (tls.Certificate, int64, error) { |
| + return tls.Certificate{}, 0, fmt.Errorf("%w: the certificate %s", ErrRedeem, what) |
| + } |
| + var r hostedwire.RedeemResponse |
| + if err := hostedwire.DecodeStrict(bytes.NewReader(out), &r); err != nil { |
| + return bad("answer does not decode") |
| + } |
| + leaf, err := x509.ParseCertificate(r.Cert) |
| + if err != nil { |
| + return bad("does not parse") |
| + } |
| + if pub, ok := leaf.PublicKey.(*ecdsa.PublicKey); !ok || !pub.Equal(&key.PublicKey) { |
| + return bad("is not for this VM's proxy key") |
| + } |
| + if now := time.Now(); now.After(leaf.NotAfter) || !slices.Contains(leaf.ExtKeyUsage, x509.ExtKeyUsageClientAuth) { |
| + return bad("is expired or not a client certificate") |
| + } |
| + if len(leaf.URIs) != 1 { |
| + return bad("does not name one launch") |
| + } |
| + id, err := ctlproxy.ParseLaunchURI(leaf.URIs[0]) |
| + if err != nil || id.LaunchID != b.LaunchID || id.AttemptID != b.AttemptID || id.VMRef != vm { |
| + return bad("names another launch, attempt or VM") |
| + } |
| + return tls.Certificate{Certificate: [][]byte{r.Cert}, PrivateKey: key, Leaf: leaf}, id.Epoch, nil |
| +} |
diff --git a/internal/runner/hosted/transport.go b/internal/runner/hosted/transport.go| new file mode 100644 |
| index 00000000..a621d60b |
| --- /dev/null |
| +++ b/internal/runner/hosted/transport.go |
| @@ -0,0 +1,210 @@ |
| +// Package hosted is a hosted runner's way out of its VM: it reads the |
| +// bootstrap vm-init left, redeems the proxy code for a client certificate |
| +// at the egress proxy's bootstrap listener, enrols with the instance, and |
| +// gives the runner an HTTP client whose every connection goes through the |
| +// proxy. Nothing here dials anything but a proxy. |
| +package hosted |
| + |
| +import ( |
| + "bufio" |
| + "context" |
| + "crypto/sha256" |
| + "crypto/subtle" |
| + "crypto/tls" |
| + "crypto/x509" |
| + "encoding/hex" |
| + "errors" |
| + "fmt" |
| + "net" |
| + "net/http" |
| + "net/netip" |
| + "time" |
| +) |
| + |
| +// alpnHTTP11 is the one application protocol the proxy speaks, at both |
| +// TLS layers. |
| +const alpnHTTP11 = "http/1.1" |
| + |
| +// servicePort is the one port a VM may reach through the proxy. |
| +const servicePort = "443" |
| + |
| +// proxyTimeout bounds one proxy's dial, TLS, CONNECT and the inner TLS. |
| +const proxyTimeout = 15 * time.Second |
| + |
| +// ErrTransport is a connection the hosted transport would not open, or |
| +// could not open through any proxy. |
| +var ErrTransport = errors.New("hosted: no connection through the proxy") |
| + |
| +// errPlainDial refuses every connection that is not TLS through a proxy. |
| +var errPlainDial = fmt.Errorf("%w: plain connections are not made", ErrTransport) |
| + |
| +// pinnedCA checks a TLS peer's chain against the intercept CA's pin: the |
| +// CA must be in the chain after the leaf, its SPKI's SHA-256 must be the |
| +// pin, and the leaf must verify for name with that CA as its only root |
| +// and no intermediates. The system roots are never consulted. |
| +type pinnedCA []byte |
| + |
| +func parsePin(s string) pinnedCA { |
| + p, err := hex.DecodeString(s) |
| + if err != nil || len(p) != sha256.Size { |
| + return nil |
| + } |
| + return p |
| +} |
| + |
| +func (p pinnedCA) verify(name string, certs []*x509.Certificate) error { |
| + if len(p) != sha256.Size { |
| + return errors.New("hosted: no valid intercept CA pin") |
| + } |
| + if len(certs) == 0 { |
| + return errors.New("hosted: the peer sent no certificate") |
| + } |
| + var ca *x509.Certificate |
| + for _, c := range certs[1:] { |
| + sum := sha256.Sum256(c.RawSubjectPublicKeyInfo) |
| + if subtle.ConstantTimeCompare(sum[:], p) == 1 { |
| + ca = c |
| + } |
| + } |
| + if ca == nil { |
| + return errors.New("hosted: the peer's chain does not carry the pinned intercept CA") |
| + } |
| + roots := x509.NewCertPool() |
| + roots.AddCert(ca) |
| + _, err := certs[0].Verify(x509.VerifyOptions{Roots: roots, DNSName: name, |
| + KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}}) |
| + if err != nil { |
| + return fmt.Errorf("hosted: the peer's certificate does not verify under the pinned intercept CA: %w", err) |
| + } |
| + return nil |
| +} |
| + |
| +// tlsConfig is the client side of either TLS layer: name checked against |
| +// the pinned CA alone, HTTP/1.1, TLS 1.2 at least. The standard chain |
| +// check is off only because VerifyConnection does it with the pinned CA |
| +// as the one root (the CA is not known before the handshake; its pin is). |
| +func (p pinnedCA) tlsConfig(name string) *tls.Config { |
| + return &tls.Config{MinVersion: tls.VersionTLS12, ServerName: name, NextProtos: []string{alpnHTTP11}, |
| + InsecureSkipVerify: true, |
| + VerifyConnection: func(cs tls.ConnectionState) error { return p.verify(name, cs.PeerCertificates) }} |
| +} |
| + |
| +// proxyDialer opens connections to service hosts through the egress |
| +// proxies: mutual TLS to the first proxy that answers, CONNECT host:443, |
| +// then TLS to host inside the tunnel. |
| +type proxyDialer struct { |
| + proxies []netip.AddrPort |
| + pin pinnedCA |
| + cert func() *tls.Certificate |
| +} |
| + |
| +// clientCert sends the current certificate whatever CAs the proxy names |
| +// (the proxy alone judges it), or none. |
| +func (d *proxyDialer) clientCert(*tls.CertificateRequestInfo) (*tls.Certificate, error) { |
| + if d.cert != nil { |
| + if c := d.cert(); c != nil { |
| + return c, nil |
| + } |
| + } |
| + return &tls.Certificate{}, nil |
| +} |
| + |
| +func (d *proxyDialer) dialTLS(ctx context.Context, _, addr string) (net.Conn, error) { |
| + host, port, err := net.SplitHostPort(addr) |
| + if err != nil || port != servicePort || host == "" { |
| + return nil, fmt.Errorf("%w: %q is not a host on port %s", ErrTransport, addr, servicePort) |
| + } |
| + var errs []error |
| + for _, p := range d.proxies { |
| + c, err := d.through(ctx, p, host) |
| + if err == nil { |
| + return c, nil |
| + } |
| + errs = append(errs, fmt.Errorf("proxy %s: %w", p, err)) |
| + if ctx.Err() != nil { |
| + break |
| + } |
| + } |
| + return nil, fmt.Errorf("%w: %s: %w", ErrTransport, host, errors.Join(errs...)) |
| +} |
| + |
| +// through opens one tunnel to host through proxy p. |
| +func (d *proxyDialer) through(ctx context.Context, p netip.AddrPort, host string) (net.Conn, error) { |
| + ctx, cancel := context.WithTimeout(ctx, proxyTimeout) |
| + defer cancel() |
| + var nd net.Dialer |
| + raw, err := nd.DialContext(ctx, "tcp", p.String()) |
| + if err != nil { |
| + return nil, err |
| + } |
| + ok := false |
| + defer func() { |
| + if !ok { |
| + raw.Close() |
| + } |
| + }() |
| + if dl, has := ctx.Deadline(); has { |
| + _ = raw.SetDeadline(dl) |
| + } |
| + outerCfg := d.pin.tlsConfig(p.Addr().String()) |
| + outerCfg.GetClientCertificate = d.clientCert |
| + outer := tls.Client(raw, outerCfg) |
| + if err := outer.HandshakeContext(ctx); err != nil { |
| + return nil, err |
| + } |
| + target := net.JoinHostPort(host, servicePort) |
| + if _, err := fmt.Fprintf(outer, "CONNECT %s HTTP/1.1\r\nHost: %s\r\n\r\n", target, target); err != nil { |
| + return nil, err |
| + } |
| + br := bufio.NewReader(outer) |
| + resp, err := http.ReadResponse(br, &http.Request{Method: http.MethodConnect}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + if resp.StatusCode != http.StatusOK { |
| + resp.Body.Close() |
| + return nil, fmt.Errorf("CONNECT %s answered %d", target, resp.StatusCode) |
| + } |
| + inner := tls.Client(&bufferedConn{Conn: outer, r: br}, d.pin.tlsConfig(host)) |
| + if err := inner.HandshakeContext(ctx); err != nil { |
| + return nil, err |
| + } |
| + if inner.ConnectionState().NegotiatedProtocol != alpnHTTP11 { |
| + return nil, errors.New("the tunnel did not agree on HTTP/1.1") |
| + } |
| + _ = raw.SetDeadline(time.Time{}) |
| + ok = true |
| + return inner, nil |
| +} |
| + |
| +// bufferedConn reads through r, which may hold bytes already read from |
| +// Conn. |
| +type bufferedConn struct { |
| + net.Conn |
| + r *bufio.Reader |
| +} |
| + |
| +func (c *bufferedConn) Read(b []byte) (int, error) { return c.r.Read(b) } |
| + |
| +// NewHTTPClient is a hosted runner's HTTP client: no environment proxy, |
| +// no plain connection, and every connection opened through the first of |
| +// proxies (egress listeners, in order) that answers, as mutual TLS with |
| +// cert's certificate (nil: none), CONNECT host:443, then TLS to host. Both |
| +// TLS layers trust only the intercept CA whose SPKI's hex SHA-256 is |
| +// caPin, and speak HTTP/1.1 only. Redirects are not followed. |
| +func NewHTTPClient(proxies []netip.AddrPort, caPin string, cert func() *tls.Certificate) *http.Client { |
| + d := &proxyDialer{proxies: append([]netip.AddrPort(nil), proxies...), pin: parsePin(caPin), cert: cert} |
| + return &http.Client{ |
| + Transport: &http.Transport{ |
| + Proxy: nil, |
| + DialContext: func(context.Context, string, string) (net.Conn, error) { |
| + return nil, errPlainDial |
| + }, |
| + DialTLSContext: d.dialTLS, |
| + ForceAttemptHTTP2: false, |
| + TLSNextProto: map[string]func(string, *tls.Conn) http.RoundTripper{}, |
| + MaxIdleConnsPerHost: 2, IdleConnTimeout: time.Minute, ResponseHeaderTimeout: time.Minute, |
| + }, |
| + CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }, |
| + } |
| +} |
diff --git a/internal/runner/thin/link.go b/internal/runner/thin/link.go| index af8e8090..eda429a4 100644 |
| --- a/internal/runner/thin/link.go |
| +++ b/internal/runner/thin/link.go |
| @@ -71,8 +71,13 @@ const HelloInterval = 30 * time.Second |
| type Link struct { |
| Origin string |
| Token string |
| - State *State |
| - Engine *Engine |
| + // TokenSource, when set, gives the bearer at each dial (a hosted |
| + // runner renews it), and Token is not used. HTTPClient, when set, |
| + // carries the dial (a hosted runner's goes through the proxy). |
| + TokenSource func() string |
| + HTTPClient *http.Client |
| + State *State |
| + Engine *Engine |
| // Steps runs dispatched step attempts; Recheck looks at what the |
| // agent reaches now (a person acted on a grant card). |
| Access *AccessEngine |
| @@ -649,7 +654,11 @@ func (l *Link) handshake(ctx context.Context, offer int) (*websocket.Conn, *wire |
| l.info("connecting", "host", host, "protocol", offer) |
| start := time.Now() |
| dctx, cancel := context.WithTimeout(ctx, 20*time.Second) |
| - c, res, err := websocket.Dial(dctx, url, &websocket.DialOptions{HTTPHeader: http.Header{"Authorization": {"Bearer " + l.Token}}, CompressionMode: websocket.CompressionDisabled}) |
| + token := l.Token |
| + if l.TokenSource != nil { |
| + token = l.TokenSource() |
| + } |
| + c, res, err := websocket.Dial(dctx, url, &websocket.DialOptions{HTTPClient: l.HTTPClient, HTTPHeader: http.Header{"Authorization": {"Bearer " + token}}, CompressionMode: websocket.CompressionDisabled}) |
| cancel() |
| if err != nil { |
| if res != nil && res.StatusCode == http.StatusForbidden { |
diff --git a/internal/runner/thin/link_hooks_test.go b/internal/runner/thin/link_hooks_test.go| new file mode 100644 |
| index 00000000..188452e8 |
| --- /dev/null |
| +++ b/internal/runner/thin/link_hooks_test.go |
| @@ -0,0 +1,101 @@ |
| +package thin |
| + |
| +import ( |
| + "context" |
| + "net" |
| + "net/http" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| + |
| + "amadan.net/oficina/equipo/internal/wire" |
| + "github.com/coder/websocket" |
| +) |
| + |
| +// hookInstance accepts the runner stream, sends each dial's bearer on |
| +// bearers and closes the socket at once, so the link dials again. |
| +func hookInstance(t *testing.T) (string, chan string) { |
| + t.Helper() |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + bearers := make(chan string, 8) |
| + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.URL.Path != wire.StreamPath { |
| + http.NotFound(w, r) |
| + return |
| + } |
| + c, err := websocket.Accept(w, r, nil) |
| + if err != nil { |
| + return |
| + } |
| + bearers <- r.Header.Get("Authorization") |
| + c.Close(websocket.StatusGoingAway, "") |
| + })} |
| + go srv.Serve(ln) |
| + t.Cleanup(func() { srv.Close() }) |
| + return ln.Addr().String(), bearers |
| +} |
| + |
| +// runHookLink runs a bare link (state and hello only) until the test ends. |
| +func runHookLink(t *testing.T, l *Link) { |
| + t.Helper() |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + state, err := OpenState(ctx, t.TempDir()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + l.State = state |
| + l.Hello = func() wire.Hello { |
| + return wire.Hello{Repos: []string{}, CreateIn: []string{}, Catalog: []wire.RepoInfo{}, Versions: map[string]string{"runner": "test"}} |
| + } |
| + done := make(chan struct{}) |
| + go func() { defer close(done); _ = l.Run(ctx) }() |
| + t.Cleanup(func() { cancel(); <-done; state.Close() }) |
| +} |
| + |
| +func nextBearer(t *testing.T, bearers chan string, what string) string { |
| + t.Helper() |
| + select { |
| + case b := <-bearers: |
| + return b |
| + case <-time.After(10 * time.Second): |
| + t.Fatalf("%s: the link never dialled", what) |
| + return "" |
| + } |
| +} |
| + |
| +// A hosted runner's bearer is renewed while it runs: the link asks |
| +// TokenSource on every dial, never a copy made at startup, and Token is |
| +// not used beside it. |
| +func TestLinkReadsTokenEachDial(t *testing.T) { |
| + addr, bearers := hookInstance(t) |
| + var current atomic.Value |
| + current.Store("first") |
| + runHookLink(t, &Link{Origin: "http://" + addr, Token: "startup", TokenSource: func() string { return current.Load().(string) }}) |
| + if got := nextBearer(t, bearers, "first dial"); got != "Bearer first" { |
| + t.Fatalf("first dial sent %q, want the source's first token", got) |
| + } |
| + current.Store("second") |
| + if got := nextBearer(t, bearers, "second dial"); got != "Bearer second" { |
| + t.Fatalf("second dial sent %q, want the source's token at that dial", got) |
| + } |
| +} |
| + |
| +// A hosted runner's link dials through the client it is given (the proxy |
| +// transport); without it the origin here cannot be reached at all. |
| +func TestLinkUsesGivenHTTPClient(t *testing.T) { |
| + addr, bearers := hookInstance(t) |
| + var dials atomic.Int64 |
| + client := &http.Client{Transport: &http.Transport{Proxy: nil, |
| + DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) { |
| + dials.Add(1) |
| + var d net.Dialer |
| + return d.DialContext(ctx, network, addr) |
| + }}} |
| + runHookLink(t, &Link{Origin: "http://link.invalid", Token: "token", HTTPClient: client}) |
| + if got := nextBearer(t, bearers, "dial through the client"); got != "Bearer token" || dials.Load() == 0 { |
| + t.Fatalf("bearer %q after %d dials through the given client", got, dials.Load()) |
| + } |
| +} |
diff --git a/internal/runnerproto/types.go b/internal/runnerproto/types.go| index d79587af..0d0c9f47 100644 |
| --- a/internal/runnerproto/types.go |
| +++ b/internal/runnerproto/types.go |
| @@ -64,6 +64,16 @@ type RunnerCredential struct { |
| Role string `json:"role,omitempty"` |
| } |
| +// HostedEnrolResponse is the instance's answer to a hosted VM's |
| +// enrolment (POST /api/hosted/enrol, wire.HostedEnrolRequest): a worker |
| +// credential bound to one job, and that job's epoch and deadline. The |
| +// credential never outlives the deadline. |
| +type HostedEnrolResponse struct { |
| + Credential RunnerCredential `json:"credential"` |
| + Epoch int64 `json:"epoch"` |
| + Deadline time.Time `json:"deadline"` |
| +} |
| + |
| type ErrorResponse struct { |
| Version int `json:"version"` |
| Error string `json:"error"` |
diff --git a/internal/vminit/hooks.go b/internal/vminit/hooks.go| index ad9a8b20..cf71d5af 100644 |
| --- a/internal/vminit/hooks.go |
| +++ b/internal/vminit/hooks.go |
| @@ -40,15 +40,6 @@ const ( |
| reasonStopping = "terminating" // /terminate came first: no runner starts |
| ) |
| -// RunnerBootstrap is the file vm-init writes for the runner, at |
| -// EnvBootstrap: the launch's bootstrap and the VM's own ID from the /run |
| -// hook. It is the runner user's, mode 0600, and the runner deletes it |
| -// once read (Task 12). |
| -type RunnerBootstrap struct { |
| - VMRef isolatedjob.Ref `json:"vm_ref"` |
| - Bootstrap hostedwire.BootstrapV2 `json:"bootstrap"` |
| -} |
| - |
| // hooks serves the lifecycle hooks. /run happens once: the first call |
| // claims it whatever its outcome, since a failed /run ends the VM. |
| type hooks struct { |
| @@ -258,7 +249,7 @@ func (h *hooks) launch(ctx context.Context, vm isolatedjob.Ref, boot hostedwire. |
| if err := h.own(tmp, acct, 0o700); err != nil { |
| return 0, "", err |
| } |
| - raw, err := json.Marshal(RunnerBootstrap{VMRef: vm, Bootstrap: boot}) |
| + raw, err := json.Marshal(hostedwire.RunnerBootstrap{VMRef: vm, Bootstrap: boot}) |
| if err != nil { |
| return 0, "", fmt.Errorf("bootstrap file: %w", err) |
| } |
diff --git a/internal/vminit/init.go b/internal/vminit/init.go| index deb11913..43ff78b1 100644 |
| --- a/internal/vminit/init.go |
| +++ b/internal/vminit/init.go |
| @@ -32,6 +32,8 @@ import ( |
| "strings" |
| "syscall" |
| "time" |
| + |
| + "amadan.net/oficina/equipo/internal/hostedwire" |
| ) |
| // Config is how the image starts vm-init. |
| @@ -64,14 +66,15 @@ type Config struct { |
| // The runner's launch. |
| const ( |
| - SubcommandChecks = "hosted-run" // purpose "checks" |
| - SubcommandCertify = "hosted-certify" // purpose "certification" |
| - // EnvBootstrap names the runner's bootstrap file (RunnerBootstrap). |
| - EnvBootstrap = "EQUIPO_HOSTED_BOOTSTRAP" |
| + SubcommandChecks = hostedwire.SubcommandChecks |
| + SubcommandCertify = hostedwire.SubcommandCertify |
| + // EnvBootstrap names the runner's bootstrap file |
| + // (hostedwire.RunnerBootstrap). |
| + EnvBootstrap = hostedwire.EnvBootstrap |
| // EnvResults names ResultsDir. |
| - EnvResults = "EQUIPO_HOSTED_RESULTS" |
| + EnvResults = hostedwire.EnvResults |
| // BootstrapFile is the bootstrap's name in StateDir. |
| - BootstrapFile = "bootstrap.json" |
| + BootstrapFile = hostedwire.BootstrapFile |
| // runnerPath is the runner's whole PATH. |
| runnerPath = "/usr/local/bin:/usr/bin:/bin" |
| // selfExe is vm-init's own binary, as measured. |
diff --git a/internal/vminit/init_test.go b/internal/vminit/init_test.go| index fb523108..a1a038d2 100644 |
| --- a/internal/vminit/init_test.go |
| +++ b/internal/vminit/init_test.go |
| @@ -440,7 +440,7 @@ func TestBootstrapFileForRunner(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - var f RunnerBootstrap |
| + var f hostedwire.RunnerBootstrap |
| if err := hostedwire.DecodeStrict(bytes.NewReader(raw), &f); err != nil { |
| t.Fatal(err) |
| } |