oficina / equipo Public

Clone
git clone https://amadan.net/oficina/equipo

Plain git — no account needed to clone.

Download

Download this file

1package hostedclient
2
3import (
4 "bytes"
5 "context"
6 "crypto/ed25519"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "net"
11 "net/http"
12 "net/http/httptest"
13 "os"
14 "os/exec"
15 "path/filepath"
16 "strings"
17 "sync/atomic"
18 "testing"
19 "time"
20
21 "amadan.net/oficina/equipo/internal/hostedctl"
22 "amadan.net/oficina/equipo/internal/hostedwire"
23 "amadan.net/oficina/equipo/internal/isolatedjob"
24 "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest"
25 "amadan.net/oficina/equipo/internal/testci"
26 "amadan.net/rastrillo/rastrillo/budget"
27)
28
29func TestMain(m *testing.M) { os.Exit(budget.Main(m)) }
30
31// Keys of these tests: the instance's signing key, a key the controller does
32// not know, and the controller's signing key.
33var (
34 keyInst = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize))
35 keyOther = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{2}, ed25519.SeedSize))
36 keyCtl = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{4}, ed25519.SeedSize))
37)
38
39const (
40 idInst hostedwire.KeyID = "inst-a"
41 imgA = isolatedjob.ImageDigest("sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
42)
43
44func ctlPublic() ed25519.PublicKey { return keyCtl.Public().(ed25519.PublicKey) }
45
46// nopAlerter drops alerts; a fresh store raises none.
47type nopAlerter struct{}
48
49func (nopAlerter) Alert(context.Context, hostedctl.Alert) error { return nil }
50
51// ctlEnv is a real controller over a fresh store and the fake provider,
52// served over TLS on 127.0.0.1, built only from hostedctl's public API.
53type ctlEnv struct {
54 ctx context.Context
55 fake *isolatedjob.Fake
56 c *hostedctl.Controller
57 srv *httptest.Server
58}
59
60func newCtlEnv(t *testing.T) *ctlEnv {
61 t.Helper()
62 ctx := context.Background()
63 clk := isolatedjobtest.NewFakeClock(time.Date(2026, 11, 19, 12, 0, 0, 0, time.UTC))
64 store, err := hostedctl.Open(ctx, filepath.Join(t.TempDir(), "hosted.db"), clk)
65 if err != nil {
66 t.Fatalf("Open = %v", err)
67 }
68 t.Cleanup(func() { _ = store.Close() })
69 fake := isolatedjob.NewFake(clk, isolatedjob.SpikeLimits())
70 c, err := hostedctl.New(hostedctl.Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{imgA: true},
71 ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" }},
72 hostedctl.Deps{Store: store, Runner: fake, Auditor: fake, Alerter: nopAlerter{}})
73 if err != nil {
74 t.Fatalf("New = %v", err)
75 }
76 if err := c.RunAudit(ctx); err != nil {
77 t.Fatalf("RunAudit = %v", err)
78 }
79 // The client signs with the real wall clock, so the handler checks
80 // timestamps against it; controller time stays on the fake clock.
81 h, err := c.Handler(hostedctl.HandlerConfig{
82 Keys: map[hostedwire.KeyID]hostedwire.VerifyKey{idInst: {Public: keyInst.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance}},
83 Signing: keyCtl,
84 Wall: time.Now,
85 })
86 if err != nil {
87 t.Fatalf("Handler = %v", err)
88 }
89 return &ctlEnv{ctx: ctx, fake: fake, c: c, srv: serveTLS(t, h)}
90}
91
92// serveTLS serves h over TLS on 127.0.0.1 only.
93func serveTLS(t *testing.T, h http.Handler) *httptest.Server {
94 t.Helper()
95 ln, err := net.Listen("tcp", "127.0.0.1:0")
96 if err != nil {
97 t.Fatal(err)
98 }
99 srv := httptest.NewUnstartedServer(h)
100 srv.Listener = ln
101 srv.StartTLS()
102 t.Cleanup(srv.Close)
103 return srv
104}
105
106// settle moves every fake VM one step and lets the controller read it.
107func (e *ctlEnv) settle(t *testing.T) {
108 t.Helper()
109 e.fake.Tick()
110 if err := e.c.Refresh(e.ctx); err != nil {
111 t.Fatalf("Refresh = %v", err)
112 }
113}
114
115// newClient builds a client for srv with the flag on.
116func newClient(t *testing.T, srv *httptest.Server, key ed25519.PrivateKey, ctl ed25519.PublicKey) *Client {
117 t.Helper()
118 t.Setenv(FlagEnv, "1")
119 cl, err := New(Config{BaseURL: srv.URL, KeyID: idInst, Key: key, ControllerKey: ctl, HTTP: srv.Client()})
120 if err != nil {
121 t.Fatalf("New = %v", err)
122 }
123 return cl
124}
125
126func launchReq(attempt string) hostedwire.LaunchRequest {
127 return hostedwire.LaunchRequest{AttemptID: attempt, TaskID: "task-1", Account: "acct-1", Image: imgA,
128 Size: isolatedjob.SizeSmall, MaxLifetimeMS: (2 * time.Hour).Milliseconds(), InstanceCode: "code-test-1"}
129}
130
131func TestClientAgainstController(t *testing.T) {
132 e := newCtlEnv(t)
133 cl := newClient(t, e.srv, keyInst, ctlPublic())
134 ctx := e.ctx
135
136 view, err := cl.Launch(ctx, launchReq("a1"))
137 if err != nil || view.AttemptID != "a1" || view.State != "starting" || view.VMRef == "" {
138 t.Fatalf("Launch = %+v, %v; want a1 starting with a VM", view, err)
139 }
140 got, err := cl.Get(ctx, "a1")
141 if err != nil || got.VMRef != view.VMRef || got.LaunchID != view.LaunchID {
142 t.Fatalf("Get = %+v, %v; want the launched job %+v", got, err, view)
143 }
144 e.settle(t)
145 if got, err = cl.Get(ctx, "a1"); err != nil || got.State != "running" {
146 t.Fatalf("Get after a refresh = %+v, %v; want running", got, err)
147 }
148
149 // Pause: drain, acknowledge, suspend.
150 gen, err := cl.Drain(ctx, "a1")
151 if err != nil || gen != 1 {
152 t.Fatalf("Drain = %d, %v; want generation 1", gen, err)
153 }
154 if err := cl.Quiescent(ctx, "a1", gen+1); !errors.Is(err, ErrGenerationCancelled) {
155 t.Fatalf("Quiescent for a generation not open = %v, want ErrGenerationCancelled", err)
156 }
157 if err := cl.Quiescent(ctx, "a1", gen); err != nil {
158 t.Fatalf("Quiescent = %v", err)
159 }
160 if err := cl.Suspend(ctx, "a1", gen); err != nil {
161 t.Fatalf("Suspend = %v", err)
162 }
163 e.settle(t)
164 if got, err = cl.Get(ctx, "a1"); err != nil || got.State != "suspended" {
165 t.Fatalf("Get after suspend = %+v, %v; want suspended", got, err)
166 }
167
168 // Resume: pending while the VM still reports suspended, then the epoch.
169 if ep, err := cl.Resume(ctx, "a1", "op-1"); !errors.Is(err, ErrResumePending) || ep != 0 {
170 t.Fatalf("first Resume = %d, %v; want 0 and ErrResumePending", ep, err)
171 }
172 e.fake.Tick()
173 if ep, err := cl.Resume(ctx, "a1", "op-1"); err != nil || ep != 1 {
174 t.Fatalf("Resume retry = %d, %v; want epoch 1", ep, err)
175 }
176
177 // An abandoned pause reopens.
178 if gen, err = cl.Drain(ctx, "a1"); err != nil || gen != 2 {
179 t.Fatalf("second Drain = %d, %v; want generation 2", gen, err)
180 }
181 if err := cl.Reopen(ctx, "a1", gen); err != nil {
182 t.Fatalf("Reopen = %v", err)
183 }
184 if got, err = cl.Get(ctx, "a1"); err != nil || got.State != "running" || got.Epoch != 1 {
185 t.Fatalf("Get after reopen = %+v, %v; want running at epoch 1", got, err)
186 }
187
188 // Stop: pending first, then proof.
189 if _, err := cl.Stop(ctx, "a1", "done"); !errors.Is(err, ErrStopPending) {
190 t.Fatalf("first Stop = %v, want ErrStopPending", err)
191 }
192 var api *APIError
193 if _, err := cl.Stop(ctx, "a1", "done"); !errors.As(err, &api) || api.Status != http.StatusAccepted || api.Code != "stop_pending" {
194 t.Fatalf("second Stop before the VM stops = %v, want an APIError 202 stop_pending", err)
195 }
196 e.fake.Tick()
197 proof, err := cl.Stop(ctx, "a1", "done")
198 if err != nil || proof.AttemptID != "a1" || proof.VMRef != view.VMRef || !proof.State.Terminal() {
199 t.Fatalf("Stop = %+v, %v; want proof for a1's VM %s", proof, err, view.VMRef)
200 }
201
202 // Refusals come back as the controller's kinds.
203 if _, err := cl.Get(ctx, "nope"); !errors.Is(err, ErrForbidden) {
204 t.Fatalf("Get of an unknown attempt = %v, want ErrForbidden", err)
205 }
206 changed := launchReq("a1")
207 changed.TaskID = "task-2"
208 if _, err := cl.Launch(ctx, changed); !errors.Is(err, ErrConflict) {
209 t.Fatalf("launch of a1 with a different request = %v, want ErrConflict", err)
210 }
211 bad := launchReq("a2")
212 bad.Image = "sha256:cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc"
213 if _, err := cl.Launch(ctx, bad); !errors.Is(err, ErrImageNotAllowed) {
214 t.Fatalf("launch with an image off the allowlist = %v, want ErrImageNotAllowed", err)
215 }
216}
217
218// fakeCtl answers every request with whatever answer returns, given the
219// request's nonce.
220func fakeCtl(t *testing.T, answer func(w http.ResponseWriter, nonce string)) *httptest.Server {
221 t.Helper()
222 return serveTLS(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
223 answer(w, r.Header.Get(hostedwire.HeaderNonce))
224 }))
225}
226
227// signedAnswer writes status and body signed by key for nonce.
228func signedAnswer(w http.ResponseWriter, status int, body []byte, nonce string, key ed25519.PrivateKey) {
229 hostedwire.SignResponse(w.Header(), status, nonce, body, key)
230 w.WriteHeader(status)
231 _, _ = w.Write(body)
232}
233
234func TestClientRefusesUnsignedResponse(t *testing.T) {
235 good, err := json.Marshal(hostedwire.JobView{AttemptID: "a1", LaunchID: "launch-1", State: "running", VMRef: "vm-1"})
236 if err != nil {
237 t.Fatal(err)
238 }
239 const replayed = "captured-nonce-000000000"
240 cases := []struct {
241 name string
242 answer func(w http.ResponseWriter, nonce string)
243 }{
244 {"unsigned", func(w http.ResponseWriter, _ string) {
245 w.WriteHeader(http.StatusOK)
246 _, _ = w.Write(good)
247 }},
248 {"signed by another key", func(w http.ResponseWriter, nonce string) {
249 signedAnswer(w, http.StatusOK, good, nonce, keyOther)
250 }},
251 {"signed for another nonce", func(w http.ResponseWriter, _ string) {
252 // A captured response replayed, naming its own nonce.
253 w.Header().Set(hostedwire.HeaderNonce, replayed)
254 signedAnswer(w, http.StatusOK, good, replayed, keyCtl)
255 }},
256 {"signed for another status", func(w http.ResponseWriter, nonce string) {
257 hostedwire.SignResponse(w.Header(), http.StatusNotFound, nonce, good, keyCtl)
258 w.WriteHeader(http.StatusOK)
259 _, _ = w.Write(good)
260 }},
261 {"body changed after signing", func(w http.ResponseWriter, nonce string) {
262 hostedwire.SignResponse(w.Header(), http.StatusOK, nonce, good, keyCtl)
263 w.WriteHeader(http.StatusOK)
264 _, _ = w.Write(bytes.Replace(good, []byte("vm-1"), []byte("vm-2"), 1))
265 }},
266 {"too large", func(w http.ResponseWriter, nonce string) {
267 big := append(bytes.Repeat([]byte(" "), hostedwire.MaxBody), good...)
268 signedAnswer(w, http.StatusOK, big, nonce, keyCtl)
269 }},
270 }
271 for _, c := range cases {
272 cl := newClient(t, fakeCtl(t, c.answer), keyInst, ctlPublic())
273 v, err := cl.Get(context.Background(), "a1")
274 if !errors.Is(err, ErrUnverified) || v != (hostedwire.JobView{}) {
275 t.Fatalf("%s: Get = %+v, %v; want nothing and ErrUnverified", c.name, v, err)
276 }
277 }
278
279 // The same server signing properly is accepted, so the refusals above
280 // are for the signature and nothing else.
281 cl := newClient(t, fakeCtl(t, func(w http.ResponseWriter, nonce string) {
282 signedAnswer(w, http.StatusOK, good, nonce, keyCtl)
283 }), keyInst, ctlPublic())
284 if v, err := cl.Get(context.Background(), "a1"); err != nil || v.VMRef != "vm-1" {
285 t.Fatalf("properly signed Get = %+v, %v; want vm-1", v, err)
286 }
287
288 // The real controller's unsigned 401, for a key it does not know, is
289 // unverified too, not a typed refusal.
290 e := newCtlEnv(t)
291 stranger := newClient(t, e.srv, keyOther, ctlPublic())
292 _, err = stranger.Launch(e.ctx, launchReq("a1"))
293 var api *APIError
294 if !errors.Is(err, ErrUnverified) || errors.As(err, &api) {
295 t.Fatalf("launch by an unknown key = %v, want ErrUnverified and no APIError", err)
296 }
297 // A client holding the wrong controller key trusts nothing it hears.
298 wrongCtl := newClient(t, e.srv, keyInst, keyOther.Public().(ed25519.PublicKey))
299 if _, err := wrongCtl.Launch(e.ctx, launchReq("a1")); !errors.Is(err, ErrUnverified) {
300 t.Fatalf("launch with the wrong controller key = %v, want ErrUnverified", err)
301 }
302
303 // A redirect is not followed: the signed request never goes elsewhere.
304 var hits atomic.Int32
305 elsewhere := serveTLS(t, http.HandlerFunc(func(http.ResponseWriter, *http.Request) { hits.Add(1) }))
306 redirect := newClient(t, fakeCtl(t, func(w http.ResponseWriter, _ string) {
307 w.Header().Set("Location", elsewhere.URL+"/v1/jobs")
308 w.WriteHeader(http.StatusTemporaryRedirect)
309 }), keyInst, ctlPublic())
310 if _, err := redirect.Launch(context.Background(), launchReq("a1")); !errors.Is(err, ErrUnverified) || hits.Load() != 0 {
311 t.Fatalf("launch answered by a redirect = %v with %d hits elsewhere, want ErrUnverified and none", err, hits.Load())
312 }
313
314 // A redirect whose Location does not parse is still verified first:
315 // unsigned, it is ErrUnverified with nothing of the answer in the error,
316 // and only one request is sent. Signed, it is an unexpected answer.
317 for _, signed := range []bool{false, true} {
318 var sent atomic.Int32
319 bad := newClient(t, fakeCtl(t, func(w http.ResponseWriter, nonce string) {
320 sent.Add(1)
321 w.Header().Set("Location", "%")
322 if signed {
323 signedAnswer(w, http.StatusTemporaryRedirect, nil, nonce, keyCtl)
324 return
325 }
326 w.WriteHeader(http.StatusTemporaryRedirect)
327 }), keyInst, ctlPublic())
328 _, err := bad.Launch(context.Background(), launchReq("a1"))
329 want := ErrUnverified
330 if signed {
331 want = ErrUnexpected
332 }
333 if !errors.Is(err, want) || sent.Load() != 1 {
334 t.Fatalf("redirect to %%, signed %v: Launch = %v after %d requests, want %v after 1", signed, err, sent.Load(), want)
335 }
336 if msg := err.Error(); !signed && (strings.Contains(msg, "%") || strings.Contains(msg, "307") ||
337 strings.Contains(msg, "redirect") || strings.Contains(msg, "Location")) {
338 t.Fatalf("unsigned redirect error %q holds text from the answer", msg)
339 }
340 }
341}
342
343// TestTransportErrorsHoldNoServerBytes: a server that answers with bytes Go
344// cannot parse (status line, header, chunked trailer) gives ErrTransport,
345// and nothing it sent appears in the error.
346func TestTransportErrorsHoldNoServerBytes(t *testing.T) {
347 for name, raw := range map[string]string{
348 "malformed status": "HTTP/1.1 EVIL\r\n\r\n",
349 "malformed header": "HTTP/1.1 200 OK\r\nEVIL-HEADER-NO-COLON\r\nContent-Length: 0\r\n\r\n",
350 "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",
351 } {
352 srv := serveTLS(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
353 conn, buf, err := http.NewResponseController(w).Hijack()
354 if err != nil {
355 t.Errorf("hijack: %v", err)
356 return
357 }
358 defer conn.Close()
359 _, _ = buf.WriteString(raw)
360 _ = buf.Flush()
361 }))
362 _, err := newClient(t, srv, keyInst, ctlPublic()).Get(context.Background(), "a1")
363 if !errors.Is(err, ErrTransport) || errors.Is(err, ErrUnverified) {
364 t.Errorf("%s: Get = %v, want ErrTransport", name, err)
365 } else if msg := err.Error(); strings.Contains(msg, "EVIL") || strings.Contains(msg, "hello") {
366 t.Errorf("%s: error %q holds bytes the server sent", name, msg)
367 }
368 }
369}
370
371// TestClientHonoursTimeoutAndCancel:the HTTP client's Timeout and the
372// caller's context both bound a call to a controller that never answers.
373func TestClientHonoursTimeoutAndCancel(t *testing.T) {
374 srv := serveTLS(t, http.HandlerFunc(func(_ http.ResponseWriter, r *http.Request) {
375 select {
376 case <-r.Context().Done():
377 case <-time.After(3 * time.Second):
378 }
379 }))
380 t.Setenv(FlagEnv, "1")
381 slow, err := New(Config{BaseURL: srv.URL, KeyID: idInst, Key: keyInst, ControllerKey: ctlPublic(),
382 HTTP: &http.Client{Transport: srv.Client().Transport, Timeout: 100 * time.Millisecond}})
383 if err != nil {
384 t.Fatal(err)
385 }
386 start := time.Now()
387 if _, err := slow.Get(context.Background(), "a1"); !errors.Is(err, context.DeadlineExceeded) || time.Since(start) > 2*time.Second {
388 t.Fatalf("Get past the HTTP timeout = %v after %v, want context.DeadlineExceeded within 2 s", err, time.Since(start))
389 }
390 ctx, cancel := context.WithCancel(context.Background())
391 time.AfterFunc(100*time.Millisecond, cancel)
392 start = time.Now()
393 if _, err := newClient(t, srv, keyInst, ctlPublic()).Get(ctx, "a1"); !errors.Is(err, context.Canceled) || time.Since(start) > 2*time.Second {
394 t.Fatalf("Get with a cancelled context = %v after %v, want context.Canceled within 2 s", err, time.Since(start))
395 }
396}
397
398// TestSignedAnswersMapToKinds: a signed refusal is the controller's word and
399// maps to its kind by status and code; a signed answer that does not fit is
400// an error too.
401func TestSignedAnswersMapToKinds(t *testing.T) {
402 refusal := func(code string) []byte {
403 b, _ := json.Marshal(hostedwire.ErrorResponse{Code: code, Message: "fixed text"})
404 return b
405 }
406 for _, c := range []struct {
407 name string
408 status int
409 body []byte
410 want error
411 }{
412 {"signed signature refusal", http.StatusUnauthorized, refusal("unauthorized"), ErrUnauthorized},
413 {"replay refused", http.StatusUnauthorized, refusal("replay"), ErrReplay},
414 {"nonce store down", http.StatusServiceUnavailable, refusal("unavailable"), ErrUnavailable},
415 {"store lost", http.StatusServiceUnavailable, refusal("store_lost"), ErrStoreLost},
416 {"throttled", http.StatusTooManyRequests, refusal("throttled"), ErrThrottled},
417 {"past deadline", http.StatusGone, refusal("past_deadline"), ErrPastDeadline},
418 {"code and status disagree", http.StatusConflict, refusal("disabled"), ErrUnexpected},
419 {"unknown code", http.StatusTeapot, refusal("teapot"), ErrUnexpected},
420 {"refusal body not strict", http.StatusConflict, []byte(`{"code":"conflict","message":"x","extra":1}`), ErrUnexpected},
421 } {
422 cl := newClient(t, fakeCtl(t, func(w http.ResponseWriter, nonce string) {
423 signedAnswer(w, c.status, c.body, nonce, keyCtl)
424 }), keyInst, ctlPublic())
425 v, err := cl.Get(context.Background(), "a1")
426 if !errors.Is(err, c.want) || errors.Is(err, ErrUnverified) || v != (hostedwire.JobView{}) {
427 t.Fatalf("%s: Get = %+v, %v; want nothing and %v", c.name, v, err, c.want)
428 }
429 }
430}
431
432// TestClientMatchesHandlerErrorCodes holds the client to the handler's own
433// list of refusals: every status and code the handler can send maps to a
434// typed kind, and the client knows no code the handler does not send.
435func TestClientMatchesHandlerErrorCodes(t *testing.T) {
436 handler := map[string]int{}
437 for _, ec := range hostedctl.ErrorCodes() {
438 if s, dup := handler[ec.Code]; dup {
439 t.Fatalf("handler code %q has statuses %d and %d", ec.Code, s, ec.Status)
440 }
441 handler[ec.Code] = ec.Status
442 body, _ := json.Marshal(hostedwire.ErrorResponse{Code: ec.Code, Message: "m"})
443 err := refusal("get", ec.Status, body)
444 var api *APIError
445 if !errors.As(err, &api) || api.Kind == nil || errors.Is(err, ErrUnexpected) {
446 t.Errorf("handler refusal %d %q maps to %v, want a typed kind", ec.Status, ec.Code, err)
447 }
448 }
449 if len(handler) < 20 {
450 t.Fatalf("hostedctl.ErrorCodes lists %d codes; the handler has more", len(handler))
451 }
452 for code, r := range refusals {
453 if s, ok := handler[code]; !ok || s != r.status {
454 t.Errorf("client maps %d %q, which the handler does not send", r.status, code)
455 }
456 }
457}
458
459// TestSignedSuccessMustFit: a signed 200 that is not the route's strict
460// JSON, or does not answer the request asked, is ErrBadResponse. One case
461// per guard.
462func TestSignedSuccessMustFit(t *testing.T) {
463 ctx := context.Background()
464 for _, c := range []struct {
465 name string
466 body string
467 call func(cl *Client) (any, error)
468 }{
469 {"launch view for another attempt", `{"attempt_id":"a9","state":"starting","vm_ref":"vm-1"}`,
470 func(cl *Client) (any, error) { return cl.Launch(ctx, launchReq("a1")) }},
471 {"get view for another attempt", `{"attempt_id":"a9","state":"running"}`,
472 func(cl *Client) (any, error) { return cl.Get(ctx, "a1") }},
473 {"get view with an unknown field", `{"attempt_id":"a1","bogus":true}`,
474 func(cl *Client) (any, error) { return cl.Get(ctx, "a1") }},
475 {"stop proof for another attempt", `{"attempt_id":"a9","vm_ref":"vm-1","state":"stopped","observed_at_ns":1}`,
476 func(cl *Client) (any, error) { return cl.Stop(ctx, "a1", "done") }},
477 {"stop proof not terminal", `{"attempt_id":"a1","vm_ref":"vm-1","state":"running","observed_at_ns":1}`,
478 func(cl *Client) (any, error) { return cl.Stop(ctx, "a1", "done") }},
479 {"drain generation 0", `{"generation":0}`,
480 func(cl *Client) (any, error) { return cl.Drain(ctx, "a1") }},
481 {"quiescent for another generation", `{"generation":7}`,
482 func(cl *Client) (any, error) { return nil, cl.Quiescent(ctx, "a1", 1) }},
483 {"suspend for another generation", `{"generation":7}`,
484 func(cl *Client) (any, error) { return nil, cl.Suspend(ctx, "a1", 1) }},
485 {"reopen for another generation", `{"generation":7}`,
486 func(cl *Client) (any, error) { return nil, cl.Reopen(ctx, "a1", 1) }},
487 {"resume epoch 0", `{"epoch":0}`,
488 func(cl *Client) (any, error) { return cl.Resume(ctx, "a1", "op-1") }},
489 } {
490 cl := newClient(t, fakeCtl(t, func(w http.ResponseWriter, nonce string) {
491 signedAnswer(w, http.StatusOK, []byte(c.body), nonce, keyCtl)
492 }), keyInst, ctlPublic())
493 got, err := c.call(cl)
494 if !errors.Is(err, ErrBadResponse) {
495 t.Errorf("%s: = %+v, %v; want ErrBadResponse", c.name, got, err)
496 continue
497 }
498 switch v := got.(type) {
499 case hostedwire.JobView:
500 if v != (hostedwire.JobView{}) {
501 t.Errorf("%s: returned %+v with the error, want nothing", c.name, v)
502 }
503 case hostedwire.StopProof:
504 if v != (hostedwire.StopProof{}) {
505 t.Errorf("%s: returned %+v with the error, want nothing", c.name, v)
506 }
507 case int64:
508 if v != 0 {
509 t.Errorf("%s: returned %d with the error, want 0", c.name, v)
510 }
511 }
512 }
513}
514
515func TestClientRefusesWithoutFlag(t *testing.T) {
516 srv := fakeCtl(t, func(http.ResponseWriter, string) {})
517 cfg := Config{BaseURL: srv.URL, KeyID: idInst, Key: keyInst, ControllerKey: ctlPublic(), HTTP: srv.Client()}
518 for _, v := range []string{"", "0", "true", "yes", " 1", "1 ", "01"} {
519 t.Setenv(FlagEnv, v)
520 if cl, err := New(cfg); !errors.Is(err, ErrRunnersOff) || cl != nil {
521 t.Fatalf("New with %s=%q = (client %v, %v); want ErrRunnersOff", FlagEnv, v, cl != nil, err)
522 }
523 }
524 os.Unsetenv(FlagEnv)
525 if _, err := New(cfg); !errors.Is(err, ErrRunnersOff) {
526 t.Fatalf("New with %s unset = %v, want ErrRunnersOff", FlagEnv, err)
527 }
528 t.Setenv(FlagEnv, "1")
529 if _, err := New(cfg); err != nil {
530 t.Fatalf("New with %s=1 = %v", FlagEnv, err)
531 }
532}
533
534func TestNewRefusesBadConfig(t *testing.T) {
535 t.Setenv(FlagEnv, "1")
536 good := Config{BaseURL: "https://127.0.0.1:8443", KeyID: idInst, Key: keyInst, ControllerKey: ctlPublic(), HTTP: &http.Client{}}
537 cl, err := New(good)
538 if err != nil {
539 t.Fatalf("New(good) = %v", err)
540 }
541 if s, want := fmt.Sprintf("%v %+v", cl, cl), "hostedclient.Client(https://127.0.0.1:8443)"; s != want+" "+want {
542 t.Fatalf("a printed client = %q, want only %q twice", s, want)
543 }
544 for name, change := range map[string]func(*Config){
545 "plain http": func(c *Config) { c.BaseURL = "http://127.0.0.1:8443" },
546 "no scheme": func(c *Config) { c.BaseURL = "127.0.0.1:8443" },
547 "no host": func(c *Config) { c.BaseURL = "https://" },
548 "a path": func(c *Config) { c.BaseURL = "https://127.0.0.1:8443/api" },
549 "a query": func(c *Config) { c.BaseURL = "https://127.0.0.1:8443?x=1" },
550 "user info": func(c *Config) { c.BaseURL = "https://u:p@127.0.0.1:8443" },
551 "no key ID": func(c *Config) { c.KeyID = "" },
552 "no key": func(c *Config) { c.Key = nil },
553 "short key": func(c *Config) { c.Key = c.Key[:ed25519.SeedSize] },
554 "no controller key": func(c *Config) { c.ControllerKey = nil },
555 "short controller key": func(c *Config) { c.ControllerKey = c.ControllerKey[:16] },
556 "no HTTP client": func(c *Config) { c.HTTP = nil },
557 } {
558 cfg := good
559 change(&cfg)
560 if cl, err := New(cfg); err == nil || cl != nil {
561 t.Errorf("New with %s = (client %v, %v); want a refusal", name, cl != nil, err)
562 }
563 }
564}
565
566func TestEmptyAttemptRefused(t *testing.T) {
567 var hits atomic.Int32
568 cl := newClient(t, fakeCtl(t, func(http.ResponseWriter, string) { hits.Add(1) }), keyInst, ctlPublic())
569 for _, a := range []string{"", ".", ".."} {
570 if _, err := cl.Get(context.Background(), a); err == nil {
571 t.Fatalf("Get(%q) = nil error, want a refusal", a)
572 }
573 }
574 if hits.Load() != 0 {
575 t.Fatalf("%d requests sent for refused attempts, want none", hits.Load())
576 }
577}
578
579// TestInstanceDoesNotCallHostedClient holds slice 1a's promise that the
580// instance never calls the hosted controller. Slice 2 deletes it.
581func TestInstanceDoesNotCallHostedClient(t *testing.T) {
582 gobin, err := exec.LookPath("go")
583 if err != nil {
584 t.Fatalf("go not on PATH: %v", err)
585 }
586 const instance = "amadan.net/oficina/equipo/cmd/equipo"
587 ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second)
588 defer cancel()
589 cmd := exec.CommandContext(ctx, gobin, "list", "-deps", instance)
590 // The child reads cmd/equipo's source, which go test does not see:
591 // declare it, so adding the import reruns this test instead of
592 // replaying a cached pass.
593 testci.GoCommand(t, cmd)
594 var stderr bytes.Buffer
595 cmd.Stderr = &stderr
596 out, err := cmd.Output()
597 if err != nil {
598 t.Fatalf("go list -deps %s: %v\n%s", instance, err, stderr.Bytes())
599 }
600 deps := strings.Fields(string(out))
601 var self bool
602 for _, d := range deps {
603 if d == "amadan.net/oficina/equipo/internal/hostedclient" {
604 t.Fatalf("%s depends on internal/hostedclient; slice 1a keeps the instance off the hosted controller", instance)
605 }
606 self = self || d == instance
607 }
608 if !self {
609 t.Fatalf("go list -deps %s did not list the package itself; got %d lines", instance, len(deps))
610 }
611}
612