| 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/ed25519" |
| 7 | "crypto/rand" |
| 8 | "crypto/tls" |
| 9 | "crypto/x509" |
| 10 | "encoding/json" |
| 11 | "errors" |
| 12 | "io" |
| 13 | "math/big" |
| 14 | "net" |
| 15 | "net/http" |
| 16 | "path/filepath" |
| 17 | "sync" |
| 18 | "sync/atomic" |
| 19 | "testing" |
| 20 | "time" |
| 21 | |
| 22 | "amadan.net/oficina/equipo/internal/hostedctl" |
| 23 | "amadan.net/oficina/equipo/internal/hostedwire" |
| 24 | "amadan.net/oficina/equipo/internal/isolatedjob" |
| 25 | "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest" |
| 26 | "github.com/aws/aws-sdk-go-v2/service/sts" |
| 27 | ) |
| 28 | |
| 29 | var ( |
| 30 | instKey = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize)) |
| 31 | ctlKey = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{4}, ed25519.SeedSize)) |
| 32 | ) |
| 33 | |
| 34 | const instID hostedwire.KeyID = "inst-1" |
| 35 | |
| 36 | // testCtl is a controller over a fresh store and the isolatedjob Fake, with |
| 37 | // a passing network audit and its API handler. |
| 38 | type testCtl struct { |
| 39 | c *hostedctl.Controller |
| 40 | store *hostedctl.Store |
| 41 | api http.Handler |
| 42 | clk *isolatedjobtest.FakeClock |
| 43 | } |
| 44 | |
| 45 | type nopAlerter struct{} |
| 46 | |
| 47 | func (nopAlerter) Alert(context.Context, hostedctl.Alert) error { return nil } |
| 48 | |
| 49 | // newTestCtl builds the controller; wrap, when set, wraps the Fake as the |
| 50 | // runner the controller calls. |
| 51 | func newTestCtl(t *testing.T, wrap func(*isolatedjob.Fake) isolatedjob.Runner) *testCtl { |
| 52 | t.Helper() |
| 53 | ctx := context.Background() |
| 54 | clk := isolatedjobtest.NewFakeClock(time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC)) |
| 55 | fake := isolatedjob.NewFake(clk, isolatedjob.SpikeLimits()) |
| 56 | var run isolatedjob.Runner = fake |
| 57 | if wrap != nil { |
| 58 | run = wrap(fake) |
| 59 | } |
| 60 | store, err := hostedctl.Open(ctx, filepath.Join(t.TempDir(), "hosted.db"), clk) |
| 61 | if err != nil { |
| 62 | t.Fatal(err) |
| 63 | } |
| 64 | t.Cleanup(func() { _ = store.Close() }) |
| 65 | c, err := hostedctl.New(hostedctl.Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{testDigest: true}, |
| 66 | ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" }}, |
| 67 | hostedctl.Deps{Store: store, Runner: run, Auditor: fake, Alerter: nopAlerter{}}) |
| 68 | if err != nil { |
| 69 | t.Fatal(err) |
| 70 | } |
| 71 | if err := c.RunAudit(ctx); err != nil { |
| 72 | t.Fatal(err) |
| 73 | } |
| 74 | keys := map[hostedwire.KeyID]hostedwire.VerifyKey{instID: {Public: instKey.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance}} |
| 75 | api, err := c.Handler(hostedctl.HandlerConfig{Keys: keys, Signing: ctlKey, Wall: clk.Wall}) |
| 76 | if err != nil { |
| 77 | t.Fatal(err) |
| 78 | } |
| 79 | return &testCtl{c: c, store: store, api: api, clk: clk} |
| 80 | } |
| 81 | |
| 82 | // testTLS returns a certificate for 127.0.0.1 and a client that trusts it. |
| 83 | func testTLS(t *testing.T) (tls.Certificate, *http.Client) { |
| 84 | t.Helper() |
| 85 | pub, priv, err := ed25519.GenerateKey(rand.Reader) |
| 86 | if err != nil { |
| 87 | t.Fatal(err) |
| 88 | } |
| 89 | tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), NotBefore: time.Now().Add(-time.Hour), |
| 90 | NotAfter: time.Now().Add(time.Hour), IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)}} |
| 91 | der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, pub, priv) |
| 92 | if err != nil { |
| 93 | t.Fatal(err) |
| 94 | } |
| 95 | leaf, err := x509.ParseCertificate(der) |
| 96 | if err != nil { |
| 97 | t.Fatal(err) |
| 98 | } |
| 99 | pool := x509.NewCertPool() |
| 100 | pool.AddCert(leaf) |
| 101 | client := &http.Client{Timeout: 10 * time.Second, Transport: &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool}}} |
| 102 | return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: priv}, client |
| 103 | } |
| 104 | |
| 105 | func listen(t *testing.T) net.Listener { |
| 106 | t.Helper() |
| 107 | ln, err := net.Listen("tcp", "127.0.0.1:0") |
| 108 | if err != nil { |
| 109 | t.Fatal(err) |
| 110 | } |
| 111 | return ln |
| 112 | } |
| 113 | |
| 114 | var nonceSeq atomic.Int64 |
| 115 | |
| 116 | // sign signs req for body as instKey at the controller's wall time and |
| 117 | // returns the nonce. |
| 118 | func (tc *testCtl) sign(t *testing.T, req *http.Request, body []byte) string { |
| 119 | t.Helper() |
| 120 | nonce := "main-test-nonce-" + time.Now().Format("150405") + "-" + big.NewInt(nonceSeq.Add(1)).String() |
| 121 | if err := hostedwire.SignRequest(req, body, instID, instKey, tc.clk.Wall(), nonce); err != nil { |
| 122 | t.Fatal(err) |
| 123 | } |
| 124 | return nonce |
| 125 | } |
| 126 | |
| 127 | func readAll(t *testing.T, resp *http.Response) []byte { |
| 128 | t.Helper() |
| 129 | defer resp.Body.Close() |
| 130 | b, err := io.ReadAll(resp.Body) |
| 131 | if err != nil { |
| 132 | t.Fatal(err) |
| 133 | } |
| 134 | return b |
| 135 | } |
| 136 | |
| 137 | // TestOptionsStarVerified: the API server hands OPTIONS * to the signed |
| 138 | // handler, not to Go's built-in answer. |
| 139 | func TestOptionsStarVerified(t *testing.T) { |
| 140 | t.Parallel() |
| 141 | tc := newTestCtl(t, nil) |
| 142 | cert, client := testTLS(t) |
| 143 | srv := newAPIServer(tc.api, cert) |
| 144 | ln := listen(t) |
| 145 | go func() { _ = srv.ServeTLS(ln, "", "") }() |
| 146 | t.Cleanup(func() { _ = srv.Close() }) |
| 147 | base := "https://" + ln.Addr().String() |
| 148 | |
| 149 | star := func() *http.Request { |
| 150 | req, err := http.NewRequest(http.MethodOptions, base, nil) |
| 151 | if err != nil { |
| 152 | t.Fatal(err) |
| 153 | } |
| 154 | req.URL.Path = "*" |
| 155 | return req |
| 156 | } |
| 157 | resp, err := client.Do(star()) |
| 158 | if err != nil { |
| 159 | t.Fatal(err) |
| 160 | } |
| 161 | body := readAll(t, resp) |
| 162 | if resp.StatusCode != http.StatusUnauthorized || resp.Header.Get(hostedwire.HeaderSignature) != "" { |
| 163 | t.Fatalf("unsigned OPTIONS * = %d %q (signature %q), want an unsigned 401", resp.StatusCode, body, resp.Header.Get(hostedwire.HeaderSignature)) |
| 164 | } |
| 165 | |
| 166 | req := star() |
| 167 | nonce := tc.sign(t, req, nil) |
| 168 | resp, err = client.Do(req) |
| 169 | if err != nil { |
| 170 | t.Fatal(err) |
| 171 | } |
| 172 | body = readAll(t, resp) |
| 173 | if resp.StatusCode != http.StatusNotFound || |
| 174 | hostedwire.VerifyResponse(resp, body, nonce, ctlKey.Public().(ed25519.PublicKey)) != nil { |
| 175 | t.Fatalf("signed OPTIONS * = %d %q, want a signed 404", resp.StatusCode, body) |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | // identityStub answers GetCallerIdentity with account and err, and records |
| 180 | // whether the call had a deadline. |
| 181 | type identityStub struct { |
| 182 | account string |
| 183 | err error |
| 184 | deadline bool |
| 185 | } |
| 186 | |
| 187 | func (s *identityStub) GetCallerIdentity(ctx context.Context, _ *sts.GetCallerIdentityInput, _ ...func(*sts.Options)) (*sts.GetCallerIdentityOutput, error) { |
| 188 | _, s.deadline = ctx.Deadline() |
| 189 | return &sts.GetCallerIdentityOutput{Account: &s.account}, s.err |
| 190 | } |
| 191 | |
| 192 | // TestProviderNamespace: the namespace is the credentials' account and the |
| 193 | // region, read with a bounded call; no account is an error, not an empty |
| 194 | // namespace (ruling R28). |
| 195 | func TestProviderNamespace(t *testing.T) { |
| 196 | t.Parallel() |
| 197 | s := &identityStub{account: "123456789012"} |
| 198 | if ns, err := providerNamespace(context.Background(), s, "eu-west-1"); ns != "aws:123456789012:eu-west-1" || err != nil || !s.deadline { |
| 199 | t.Fatalf("providerNamespace = (%q, %v), deadline %v; want aws:123456789012:eu-west-1 from a bounded call", ns, err, s.deadline) |
| 200 | } |
| 201 | for _, bad := range []*identityStub{{account: ""}, {account: "1", err: errors.New("denied")}} { |
| 202 | if ns, err := providerNamespace(context.Background(), bad, "eu-west-1"); ns != "" || err == nil { |
| 203 | t.Errorf("providerNamespace(account %q, error %v) = (%q, %v), want an error", bad.account, bad.err, ns, err) |
| 204 | } |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | // getBlock wraps the Fake. Once armed, Get closes entered and waits for its |
| 209 | // context to end, as a stalled provider read that honours cancellation. |
| 210 | type getBlock struct { |
| 211 | isolatedjob.Runner |
| 212 | armed atomic.Bool |
| 213 | once sync.Once |
| 214 | entered chan struct{} |
| 215 | } |
| 216 | |
| 217 | func (g *getBlock) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) { |
| 218 | if !g.armed.Load() { |
| 219 | return g.Runner.Get(ctx, ref) |
| 220 | } |
| 221 | g.once.Do(func() { close(g.entered) }) |
| 222 | <-ctx.Done() |
| 223 | return isolatedjob.Job{}, ctx.Err() |
| 224 | } |
| 225 | |
| 226 | // TestShutdownCancelsReaperWithRequests: a reaper pass is stuck in a Get |
| 227 | // that ends only with its context, holding the attempt's lock, and a Stop |
| 228 | // request for that attempt waits for the lock. On a signal serve must |
| 229 | // cancel the reaper along with the requests before joining either, or the |
| 230 | // Stop handler, and with it shutdown, waits on the lock (C2, R27). |
| 231 | func TestShutdownCancelsReaperWithRequests(t *testing.T) { |
| 232 | t.Parallel() |
| 233 | gb := &getBlock{entered: make(chan struct{})} |
| 234 | tc := newTestCtl(t, func(f *isolatedjob.Fake) isolatedjob.Runner { gb.Runner = f; return gb }) |
| 235 | if _, err := tc.c.Launch(context.Background(), instID, hostedwire.VerifyKey{Role: hostedwire.RoleInstance}, |
| 236 | hostedctl.LaunchRequest{AttemptID: "a1", TaskID: "t1", Account: "acct", Image: testDigest, |
| 237 | Size: isolatedjob.SizeSmall, MaxLifetime: 2 * time.Hour, InstanceCode: "code-1"}); err != nil { |
| 238 | t.Fatal(err) |
| 239 | } |
| 240 | gb.armed.Store(true) |
| 241 | var once sync.Once |
| 242 | entered := make(chan struct{}) |
| 243 | api := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 244 | once.Do(func() { close(entered) }) |
| 245 | tc.api.ServeHTTP(w, r) |
| 246 | }) |
| 247 | cert, client := testTLS(t) |
| 248 | apiLn, metricsLn := listen(t), listen(t) |
| 249 | ctx, signal := context.WithCancel(context.Background()) |
| 250 | defer signal() |
| 251 | served := make(chan error, 1) |
| 252 | go func() { |
| 253 | served <- serve(ctx, tc.c, newAPIServer(api, cert), apiLn, newMetricsServer(hostedctl.NewMetrics().Handler(tc.c)), |
| 254 | metricsLn, 100*time.Millisecond) |
| 255 | }() |
| 256 | select { |
| 257 | case <-gb.entered: |
| 258 | case <-time.After(10 * time.Second): |
| 259 | t.Fatal("the reaper's Get never reached the provider") |
| 260 | } |
| 261 | body, _ := json.Marshal(hostedwire.StopRequest{Reason: "done"}) |
| 262 | req, err := http.NewRequest(http.MethodPost, "https://"+apiLn.Addr().String()+"/v1/jobs/a1/stop", bytes.NewReader(body)) |
| 263 | if err != nil { |
| 264 | t.Fatal(err) |
| 265 | } |
| 266 | tc.sign(t, req, body) |
| 267 | go func() { |
| 268 | if resp, err := client.Do(req); err == nil { |
| 269 | _ = resp.Body.Close() |
| 270 | } |
| 271 | }() |
| 272 | select { |
| 273 | case <-entered: |
| 274 | case <-time.After(10 * time.Second): |
| 275 | t.Fatal("the Stop request never reached its handler") |
| 276 | } |
| 277 | signal() |
| 278 | select { |
| 279 | case <-served: |
| 280 | case <-time.After(10 * time.Second): |
| 281 | t.Fatal("serve did not return within 10 s of the signal") |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | // blockingRunner holds every Launch until its context ends, then takes a |
| 286 | // while more to return, like a provider call settling. |
| 287 | type blockingRunner struct { |
| 288 | *isolatedjob.Fake |
| 289 | once sync.Once |
| 290 | entered chan struct{} |
| 291 | } |
| 292 | |
| 293 | func (b *blockingRunner) Launch(ctx context.Context, _ isolatedjob.LaunchSpec) (isolatedjob.Ref, error) { |
| 294 | b.once.Do(func() { close(b.entered) }) |
| 295 | <-ctx.Done() |
| 296 | time.Sleep(300 * time.Millisecond) |
| 297 | return "", ctx.Err() |
| 298 | } |
| 299 | |
| 300 | // TestShutdownDrainsRequests: on a signal serve stops accepting, gives |
| 301 | // requests the drain time, cancels the ones left, and returns only after |
| 302 | // every handler has finished, so the store is never closed under one. |
| 303 | func TestShutdownDrainsRequests(t *testing.T) { |
| 304 | t.Parallel() |
| 305 | br := &blockingRunner{entered: make(chan struct{})} |
| 306 | tc := newTestCtl(t, func(f *isolatedjob.Fake) isolatedjob.Runner { br.Fake = f; return br }) |
| 307 | var finished atomic.Bool |
| 308 | api := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 309 | tc.api.ServeHTTP(w, r) |
| 310 | finished.Store(true) |
| 311 | }) |
| 312 | cert, client := testTLS(t) |
| 313 | apiLn, metricsLn := listen(t), listen(t) |
| 314 | m := hostedctl.NewMetrics() |
| 315 | ctx, signal := context.WithCancel(context.Background()) |
| 316 | defer signal() |
| 317 | served := make(chan error, 1) |
| 318 | go func() { |
| 319 | served <- serve(ctx, tc.c, newAPIServer(api, cert), apiLn, newMetricsServer(m.Handler(tc.c)), metricsLn, 100*time.Millisecond) |
| 320 | }() |
| 321 | |
| 322 | body, _ := json.Marshal(hostedwire.LaunchRequest{AttemptID: "a1", TaskID: "t1", Account: "acct", Image: testDigest, |
| 323 | Size: isolatedjob.SizeSmall, MaxLifetimeMS: (2 * time.Hour).Milliseconds(), InstanceCode: "code-1"}) |
| 324 | req, err := http.NewRequest(http.MethodPost, "https://"+apiLn.Addr().String()+"/v1/jobs", bytes.NewReader(body)) |
| 325 | if err != nil { |
| 326 | t.Fatal(err) |
| 327 | } |
| 328 | tc.sign(t, req, body) |
| 329 | go func() { |
| 330 | if resp, err := client.Do(req); err == nil { |
| 331 | _ = resp.Body.Close() |
| 332 | } |
| 333 | }() |
| 334 | select { |
| 335 | case <-br.entered: |
| 336 | case <-time.After(10 * time.Second): |
| 337 | t.Fatal("the launch never reached the provider") |
| 338 | } |
| 339 | |
| 340 | signal() |
| 341 | select { |
| 342 | case <-served: |
| 343 | case <-time.After(10 * time.Second): |
| 344 | t.Fatal("serve did not return after the signal") |
| 345 | } |
| 346 | if !finished.Load() { |
| 347 | t.Fatal("serve returned while a request handler was still running") |
| 348 | } |
| 349 | // The store is still whole: the intent waits for replay, and Close works. |
| 350 | v, err := tc.c.Get(context.Background(), instID, "a1") |
| 351 | if err != nil || v.State != hostedctl.JobWaiting { |
| 352 | t.Fatalf("Get(a1) after shutdown = %+v, %v; want the intent waiting", v, err) |
| 353 | } |
| 354 | if err := tc.store.Close(); err != nil { |
| 355 | t.Fatalf("store Close after shutdown = %v", err) |
| 356 | } |
| 357 | } |
| 358 | |