| 1 | package hostedctl |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto/ed25519" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "net" |
| 11 | "net/http" |
| 12 | "net/http/httptest" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | "time" |
| 16 | |
| 17 | "amadan.net/oficina/equipo/internal/hostedwire" |
| 18 | "amadan.net/oficina/equipo/internal/isolatedjob" |
| 19 | ) |
| 20 | |
| 21 | // Keys of the HTTP tests: two instance keys, an operator key and the |
| 22 | // controller's signing key. |
| 23 | var ( |
| 24 | keyInstA = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize)) |
| 25 | keyInstB = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{2}, ed25519.SeedSize)) |
| 26 | keyOp = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{3}, ed25519.SeedSize)) |
| 27 | keyCtl = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{4}, ed25519.SeedSize)) |
| 28 | ) |
| 29 | |
| 30 | const ( |
| 31 | idInstA hostedwire.KeyID = "inst-a" |
| 32 | idInstB hostedwire.KeyID = "inst-b" |
| 33 | idOp hostedwire.KeyID = "op-1" |
| 34 | ) |
| 35 | |
| 36 | func testKeys() map[hostedwire.KeyID]hostedwire.VerifyKey { |
| 37 | return map[hostedwire.KeyID]hostedwire.VerifyKey{ |
| 38 | idInstA: {Public: keyInstA.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance}, |
| 39 | idInstB: {Public: keyInstB.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance}, |
| 40 | idOp: {Public: keyOp.Public().(ed25519.PublicKey), Role: hostedwire.RoleOperator}, |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | // apiEnv is a launchEnv with the controller's API served over TLS on |
| 45 | // 127.0.0.1. |
| 46 | type apiEnv struct { |
| 47 | *launchEnv |
| 48 | srv *httptest.Server |
| 49 | metrics *Metrics |
| 50 | nonces int |
| 51 | } |
| 52 | |
| 53 | func newAPIEnv(t *testing.T, enabled bool) *apiEnv { |
| 54 | t.Helper() |
| 55 | e := &apiEnv{launchEnv: newLaunchEnv(t)} |
| 56 | if !enabled { |
| 57 | e.cfg.Enabled = false |
| 58 | e.newController() |
| 59 | e.audit() |
| 60 | } |
| 61 | e.serve() |
| 62 | return e |
| 63 | } |
| 64 | |
| 65 | // serve starts (or restarts) the API server over the current controller. |
| 66 | func (e *apiEnv) serve() { |
| 67 | e.t.Helper() |
| 68 | if e.srv != nil { |
| 69 | e.srv.Close() |
| 70 | } |
| 71 | e.metrics = NewMetrics() |
| 72 | h, err := e.c.Handler(HandlerConfig{Keys: testKeys(), Signing: keyCtl, Wall: e.clk.Wall, Metrics: e.metrics}) |
| 73 | if err != nil { |
| 74 | e.t.Fatalf("Handler = %v", err) |
| 75 | } |
| 76 | ln, err := net.Listen("tcp", "127.0.0.1:0") |
| 77 | if err != nil { |
| 78 | e.t.Fatal(err) |
| 79 | } |
| 80 | e.srv = httptest.NewUnstartedServer(h) |
| 81 | e.srv.Listener = ln |
| 82 | e.srv.StartTLS() |
| 83 | e.t.Cleanup(e.srv.Close) |
| 84 | } |
| 85 | |
| 86 | // reply is one answer from the API. |
| 87 | type reply struct { |
| 88 | status int |
| 89 | body []byte |
| 90 | resp *http.Response |
| 91 | nonce string |
| 92 | } |
| 93 | |
| 94 | // signed reports whether the reply carries a controller signature bound to |
| 95 | // its request's nonce. |
| 96 | func (r reply) signed() bool { |
| 97 | return hostedwire.VerifyResponse(r.resp, r.body, r.nonce, keyCtl.Public().(ed25519.PublicKey)) == nil |
| 98 | } |
| 99 | |
| 100 | // errBody decodes an ErrorResponse. |
| 101 | func (r reply) errBody(t *testing.T) hostedwire.ErrorResponse { |
| 102 | t.Helper() |
| 103 | var er hostedwire.ErrorResponse |
| 104 | if err := json.Unmarshal(r.body, &er); err != nil { |
| 105 | t.Fatalf("error body %q: %v", r.body, err) |
| 106 | } |
| 107 | return er |
| 108 | } |
| 109 | |
| 110 | // nextNonce returns a fresh nonce for this env. |
| 111 | func (e *apiEnv) nextNonce() string { |
| 112 | e.nonces++ |
| 113 | return fmt.Sprintf("test-nonce-%010d", e.nonces) |
| 114 | } |
| 115 | |
| 116 | // newRequest builds a request signed by key under id with a fresh nonce. |
| 117 | func (e *apiEnv) newRequest(method, path string, body []byte, id hostedwire.KeyID, key ed25519.PrivateKey) (*http.Request, string) { |
| 118 | e.t.Helper() |
| 119 | req, err := http.NewRequest(method, e.srv.URL+path, bytes.NewReader(body)) |
| 120 | if err != nil { |
| 121 | e.t.Fatal(err) |
| 122 | } |
| 123 | nonce := e.nextNonce() |
| 124 | if err := hostedwire.SignRequest(req, body, id, key, e.clk.Wall(), nonce); err != nil { |
| 125 | e.t.Fatal(err) |
| 126 | } |
| 127 | return req, nonce |
| 128 | } |
| 129 | |
| 130 | func (e *apiEnv) send(req *http.Request, nonce string) reply { |
| 131 | e.t.Helper() |
| 132 | resp, err := e.srv.Client().Do(req) |
| 133 | if err != nil { |
| 134 | e.t.Fatalf("%s %s: %v", req.Method, req.URL.Path, err) |
| 135 | } |
| 136 | defer resp.Body.Close() |
| 137 | b, err := io.ReadAll(resp.Body) |
| 138 | if err != nil { |
| 139 | e.t.Fatal(err) |
| 140 | } |
| 141 | return reply{status: resp.StatusCode, body: b, resp: resp, nonce: nonce} |
| 142 | } |
| 143 | |
| 144 | // call sends one signed request and wants a signed reply. |
| 145 | func (e *apiEnv) call(method, path string, body any, id hostedwire.KeyID, key ed25519.PrivateKey) reply { |
| 146 | e.t.Helper() |
| 147 | var raw []byte |
| 148 | switch b := body.(type) { |
| 149 | case nil: |
| 150 | case string: |
| 151 | raw = []byte(b) |
| 152 | default: |
| 153 | var err error |
| 154 | if raw, err = json.Marshal(b); err != nil { |
| 155 | e.t.Fatal(err) |
| 156 | } |
| 157 | } |
| 158 | r := e.send(e.newRequest(method, path, raw, id, key)) |
| 159 | if !r.signed() { |
| 160 | e.t.Fatalf("%s %s answered %d %q without a valid signature", method, path, r.status, r.body) |
| 161 | } |
| 162 | return r |
| 163 | } |
| 164 | |
| 165 | func wireLaunch(attempt string) hostedwire.LaunchRequest { |
| 166 | return hostedwire.LaunchRequest{AttemptID: attempt, TaskID: "task-1", Account: "acct-1", Image: imgA, |
| 167 | Size: isolatedjob.SizeSmall, MaxLifetimeMS: (2 * time.Hour).Milliseconds(), InstanceCode: testCode} |
| 168 | } |
| 169 | |
| 170 | // launch launches attempt as instance A and wants a 200. |
| 171 | func (e *apiEnv) launch(attempt string) hostedwire.JobView { |
| 172 | e.t.Helper() |
| 173 | r := e.call("POST", "/v1/jobs", wireLaunch(attempt), idInstA, keyInstA) |
| 174 | if r.status != http.StatusOK { |
| 175 | e.t.Fatalf("launch %s = %d %s", attempt, r.status, r.body) |
| 176 | } |
| 177 | var v hostedwire.JobView |
| 178 | if err := hostedwire.DecodeStrict(bytes.NewReader(r.body), &v); err != nil { |
| 179 | e.t.Fatalf("launch reply %q: %v", r.body, err) |
| 180 | } |
| 181 | return v |
| 182 | } |
| 183 | |
| 184 | // jobRoutes are the attempt routes with a valid body for each. |
| 185 | func jobRoutes(attempt string) []struct { |
| 186 | method, path string |
| 187 | body any |
| 188 | } { |
| 189 | p := "/v1/jobs/" + attempt |
| 190 | return []struct { |
| 191 | method, path string |
| 192 | body any |
| 193 | }{ |
| 194 | {"GET", p, nil}, |
| 195 | {"POST", p + "/stop", hostedwire.StopRequest{Reason: "done"}}, |
| 196 | {"POST", p + "/drain", hostedwire.DrainRequest{}}, |
| 197 | {"POST", p + "/quiescent", hostedwire.QuiescentRequest{Generation: 1}}, |
| 198 | {"POST", p + "/suspend", hostedwire.SuspendRequest{Generation: 1}}, |
| 199 | {"POST", p + "/reopen", hostedwire.ReopenRequest{Generation: 1}}, |
| 200 | {"POST", p + "/resume", hostedwire.ResumeRequest{OperationID: "op-1"}}, |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | // fixedBody is the exact body of a refusal with code. |
| 205 | func fixedBody(t *testing.T, code string) string { |
| 206 | t.Helper() |
| 207 | for _, a := range apiErrors { |
| 208 | if a.code == code { |
| 209 | b, _ := json.Marshal(hostedwire.ErrorResponse{Code: a.code, Message: a.msg}) |
| 210 | return string(b) |
| 211 | } |
| 212 | } |
| 213 | t.Fatalf("no API error with code %q", code) |
| 214 | return "" |
| 215 | } |
| 216 | |
| 217 | func TestRoutesEnforceRoles(t *testing.T) { |
| 218 | t.Parallel() |
| 219 | e := newAPIEnv(t, true) |
| 220 | view := e.launch("a1") |
| 221 | |
| 222 | // The operator key may use no job route: the handler refuses it with a |
| 223 | // signed 403 and its own audit row, before any controller method runs. |
| 224 | routes := append(jobRoutes("a1"), struct { |
| 225 | method, path string |
| 226 | body any |
| 227 | }{"POST", "/v1/jobs", wireLaunch("a2")}) |
| 228 | for _, rt := range routes { |
| 229 | before := len(auditRows(t, e.store)) |
| 230 | r := e.call(rt.method, rt.path, rt.body, idOp, keyOp) |
| 231 | if r.status != http.StatusForbidden || string(r.body) != fixedBody(t, "forbidden") { |
| 232 | t.Fatalf("operator %s %s = %d %s, want 403 %s", rt.method, rt.path, r.status, r.body, fixedBody(t, "forbidden")) |
| 233 | } |
| 234 | rows := auditRows(t, e.store) |
| 235 | if len(rows) != before+1 { |
| 236 | t.Fatalf("operator %s %s wrote %d audit rows, want 1", rt.method, rt.path, len(rows)-before) |
| 237 | } |
| 238 | if a := rows[len(rows)-1]; a.Action != actionAPIRefused || a.Actor != idOp { |
| 239 | t.Fatalf("operator %s %s audit row = %+v, want %s by %s", rt.method, rt.path, a, actionAPIRefused, idOp) |
| 240 | } |
| 241 | } |
| 242 | if j, _ := e.job("a1"); j.state != JobStarting || e.jobCount() != 1 { |
| 243 | t.Fatalf("after the operator's refused calls: a1 %s, %d jobs; want a1 starting and no new job", j.state, e.jobCount()) |
| 244 | } |
| 245 | |
| 246 | // An instance key may not list VMs. |
| 247 | before := len(auditRows(t, e.store)) |
| 248 | if r := e.call("GET", "/v1/vms", nil, idInstA, keyInstA); r.status != http.StatusForbidden { |
| 249 | t.Fatalf("instance GET /v1/vms = %d %s, want 403", r.status, r.body) |
| 250 | } |
| 251 | if rows := auditRows(t, e.store); len(rows) != before+1 || rows[len(rows)-1].Action != actionAPIRefused { |
| 252 | t.Fatalf("instance GET /v1/vms audit rows %v, want one %s", rows[before:], actionAPIRefused) |
| 253 | } |
| 254 | |
| 255 | // The operator key lists VMs, each with its attempt. |
| 256 | r := e.call("GET", "/v1/vms", nil, idOp, keyOp) |
| 257 | if r.status != http.StatusOK { |
| 258 | t.Fatalf("operator GET /v1/vms = %d %s", r.status, r.body) |
| 259 | } |
| 260 | var list hostedwire.VMListResponse |
| 261 | if err := hostedwire.DecodeStrict(bytes.NewReader(r.body), &list); err != nil { |
| 262 | t.Fatal(err) |
| 263 | } |
| 264 | if len(list.VMs) != 1 || list.VMs[0].VMRef != view.VMRef || list.VMs[0].AttemptID != "a1" { |
| 265 | t.Fatalf("GET /v1/vms = %+v, want only a1's VM %s", list.VMs, view.VMRef) |
| 266 | } |
| 267 | } |
| 268 | |
| 269 | func TestInstanceKeySeesOnlyItsJobs(t *testing.T) { |
| 270 | t.Parallel() |
| 271 | e := newAPIEnv(t, true) |
| 272 | view := e.launch("a1") |
| 273 | if view.AttemptID != "a1" || view.State != JobStarting || view.VMRef == "" || len(view.LaunchID) != launchIDLen { |
| 274 | t.Fatalf("launch view = %+v", view) |
| 275 | } |
| 276 | r := e.call("GET", "/v1/jobs/a1", nil, idInstA, keyInstA) |
| 277 | if r.status != http.StatusOK { |
| 278 | t.Fatalf("creator GET = %d %s", r.status, r.body) |
| 279 | } |
| 280 | |
| 281 | // Another instance key gets the same 403 for a1 and for an attempt |
| 282 | // that does not exist, so it learns nothing of a1. |
| 283 | for _, attempt := range []string{"a1", "nope"} { |
| 284 | for _, rt := range jobRoutes(attempt) { |
| 285 | r := e.call(rt.method, rt.path, rt.body, idInstB, keyInstB) |
| 286 | if r.status != http.StatusForbidden || string(r.body) != fixedBody(t, "forbidden") { |
| 287 | t.Fatalf("instance B %s %s = %d %s, want 403", rt.method, rt.path, r.status, r.body) |
| 288 | } |
| 289 | } |
| 290 | } |
| 291 | if j, _ := e.job("a1"); j.state != JobStarting || j.stopRequested.Valid { |
| 292 | t.Fatalf("a1 after instance B's calls = %s (stop asked %v), want starting with no stop", j.state, j.stopRequested.Valid) |
| 293 | } |
| 294 | // A second launch of a1 by B is a conflict, not a takeover. |
| 295 | if r := e.call("POST", "/v1/jobs", wireLaunch("a1"), idInstB, keyInstB); r.status != http.StatusConflict { |
| 296 | t.Fatalf("instance B relaunch of a1 = %d %s, want 409", r.status, r.body) |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | func TestUnknownFieldsRefused(t *testing.T) { |
| 301 | t.Parallel() |
| 302 | e := newAPIEnv(t, true) |
| 303 | good, _ := json.Marshal(wireLaunch("a1")) |
| 304 | extra := strings.Replace(string(good), "{", `{"vm_ref":"vm-9",`, 1) |
| 305 | upper := strings.Replace(string(good), `"attempt_id"`, `"Attempt_ID"`, 1) |
| 306 | twice := strings.Replace(string(good), "{", `{"attempt_id":"a9",`, 1) |
| 307 | for _, c := range []struct{ name, body string }{{"unknown field", extra}, {"upper-case key", upper}, |
| 308 | {"repeated key", twice}, {"two objects", string(good) + string(good)}, {"not an object", `[1]`}, {"empty", ``}} { |
| 309 | r := e.call("POST", "/v1/jobs", c.body, idInstA, keyInstA) |
| 310 | if r.status != http.StatusBadRequest || string(r.body) != fixedBody(t, "bad_json") { |
| 311 | t.Fatalf("launch with %s = %d %s, want 400 %s", c.name, r.status, r.body, fixedBody(t, "bad_json")) |
| 312 | } |
| 313 | } |
| 314 | if n := e.jobCount(); n != 0 { |
| 315 | t.Fatalf("%d jobs after refused launches, want 0", n) |
| 316 | } |
| 317 | e.launch("a1") |
| 318 | for path, body := range map[string]string{ |
| 319 | "/v1/jobs/a1/stop": `{"reason":"done","force":true}`, |
| 320 | "/v1/jobs/a1/drain": `{"generation":1}`, |
| 321 | "/v1/jobs/a1": `{}`, // GET takes no body |
| 322 | } { |
| 323 | method := "POST" |
| 324 | if path == "/v1/jobs/a1" { |
| 325 | method = "GET" |
| 326 | } |
| 327 | if r := e.call(method, path, body, idInstA, keyInstA); r.status != http.StatusBadRequest { |
| 328 | t.Fatalf("%s %s with %s = %d %s, want 400", method, path, body, r.status, r.body) |
| 329 | } |
| 330 | } |
| 331 | if j, _ := e.job("a1"); j.stopRequested.Valid || j.state != JobStarting { |
| 332 | t.Fatalf("a1 after refused bodies = %s, stop asked %v; want untouched", j.state, j.stopRequested.Valid) |
| 333 | } |
| 334 | } |
| 335 | |
| 336 | func TestResponsesSigned(t *testing.T) { |
| 337 | t.Parallel() |
| 338 | e := newAPIEnv(t, true) |
| 339 | |
| 340 | // Success, refusals and unknown routes are all signed, bound to the |
| 341 | // request's nonce. |
| 342 | req, nonce := e.newRequest("POST", "/v1/jobs", mustJSON(t, wireLaunch("a1")), idInstA, keyInstA) |
| 343 | r := e.send(req, nonce) |
| 344 | if r.status != http.StatusOK || !r.signed() { |
| 345 | t.Fatalf("launch = %d %s, signed %v; want a signed 200", r.status, r.body, r.signed()) |
| 346 | } |
| 347 | r.nonce = e.nextNonce() |
| 348 | if r.signed() { |
| 349 | t.Fatal("the launch reply verifies against another nonce") |
| 350 | } |
| 351 | for _, c := range []struct { |
| 352 | method, path string |
| 353 | want int |
| 354 | code string |
| 355 | }{ |
| 356 | {"GET", "/v1/nothing", http.StatusNotFound, "no_route"}, |
| 357 | {"GET", "/v1/jobs/a1/stop", http.StatusMethodNotAllowed, "method"}, |
| 358 | {"DELETE", "/v1/jobs/a1", http.StatusMethodNotAllowed, "method"}, |
| 359 | {"GET", "/v1/vms?all=1", http.StatusBadRequest, "query"}, |
| 360 | } { |
| 361 | r := e.call(c.method, c.path, nil, idOp, keyOp) |
| 362 | if r.status != c.want || string(r.body) != fixedBody(t, c.code) { |
| 363 | t.Fatalf("%s %s = %d %s, want signed %d %s", c.method, c.path, r.status, r.body, c.want, fixedBody(t, c.code)) |
| 364 | } |
| 365 | } |
| 366 | |
| 367 | // A request that fails verification is answered unsigned, with a |
| 368 | // fixed body naming no reason. |
| 369 | unauth := fixedBody(t, "unauthorized") |
| 370 | check := func(name string, r reply, status int, body string) { |
| 371 | t.Helper() |
| 372 | if r.status != status || string(r.body) != body || r.resp.Header.Get(hostedwire.HeaderSignature) != "" { |
| 373 | t.Fatalf("%s = %d %q (signature %q), want unsigned %d %s", name, r.status, r.body, |
| 374 | r.resp.Header.Get(hostedwire.HeaderSignature), status, body) |
| 375 | } |
| 376 | } |
| 377 | plain, _ := http.NewRequest("GET", e.srv.URL+"/v1/jobs/a1", nil) |
| 378 | check("unsigned request", e.send(plain, "nonce-unused-0000000"), http.StatusUnauthorized, unauth) |
| 379 | |
| 380 | req, nonce = e.newRequest("GET", "/v1/jobs/a1", nil, idInstA, keyInstB) // B's key under A's ID |
| 381 | check("wrong key", e.send(req, nonce), http.StatusUnauthorized, unauth) |
| 382 | |
| 383 | req, nonce = e.newRequest("GET", "/v1/jobs/a1", nil, "inst-z", keyInstA) |
| 384 | check("unknown key ID", e.send(req, nonce), http.StatusUnauthorized, unauth) |
| 385 | |
| 386 | req, nonce = e.newRequest("GET", "/v1/jobs/a1", nil, idInstA, keyInstA) |
| 387 | again := req.Clone(req.Context()) |
| 388 | if r := e.send(req, nonce); r.status != http.StatusOK || !r.signed() { |
| 389 | t.Fatalf("first send = %d %s", r.status, r.body) |
| 390 | } |
| 391 | // A replay carries a valid signature, so its refusal is signed, bound to |
| 392 | // the replayed nonce (ruling R25). |
| 393 | r = e.send(again, nonce) |
| 394 | if r.status != http.StatusUnauthorized || string(r.body) != fixedBody(t, "replay") || !r.signed() { |
| 395 | t.Fatalf("replay = %d %s, signed %v; want a signed 401 %s", r.status, r.body, r.signed(), fixedBody(t, "replay")) |
| 396 | } |
| 397 | |
| 398 | req, nonce = e.newRequest("GET", "/v1/jobs/a1", nil, idInstA, keyInstA) |
| 399 | e.clk.SetWall(testWall.Add(hostedwire.MaxSkew + time.Second)) |
| 400 | check("skewed", e.send(req, nonce), http.StatusUnauthorized, unauth) |
| 401 | e.clk.SetWall(testWall) |
| 402 | |
| 403 | big := bytes.Repeat([]byte{' '}, hostedwire.MaxBody+1) |
| 404 | req, nonce = e.newRequest("POST", "/v1/jobs", nil, idInstA, keyInstA) |
| 405 | req.Body, req.ContentLength = io.NopCloser(bytes.NewReader(big)), int64(len(big)) |
| 406 | check("too large", e.send(req, nonce), http.StatusRequestEntityTooLarge, fixedBody(t, "too_large")) |
| 407 | |
| 408 | // A nonce-store failure comes after the signature verified: signed 503 |
| 409 | // (the closed store reports store_lost, first in the table). |
| 410 | if err := e.store.Close(); err != nil { |
| 411 | t.Fatal(err) |
| 412 | } |
| 413 | req, nonce = e.newRequest("GET", "/v1/jobs/a1", nil, idInstA, keyInstA) |
| 414 | r = e.send(req, nonce) |
| 415 | if r.status != http.StatusServiceUnavailable || string(r.body) != fixedBody(t, "store_lost") || !r.signed() { |
| 416 | t.Fatalf("nonce store down = %d %s, signed %v; want a signed 503 %s", r.status, r.body, r.signed(), fixedBody(t, "store_lost")) |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | // TestResponsesSignedForHead: Go never sends a HEAD response's body, so the |
| 421 | // signature must cover the empty body the client receives. |
| 422 | func TestResponsesSignedForHead(t *testing.T) { |
| 423 | t.Parallel() |
| 424 | e := newAPIEnv(t, true) |
| 425 | e.launch("a1") |
| 426 | for path, want := range map[string]int{"/v1/jobs/a1": http.StatusMethodNotAllowed, "/v1/nothing": http.StatusNotFound} { |
| 427 | req, nonce := e.newRequest("HEAD", path, nil, idInstA, keyInstA) |
| 428 | r := e.send(req, nonce) |
| 429 | if r.status != want || len(r.body) != 0 || !r.signed() { |
| 430 | t.Fatalf("HEAD %s = %d %q, signed %v; want a signed %d with no body", path, r.status, r.body, r.signed(), want) |
| 431 | } |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | func mustJSON(t *testing.T, v any) []byte { |
| 436 | t.Helper() |
| 437 | b, err := json.Marshal(v) |
| 438 | if err != nil { |
| 439 | t.Fatal(err) |
| 440 | } |
| 441 | return b |
| 442 | } |
| 443 | |
| 444 | func TestDisabledRefusesLaunchButServesStop(t *testing.T) { |
| 445 | t.Parallel() |
| 446 | e := newAPIEnv(t, true) |
| 447 | e.launch("a1") |
| 448 | |
| 449 | // The same store under a controller with launches off. |
| 450 | e.cfg.Enabled = false |
| 451 | e.newController() |
| 452 | e.audit() |
| 453 | e.serve() |
| 454 | |
| 455 | r := e.call("POST", "/v1/jobs", wireLaunch("a2"), idInstA, keyInstA) |
| 456 | if r.status != http.StatusServiceUnavailable || r.errBody(t).Code != "disabled" { |
| 457 | t.Fatalf("launch while disabled = %d %s, want 503 disabled", r.status, r.body) |
| 458 | } |
| 459 | if e.jobCount() != 1 { |
| 460 | t.Fatalf("%d jobs, want only a1", e.jobCount()) |
| 461 | } |
| 462 | |
| 463 | // Stop is served: pending first, then proof. |
| 464 | stop := hostedwire.StopRequest{Reason: "done"} |
| 465 | r = e.call("POST", "/v1/jobs/a1/stop", stop, idInstA, keyInstA) |
| 466 | if r.status != http.StatusAccepted || r.errBody(t).Code != "stop_pending" { |
| 467 | t.Fatalf("stop while disabled = %d %s, want 202 stop_pending", r.status, r.body) |
| 468 | } |
| 469 | e.fake.Tick() |
| 470 | r = e.call("POST", "/v1/jobs/a1/stop", stop, idInstA, keyInstA) |
| 471 | var proof hostedwire.StopProof |
| 472 | if r.status != http.StatusOK || hostedwire.DecodeStrict(bytes.NewReader(r.body), &proof) != nil || |
| 473 | proof.AttemptID != "a1" || !proof.State.Terminal() { |
| 474 | t.Fatalf("second stop = %d %s, want 200 with proof", r.status, r.body) |
| 475 | } |
| 476 | } |
| 477 | |
| 478 | func TestMetricsCountJobsByState(t *testing.T) { |
| 479 | t.Parallel() |
| 480 | e := newAPIEnv(t, true) |
| 481 | e.launch("a1") |
| 482 | e.launch("a2") |
| 483 | e.call("POST", "/v1/jobs/a1/stop", hostedwire.StopRequest{Reason: "done"}, idInstA, keyInstA) |
| 484 | e.call("GET", "/v1/vms", nil, idInstA, keyInstA) // a refusal |
| 485 | |
| 486 | got := e.scrape() |
| 487 | for _, line := range []string{ |
| 488 | `equipo_hosted_jobs{state="starting"} 1`, |
| 489 | `equipo_hosted_jobs{state="stopping"} 1`, |
| 490 | `equipo_hosted_jobs{state="waiting"} 0`, |
| 491 | `equipo_hosted_store_readable 1`, |
| 492 | `equipo_hosted_launches_total{result="starting"} 2`, |
| 493 | `equipo_hosted_errors_total{route="stop",code="stop_pending"} 1`, |
| 494 | `equipo_hosted_errors_total{route="vms",code="forbidden"} 1`, |
| 495 | `equipo_hosted_network_audit_passing 1`, |
| 496 | } { |
| 497 | if !strings.Contains(got, "\n"+line+"\n") { |
| 498 | t.Errorf("metrics lack %q:\n%s", line, got) |
| 499 | } |
| 500 | } |
| 501 | if strings.Contains(got, "\nequipo_hosted_reap_last_error ") { |
| 502 | t.Errorf("metrics report a reaper pass before any ran:\n%s", got) |
| 503 | } |
| 504 | |
| 505 | // After a pass whose alert is delivered, its results and the alert show. |
| 506 | al := e.metrics.CountAlerts(&recordingAlerter{}) |
| 507 | if err := al.Alert(e.ctx, Alert{Kind: AlertOrphanStopped, Detail: "vm-1"}); err != nil { |
| 508 | t.Fatal(err) |
| 509 | } |
| 510 | failing := e.metrics.CountAlerts(&recordingAlerter{fail: errors.New("down")}) |
| 511 | _ = failing.Alert(e.ctx, Alert{Kind: AlertAuditFailed}) |
| 512 | e.reap() |
| 513 | got = e.scrape() |
| 514 | for _, line := range []string{ |
| 515 | `equipo_hosted_reap_last_error 0`, |
| 516 | `equipo_hosted_reap_last_orphans_stopped 0`, |
| 517 | `equipo_hosted_reap_last_orphans_deferred 0`, |
| 518 | `equipo_hosted_alerts_total{kind="orphan_stopped",result="sent"} 1`, |
| 519 | `equipo_hosted_alerts_total{kind="audit_failed",result="failed"} 1`, |
| 520 | } { |
| 521 | if !strings.Contains(got, "\n"+line+"\n") { |
| 522 | t.Errorf("metrics after a pass lack %q:\n%s", line, got) |
| 523 | } |
| 524 | } |
| 525 | |
| 526 | // An unreadable store leaves the job counts out, never zero. |
| 527 | if err := e.store.Close(); err != nil { |
| 528 | t.Fatal(err) |
| 529 | } |
| 530 | got = e.scrape() |
| 531 | if strings.Contains(got, "equipo_hosted_jobs{") || !strings.Contains(got, "\nequipo_hosted_store_readable 0\n") { |
| 532 | t.Fatalf("metrics with the store closed:\n%s", got) |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | // scrape reads the metrics page. |
| 537 | func (e *apiEnv) scrape() string { |
| 538 | e.t.Helper() |
| 539 | rec := httptest.NewRecorder() |
| 540 | e.metrics.Handler(e.c).ServeHTTP(rec, httptest.NewRequest("GET", "/metrics", nil)) |
| 541 | if rec.Code != http.StatusOK { |
| 542 | e.t.Fatalf("GET /metrics = %d", rec.Code) |
| 543 | } |
| 544 | return "\n" + rec.Body.String() |
| 545 | } |
| 546 | |
| 547 | func TestRoutesMapErrorsToStatus(t *testing.T) { |
| 548 | t.Parallel() |
| 549 | for _, c := range []struct { |
| 550 | err error |
| 551 | want int |
| 552 | }{ |
| 553 | {isolatedjob.ErrInvalid, 400}, {hostedwire.ErrBadJSON, 400}, {ErrImageNotAllowed, 400}, |
| 554 | {hostedwire.ErrBadSignature, 401}, {hostedwire.ErrSkew, 401}, {hostedwire.ErrReplay, 401}, {hostedwire.ErrUnknownKey, 401}, |
| 555 | {ErrForbidden, 403}, {isolatedjob.ErrNotFound, 404}, |
| 556 | {isolatedjob.ErrConflict, 409}, {ErrGenerationCancelled, 409}, {ErrNotQuiescent, 409}, {ErrResumePending, 409}, |
| 557 | {ErrReplacementLive, 409}, {ErrStateUnknown, 409}, |
| 558 | {ErrStopPending, 202}, {ErrPastDeadline, 410}, {hostedwire.ErrTooLarge, 413}, {isolatedjob.ErrThrottled, 429}, |
| 559 | {ErrDisabled, 503}, {ErrNetworkAudit, 503}, {ErrStoreLost, 503}, {ErrProviderLaunch, 502}, |
| 560 | {errors.New("anything else"), 500}, |
| 561 | // A refusal whose audit row could not be written because the store |
| 562 | // is gone reports the store. |
| 563 | {errors.Join(ErrForbidden, fmt.Errorf("%w: gone", ErrStoreLost)), 503}, |
| 564 | } { |
| 565 | a := lookupError(fmt.Errorf("%w: secret detail", c.err)) |
| 566 | if a.status != c.want || strings.Contains(a.msg, "secret") || a.msg == "" || a.code == "" { |
| 567 | t.Errorf("lookupError(%v) = %+v, want status %d with a fixed message", c.err, a, c.want) |
| 568 | } |
| 569 | } |
| 570 | } |
| 571 | |