package hostedclient import ( "bytes" "context" "crypto/ed25519" "encoding/json" "errors" "fmt" "net" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "strings" "sync/atomic" "testing" "time" "amadan.net/oficina/equipo/internal/hostedctl" "amadan.net/oficina/equipo/internal/hostedwire" "amadan.net/oficina/equipo/internal/isolatedjob" "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest" "amadan.net/oficina/equipo/internal/testci" "amadan.net/rastrillo/rastrillo/budget" ) func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } // Keys of these tests: the instance's signing key, a key the controller does // not know, and the controller's signing key. var ( keyInst = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize)) keyOther = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{2}, ed25519.SeedSize)) keyCtl = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{4}, ed25519.SeedSize)) ) const ( idInst hostedwire.KeyID = "inst-a" imgA = isolatedjob.ImageDigest("sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") ) func ctlPublic() ed25519.PublicKey { return keyCtl.Public().(ed25519.PublicKey) } // nopAlerter drops alerts; a fresh store raises none. type nopAlerter struct{} func (nopAlerter) Alert(context.Context, hostedctl.Alert) error { return nil } // ctlEnv is a real controller over a fresh store and the fake provider, // served over TLS on 127.0.0.1, built only from hostedctl's public API. type ctlEnv struct { ctx context.Context fake *isolatedjob.Fake c *hostedctl.Controller srv *httptest.Server } func newCtlEnv(t *testing.T) *ctlEnv { t.Helper() ctx := context.Background() clk := isolatedjobtest.NewFakeClock(time.Date(2026, 11, 19, 12, 0, 0, 0, time.UTC)) store, err := hostedctl.Open(ctx, filepath.Join(t.TempDir(), "hosted.db"), clk) if err != nil { t.Fatalf("Open = %v", err) } t.Cleanup(func() { _ = store.Close() }) fake := isolatedjob.NewFake(clk, isolatedjob.SpikeLimits()) c, err := hostedctl.New(hostedctl.Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{imgA: true}, ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" }}, hostedctl.Deps{Store: store, Runner: fake, Auditor: fake, Alerter: nopAlerter{}}) if err != nil { t.Fatalf("New = %v", err) } if err := c.RunAudit(ctx); err != nil { t.Fatalf("RunAudit = %v", err) } // The client signs with the real wall clock, so the handler checks // timestamps against it; controller time stays on the fake clock. h, err := c.Handler(hostedctl.HandlerConfig{ Keys: map[hostedwire.KeyID]hostedwire.VerifyKey{idInst: {Public: keyInst.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance}}, Signing: keyCtl, Wall: time.Now, }) if err != nil { t.Fatalf("Handler = %v", err) } return &ctlEnv{ctx: ctx, fake: fake, c: c, srv: serveTLS(t, h)} } // serveTLS serves h over TLS on 127.0.0.1 only. func serveTLS(t *testing.T, h http.Handler) *httptest.Server { t.Helper() ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } srv := httptest.NewUnstartedServer(h) srv.Listener = ln srv.StartTLS() t.Cleanup(srv.Close) return srv } // settle moves every fake VM one step and lets the controller read it. func (e *ctlEnv) settle(t *testing.T) { t.Helper() e.fake.Tick() if err := e.c.Refresh(e.ctx); err != nil { t.Fatalf("Refresh = %v", err) } } // newClient builds a client for srv with the flag on. func newClient(t *testing.T, srv *httptest.Server, key ed25519.PrivateKey, ctl ed25519.PublicKey) *Client { t.Helper() t.Setenv(FlagEnv, "1") cl, err := New(Config{BaseURL: srv.URL, KeyID: idInst, Key: key, ControllerKey: ctl, HTTP: srv.Client()}) if err != nil { t.Fatalf("New = %v", err) } return cl } func launchReq(attempt string) hostedwire.LaunchRequest { return hostedwire.LaunchRequest{AttemptID: attempt, TaskID: "task-1", Account: "acct-1", Image: imgA, Size: isolatedjob.SizeSmall, MaxLifetimeMS: (2 * time.Hour).Milliseconds(), InstanceCode: "code-test-1"} } func TestClientAgainstController(t *testing.T) { e := newCtlEnv(t) cl := newClient(t, e.srv, keyInst, ctlPublic()) ctx := e.ctx view, err := cl.Launch(ctx, launchReq("a1")) if err != nil || view.AttemptID != "a1" || view.State != "starting" || view.VMRef == "" { t.Fatalf("Launch = %+v, %v; want a1 starting with a VM", view, err) } got, err := cl.Get(ctx, "a1") if err != nil || got.VMRef != view.VMRef || got.LaunchID != view.LaunchID { t.Fatalf("Get = %+v, %v; want the launched job %+v", got, err, view) } e.settle(t) if got, err = cl.Get(ctx, "a1"); err != nil || got.State != "running" { t.Fatalf("Get after a refresh = %+v, %v; want running", got, err) } // Pause: drain, acknowledge, suspend. gen, err := cl.Drain(ctx, "a1") if err != nil || gen != 1 { t.Fatalf("Drain = %d, %v; want generation 1", gen, err) } if err := cl.Quiescent(ctx, "a1", gen+1); !errors.Is(err, ErrGenerationCancelled) { t.Fatalf("Quiescent for a generation not open = %v, want ErrGenerationCancelled", err) } if err := cl.Quiescent(ctx, "a1", gen); err != nil { t.Fatalf("Quiescent = %v", err) } if err := cl.Suspend(ctx, "a1", gen); err != nil { t.Fatalf("Suspend = %v", err) } e.settle(t) if got, err = cl.Get(ctx, "a1"); err != nil || got.State != "suspended" { t.Fatalf("Get after suspend = %+v, %v; want suspended", got, err) } // Resume: pending while the VM still reports suspended, then the epoch. if ep, err := cl.Resume(ctx, "a1", "op-1"); !errors.Is(err, ErrResumePending) || ep != 0 { t.Fatalf("first Resume = %d, %v; want 0 and ErrResumePending", ep, err) } e.fake.Tick() if ep, err := cl.Resume(ctx, "a1", "op-1"); err != nil || ep != 1 { t.Fatalf("Resume retry = %d, %v; want epoch 1", ep, err) } // An abandoned pause reopens. if gen, err = cl.Drain(ctx, "a1"); err != nil || gen != 2 { t.Fatalf("second Drain = %d, %v; want generation 2", gen, err) } if err := cl.Reopen(ctx, "a1", gen); err != nil { t.Fatalf("Reopen = %v", err) } if got, err = cl.Get(ctx, "a1"); err != nil || got.State != "running" || got.Epoch != 1 { t.Fatalf("Get after reopen = %+v, %v; want running at epoch 1", got, err) } // Stop: pending first, then proof. if _, err := cl.Stop(ctx, "a1", "done"); !errors.Is(err, ErrStopPending) { t.Fatalf("first Stop = %v, want ErrStopPending", err) } var api *APIError if _, err := cl.Stop(ctx, "a1", "done"); !errors.As(err, &api) || api.Status != http.StatusAccepted || api.Code != "stop_pending" { t.Fatalf("second Stop before the VM stops = %v, want an APIError 202 stop_pending", err) } e.fake.Tick() proof, err := cl.Stop(ctx, "a1", "done") if err != nil || proof.AttemptID != "a1" || proof.VMRef != view.VMRef || !proof.State.Terminal() { t.Fatalf("Stop = %+v, %v; want proof for a1's VM %s", proof, err, view.VMRef) } // Refusals come back as the controller's kinds. if _, err := cl.Get(ctx, "nope"); !errors.Is(err, ErrForbidden) { t.Fatalf("Get of an unknown attempt = %v, want ErrForbidden", err) } changed := launchReq("a1") changed.TaskID = "task-2" if _, err := cl.Launch(ctx, changed); !errors.Is(err, ErrConflict) { t.Fatalf("launch of a1 with a different request = %v, want ErrConflict", err) } bad := launchReq("a2") bad.Image = "sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc" if _, err := cl.Launch(ctx, bad); !errors.Is(err, ErrImageNotAllowed) { t.Fatalf("launch with an image off the allowlist = %v, want ErrImageNotAllowed", err) } } // fakeCtl answers every request with whatever answer returns, given the // request's nonce. func fakeCtl(t *testing.T, answer func(w http.ResponseWriter, nonce string)) *httptest.Server { t.Helper() return serveTLS(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { answer(w, r.Header.Get(hostedwire.HeaderNonce)) })) } // signedAnswer writes status and body signed by key for nonce. func signedAnswer(w http.ResponseWriter, status int, body []byte, nonce string, key ed25519.PrivateKey) { hostedwire.SignResponse(w.Header(), status, nonce, body, key) w.WriteHeader(status) _, _ = w.Write(body) } func TestClientRefusesUnsignedResponse(t *testing.T) { good, err := json.Marshal(hostedwire.JobView{AttemptID: "a1", LaunchID: "launch-1", State: "running", VMRef: "vm-1"}) if err != nil { t.Fatal(err) } const replayed = "captured-nonce-000000000" cases := []struct { name string answer func(w http.ResponseWriter, nonce string) }{ {"unsigned", func(w http.ResponseWriter, _ string) { w.WriteHeader(http.StatusOK) _, _ = w.Write(good) }}, {"signed by another key", func(w http.ResponseWriter, nonce string) { signedAnswer(w, http.StatusOK, good, nonce, keyOther) }}, {"signed for another nonce", func(w http.ResponseWriter, _ string) { // A captured response replayed, naming its own nonce. w.Header().Set(hostedwire.HeaderNonce, replayed) signedAnswer(w, http.StatusOK, good, replayed, keyCtl) }}, {"signed for another status", func(w http.ResponseWriter, nonce string) { hostedwire.SignResponse(w.Header(), http.StatusNotFound, nonce, good, keyCtl) w.WriteHeader(http.StatusOK) _, _ = w.Write(good) }}, {"body changed after signing", func(w http.ResponseWriter, nonce string) { hostedwire.SignResponse(w.Header(), http.StatusOK, nonce, good, keyCtl) w.WriteHeader(http.StatusOK) _, _ = w.Write(bytes.Replace(good, []byte("vm-1"), []byte("vm-2"), 1)) }}, {"too large", func(w http.ResponseWriter, nonce string) { big := append(bytes.Repeat([]byte(" "), hostedwire.MaxBody), good...) signedAnswer(w, http.StatusOK, big, nonce, keyCtl) }}, } for _, c := range cases { cl := newClient(t, fakeCtl(t, c.answer), keyInst, ctlPublic()) v, err := cl.Get(context.Background(), "a1") if !errors.Is(err, ErrUnverified) || v != (hostedwire.JobView{}) { t.Fatalf("%s: Get = %+v, %v; want nothing and ErrUnverified", c.name, v, err) } } // The same server signing properly is accepted, so the refusals above // are for the signature and nothing else. cl := newClient(t, fakeCtl(t, func(w http.ResponseWriter, nonce string) { signedAnswer(w, http.StatusOK, good, nonce, keyCtl) }), keyInst, ctlPublic()) if v, err := cl.Get(context.Background(), "a1"); err != nil || v.VMRef != "vm-1" { t.Fatalf("properly signed Get = %+v, %v; want vm-1", v, err) } // The real controller's unsigned 401, for a key it does not know, is // unverified too, not a typed refusal. e := newCtlEnv(t) stranger := newClient(t, e.srv, keyOther, ctlPublic()) _, err = stranger.Launch(e.ctx, launchReq("a1")) var api *APIError if !errors.Is(err, ErrUnverified) || errors.As(err, &api) { t.Fatalf("launch by an unknown key = %v, want ErrUnverified and no APIError", err) } // A client holding the wrong controller key trusts nothing it hears. wrongCtl := newClient(t, e.srv, keyInst, keyOther.Public().(ed25519.PublicKey)) if _, err := wrongCtl.Launch(e.ctx, launchReq("a1")); !errors.Is(err, ErrUnverified) { t.Fatalf("launch with the wrong controller key = %v, want ErrUnverified", err) } // A redirect is not followed: the signed request never goes elsewhere. var hits atomic.Int32 elsewhere := serveTLS(t, http.HandlerFunc(func(http.ResponseWriter, *http.Request) { hits.Add(1) })) redirect := newClient(t, fakeCtl(t, func(w http.ResponseWriter, _ string) { w.Header().Set("Location", elsewhere.URL+"/v1/jobs") w.WriteHeader(http.StatusTemporaryRedirect) }), keyInst, ctlPublic()) if _, err := redirect.Launch(context.Background(), launchReq("a1")); !errors.Is(err, ErrUnverified) || hits.Load() != 0 { t.Fatalf("launch answered by a redirect = %v with %d hits elsewhere, want ErrUnverified and none", err, hits.Load()) } // A redirect whose Location does not parse is still verified first: // unsigned, it is ErrUnverified with nothing of the answer in the error, // and only one request is sent. Signed, it is an unexpected answer. for _, signed := range []bool{false, true} { var sent atomic.Int32 bad := newClient(t, fakeCtl(t, func(w http.ResponseWriter, nonce string) { sent.Add(1) w.Header().Set("Location", "%") if signed { signedAnswer(w, http.StatusTemporaryRedirect, nil, nonce, keyCtl) return } w.WriteHeader(http.StatusTemporaryRedirect) }), keyInst, ctlPublic()) _, err := bad.Launch(context.Background(), launchReq("a1")) want := ErrUnverified if signed { want = ErrUnexpected } if !errors.Is(err, want) || sent.Load() != 1 { t.Fatalf("redirect to %%, signed %v: Launch = %v after %d requests, want %v after 1", signed, err, sent.Load(), want) } if msg := err.Error(); !signed && (strings.Contains(msg, "%") || strings.Contains(msg, "307") || strings.Contains(msg, "redirect") || strings.Contains(msg, "Location")) { t.Fatalf("unsigned redirect error %q holds text from the answer", msg) } } } // TestTransportErrorsHoldNoServerBytes: a server that answers with bytes Go // cannot parse (status line, header, chunked trailer) gives ErrTransport, // and nothing it sent appears in the error. func TestTransportErrorsHoldNoServerBytes(t *testing.T) { for name, raw := range map[string]string{ "malformed status": "HTTP/1.1 EVIL\r\n\r\n", "malformed header": "HTTP/1.1 200 OK\r\nEVIL-HEADER-NO-COLON\r\nContent-Length: 0\r\n\r\n", "malformed trailer": "HTTP/1.1 200 OK\r\nTransfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\nEVIL-TRAILER\r\n\r\n", } { srv := serveTLS(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { conn, buf, err := http.NewResponseController(w).Hijack() if err != nil { t.Errorf("hijack: %v", err) return } defer conn.Close() _, _ = buf.WriteString(raw) _ = buf.Flush() })) _, err := newClient(t, srv, keyInst, ctlPublic()).Get(context.Background(), "a1") if !errors.Is(err, ErrTransport) || errors.Is(err, ErrUnverified) { t.Errorf("%s: Get = %v, want ErrTransport", name, err) } else if msg := err.Error(); strings.Contains(msg, "EVIL") || strings.Contains(msg, "hello") { t.Errorf("%s: error %q holds bytes the server sent", name, msg) } } } // TestClientHonoursTimeoutAndCancel:the HTTP client's Timeout and the // caller's context both bound a call to a controller that never answers. func TestClientHonoursTimeoutAndCancel(t *testing.T) { srv := serveTLS(t, http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) { select { case <-r.Context().Done(): case <-time.After(3 * time.Second): } })) t.Setenv(FlagEnv, "1") slow, err := New(Config{BaseURL: srv.URL, KeyID: idInst, Key: keyInst, ControllerKey: ctlPublic(), HTTP: &http.Client{Transport: srv.Client().Transport, Timeout: 100 * time.Millisecond}}) if err != nil { t.Fatal(err) } start := time.Now() if _, err := slow.Get(context.Background(), "a1"); !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > 2*time.Second { t.Fatalf("Get past the HTTP timeout = %v after %v, want context.DeadlineExceeded within 2 s", err, time.Since(start)) } ctx, cancel := context.WithCancel(context.Background()) time.AfterFunc(100*time.Millisecond, cancel) start = time.Now() if _, err := newClient(t, srv, keyInst, ctlPublic()).Get(ctx, "a1"); !errors.Is(err, context.Canceled) || time.Since(start) > 2*time.Second { t.Fatalf("Get with a cancelled context = %v after %v, want context.Canceled within 2 s", err, time.Since(start)) } } // TestSignedAnswersMapToKinds: a signed refusal is the controller's word and // maps to its kind by status and code; a signed answer that does not fit is // an error too. func TestSignedAnswersMapToKinds(t *testing.T) { refusal := func(code string) []byte { b, _ := json.Marshal(hostedwire.ErrorResponse{Code: code, Message: "fixed text"}) return b } for _, c := range []struct { name string status int body []byte want error }{ {"signed signature refusal", http.StatusUnauthorized, refusal("unauthorized"), ErrUnauthorized}, {"replay refused", http.StatusUnauthorized, refusal("replay"), ErrReplay}, {"nonce store down", http.StatusServiceUnavailable, refusal("unavailable"), ErrUnavailable}, {"store lost", http.StatusServiceUnavailable, refusal("store_lost"), ErrStoreLost}, {"throttled", http.StatusTooManyRequests, refusal("throttled"), ErrThrottled}, {"past deadline", http.StatusGone, refusal("past_deadline"), ErrPastDeadline}, {"code and status disagree", http.StatusConflict, refusal("disabled"), ErrUnexpected}, {"unknown code", http.StatusTeapot, refusal("teapot"), ErrUnexpected}, {"refusal body not strict", http.StatusConflict, []byte(`{"code":"conflict","message":"x","extra":1}`), ErrUnexpected}, } { cl := newClient(t, fakeCtl(t, func(w http.ResponseWriter, nonce string) { signedAnswer(w, c.status, c.body, nonce, keyCtl) }), keyInst, ctlPublic()) v, err := cl.Get(context.Background(), "a1") if !errors.Is(err, c.want) || errors.Is(err, ErrUnverified) || v != (hostedwire.JobView{}) { t.Fatalf("%s: Get = %+v, %v; want nothing and %v", c.name, v, err, c.want) } } } // TestClientMatchesHandlerErrorCodes holds the client to the handler's own // list of refusals: every status and code the handler can send maps to a // typed kind, and the client knows no code the handler does not send. func TestClientMatchesHandlerErrorCodes(t *testing.T) { handler := map[string]int{} for _, ec := range hostedctl.ErrorCodes() { if s, dup := handler[ec.Code]; dup { t.Fatalf("handler code %q has statuses %d and %d", ec.Code, s, ec.Status) } handler[ec.Code] = ec.Status body, _ := json.Marshal(hostedwire.ErrorResponse{Code: ec.Code, Message: "m"}) err := refusal("get", ec.Status, body) var api *APIError if !errors.As(err, &api) || api.Kind == nil || errors.Is(err, ErrUnexpected) { t.Errorf("handler refusal %d %q maps to %v, want a typed kind", ec.Status, ec.Code, err) } } if len(handler) < 20 { t.Fatalf("hostedctl.ErrorCodes lists %d codes; the handler has more", len(handler)) } for code, r := range refusals { if s, ok := handler[code]; !ok || s != r.status { t.Errorf("client maps %d %q, which the handler does not send", r.status, code) } } } // TestSignedSuccessMustFit: a signed 200 that is not the route's strict // JSON, or does not answer the request asked, is ErrBadResponse. One case // per guard. func TestSignedSuccessMustFit(t *testing.T) { ctx := context.Background() for _, c := range []struct { name string body string call func(cl *Client) (any, error) }{ {"launch view for another attempt", `{"attempt_id":"a9","state":"starting","vm_ref":"vm-1"}`, func(cl *Client) (any, error) { return cl.Launch(ctx, launchReq("a1")) }}, {"get view for another attempt", `{"attempt_id":"a9","state":"running"}`, func(cl *Client) (any, error) { return cl.Get(ctx, "a1") }}, {"get view with an unknown field", `{"attempt_id":"a1","bogus":true}`, func(cl *Client) (any, error) { return cl.Get(ctx, "a1") }}, {"stop proof for another attempt", `{"attempt_id":"a9","vm_ref":"vm-1","state":"stopped","observed_at_ns":1}`, func(cl *Client) (any, error) { return cl.Stop(ctx, "a1", "done") }}, {"stop proof not terminal", `{"attempt_id":"a1","vm_ref":"vm-1","state":"running","observed_at_ns":1}`, func(cl *Client) (any, error) { return cl.Stop(ctx, "a1", "done") }}, {"drain generation 0", `{"generation":0}`, func(cl *Client) (any, error) { return cl.Drain(ctx, "a1") }}, {"quiescent for another generation", `{"generation":7}`, func(cl *Client) (any, error) { return nil, cl.Quiescent(ctx, "a1", 1) }}, {"suspend for another generation", `{"generation":7}`, func(cl *Client) (any, error) { return nil, cl.Suspend(ctx, "a1", 1) }}, {"reopen for another generation", `{"generation":7}`, func(cl *Client) (any, error) { return nil, cl.Reopen(ctx, "a1", 1) }}, {"resume epoch 0", `{"epoch":0}`, func(cl *Client) (any, error) { return cl.Resume(ctx, "a1", "op-1") }}, } { cl := newClient(t, fakeCtl(t, func(w http.ResponseWriter, nonce string) { signedAnswer(w, http.StatusOK, []byte(c.body), nonce, keyCtl) }), keyInst, ctlPublic()) got, err := c.call(cl) if !errors.Is(err, ErrBadResponse) { t.Errorf("%s: = %+v, %v; want ErrBadResponse", c.name, got, err) continue } switch v := got.(type) { case hostedwire.JobView: if v != (hostedwire.JobView{}) { t.Errorf("%s: returned %+v with the error, want nothing", c.name, v) } case hostedwire.StopProof: if v != (hostedwire.StopProof{}) { t.Errorf("%s: returned %+v with the error, want nothing", c.name, v) } case int64: if v != 0 { t.Errorf("%s: returned %d with the error, want 0", c.name, v) } } } } func TestClientRefusesWithoutFlag(t *testing.T) { srv := fakeCtl(t, func(http.ResponseWriter, string) {}) cfg := Config{BaseURL: srv.URL, KeyID: idInst, Key: keyInst, ControllerKey: ctlPublic(), HTTP: srv.Client()} for _, v := range []string{"", "0", "true", "yes", " 1", "1 ", "01"} { t.Setenv(FlagEnv, v) if cl, err := New(cfg); !errors.Is(err, ErrRunnersOff) || cl != nil { t.Fatalf("New with %s=%q = (client %v, %v); want ErrRunnersOff", FlagEnv, v, cl != nil, err) } } os.Unsetenv(FlagEnv) if _, err := New(cfg); !errors.Is(err, ErrRunnersOff) { t.Fatalf("New with %s unset = %v, want ErrRunnersOff", FlagEnv, err) } t.Setenv(FlagEnv, "1") if _, err := New(cfg); err != nil { t.Fatalf("New with %s=1 = %v", FlagEnv, err) } } func TestNewRefusesBadConfig(t *testing.T) { t.Setenv(FlagEnv, "1") good := Config{BaseURL: "https://127.0.0.1:8443", KeyID: idInst, Key: keyInst, ControllerKey: ctlPublic(), HTTP: &http.Client{}} cl, err := New(good) if err != nil { t.Fatalf("New(good) = %v", err) } if s, want := fmt.Sprintf("%v %+v", cl, cl), "hostedclient.Client(https://127.0.0.1:8443)"; s != want+" "+want { t.Fatalf("a printed client = %q, want only %q twice", s, want) } for name, change := range map[string]func(*Config){ "plain http": func(c *Config) { c.BaseURL = "http://127.0.0.1:8443" }, "no scheme": func(c *Config) { c.BaseURL = "127.0.0.1:8443" }, "no host": func(c *Config) { c.BaseURL = "https://" }, "a path": func(c *Config) { c.BaseURL = "https://127.0.0.1:8443/api" }, "a query": func(c *Config) { c.BaseURL = "https://127.0.0.1:8443?x=1" }, "user info": func(c *Config) { c.BaseURL = "https://u:p@127.0.0.1:8443" }, "no key ID": func(c *Config) { c.KeyID = "" }, "no key": func(c *Config) { c.Key = nil }, "short key": func(c *Config) { c.Key = c.Key[:ed25519.SeedSize] }, "no controller key": func(c *Config) { c.ControllerKey = nil }, "short controller key": func(c *Config) { c.ControllerKey = c.ControllerKey[:16] }, "no HTTP client": func(c *Config) { c.HTTP = nil }, } { cfg := good change(&cfg) if cl, err := New(cfg); err == nil || cl != nil { t.Errorf("New with %s = (client %v, %v); want a refusal", name, cl != nil, err) } } } func TestEmptyAttemptRefused(t *testing.T) { var hits atomic.Int32 cl := newClient(t, fakeCtl(t, func(http.ResponseWriter, string) { hits.Add(1) }), keyInst, ctlPublic()) for _, a := range []string{"", ".", ".."} { if _, err := cl.Get(context.Background(), a); err == nil { t.Fatalf("Get(%q) = nil error, want a refusal", a) } } if hits.Load() != 0 { t.Fatalf("%d requests sent for refused attempts, want none", hits.Load()) } } // TestInstanceDoesNotCallHostedClient holds slice 1a's promise that the // instance never calls the hosted controller. Slice 2 deletes it. func TestInstanceDoesNotCallHostedClient(t *testing.T) { gobin, err := exec.LookPath("go") if err != nil { t.Fatalf("go not on PATH: %v", err) } const instance = "amadan.net/oficina/equipo/cmd/equipo" ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) defer cancel() cmd := exec.CommandContext(ctx, gobin, "list", "-deps", instance) // The child reads cmd/equipo's source, which go test does not see: // declare it, so adding the import reruns this test instead of // replaying a cached pass. testci.GoCommand(t, cmd) var stderr bytes.Buffer cmd.Stderr = &stderr out, err := cmd.Output() if err != nil { t.Fatalf("go list -deps %s: %v\n%s", instance, err, stderr.Bytes()) } deps := strings.Fields(string(out)) var self bool for _, d := range deps { if d == "amadan.net/oficina/equipo/internal/hostedclient" { t.Fatalf("%s depends on internal/hostedclient; slice 1a keeps the instance off the hosted controller", instance) } self = self || d == instance } if !self { t.Fatalf("go list -deps %s did not list the package itself; got %d lines", instance, len(deps)) } }