oficina / equipo Public

runner: hosted redeem fails over on 5xx; dial seam and guard tests

Review round 1 of Task 12: a bootstrap listener that cannot reach the
controller (502) no longer stops the redemption from asking the next
proxy; every dial goes through one seam so TestNoDirectDial sees each
address tried; negative tests for every enrolment-answer and proxy
certificate guard, with mutations 79 to 92 recorded.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev d06b7a0e01b96a1eb870fa53c1db686f0e5440a7 parent a50e472
7 files changed, +299 −15
  • docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md +72 −0
  • internal/hostedproxy/proxytest/harness.go +29 −3
  • internal/runner/hosted/export_test.go +10 −0
  • internal/runner/hosted/guards_test.go +121 −0
  • internal/runner/hosted/hosted_test.go +55 −6
  • internal/runner/hosted/redeem.go +7 −4
  • internal/runner/hosted/transport.go +5 −2
diff --git a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
index 6d4d119b..9bd8f28b 100644
--- a/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
+++ b/docs/superpowers/plans/HOSTED-SLICE2-PROGRESS.md
@@ -830,3 +830,75 @@ Mutation checks. Each was applied with the `sed` shown, then the `go test` shown
- `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.
+
+### Task 12 review round 1 (t12-r1.md: three Important findings, all fixed; concerns 1 to 4 accepted)
+
+1. **Redemption fails over on a proxy that cannot reach the controller.** A 5xx from a bootstrap listener (the proxy's 502 `controller_unavailable` among them) now moves to the next listener before any backoff, as a connection error already did. A 403 or 429 is the controller's own answer and still ends the round. New subtest `TestTransportFailsOver/redeem_past_a_502`: the harness's proxy is cut from the controller (`Partition(true)`), a second proxy (new `proxytest.Harness.AddProxy`: the same intercept CA, key, origins and log, with its own listeners and a direct path to the controller) answers; the decision log shows the redemption answered 502 by the first proxy, then 200 by the second, and Start enrols.
+2. **TestNoDirectDial watches every dial.** Every TCP connection the package opens now goes through one seam, `dialContext` (tests replace it with `SetDial` in export_test.go). The test records each dial and forwards it. It requests destinations on 443 (`instance.example.test`, `127.0.0.1`, `203.0.113.10`) and the earlier ones, then runs Start, with both egress and both bootstrap listeners down and on four distinct addresses. It asserts that every address dialled is one of those four and that each of the four was tried. The environment proxies and the counting listener stay as before.
+3. **Negative tests for every guard** (internal `guards_test.go`):
+ - `TestEnrolAnswerGuards`: a good answer passes; refused are a primary's credential, no role, no token, a token with a space, a token with a line break, no runner ID, another epoch, an expired credential, one expiring past the deadline, and an answer that does not decode.
+ - `TestProxyCertGuards`: a good certificate passes with its epoch; refused are another key, a server certificate, an expired one, no launch URI, two, another launch, attempt or VM, a URI of another scheme, an answer that does not decode and bytes that are not a certificate.
+
+Re-run:
+- `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.
+- `make budget build vet` (darwin runner build and vet included): ok. gofmt and `git diff --check`: clean.
+
+Mutation checks, run as before (sed, `go test ... -count=1`, restored with `cp`, `cmp` clean after each; each compiled and failed on an assertion; output cut). `H=./internal/runner/hosted`.
+
+79. Redemption does not fail over on a 5xx.
+ - `sed -i 's|continue // this proxy cannot reach the controller; the next may|break|' internal/runner/hosted/redeem.go`
+ - `go test $H -run '^TestTransportFailsOver$'`
+ - FAIL: `hosted_test.go:326: Start with the first proxy cut from the controller: hosted: proxy code not redeemed after 2s: bootstrap listener 127.0.0.1:37111 answered 502 "controller_unavailable", 0 enrolments`. Restored.
+80. A direct dial after the proxies fail.
+ - `sed -i 's|^\treturn nil, fmt.Errorf("%w: %s: %w", ErrTransport, host, errors.Join(errs...))|\tif c, err := dialContext(ctx, "tcp", addr); err == nil {\n\t\treturn c, nil\n\t}\n&|' internal/runner/hosted/transport.go`
+ - `go test $H -run '^TestNoDirectDial$'`
+ - FAIL: `hosted_test.go:540: dialled instance.example.test:443, which is no proxy listener` (also `127.0.0.1:443`, `203.0.113.10:443`). Restored.
+81. The enrol answer's role is not checked.
+ - `sed -i 's|case cred.Role != wire.RoleWorker:|case false:|' internal/runner/hosted/enrol.go`
+ - `go test $H -run '^TestEnrolAnswerGuards$'`
+ - FAIL: `guards_test.go:55: a primary's credential: accepted`, `no role: accepted`. Restored.
+82. The token is not checked as a header value.
+ - `sed -i 's/case cred.Token == "" || !headerSafe(cred.Token) || cred.RunnerID == "":/case cred.Token == "" || cred.RunnerID == "":/' internal/runner/hosted/enrol.go`
+ - `go test $H -run '^TestEnrolAnswerGuards$'`
+ - FAIL: `guards_test.go:55: a token with a space: accepted`, `a token with a line break: accepted`. Restored.
+83. The epoch is not compared.
+ - `sed -i 's|case r.Epoch != epoch:|case false:|' internal/runner/hosted/enrol.go`
+ - `go test $H -run '^TestEnrolAnswerGuards$'`
+ - FAIL: `guards_test.go:55: another epoch: accepted`. Restored.
+84. An expiry past the deadline is accepted.
+ - `sed -i 's/case !cred.ExpiresAt.After(now) || cred.ExpiresAt.After(r.Deadline):/case !cred.ExpiresAt.After(now):/' internal/runner/hosted/enrol.go`
+ - `go test $H -run '^TestEnrolAnswerGuards$'`
+ - FAIL: `guards_test.go:55: expiring past the deadline: accepted`. Restored.
+85. The certificate's key is not compared.
+ - `sed -i 's/if pub, ok := leaf.PublicKey.(\*ecdsa.PublicKey); !ok || !pub.Equal(\&key.PublicKey) {/if _, ok := leaf.PublicKey.(*ecdsa.PublicKey); !ok {/' internal/runner/hosted/redeem.go`
+ - `go test $H -run '^TestProxyCertGuards$'`
+ - FAIL: `guards_test.go:113: another key: accepted`. Restored.
+86. The certificate's VM is not compared.
+ - `sed -i 's/ || id.VMRef != vm {/ {/' internal/runner/hosted/redeem.go`
+ - `go test $H -run '^TestProxyCertGuards$'`
+ - FAIL: `guards_test.go:113: another VM: accepted`. Restored.
+87. The certificate's launch and attempt are not compared.
+ - `sed -i 's/id.LaunchID != b.LaunchID || id.AttemptID != b.AttemptID || //' internal/runner/hosted/redeem.go`
+ - `go test $H -run '^TestProxyCertGuards$'`
+ - FAIL: `guards_test.go:113: another launch: accepted`, `another attempt: accepted`. Restored.
+88. The certificate's expiry and client use are not checked.
+ - `sed -i 's/if now := time.Now(); now.After(leaf.NotAfter) || !slices.Contains(leaf.ExtKeyUsage, x509.ExtKeyUsageClientAuth) {/if now := time.Now(); now.IsZero() {/' internal/runner/hosted/redeem.go`
+ - `go test $H -run '^TestProxyCertGuards$'`
+ - FAIL: `guards_test.go:113: a server certificate: accepted`, `expired: accepted`. Restored.
+89. The link ignores the injected client.
+ - `sed -i 's/websocket.DialOptions{HTTPClient: l.HTTPClient, /websocket.DialOptions{/' internal/runner/thin/link.go`
+ - `go test ./internal/runner/thin -run '^TestLinkUsesGivenHTTPClient$'`
+ - FAIL: `link_hooks_test.go:98: dial through the client: the link never dialled`. Restored.
+90. The transport tries only the first proxy.
+ - `sed -i 's/for _, p := range d.proxies {/for _, p := range d.proxies[:1] {/' internal/runner/hosted/transport.go`
+ - `go test $H -run '^TestTransportFailsOver$'`
+ - FAIL: `hosted_test.go:301: GET through the second proxy = 0 "", ... dial tcp 127.0.0.1:42511: connect: connection refused`. Restored.
+91. The enrolment names another VM.
+ - `sed -i 's/VMRef: string(vm),$/VMRef: b.LaunchID,/' internal/runner/hosted/enrol.go`
+ - `go test $H -run '^TestEnrolSendsVMRefAndKey$'`
+ - FAIL: `hosted_test.go:213: enrolment {Code:... LaunchID:l-1 VMRef:l-1 ...}, want the instance code, launch l-1 and VM vm-1`. Restored.
+92. The enrolment sends another key.
+ - `sed -i 's/MachinePublicKey: machine})/MachinePublicKey: make([]byte, len(machine))})/' internal/runner/hosted/enrol.go`
+ - `go test $H -run '^TestEnrolSendsVMRefAndKey$'`
+ - FAIL: `hosted_test.go:217: enrolment key 0000...0000 is not the stored ed25519 machine key's`. Restored.
diff --git a/internal/hostedproxy/proxytest/harness.go b/internal/hostedproxy/proxytest/harness.go
index 28db94d1..e8abbaa8 100644
--- a/internal/hostedproxy/proxytest/harness.go
+++ b/internal/hostedproxy/proxytest/harness.go
@@ -719,7 +719,8 @@ type Harness struct {
ProxyKey ed25519.PrivateKey
t testing.TB
- routes sync.Map // path -> http.HandlerFunc on the service origin (Handle)
+ cfg hostedproxy.Config // Proxy's, for AddProxy
+ routes sync.Map // path -> http.HandlerFunc on the service origin (Handle)
originHits atomic.Int64
otherHits atomic.Int64
part *partition
@@ -755,7 +756,7 @@ func New(t testing.TB) *Harness {
dials := map[string]string{hostAddr + ":443": h.Origin.Listener.Addr().String(),
otherAddr + ":443": h.Other.Listener.Addr().String()}
- srv, err := hostedproxy.NewServer(hostedproxy.Config{
+ h.cfg = hostedproxy.Config{
Egress: netip.MustParseAddrPort("127.0.0.1:0"), Boot: netip.MustParseAddrPort("127.0.0.1:0"),
ControllerURL: "https://" + h.part.ln.Addr().String(), ControllerKey: h.Controller.key.Public().(ed25519.PublicKey),
ControllerTLSPin: spkiPin(h.Controller.srv.Certificate()), KeyID: ProxyKey, Key: proxyKey,
@@ -769,7 +770,8 @@ func New(t testing.TB) *Harness {
var d net.Dialer
return d.DialContext(ctx, network, to)
},
- })
+ }
+ srv, err := hostedproxy.NewServer(h.cfg)
if err != nil {
t.Fatalf("NewServer: %v", err)
}
@@ -794,6 +796,30 @@ func New(t testing.TB) *Harness {
return h
}
+// AddProxy starts a second proxy beside Proxy: the same intercept CA,
+// key, origins and log, on its own listeners, reaching the controller
+// directly (Partition does not cut it), and holding the current feed.
+func (h *Harness) AddProxy(t testing.TB) *hostedproxy.Server {
+ t.Helper()
+ cfg := h.cfg
+ cfg.Egress, cfg.Boot = netip.MustParseAddrPort("127.0.0.1:0"), netip.MustParseAddrPort("127.0.0.1:0")
+ cfg.ControllerURL = "https://" + h.Controller.Addr()
+ srv, err := hostedproxy.NewServer(cfg)
+ if err != nil {
+ t.Fatalf("NewServer: %v", err)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ if err := srv.Start(ctx); err != nil {
+ cancel()
+ t.Fatalf("Start: %v", err)
+ }
+ t.Cleanup(func() { cancel(); _ = srv.Close() })
+ if err := srv.Poll(ctx); err != nil {
+ t.Fatalf("Poll: %v", err)
+ }
+ return srv
+}
+
// Partition cuts (true) or heals the proxy's path to the controller; the
// controller itself stays up.
func (h *Harness) Partition(cut bool) { h.part.set(cut) }
diff --git a/internal/runner/hosted/export_test.go b/internal/runner/hosted/export_test.go
index e469d973..88fe1f0f 100644
--- a/internal/runner/hosted/export_test.go
+++ b/internal/runner/hosted/export_test.go
@@ -1,6 +1,8 @@
package hosted
import (
+ "context"
+ "net"
"testing"
"time"
)
@@ -12,3 +14,11 @@ func SetRedeemTiming(t testing.TB, patience, firstWait time.Duration) {
redeemPatience, redeemFirstWait = patience, firstWait
t.Cleanup(func() { redeemPatience, redeemFirstWait = p, w })
}
+
+// SetDial replaces every TCP dial the package makes with dial, for one
+// test.
+func SetDial(t testing.TB, dial func(ctx context.Context, network, addr string) (net.Conn, error)) {
+ d := dialContext
+ dialContext = dial
+ t.Cleanup(func() { dialContext = d })
+}
diff --git a/internal/runner/hosted/guards_test.go b/internal/runner/hosted/guards_test.go
new file mode 100644
index 00000000..31a0b21a
--- /dev/null
+++ b/internal/runner/hosted/guards_test.go
@@ -0,0 +1,121 @@
+package hosted
+
+import (
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/x509"
+ "encoding/json"
+ "math/big"
+ "net/url"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/equipo/internal/hostedctl/ctlproxy"
+ "amadan.net/oficina/equipo/internal/hostedwire"
+ "amadan.net/oficina/equipo/internal/isolatedjob"
+ "amadan.net/oficina/equipo/internal/runnerproto"
+ "amadan.net/oficina/equipo/internal/wire"
+)
+
+// The instance's enrolment answer is used only when it is a worker
+// credential with a usable token and runner ID, for the proxy
+// certificate's epoch, and expiring in the future, not past the job's
+// deadline.
+func TestEnrolAnswerGuards(t *testing.T) {
+ const epoch = 3
+ good := func() runnerproto.HostedEnrolResponse {
+ end := time.Now().Add(time.Hour).Truncate(time.Second)
+ return runnerproto.HostedEnrolResponse{Epoch: epoch, Deadline: end,
+ Credential: runnerproto.RunnerCredential{Token: "bearer-1", RunnerID: "r-1", Role: wire.RoleWorker, ExpiresAt: end}}
+ }
+ cases := map[string]func(*runnerproto.HostedEnrolResponse){
+ "a primary's credential": func(r *runnerproto.HostedEnrolResponse) { r.Credential.Role = wire.RolePrimary },
+ "no role": func(r *runnerproto.HostedEnrolResponse) { r.Credential.Role = "" },
+ "no token": func(r *runnerproto.HostedEnrolResponse) { r.Credential.Token = "" },
+ "a token with a space": func(r *runnerproto.HostedEnrolResponse) { r.Credential.Token = "bearer 1" },
+ "a token with a line break": func(r *runnerproto.HostedEnrolResponse) { r.Credential.Token = "bearer\r\nX-Evil: 1" },
+ "no runner ID": func(r *runnerproto.HostedEnrolResponse) { r.Credential.RunnerID = "" },
+ "another epoch": func(r *runnerproto.HostedEnrolResponse) { r.Epoch = epoch + 1 },
+ "expired": func(r *runnerproto.HostedEnrolResponse) { r.Credential.ExpiresAt = time.Now().Add(-time.Second) },
+ "expiring past the deadline": func(r *runnerproto.HostedEnrolResponse) { r.Deadline = r.Credential.ExpiresAt.Add(-time.Second) },
+ }
+ raw, _ := json.Marshal(good())
+ if _, err := acceptCredential(raw, epoch); err != nil {
+ t.Fatalf("a good answer was refused: %v", err)
+ }
+ if _, err := acceptCredential([]byte("not json"), epoch); err == nil {
+ t.Error("an answer that does not decode was accepted")
+ }
+ for name, mutate := range cases {
+ r := good()
+ mutate(&r)
+ raw, _ := json.Marshal(r)
+ if _, err := acceptCredential(raw, epoch); err == nil {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+}
+
+// The proxy certificate is used only when it is for this VM's key, a
+// client certificate valid now, naming exactly one launch URI for this
+// launch, attempt and VM.
+func TestProxyCertGuards(t *testing.T) {
+ key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ other, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ caKey, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ caTmpl := &x509.Certificate{SerialNumber: big.NewInt(1), IsCA: true, BasicConstraintsValid: true,
+ NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), KeyUsage: x509.KeyUsageCertSign}
+ caDER, _ := x509.CreateCertificate(rand.Reader, caTmpl, caTmpl, &caKey.PublicKey, caKey)
+ ca, _ := x509.ParseCertificate(caDER)
+ b := hostedwire.BootstrapV2{LaunchID: "l-1", AttemptID: "a-1"}
+ id := func(launch, attempt, vm string) *url.URL {
+ return ctlproxy.LaunchIdentity{LaunchID: launch, AttemptID: attempt, VMRef: isolatedjob.Ref(vm), Epoch: 3}.URI()
+ }
+ type cert struct {
+ pub *ecdsa.PublicKey
+ uris []*url.URL
+ usage []x509.ExtKeyUsage
+ notAfter time.Time
+ }
+ good := func() cert {
+ return cert{pub: &key.PublicKey, uris: []*url.URL{id("l-1", "a-1", "vm-1")},
+ usage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, notAfter: time.Now().Add(15 * time.Minute)}
+ }
+ answer := func(c cert) []byte {
+ der, err := x509.CreateCertificate(rand.Reader, &x509.Certificate{SerialNumber: big.NewInt(7), URIs: c.uris,
+ NotBefore: time.Now().Add(-2 * time.Minute), NotAfter: c.notAfter, ExtKeyUsage: c.usage, KeyUsage: x509.KeyUsageDigitalSignature},
+ ca, c.pub, caKey)
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, _ := json.Marshal(hostedwire.RedeemResponse{Cert: der, NotAfterNS: 1})
+ return raw
+ }
+ if _, epoch, err := acceptCert(answer(good()), b, "vm-1", key); err != nil || epoch != 3 {
+ t.Fatalf("a good certificate: epoch %d, %v", epoch, err)
+ }
+ cases := map[string]func(*cert){
+ "another key": func(c *cert) { c.pub = &other.PublicKey },
+ "a server certificate": func(c *cert) { c.usage = []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth} },
+ "expired": func(c *cert) { c.notAfter = time.Now().Add(-time.Minute) },
+ "no launch URI": func(c *cert) { c.uris = nil },
+ "two launch URIs": func(c *cert) { c.uris = append(c.uris, id("l-1", "a-1", "vm-1")) },
+ "another launch": func(c *cert) { c.uris = []*url.URL{id("l-2", "a-1", "vm-1")} },
+ "another attempt": func(c *cert) { c.uris = []*url.URL{id("l-1", "a-2", "vm-1")} },
+ "another VM": func(c *cert) { c.uris = []*url.URL{id("l-1", "a-1", "vm-2")} },
+ "a URI of another kind": func(c *cert) { c.uris = []*url.URL{{Scheme: "https", Host: "l-1", Path: "/a-1/vm-1/3"}} },
+ }
+ for name, mutate := range cases {
+ c := good()
+ mutate(&c)
+ if _, _, err := acceptCert(answer(c), b, "vm-1", key); err == nil {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+ for name, raw := range map[string][]byte{"not json": []byte("{"), "not a certificate": []byte(`{"cert":"AAAA","not_after_ns":1}`)} {
+ if _, _, err := acceptCert(raw, b, "vm-1", key); err == nil {
+ t.Errorf("%s: accepted", name)
+ }
+ }
+}
diff --git a/internal/runner/hosted/hosted_test.go b/internal/runner/hosted/hosted_test.go
index 2177316b..00c5fac7 100644
--- a/internal/runner/hosted/hosted_test.go
+++ b/internal/runner/hosted/hosted_test.go
@@ -23,6 +23,7 @@ import (
"os"
"path/filepath"
"reflect"
+ "slices"
"strings"
"sync"
"sync/atomic"
@@ -310,6 +311,30 @@ func TestTransportFailsOver(t *testing.T) {
if status, _, err := get(s.HTTPClient(), protocolURL); err != nil || status != http.StatusOK {
t.Errorf("the session's client = %d, %v", status, err)
}
+ // A first proxy that is up but cannot reach the controller answers
+ // the redemption 502: the second proxy is asked before any backoff.
+ t.Run("redeem past a 502", func(t *testing.T) {
+ hosted.SetRedeemTiming(t, 2*time.Second, 50*time.Millisecond)
+ h := proxytest.New(t)
+ f := enrolOn(h)
+ second := h.AddProxy(t)
+ h.Partition(true)
+ b := bootstrap(h)
+ b.Proxies = []netip.AddrPort{h.Proxy.EgressAddr(), second.EgressAddr()}
+ b.ProxyBoot = []netip.AddrPort{h.Proxy.BootAddr(), second.BootAddr()}
+ if _, err := start(t, b, t.TempDir()); err != nil || len(f.requests()) != 1 {
+ t.Fatalf("Start with the first proxy cut from the controller: %v, %d enrolments", err, len(f.requests()))
+ }
+ var statuses []int
+ for _, l := range h.Log.Lines(t) {
+ if l.Route == "redeem" {
+ statuses = append(statuses, l.Status)
+ }
+ }
+ if !slices.Equal(statuses, []int{http.StatusBadGateway, http.StatusOK}) {
+ t.Errorf("redemptions answered %v, want the first proxy's 502 then the second's 200", statuses)
+ }
+ })
}
// testCA is a CA the test controls.
@@ -458,6 +483,8 @@ func TestTransportPinsInterceptCA(t *testing.T) {
// With both proxies down, nothing reaches the instance any other way: no
// direct dial, no environment proxy, no plain HTTP, no port but 443.
+// Every TCP dial the package makes is watched: only the proxies'
+// listeners are ever dialled, for destinations on 443 included.
func TestNoDirectDial(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
@@ -480,22 +507,44 @@ func TestNoDirectDial(t *testing.T) {
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"} {
+ var mu sync.Mutex
+ var dialled []string
+ hosted.SetDial(t, func(ctx context.Context, network, addr string) (net.Conn, error) {
+ mu.Lock()
+ dialled = append(dialled, addr)
+ mu.Unlock()
+ var d net.Dialer
+ return d.DialContext(ctx, network, addr)
+ })
+ egress1, egress2, boot1, boot2 := deadAddr(t), deadAddr(t), deadAddr(t), deadAddr(t)
+ allowed := map[string]bool{egress1.String(): true, egress2.String(): true, boot1.String(): true, boot2.String(): true}
+ c := hosted.NewHTTPClient([]netip.AddrPort{egress1, egress2}, strings.Repeat("ab", 32), nil)
+ for _, url := range []string{protocolURL, "https://127.0.0.1/api/runner/protocol", "https://203.0.113.10/api/runner/protocol",
+ "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),
+ AttemptID: "a-1", InstanceCode: instanceCode, ProxyCode: proxytest.ProxyCode, Proxies: []netip.AddrPort{egress1, egress2},
+ ProxyBoot: []netip.AddrPort{boot1, boot2}, 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")
}
+ mu.Lock()
+ defer mu.Unlock()
+ for _, a := range dialled {
+ if !allowed[a] {
+ t.Errorf("dialled %s, which is no proxy listener", a)
+ }
+ }
+ for _, p := range []netip.AddrPort{egress1, egress2, boot1, boot2} {
+ if !slices.Contains(dialled, p.String()) {
+ t.Errorf("never tried proxy listener %s (dialled %q)", p, dialled)
+ }
+ }
if n := accepted.Load(); n != 0 {
t.Errorf("the instance's address was dialled directly %d times", n)
}
diff --git a/internal/runner/hosted/redeem.go b/internal/runner/hosted/redeem.go
index 11565711..aea385a9 100644
--- a/internal/runner/hosted/redeem.go
+++ b/internal/runner/hosted/redeem.go
@@ -51,8 +51,7 @@ func bootClient(boot []netip.AddrPort, pin pinnedCA, cert func() *tls.Certificat
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)
+ raw, err := dialContext(ctx, "tcp", addr)
if err != nil {
return nil, err
}
@@ -113,7 +112,8 @@ func csrFor(key *ecdsa.PrivateKey) ([]byte, error) {
}
// redeem trades b's proxy code for a client certificate for key, asking
-// each bootstrap listener in turn, and again within redeemPatience while
+// each bootstrap listener in turn while one is unreachable or cannot reach
+// the controller (5xx), and all of them 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) {
@@ -144,7 +144,10 @@ func redeem(ctx context.Context, c *http.Client, b hostedwire.BootstrapV2, vm is
if !retryable(status) {
return tls.Certificate{}, 0, fmt.Errorf("%w: %w", ErrRedeem, last)
}
- break // both proxies ask the same controller
+ if status >= 500 {
+ continue // this proxy cannot reach the controller; the next may
+ }
+ break // the controller's own answer: the next proxy asks the same one
}
left := time.Until(giveUp)
if left <= 0 {
diff --git a/internal/runner/hosted/transport.go b/internal/runner/hosted/transport.go
index a621d60b..19d48681 100644
--- a/internal/runner/hosted/transport.go
+++ b/internal/runner/hosted/transport.go
@@ -31,6 +31,10 @@ const servicePort = "443"
// proxyTimeout bounds one proxy's dial, TLS, CONNECT and the inner TLS.
const proxyTimeout = 15 * time.Second
+// dialContext opens every TCP connection this package makes, each to a
+// proxy listener; tests watch it.
+var dialContext = (&net.Dialer{}).DialContext
+
// 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")
@@ -132,8 +136,7 @@ func (d *proxyDialer) dialTLS(ctx context.Context, _, addr string) (net.Conn, er
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())
+ raw, err := dialContext(ctx, "tcp", p.String())
if err != nil {
return nil, err
}