package hostedctl import ( "bytes" "crypto/ed25519" "encoding/json" "errors" "fmt" "io" "net" "net/http" "net/http/httptest" "strings" "testing" "time" "amadan.net/oficina/equipo/internal/hostedwire" "amadan.net/oficina/equipo/internal/isolatedjob" ) // Keys of the HTTP tests: two instance keys, an operator key and the // controller's signing key. var ( keyInstA = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize)) keyInstB = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{2}, ed25519.SeedSize)) keyOp = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{3}, ed25519.SeedSize)) keyCtl = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{4}, ed25519.SeedSize)) ) const ( idInstA hostedwire.KeyID = "inst-a" idInstB hostedwire.KeyID = "inst-b" idOp hostedwire.KeyID = "op-1" ) func testKeys() map[hostedwire.KeyID]hostedwire.VerifyKey { return map[hostedwire.KeyID]hostedwire.VerifyKey{ idInstA: {Public: keyInstA.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance}, idInstB: {Public: keyInstB.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance}, idOp: {Public: keyOp.Public().(ed25519.PublicKey), Role: hostedwire.RoleOperator}, } } // apiEnv is a launchEnv with the controller's API served over TLS on // 127.0.0.1. type apiEnv struct { *launchEnv srv *httptest.Server metrics *Metrics nonces int } func newAPIEnv(t *testing.T, enabled bool) *apiEnv { t.Helper() e := &apiEnv{launchEnv: newLaunchEnv(t)} if !enabled { e.cfg.Enabled = false e.newController() e.audit() } e.serve() return e } // serve starts (or restarts) the API server over the current controller. func (e *apiEnv) serve() { e.t.Helper() if e.srv != nil { e.srv.Close() } e.metrics = NewMetrics() h, err := e.c.Handler(HandlerConfig{Keys: testKeys(), Signing: keyCtl, Wall: e.clk.Wall, Metrics: e.metrics}) if err != nil { e.t.Fatalf("Handler = %v", err) } ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { e.t.Fatal(err) } e.srv = httptest.NewUnstartedServer(h) e.srv.Listener = ln e.srv.StartTLS() e.t.Cleanup(e.srv.Close) } // reply is one answer from the API. type reply struct { status int body []byte resp *http.Response nonce string } // signed reports whether the reply carries a controller signature bound to // its request's nonce. func (r reply) signed() bool { return hostedwire.VerifyResponse(r.resp, r.body, r.nonce, keyCtl.Public().(ed25519.PublicKey)) == nil } // errBody decodes an ErrorResponse. func (r reply) errBody(t *testing.T) hostedwire.ErrorResponse { t.Helper() var er hostedwire.ErrorResponse if err := json.Unmarshal(r.body, &er); err != nil { t.Fatalf("error body %q: %v", r.body, err) } return er } // nextNonce returns a fresh nonce for this env. func (e *apiEnv) nextNonce() string { e.nonces++ return fmt.Sprintf("test-nonce-%010d", e.nonces) } // newRequest builds a request signed by key under id with a fresh nonce. func (e *apiEnv) newRequest(method, path string, body []byte, id hostedwire.KeyID, key ed25519.PrivateKey) (*http.Request, string) { e.t.Helper() req, err := http.NewRequest(method, e.srv.URL+path, bytes.NewReader(body)) if err != nil { e.t.Fatal(err) } nonce := e.nextNonce() if err := hostedwire.SignRequest(req, body, id, key, e.clk.Wall(), nonce); err != nil { e.t.Fatal(err) } return req, nonce } func (e *apiEnv) send(req *http.Request, nonce string) reply { e.t.Helper() resp, err := e.srv.Client().Do(req) if err != nil { e.t.Fatalf("%s %s: %v", req.Method, req.URL.Path, err) } defer resp.Body.Close() b, err := io.ReadAll(resp.Body) if err != nil { e.t.Fatal(err) } return reply{status: resp.StatusCode, body: b, resp: resp, nonce: nonce} } // call sends one signed request and wants a signed reply. func (e *apiEnv) call(method, path string, body any, id hostedwire.KeyID, key ed25519.PrivateKey) reply { e.t.Helper() var raw []byte switch b := body.(type) { case nil: case string: raw = []byte(b) default: var err error if raw, err = json.Marshal(b); err != nil { e.t.Fatal(err) } } r := e.send(e.newRequest(method, path, raw, id, key)) if !r.signed() { e.t.Fatalf("%s %s answered %d %q without a valid signature", method, path, r.status, r.body) } return r } func wireLaunch(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: testCode} } // launch launches attempt as instance A and wants a 200. func (e *apiEnv) launch(attempt string) hostedwire.JobView { e.t.Helper() r := e.call("POST", "/v1/jobs", wireLaunch(attempt), idInstA, keyInstA) if r.status != http.StatusOK { e.t.Fatalf("launch %s = %d %s", attempt, r.status, r.body) } var v hostedwire.JobView if err := hostedwire.DecodeStrict(bytes.NewReader(r.body), &v); err != nil { e.t.Fatalf("launch reply %q: %v", r.body, err) } return v } // jobRoutes are the attempt routes with a valid body for each. func jobRoutes(attempt string) []struct { method, path string body any } { p := "/v1/jobs/" + attempt return []struct { method, path string body any }{ {"GET", p, nil}, {"POST", p + "/stop", hostedwire.StopRequest{Reason: "done"}}, {"POST", p + "/drain", hostedwire.DrainRequest{}}, {"POST", p + "/quiescent", hostedwire.QuiescentRequest{Generation: 1}}, {"POST", p + "/suspend", hostedwire.SuspendRequest{Generation: 1}}, {"POST", p + "/reopen", hostedwire.ReopenRequest{Generation: 1}}, {"POST", p + "/resume", hostedwire.ResumeRequest{OperationID: "op-1"}}, } } // fixedBody is the exact body of a refusal with code. func fixedBody(t *testing.T, code string) string { t.Helper() for _, a := range apiErrors { if a.code == code { b, _ := json.Marshal(hostedwire.ErrorResponse{Code: a.code, Message: a.msg}) return string(b) } } t.Fatalf("no API error with code %q", code) return "" } func TestRoutesEnforceRoles(t *testing.T) { t.Parallel() e := newAPIEnv(t, true) view := e.launch("a1") // The operator key may use no job route: the handler refuses it with a // signed 403 and its own audit row, before any controller method runs. routes := append(jobRoutes("a1"), struct { method, path string body any }{"POST", "/v1/jobs", wireLaunch("a2")}) for _, rt := range routes { before := len(auditRows(t, e.store)) r := e.call(rt.method, rt.path, rt.body, idOp, keyOp) if r.status != http.StatusForbidden || string(r.body) != fixedBody(t, "forbidden") { t.Fatalf("operator %s %s = %d %s, want 403 %s", rt.method, rt.path, r.status, r.body, fixedBody(t, "forbidden")) } rows := auditRows(t, e.store) if len(rows) != before+1 { t.Fatalf("operator %s %s wrote %d audit rows, want 1", rt.method, rt.path, len(rows)-before) } if a := rows[len(rows)-1]; a.Action != actionAPIRefused || a.Actor != idOp { t.Fatalf("operator %s %s audit row = %+v, want %s by %s", rt.method, rt.path, a, actionAPIRefused, idOp) } } if j, _ := e.job("a1"); j.state != JobStarting || e.jobCount() != 1 { t.Fatalf("after the operator's refused calls: a1 %s, %d jobs; want a1 starting and no new job", j.state, e.jobCount()) } // An instance key may not list VMs. before := len(auditRows(t, e.store)) if r := e.call("GET", "/v1/vms", nil, idInstA, keyInstA); r.status != http.StatusForbidden { t.Fatalf("instance GET /v1/vms = %d %s, want 403", r.status, r.body) } if rows := auditRows(t, e.store); len(rows) != before+1 || rows[len(rows)-1].Action != actionAPIRefused { t.Fatalf("instance GET /v1/vms audit rows %v, want one %s", rows[before:], actionAPIRefused) } // The operator key lists VMs, each with its attempt. r := e.call("GET", "/v1/vms", nil, idOp, keyOp) if r.status != http.StatusOK { t.Fatalf("operator GET /v1/vms = %d %s", r.status, r.body) } var list hostedwire.VMListResponse if err := hostedwire.DecodeStrict(bytes.NewReader(r.body), &list); err != nil { t.Fatal(err) } if len(list.VMs) != 1 || list.VMs[0].VMRef != view.VMRef || list.VMs[0].AttemptID != "a1" { t.Fatalf("GET /v1/vms = %+v, want only a1's VM %s", list.VMs, view.VMRef) } } func TestInstanceKeySeesOnlyItsJobs(t *testing.T) { t.Parallel() e := newAPIEnv(t, true) view := e.launch("a1") if view.AttemptID != "a1" || view.State != JobStarting || view.VMRef == "" || len(view.LaunchID) != launchIDLen { t.Fatalf("launch view = %+v", view) } r := e.call("GET", "/v1/jobs/a1", nil, idInstA, keyInstA) if r.status != http.StatusOK { t.Fatalf("creator GET = %d %s", r.status, r.body) } // Another instance key gets the same 403 for a1 and for an attempt // that does not exist, so it learns nothing of a1. for _, attempt := range []string{"a1", "nope"} { for _, rt := range jobRoutes(attempt) { r := e.call(rt.method, rt.path, rt.body, idInstB, keyInstB) if r.status != http.StatusForbidden || string(r.body) != fixedBody(t, "forbidden") { t.Fatalf("instance B %s %s = %d %s, want 403", rt.method, rt.path, r.status, r.body) } } } if j, _ := e.job("a1"); j.state != JobStarting || j.stopRequested.Valid { t.Fatalf("a1 after instance B's calls = %s (stop asked %v), want starting with no stop", j.state, j.stopRequested.Valid) } // A second launch of a1 by B is a conflict, not a takeover. if r := e.call("POST", "/v1/jobs", wireLaunch("a1"), idInstB, keyInstB); r.status != http.StatusConflict { t.Fatalf("instance B relaunch of a1 = %d %s, want 409", r.status, r.body) } } func TestUnknownFieldsRefused(t *testing.T) { t.Parallel() e := newAPIEnv(t, true) good, _ := json.Marshal(wireLaunch("a1")) extra := strings.Replace(string(good), "{", `{"vm_ref":"vm-9",`, 1) upper := strings.Replace(string(good), `"attempt_id"`, `"Attempt_ID"`, 1) twice := strings.Replace(string(good), "{", `{"attempt_id":"a9",`, 1) for _, c := range []struct{ name, body string }{{"unknown field", extra}, {"upper-case key", upper}, {"repeated key", twice}, {"two objects", string(good) + string(good)}, {"not an object", `[1]`}, {"empty", ``}} { r := e.call("POST", "/v1/jobs", c.body, idInstA, keyInstA) if r.status != http.StatusBadRequest || string(r.body) != fixedBody(t, "bad_json") { t.Fatalf("launch with %s = %d %s, want 400 %s", c.name, r.status, r.body, fixedBody(t, "bad_json")) } } if n := e.jobCount(); n != 0 { t.Fatalf("%d jobs after refused launches, want 0", n) } e.launch("a1") for path, body := range map[string]string{ "/v1/jobs/a1/stop": `{"reason":"done","force":true}`, "/v1/jobs/a1/drain": `{"generation":1}`, "/v1/jobs/a1": `{}`, // GET takes no body } { method := "POST" if path == "/v1/jobs/a1" { method = "GET" } if r := e.call(method, path, body, idInstA, keyInstA); r.status != http.StatusBadRequest { t.Fatalf("%s %s with %s = %d %s, want 400", method, path, body, r.status, r.body) } } if j, _ := e.job("a1"); j.stopRequested.Valid || j.state != JobStarting { t.Fatalf("a1 after refused bodies = %s, stop asked %v; want untouched", j.state, j.stopRequested.Valid) } } func TestResponsesSigned(t *testing.T) { t.Parallel() e := newAPIEnv(t, true) // Success, refusals and unknown routes are all signed, bound to the // request's nonce. req, nonce := e.newRequest("POST", "/v1/jobs", mustJSON(t, wireLaunch("a1")), idInstA, keyInstA) r := e.send(req, nonce) if r.status != http.StatusOK || !r.signed() { t.Fatalf("launch = %d %s, signed %v; want a signed 200", r.status, r.body, r.signed()) } r.nonce = e.nextNonce() if r.signed() { t.Fatal("the launch reply verifies against another nonce") } for _, c := range []struct { method, path string want int code string }{ {"GET", "/v1/nothing", http.StatusNotFound, "no_route"}, {"GET", "/v1/jobs/a1/stop", http.StatusMethodNotAllowed, "method"}, {"DELETE", "/v1/jobs/a1", http.StatusMethodNotAllowed, "method"}, {"GET", "/v1/vms?all=1", http.StatusBadRequest, "query"}, } { r := e.call(c.method, c.path, nil, idOp, keyOp) if r.status != c.want || string(r.body) != fixedBody(t, c.code) { t.Fatalf("%s %s = %d %s, want signed %d %s", c.method, c.path, r.status, r.body, c.want, fixedBody(t, c.code)) } } // A request that fails verification is answered unsigned, with a // fixed body naming no reason. unauth := fixedBody(t, "unauthorized") check := func(name string, r reply, status int, body string) { t.Helper() if r.status != status || string(r.body) != body || r.resp.Header.Get(hostedwire.HeaderSignature) != "" { t.Fatalf("%s = %d %q (signature %q), want unsigned %d %s", name, r.status, r.body, r.resp.Header.Get(hostedwire.HeaderSignature), status, body) } } plain, _ := http.NewRequest("GET", e.srv.URL+"/v1/jobs/a1", nil) check("unsigned request", e.send(plain, "nonce-unused-0000000"), http.StatusUnauthorized, unauth) req, nonce = e.newRequest("GET", "/v1/jobs/a1", nil, idInstA, keyInstB) // B's key under A's ID check("wrong key", e.send(req, nonce), http.StatusUnauthorized, unauth) req, nonce = e.newRequest("GET", "/v1/jobs/a1", nil, "inst-z", keyInstA) check("unknown key ID", e.send(req, nonce), http.StatusUnauthorized, unauth) req, nonce = e.newRequest("GET", "/v1/jobs/a1", nil, idInstA, keyInstA) again := req.Clone(req.Context()) if r := e.send(req, nonce); r.status != http.StatusOK || !r.signed() { t.Fatalf("first send = %d %s", r.status, r.body) } // A replay carries a valid signature, so its refusal is signed, bound to // the replayed nonce (ruling R25). r = e.send(again, nonce) if r.status != http.StatusUnauthorized || string(r.body) != fixedBody(t, "replay") || !r.signed() { t.Fatalf("replay = %d %s, signed %v; want a signed 401 %s", r.status, r.body, r.signed(), fixedBody(t, "replay")) } req, nonce = e.newRequest("GET", "/v1/jobs/a1", nil, idInstA, keyInstA) e.clk.SetWall(testWall.Add(hostedwire.MaxSkew + time.Second)) check("skewed", e.send(req, nonce), http.StatusUnauthorized, unauth) e.clk.SetWall(testWall) big := bytes.Repeat([]byte{' '}, hostedwire.MaxBody+1) req, nonce = e.newRequest("POST", "/v1/jobs", nil, idInstA, keyInstA) req.Body, req.ContentLength = io.NopCloser(bytes.NewReader(big)), int64(len(big)) check("too large", e.send(req, nonce), http.StatusRequestEntityTooLarge, fixedBody(t, "too_large")) // A nonce-store failure comes after the signature verified: signed 503 // (the closed store reports store_lost, first in the table). if err := e.store.Close(); err != nil { t.Fatal(err) } req, nonce = e.newRequest("GET", "/v1/jobs/a1", nil, idInstA, keyInstA) r = e.send(req, nonce) if r.status != http.StatusServiceUnavailable || string(r.body) != fixedBody(t, "store_lost") || !r.signed() { t.Fatalf("nonce store down = %d %s, signed %v; want a signed 503 %s", r.status, r.body, r.signed(), fixedBody(t, "store_lost")) } } // TestResponsesSignedForHead: Go never sends a HEAD response's body, so the // signature must cover the empty body the client receives. func TestResponsesSignedForHead(t *testing.T) { t.Parallel() e := newAPIEnv(t, true) e.launch("a1") for path, want := range map[string]int{"/v1/jobs/a1": http.StatusMethodNotAllowed, "/v1/nothing": http.StatusNotFound} { req, nonce := e.newRequest("HEAD", path, nil, idInstA, keyInstA) r := e.send(req, nonce) if r.status != want || len(r.body) != 0 || !r.signed() { t.Fatalf("HEAD %s = %d %q, signed %v; want a signed %d with no body", path, r.status, r.body, r.signed(), want) } } } func mustJSON(t *testing.T, v any) []byte { t.Helper() b, err := json.Marshal(v) if err != nil { t.Fatal(err) } return b } func TestDisabledRefusesLaunchButServesStop(t *testing.T) { t.Parallel() e := newAPIEnv(t, true) e.launch("a1") // The same store under a controller with launches off. e.cfg.Enabled = false e.newController() e.audit() e.serve() r := e.call("POST", "/v1/jobs", wireLaunch("a2"), idInstA, keyInstA) if r.status != http.StatusServiceUnavailable || r.errBody(t).Code != "disabled" { t.Fatalf("launch while disabled = %d %s, want 503 disabled", r.status, r.body) } if e.jobCount() != 1 { t.Fatalf("%d jobs, want only a1", e.jobCount()) } // Stop is served: pending first, then proof. stop := hostedwire.StopRequest{Reason: "done"} r = e.call("POST", "/v1/jobs/a1/stop", stop, idInstA, keyInstA) if r.status != http.StatusAccepted || r.errBody(t).Code != "stop_pending" { t.Fatalf("stop while disabled = %d %s, want 202 stop_pending", r.status, r.body) } e.fake.Tick() r = e.call("POST", "/v1/jobs/a1/stop", stop, idInstA, keyInstA) var proof hostedwire.StopProof if r.status != http.StatusOK || hostedwire.DecodeStrict(bytes.NewReader(r.body), &proof) != nil || proof.AttemptID != "a1" || !proof.State.Terminal() { t.Fatalf("second stop = %d %s, want 200 with proof", r.status, r.body) } } func TestMetricsCountJobsByState(t *testing.T) { t.Parallel() e := newAPIEnv(t, true) e.launch("a1") e.launch("a2") e.call("POST", "/v1/jobs/a1/stop", hostedwire.StopRequest{Reason: "done"}, idInstA, keyInstA) e.call("GET", "/v1/vms", nil, idInstA, keyInstA) // a refusal got := e.scrape() for _, line := range []string{ `equipo_hosted_jobs{state="starting"} 1`, `equipo_hosted_jobs{state="stopping"} 1`, `equipo_hosted_jobs{state="waiting"} 0`, `equipo_hosted_store_readable 1`, `equipo_hosted_launches_total{result="starting"} 2`, `equipo_hosted_errors_total{route="stop",code="stop_pending"} 1`, `equipo_hosted_errors_total{route="vms",code="forbidden"} 1`, `equipo_hosted_network_audit_passing 1`, } { if !strings.Contains(got, "\n"+line+"\n") { t.Errorf("metrics lack %q:\n%s", line, got) } } if strings.Contains(got, "\nequipo_hosted_reap_last_error ") { t.Errorf("metrics report a reaper pass before any ran:\n%s", got) } // After a pass whose alert is delivered, its results and the alert show. al := e.metrics.CountAlerts(&recordingAlerter{}) if err := al.Alert(e.ctx, Alert{Kind: AlertOrphanStopped, Detail: "vm-1"}); err != nil { t.Fatal(err) } failing := e.metrics.CountAlerts(&recordingAlerter{fail: errors.New("down")}) _ = failing.Alert(e.ctx, Alert{Kind: AlertAuditFailed}) e.reap() got = e.scrape() for _, line := range []string{ `equipo_hosted_reap_last_error 0`, `equipo_hosted_reap_last_orphans_stopped 0`, `equipo_hosted_reap_last_orphans_deferred 0`, `equipo_hosted_alerts_total{kind="orphan_stopped",result="sent"} 1`, `equipo_hosted_alerts_total{kind="audit_failed",result="failed"} 1`, } { if !strings.Contains(got, "\n"+line+"\n") { t.Errorf("metrics after a pass lack %q:\n%s", line, got) } } // An unreadable store leaves the job counts out, never zero. if err := e.store.Close(); err != nil { t.Fatal(err) } got = e.scrape() if strings.Contains(got, "equipo_hosted_jobs{") || !strings.Contains(got, "\nequipo_hosted_store_readable 0\n") { t.Fatalf("metrics with the store closed:\n%s", got) } } // scrape reads the metrics page. func (e *apiEnv) scrape() string { e.t.Helper() rec := httptest.NewRecorder() e.metrics.Handler(e.c).ServeHTTP(rec, httptest.NewRequest("GET", "/metrics", nil)) if rec.Code != http.StatusOK { e.t.Fatalf("GET /metrics = %d", rec.Code) } return "\n" + rec.Body.String() } func TestRoutesMapErrorsToStatus(t *testing.T) { t.Parallel() for _, c := range []struct { err error want int }{ {isolatedjob.ErrInvalid, 400}, {hostedwire.ErrBadJSON, 400}, {ErrImageNotAllowed, 400}, {hostedwire.ErrBadSignature, 401}, {hostedwire.ErrSkew, 401}, {hostedwire.ErrReplay, 401}, {hostedwire.ErrUnknownKey, 401}, {ErrForbidden, 403}, {isolatedjob.ErrNotFound, 404}, {isolatedjob.ErrConflict, 409}, {ErrGenerationCancelled, 409}, {ErrNotQuiescent, 409}, {ErrResumePending, 409}, {ErrReplacementLive, 409}, {ErrStateUnknown, 409}, {ErrStopPending, 202}, {ErrPastDeadline, 410}, {hostedwire.ErrTooLarge, 413}, {isolatedjob.ErrThrottled, 429}, {ErrDisabled, 503}, {ErrNetworkAudit, 503}, {ErrStoreLost, 503}, {ErrProviderLaunch, 502}, {errors.New("anything else"), 500}, // A refusal whose audit row could not be written because the store // is gone reports the store. {errors.Join(ErrForbidden, fmt.Errorf("%w: gone", ErrStoreLost)), 503}, } { a := lookupError(fmt.Errorf("%w: secret detail", c.err)) if a.status != c.want || strings.Contains(a.msg, "secret") || a.msg == "" || a.code == "" { t.Errorf("lookupError(%v) = %+v, want status %d with a fixed message", c.err, a, c.want) } } }