package install import ( "bytes" "context" "crypto/sha256" "database/sql" "encoding/base64" "encoding/hex" "encoding/json" "errors" "io" "log/slog" "net/http" "net/http/httptest" "os" "sync/atomic" "testing" "time" "amadan.net/rastrillo/rastrillo/budget" "amadan.net/rastrillo/rastrillo/crypto" "amadan.net/rastrillo/rastrillo/dbtest" "amadan.net/oficina/base/internal/config" "amadan.net/oficina/base/internal/platform" "amadan.net/oficina/base/internal/store" ) var template = dbtest.FromSet(store.BootSchema) func TestMain(m *testing.M) { code := budget.Main(m) template.Remove() os.Exit(code) } func setup(t *testing.T, probe func(context.Context, string) error) (*Installer, *platform.Fake, *sql.DB, config.Config) { t.Helper() kp, err := crypto.Generate() if err != nil { t.Fatal(err) } cfg := config.Config{Origin: "https://base.example.com", Name: "Acme", Slug: "acme", AppsDomain: "bab.oncarlos.com", AssertionKey: kp} db := template.Open(t) pf := platform.NewFake() if probe == nil { probe = func(context.Context, string) error { return nil } } return New(db, cfg, pf, probe, slog.New(slog.NewTextHandler(io.Discard, nil))), pf, db, cfg } func state(t *testing.T, db *sql.DB, app string) store.Install { t.Helper() all, err := store.Installs(context.Background(), db) if err != nil { t.Fatal(err) } for _, i := range all { if i.App == app { return i } } return store.Install{} } func TestInstallWritesEnvThenCreates(t *testing.T) { in, pf, db, cfg := setup(t, nil) if err := in.Install(context.Background(), "scratchpad"); err != nil { t.Fatal(err) } calls := pf.Calls() if len(calls) != 2 || calls[0].Method != "SetEnv" || calls[1].Method != "CreateInstance" { t.Fatalf("calls = %+v", calls) } label := "acme-scratchpad" kid, pub := KeySet(cfg.AssertionKey) keys, _ := json.Marshal(map[string]string{kid: base64.StdEncoding.EncodeToString(pub)}) want := map[string]string{ "BASE_APP_ORIGIN": "https://acme-scratchpad.bab.oncarlos.com", "BASE_APP_ISSUER": cfg.Origin, "BASE_APP_CONSUMER_ID": "scratchpad", "BASE_APP_KEYS": base64.StdEncoding.EncodeToString(keys), } if calls[0].Environment != label || len(calls[0].Vars) != 4 { t.Fatalf("setenv = %+v", calls[0]) } for k, v := range want { if calls[0].Vars[k] != v { t.Errorf("%s = %q, want %q", k, calls[0].Vars[k], v) } } if c := calls[1]; c.App != "scratchpad" || c.Host != label+".bab.oncarlos.com" || c.Environment != label { t.Errorf("create = %+v", c) } if s := state(t, db, "scratchpad"); s.State != "installed" || s.Host != label+".bab.oncarlos.com" { t.Errorf("row = %+v", s) } } func TestKeySetIsHexSHA256OfSignPub(t *testing.T) { kp, _ := crypto.Generate() sum := sha256.Sum256(kp.SignPub()) kid, pub := KeySet(kp) if kid != hex.EncodeToString(sum[:]) || !bytes.Equal(pub, kp.SignPub()) || len(pub) != 65 { t.Fatalf("kid %q pub %x", kid, pub) } } func TestInstallTwiceIsOneInstance(t *testing.T) { entered := make(chan struct{}, 2) gate := make(chan struct{}) in, pf, _, _ := setup(t, func(context.Context, string) error { entered <- struct{}{}; <-gate; return nil }) errs := make(chan error, 2) go func() { errs <- in.Install(context.Background(), "scratchpad") }() <-entered // first call is now mid-install go func() { errs <- in.Install(context.Background(), "scratchpad") }() if err := <-errs; err != nil { // the second returns while the first is still held t.Fatalf("second Install: %v", err) } close(gate) if err := <-errs; err != nil { t.Fatalf("first Install: %v", err) } creates := 0 for _, c := range pf.Calls() { if c.Method == "CreateInstance" { creates++ } } if creates != 1 || len(entered) != 0 { t.Fatalf("creates %d extra probes %d", creates, len(entered)) } } func TestInstallCreateRefusedMarksFailed(t *testing.T) { in, pf, db, _ := setup(t, nil) pf.Fail("CreateInstance", errors.New("platform said no: secret body")) if err := in.Install(context.Background(), "scratchpad"); err == nil { t.Error("want an error") } s := state(t, db, "scratchpad") if s.State != "failed" || s.Error == "" { t.Fatalf("row = %+v", s) } pf.Fail("CreateInstance", nil) if err := in.Install(context.Background(), "scratchpad"); err != nil { t.Fatal(err) } if s := state(t, db, "scratchpad"); s.State != "installed" { t.Errorf("after retry: %+v", s) } } func TestInstallNeverAnswersMarksFailed(t *testing.T) { in, _, db, _ := setup(t, func(context.Context, string) error { return context.DeadlineExceeded }) _ = in.Install(context.Background(), "scratchpad") if s := state(t, db, "scratchpad"); s.State != "failed" || s.Error == "" { t.Fatalf("row = %+v", s) } } func TestInstallUnknownApp(t *testing.T) { in, pf, _, _ := setup(t, nil) if err := in.Install(context.Background(), "nope"); err == nil { t.Error("want error") } if len(pf.Calls()) != 0 { t.Error("platform called") } } func TestUninstallDeletesInstanceKeepsNothingInBase(t *testing.T) { in, pf, db, _ := setup(t, nil) if err := in.Install(context.Background(), "scratchpad"); err != nil { t.Fatal(err) } if err := in.Uninstall(context.Background(), "scratchpad"); err != nil { t.Fatal(err) } calls := pf.Calls() last := calls[len(calls)-1] if last.Method != "DeleteInstance" || last.Host != "acme-scratchpad.bab.oncarlos.com" || last.App != "scratchpad" { t.Errorf("last = %+v", last) } if s := state(t, db, "scratchpad"); s.App != "" { t.Errorf("row remains: %+v", s) } } func TestEnsureDefaultsInstallsWelcomeOnce(t *testing.T) { in, pf, db, _ := setup(t, nil) for range 2 { if err := in.EnsureDefaults(context.Background()); err != nil { t.Fatal(err) } } creates := 0 for _, c := range pf.Calls() { if c.Method == "CreateInstance" { creates++ if c.App != "welcome" { t.Errorf("app = %s", c.App) } } } if creates != 1 { t.Errorf("creates = %d", creates) } if s := state(t, db, "welcome"); s.State != "installed" { t.Errorf("row = %+v", s) } if s := state(t, db, "scratchpad"); s.App != "" { t.Error("scratchpad installed") } } func TestProbeVersion(t *testing.T) { var hits atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/api/version" { http.NotFound(w, r) return } if hits.Add(1) < 3 { w.WriteHeader(http.StatusBadGateway) return } })) defer srv.Close() p := probeVersion(srv.Client(), 5*time.Millisecond, 2*time.Second) if err := p(context.Background(), srv.URL); err != nil || hits.Load() != 3 { t.Fatalf("err %v hits %d", err, hits.Load()) } } func TestProbeVersionGivesUp(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(502) })) defer srv.Close() p := probeVersion(srv.Client(), 5*time.Millisecond, 50*time.Millisecond) if err := p(context.Background(), srv.URL); err == nil { t.Fatal("want error") } } // blockingClient pauses CreateInstance until released. type blockingClient struct { platform.Client entered chan struct{} release chan struct{} } func (b *blockingClient) CreateInstance(ctx context.Context, app, host, env string) error { b.entered <- struct{}{} <-b.release return b.Client.CreateInstance(ctx, app, host, env) } func TestUninstallRefusedWhileInstalling(t *testing.T) { in, pf, db, _ := setup(t, nil) bc := &blockingClient{Client: pf, entered: make(chan struct{}), release: make(chan struct{})} in.pc = bc done := make(chan error, 1) go func() { done <- in.Install(context.Background(), "scratchpad") }() <-bc.entered if err := in.Uninstall(context.Background(), "scratchpad"); !errors.Is(err, ErrBusy) { t.Fatalf("Uninstall = %v, want ErrBusy", err) } for _, c := range pf.Calls() { if c.Method == "DeleteInstance" { t.Fatal("DeleteInstance called while installing") } } close(bc.release) if err := <-done; err != nil { t.Fatal(err) } if s := state(t, db, "scratchpad"); s.State != "installed" { t.Errorf("row = %+v", s) } } func TestInstallFinalStateSurvivesCancelledContext(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) in, _, db, _ := setup(t, func(context.Context, string) error { cancel(); return nil }) if err := in.Install(ctx, "scratchpad"); err != nil { t.Fatal(err) } if s := state(t, db, "scratchpad"); s.State != "installed" { t.Errorf("row = %+v", s) } } func TestInstallFailsWhenRowVanishes(t *testing.T) { var in *Installer var db *sql.DB in, _, db, _ = setup(t, nil) in.probe = func(ctx context.Context, _ string) error { _, err := db.ExecContext(ctx, `DELETE FROM installs`) return err } if err := in.Install(context.Background(), "scratchpad"); err == nil { t.Fatal("want an error when the row is gone") } } func TestUninstallMissingRowMakesNoPlatformCall(t *testing.T) { in, pf, _, _ := setup(t, nil) if err := in.Uninstall(context.Background(), "scratchpad"); !errors.Is(err, store.ErrNoInstall) { t.Fatalf("Uninstall = %v, want ErrNoInstall", err) } if len(pf.Calls()) != 0 { t.Fatalf("calls = %+v", pf.Calls()) } } func TestUninstallRefusedWhileReinstallingFailedRow(t *testing.T) { in, pf, db, _ := setup(t, nil) ctx := context.Background() if ok, err := store.ClaimInstall(ctx, db, "scratchpad", "acme-scratchpad.bab.oncarlos.com"); err != nil || !ok { t.Fatal(ok, err) } if err := store.SetInstallState(ctx, db, "scratchpad", "failed", "x"); err != nil { t.Fatal(err) } bc := &blockingClient{Client: pf, entered: make(chan struct{}), release: make(chan struct{})} in.pc = bc done := make(chan error, 1) go func() { done <- in.Install(ctx, "scratchpad") }() <-bc.entered if err := in.Uninstall(ctx, "scratchpad"); !errors.Is(err, ErrBusy) { t.Fatalf("Uninstall = %v, want ErrBusy", err) } for _, c := range pf.Calls() { if c.Method == "DeleteInstance" { t.Fatal("DeleteInstance called during reinstall") } } close(bc.release) if err := <-done; err != nil { t.Fatal(err) } if s := state(t, db, "scratchpad"); s.State != "installed" { t.Errorf("row = %+v", s) } } func TestInstalledWriteFailsRowEndsFailed(t *testing.T) { in, _, db, _ := setup(t, nil) _, err := db.Exec(`CREATE TRIGGER no_installed BEFORE UPDATE ON installs WHEN NEW.state = 'installed' BEGIN SELECT RAISE(ABORT, 'nope'); END`) if err != nil { t.Fatal(err) } if err := in.Install(context.Background(), "scratchpad"); err == nil { t.Fatal("want an error") } if s := state(t, db, "scratchpad"); s.State != "failed" || s.Error == "" { t.Fatalf("row = %+v", s) } } // Finding 1: the instance Base removes is the one it recorded, even after // the slug or apps domain changed. func TestUninstallDeletesRecordedHost(t *testing.T) { in, pf, db, _ := setup(t, nil) if err := in.Install(context.Background(), "scratchpad"); err != nil { t.Fatal(err) } in.cfg.Slug, in.cfg.AppsDomain = "newco", "elsewhere.example" if err := in.Uninstall(context.Background(), "scratchpad"); err != nil { t.Fatal(err) } calls := pf.Calls() if last := calls[len(calls)-1]; last.Method != "DeleteInstance" || last.Host != "acme-scratchpad.bab.oncarlos.com" { t.Fatalf("deleted %+v, want the recorded host", last) } if s := state(t, db, "scratchpad"); s.App != "" { t.Errorf("row remains: %+v", s) } } // cancelOnDelete cancels the caller's context the moment Platform accepts the // delete, as a browser that disconnects then would. type cancelOnDelete struct { platform.Client cancel context.CancelFunc } func (c cancelOnDelete) DeleteInstance(ctx context.Context, app, host string) error { err := c.Client.DeleteInstance(ctx, app, host) c.cancel() return err } // Finding 2: once Platform has removed the instance, Base forgets the // install even if the request that asked has gone. func TestUninstallFinishesAfterCallerCancels(t *testing.T) { in, pf, db, _ := setup(t, nil) if err := in.Install(context.Background(), "scratchpad"); err != nil { t.Fatal(err) } ctx, cancel := context.WithCancel(context.Background()) in.pc = cancelOnDelete{Client: pf, cancel: cancel} if err := in.Uninstall(ctx, "scratchpad"); err != nil { t.Fatalf("Uninstall: %v", err) } if s := state(t, db, "scratchpad"); s.App != "" { t.Fatalf("a removed instance is still marked %q", s.State) } } func creates(pf *platform.Fake, app string) int { n := 0 for _, c := range pf.Calls() { if c.Method == "CreateInstance" && c.App == app { n++ } } return n } // Finding 4 (R28): an owner who uninstalls Welcome does not get it back on // the next boot; installing it from the Store brings it back. func TestUninstalledDefaultStaysRemoved(t *testing.T) { in, pf, db, _ := setup(t, nil) ctx := context.Background() if err := in.EnsureDefaults(ctx); err != nil { t.Fatal(err) } if err := in.Uninstall(ctx, "welcome"); err != nil { t.Fatal(err) } for range 2 { // two more boots if err := in.EnsureDefaults(ctx); err != nil { t.Fatal(err) } } if n := creates(pf, "welcome"); n != 1 { t.Fatalf("Welcome created %d times, want once", n) } if s := state(t, db, "welcome"); s.App != "" { t.Fatalf("Welcome came back: %+v", s) } if err := in.Install(ctx, "welcome"); err != nil { // the Store's install t.Fatal(err) } if s := state(t, db, "welcome"); s.State != "installed" { t.Fatalf("Store install: %+v", s) } // Installed again by hand, it is a default like any other: a failed // install is retried at boot. if err := in.EnsureDefaults(ctx); err != nil { t.Fatal(err) } if n := creates(pf, "welcome"); n != 2 { t.Fatalf("Welcome created %d times, want twice", n) } } // blockSetEnv holds the first platform write until released. type blockSetEnv struct { platform.Client entered chan struct{} release chan struct{} } func (b *blockSetEnv) SetEnv(ctx context.Context, app, env string, vars map[string]string) error { b.entered <- struct{}{} <-b.release return b.Client.SetEnv(ctx, app, env, vars) } // Finding 5 (R33): Start has claimed the install by the time it returns, and // the rest runs on after the caller's context is cancelled. func TestStartClaimsThenProvisionsInBackground(t *testing.T) { in, pf, db, _ := setup(t, nil) bc := &blockSetEnv{Client: pf, entered: make(chan struct{}, 1), release: make(chan struct{})} in.pc = bc ctx, cancel := context.WithCancel(context.Background()) if err := in.Start(ctx, "scratchpad"); err != nil { t.Fatal(err) } cancel() // the request has ended if s := state(t, db, "scratchpad"); s.State != "installing" { t.Fatalf("after Start the row is %+v, want installing", s) } <-bc.entered // A second Start while the first is running does nothing. if err := in.Start(context.Background(), "scratchpad"); err != nil { t.Fatal(err) } close(bc.release) deadline := time.Now().Add(5 * time.Second) for state(t, db, "scratchpad").State != "installed" { if time.Now().After(deadline) { t.Fatalf("install did not finish: %+v", state(t, db, "scratchpad")) } time.Sleep(5 * time.Millisecond) } if n := creates(pf, "scratchpad"); n != 1 { t.Fatalf("creates = %d", n) } } func TestStartUnknownAppIsAnError(t *testing.T) { in, pf, _, _ := setup(t, nil) if err := in.Start(context.Background(), "nope"); err == nil { t.Fatal("want an error") } if len(pf.Calls()) != 0 { t.Fatal("platform called") } }