package main import ( "bytes" "context" "crypto/ed25519" "crypto/rand" "crypto/tls" "crypto/x509" "encoding/json" "errors" "io" "math/big" "net" "net/http" "path/filepath" "sync" "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" "github.com/aws/aws-sdk-go-v2/service/sts" ) var ( instKey = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize)) ctlKey = ed25519.NewKeyFromSeed(bytes.Repeat([]byte{4}, ed25519.SeedSize)) ) const instID hostedwire.KeyID = "inst-1" // testCtl is a controller over a fresh store and the isolatedjob Fake, with // a passing network audit and its API handler. type testCtl struct { c *hostedctl.Controller store *hostedctl.Store api http.Handler clk *isolatedjobtest.FakeClock } type nopAlerter struct{} func (nopAlerter) Alert(context.Context, hostedctl.Alert) error { return nil } // newTestCtl builds the controller; wrap, when set, wraps the Fake as the // runner the controller calls. func newTestCtl(t *testing.T, wrap func(*isolatedjob.Fake) isolatedjob.Runner) *testCtl { t.Helper() ctx := context.Background() clk := isolatedjobtest.NewFakeClock(time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC)) fake := isolatedjob.NewFake(clk, isolatedjob.SpikeLimits()) var run isolatedjob.Runner = fake if wrap != nil { run = wrap(fake) } store, err := hostedctl.Open(ctx, filepath.Join(t.TempDir(), "hosted.db"), clk) if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = store.Close() }) c, err := hostedctl.New(hostedctl.Config{Enabled: true, Images: map[isolatedjob.ImageDigest]bool{testDigest: true}, ProviderNamespace: "test", ProviderFingerprint: func(isolatedjob.ImageDigest, isolatedjob.Size) string { return "" }}, hostedctl.Deps{Store: store, Runner: run, Auditor: fake, Alerter: nopAlerter{}}) if err != nil { t.Fatal(err) } if err := c.RunAudit(ctx); err != nil { t.Fatal(err) } keys := map[hostedwire.KeyID]hostedwire.VerifyKey{instID: {Public: instKey.Public().(ed25519.PublicKey), Role: hostedwire.RoleInstance}} api, err := c.Handler(hostedctl.HandlerConfig{Keys: keys, Signing: ctlKey, Wall: clk.Wall}) if err != nil { t.Fatal(err) } return &testCtl{c: c, store: store, api: api, clk: clk} } // testTLS returns a certificate for 127.0.0.1 and a client that trusts it. func testTLS(t *testing.T) (tls.Certificate, *http.Client) { t.Helper() pub, priv, err := ed25519.GenerateKey(rand.Reader) if err != nil { t.Fatal(err) } tmpl := &x509.Certificate{SerialNumber: big.NewInt(1), NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(time.Hour), IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1)}} der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, pub, priv) if err != nil { t.Fatal(err) } leaf, err := x509.ParseCertificate(der) if err != nil { t.Fatal(err) } pool := x509.NewCertPool() pool.AddCert(leaf) client := &http.Client{Timeout: 10 * time.Second, Transport: &http.Transport{TLSClientConfig: &tls.Config{RootCAs: pool}}} return tls.Certificate{Certificate: [][]byte{der}, PrivateKey: priv}, client } func listen(t *testing.T) net.Listener { t.Helper() ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } return ln } var nonceSeq atomic.Int64 // sign signs req for body as instKey at the controller's wall time and // returns the nonce. func (tc *testCtl) sign(t *testing.T, req *http.Request, body []byte) string { t.Helper() nonce := "main-test-nonce-" + time.Now().Format("150405") + "-" + big.NewInt(nonceSeq.Add(1)).String() if err := hostedwire.SignRequest(req, body, instID, instKey, tc.clk.Wall(), nonce); err != nil { t.Fatal(err) } return nonce } func readAll(t *testing.T, resp *http.Response) []byte { t.Helper() defer resp.Body.Close() b, err := io.ReadAll(resp.Body) if err != nil { t.Fatal(err) } return b } // TestOptionsStarVerified: the API server hands OPTIONS * to the signed // handler, not to Go's built-in answer. func TestOptionsStarVerified(t *testing.T) { t.Parallel() tc := newTestCtl(t, nil) cert, client := testTLS(t) srv := newAPIServer(tc.api, cert) ln := listen(t) go func() { _ = srv.ServeTLS(ln, "", "") }() t.Cleanup(func() { _ = srv.Close() }) base := "https://" + ln.Addr().String() star := func() *http.Request { req, err := http.NewRequest(http.MethodOptions, base, nil) if err != nil { t.Fatal(err) } req.URL.Path = "*" return req } resp, err := client.Do(star()) if err != nil { t.Fatal(err) } body := readAll(t, resp) if resp.StatusCode != http.StatusUnauthorized || resp.Header.Get(hostedwire.HeaderSignature) != "" { t.Fatalf("unsigned OPTIONS * = %d %q (signature %q), want an unsigned 401", resp.StatusCode, body, resp.Header.Get(hostedwire.HeaderSignature)) } req := star() nonce := tc.sign(t, req, nil) resp, err = client.Do(req) if err != nil { t.Fatal(err) } body = readAll(t, resp) if resp.StatusCode != http.StatusNotFound || hostedwire.VerifyResponse(resp, body, nonce, ctlKey.Public().(ed25519.PublicKey)) != nil { t.Fatalf("signed OPTIONS * = %d %q, want a signed 404", resp.StatusCode, body) } } // identityStub answers GetCallerIdentity with account and err, and records // whether the call had a deadline. type identityStub struct { account string err error deadline bool } func (s *identityStub) GetCallerIdentity(ctx context.Context, _ *sts.GetCallerIdentityInput, _ ...func(*sts.Options)) (*sts.GetCallerIdentityOutput, error) { _, s.deadline = ctx.Deadline() return &sts.GetCallerIdentityOutput{Account: &s.account}, s.err } // TestProviderNamespace: the namespace is the credentials' account and the // region, read with a bounded call; no account is an error, not an empty // namespace (ruling R28). func TestProviderNamespace(t *testing.T) { t.Parallel() s := &identityStub{account: "123456789012"} if ns, err := providerNamespace(context.Background(), s, "eu-west-1"); ns != "aws:123456789012:eu-west-1" || err != nil || !s.deadline { t.Fatalf("providerNamespace = (%q, %v), deadline %v; want aws:123456789012:eu-west-1 from a bounded call", ns, err, s.deadline) } for _, bad := range []*identityStub{{account: ""}, {account: "1", err: errors.New("denied")}} { if ns, err := providerNamespace(context.Background(), bad, "eu-west-1"); ns != "" || err == nil { t.Errorf("providerNamespace(account %q, error %v) = (%q, %v), want an error", bad.account, bad.err, ns, err) } } } // getBlock wraps the Fake. Once armed, Get closes entered and waits for its // context to end, as a stalled provider read that honours cancellation. type getBlock struct { isolatedjob.Runner armed atomic.Bool once sync.Once entered chan struct{} } func (g *getBlock) Get(ctx context.Context, ref isolatedjob.Ref) (isolatedjob.Job, error) { if !g.armed.Load() { return g.Runner.Get(ctx, ref) } g.once.Do(func() { close(g.entered) }) <-ctx.Done() return isolatedjob.Job{}, ctx.Err() } // TestShutdownCancelsReaperWithRequests: a reaper pass is stuck in a Get // that ends only with its context, holding the attempt's lock, and a Stop // request for that attempt waits for the lock. On a signal serve must // cancel the reaper along with the requests before joining either, or the // Stop handler, and with it shutdown, waits on the lock (C2, R27). func TestShutdownCancelsReaperWithRequests(t *testing.T) { t.Parallel() gb := &getBlock{entered: make(chan struct{})} tc := newTestCtl(t, func(f *isolatedjob.Fake) isolatedjob.Runner { gb.Runner = f; return gb }) if _, err := tc.c.Launch(context.Background(), instID, hostedwire.VerifyKey{Role: hostedwire.RoleInstance}, hostedctl.LaunchRequest{AttemptID: "a1", TaskID: "t1", Account: "acct", Image: testDigest, Size: isolatedjob.SizeSmall, MaxLifetime: 2 * time.Hour, InstanceCode: "code-1"}); err != nil { t.Fatal(err) } gb.armed.Store(true) var once sync.Once entered := make(chan struct{}) api := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { once.Do(func() { close(entered) }) tc.api.ServeHTTP(w, r) }) cert, client := testTLS(t) apiLn, metricsLn := listen(t), listen(t) ctx, signal := context.WithCancel(context.Background()) defer signal() served := make(chan error, 1) go func() { served <- serve(ctx, tc.c, newAPIServer(api, cert), apiLn, newMetricsServer(hostedctl.NewMetrics().Handler(tc.c)), metricsLn, 100*time.Millisecond) }() select { case <-gb.entered: case <-time.After(10 * time.Second): t.Fatal("the reaper's Get never reached the provider") } body, _ := json.Marshal(hostedwire.StopRequest{Reason: "done"}) req, err := http.NewRequest(http.MethodPost, "https://"+apiLn.Addr().String()+"/v1/jobs/a1/stop", bytes.NewReader(body)) if err != nil { t.Fatal(err) } tc.sign(t, req, body) go func() { if resp, err := client.Do(req); err == nil { _ = resp.Body.Close() } }() select { case <-entered: case <-time.After(10 * time.Second): t.Fatal("the Stop request never reached its handler") } signal() select { case <-served: case <-time.After(10 * time.Second): t.Fatal("serve did not return within 10 s of the signal") } } // blockingRunner holds every Launch until its context ends, then takes a // while more to return, like a provider call settling. type blockingRunner struct { *isolatedjob.Fake once sync.Once entered chan struct{} } func (b *blockingRunner) Launch(ctx context.Context, _ isolatedjob.LaunchSpec) (isolatedjob.Ref, error) { b.once.Do(func() { close(b.entered) }) <-ctx.Done() time.Sleep(300 * time.Millisecond) return "", ctx.Err() } // TestShutdownDrainsRequests: on a signal serve stops accepting, gives // requests the drain time, cancels the ones left, and returns only after // every handler has finished, so the store is never closed under one. func TestShutdownDrainsRequests(t *testing.T) { t.Parallel() br := &blockingRunner{entered: make(chan struct{})} tc := newTestCtl(t, func(f *isolatedjob.Fake) isolatedjob.Runner { br.Fake = f; return br }) var finished atomic.Bool api := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { tc.api.ServeHTTP(w, r) finished.Store(true) }) cert, client := testTLS(t) apiLn, metricsLn := listen(t), listen(t) m := hostedctl.NewMetrics() ctx, signal := context.WithCancel(context.Background()) defer signal() served := make(chan error, 1) go func() { served <- serve(ctx, tc.c, newAPIServer(api, cert), apiLn, newMetricsServer(m.Handler(tc.c)), metricsLn, 100*time.Millisecond) }() body, _ := json.Marshal(hostedwire.LaunchRequest{AttemptID: "a1", TaskID: "t1", Account: "acct", Image: testDigest, Size: isolatedjob.SizeSmall, MaxLifetimeMS: (2 * time.Hour).Milliseconds(), InstanceCode: "code-1"}) req, err := http.NewRequest(http.MethodPost, "https://"+apiLn.Addr().String()+"/v1/jobs", bytes.NewReader(body)) if err != nil { t.Fatal(err) } tc.sign(t, req, body) go func() { if resp, err := client.Do(req); err == nil { _ = resp.Body.Close() } }() select { case <-br.entered: case <-time.After(10 * time.Second): t.Fatal("the launch never reached the provider") } signal() select { case <-served: case <-time.After(10 * time.Second): t.Fatal("serve did not return after the signal") } if !finished.Load() { t.Fatal("serve returned while a request handler was still running") } // The store is still whole: the intent waits for replay, and Close works. v, err := tc.c.Get(context.Background(), instID, "a1") if err != nil || v.State != hostedctl.JobWaiting { t.Fatalf("Get(a1) after shutdown = %+v, %v; want the intent waiting", v, err) } if err := tc.store.Close(); err != nil { t.Fatalf("store Close after shutdown = %v", err) } }