package hostedctl import ( "context" "database/sql" "database/sql/driver" "errors" "net/url" "os" "path/filepath" "strings" "sync" "testing" "time" "amadan.net/oficina/equipo/internal/hostedwire" "amadan.net/oficina/equipo/internal/isolatedjob" "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest" "amadan.net/rastrillo/rastrillo/budget" ) func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } var testWall = time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC) // openStore opens the store at path and closes it when the test ends. func openStore(t *testing.T, path string, c isolatedjob.Clock) *Store { t.Helper() s, err := Open(context.Background(), path, c) if err != nil { t.Fatalf("Open(%s) = %v", path, err) } t.Cleanup(func() { _ = s.Close() }) return s } // rawDB opens path directly, past the store, to look at or tamper with it. func rawDB(t *testing.T, path string) *sql.DB { t.Helper() db, err := sql.Open("sqlite", (&url.URL{Scheme: "file", Path: path}).String()+"?_pragma=busy_timeout(5000)") if err != nil { t.Fatal(err) } t.Cleanup(func() { _ = db.Close() }) return db } func insertJob(ctx context.Context, tx *sql.Tx, attempt string) error { _, err := tx.ExecContext(ctx, `INSERT INTO jobs (attempt_id, launch_id, task_id, account_id, actor_key, purpose, spec_json, spec_sha256, state, launched_t, deadline_t, drain_t, stop_t) VALUES (?, ?, 'task-1', 'acct-1', 'inst-1', 'task', '{"image":"a"}', 'aaaa', 'waiting', 0, 100, 50, 90)`, attempt, "launch-"+attempt) return err } func TestStoreMigratesTwice(t *testing.T) { ctx := context.Background() path := filepath.Join(t.TempDir(), "hosted.db") s, err := Open(ctx, path, isolatedjobtest.NewFakeClock(testWall)) if err != nil { t.Fatalf("first Open = %v", err) } if s.Restarted() { t.Fatal("first Open of a fresh database: Restarted() = true, want false") } if err := s.Tx(ctx, func(tx *sql.Tx) error { return insertJob(ctx, tx, "att-1") }); err != nil { t.Fatalf("insert job = %v", err) } if err := s.Close(); err != nil { t.Fatal(err) } s2 := openStore(t, path, isolatedjobtest.NewFakeClock(testWall)) if !s2.Restarted() { t.Fatal("second Open: Restarted() = false, want true") } var n int if err := s2.Tx(ctx, func(tx *sql.Tx) error { return tx.QueryRowContext(ctx, `SELECT count(*) FROM jobs WHERE attempt_id = 'att-1'`).Scan(&n) }); err != nil { t.Fatal(err) } if n != 1 { t.Fatalf("jobs after a second Open = %d rows, want 1: the second Open must not reapply the schema", n) } _ = s2.Close() var version int if err := rawDB(t, path).QueryRow(`PRAGMA user_version`).Scan(&version); err != nil { t.Fatal(err) } if version != schemaVersion() { t.Fatalf("user_version = %d, want %d", version, schemaVersion()) } for _, table := range []string{"jobs", "resume_ops", "unmatched_vms", "nonces", "audit", "clock"} { var name string err := rawDB(t, path).QueryRow(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`, table).Scan(&name) if err != nil { t.Fatalf("table %s missing: %v", table, err) } } } func TestStoreRefusesNewerSchema(t *testing.T) { ctx := context.Background() path := filepath.Join(t.TempDir(), "hosted.db") s, err := Open(ctx, path, isolatedjobtest.NewFakeClock(testWall)) if err != nil { t.Fatal(err) } _ = s.Close() db := rawDB(t, path) if _, err := db.Exec(`PRAGMA user_version = 99`); err != nil { t.Fatal(err) } _ = db.Close() s, err = Open(ctx, path, isolatedjobtest.NewFakeClock(testWall)) if err == nil { _ = s.Close() t.Fatal("Open of a database at schema 99 = nil error, want ErrSchemaNewer") } if !errors.Is(err, ErrSchemaNewer) { t.Fatalf("Open of a database at schema 99 = %v, want ErrSchemaNewer", err) } } func auditRows(t *testing.T, s *Store) []Audit { t.Helper() ctx := context.Background() var out []Audit err := s.Tx(ctx, func(tx *sql.Tx) error { rows, err := tx.QueryContext(ctx, `SELECT actor_key, account_id, task_id, attempt_id, action, reason, at_t FROM audit ORDER BY id`) if err != nil { return err } defer rows.Close() for rows.Next() { var a Audit var actor string var at int64 if err := rows.Scan(&actor, &a.Account, &a.Task, &a.Attempt, &a.Action, &a.Reason, &at); err != nil { return err } a.Actor, a.At = hostedwire.KeyID(actor), T(at) out = append(out, a) } return rows.Err() }) if err != nil { t.Fatalf("read audit = %v", err) } return out } func TestAuditRollsBackWithTx(t *testing.T) { ctx := context.Background() s := openStore(t, filepath.Join(t.TempDir(), "hosted.db"), isolatedjobtest.NewFakeClock(testWall)) a := Audit{Actor: "inst-1", Account: "acct-1", Task: "task-1", Attempt: "att-1", Action: "launch", Reason: "asked", At: 5} failed := errors.New("later step failed") err := s.Tx(ctx, func(tx *sql.Tx) error { if err := appendAudit(tx, a); err != nil { return err } return failed }) if !errors.Is(err, failed) { t.Fatalf("Tx = %v, want the function's own error", err) } func() { defer func() { _ = recover() }() _ = s.Tx(ctx, func(tx *sql.Tx) error { if err := appendAudit(tx, a); err != nil { return err } panic("boom") }) }() if got := auditRows(t, s); len(got) != 0 { t.Fatalf("audit after a failed and a panicking Tx = %v, want no rows", got) } if err := s.Tx(ctx, func(tx *sql.Tx) error { return appendAudit(tx, a) }); err != nil { t.Fatalf("Tx = %v", err) } if got := auditRows(t, s); len(got) != 1 || got[0] != a { t.Fatalf("audit after a committed Tx = %v, want [%v]", got, a) } if err := s.Tx(ctx, func(tx *sql.Tx) error { return appendAudit(tx, Audit{Actor: "inst-1"}) }); err == nil { t.Fatal("appendAudit with no action = nil, want an error") } } func TestSpecImmutable(t *testing.T) { ctx := context.Background() s := openStore(t, filepath.Join(t.TempDir(), "hosted.db"), isolatedjobtest.NewFakeClock(testWall)) if err := s.Tx(ctx, func(tx *sql.Tx) error { return insertJob(ctx, tx, "att-1") }); err != nil { t.Fatal(err) } if err := s.Tx(ctx, func(tx *sql.Tx) error { _, err := tx.ExecContext(ctx, `UPDATE jobs SET state = 'starting', vm_ref = 'vm-1', revision = revision + 1 WHERE attempt_id = 'att-1'`) return err }); err != nil { t.Fatalf("update of state and vm_ref = %v, want nil", err) } for _, change := range []string{ `UPDATE jobs SET spec_json = '{"image":"b"}' WHERE attempt_id = 'att-1'`, `UPDATE jobs SET spec_sha256 = 'bbbb' WHERE attempt_id = 'att-1'`, `UPDATE jobs SET spec_json = NULL WHERE attempt_id = 'att-1'`, `UPDATE jobs SET provider_fingerprint = 'other' WHERE attempt_id = 'att-1'`, } { err := s.Tx(ctx, func(tx *sql.Tx) error { _, err := tx.ExecContext(ctx, change) return err }) if err == nil || !strings.Contains(err.Error(), "spec is immutable") { t.Errorf("%s = %v, want 'spec is immutable'", change, err) } } var spec, sum string if err := s.Tx(ctx, func(tx *sql.Tx) error { return tx.QueryRowContext(ctx, `SELECT spec_json, spec_sha256 FROM jobs WHERE attempt_id = 'att-1'`).Scan(&spec, &sum) }); err != nil { t.Fatal(err) } if spec != `{"image":"a"}` || sum != "aaaa" { t.Fatalf("spec after refused updates = %q %q, want the original", spec, sum) } } // TestJobsNeverReplaced: no statement removes a jobs row, so neither its spec // nor its resume history can be swapped out by a replace. func TestJobsNeverReplaced(t *testing.T) { ctx := context.Background() s := openStore(t, filepath.Join(t.TempDir(), "hosted.db"), isolatedjobtest.NewFakeClock(testWall)) if err := s.Tx(ctx, func(tx *sql.Tx) error { if err := insertJob(ctx, tx, "att-1"); err != nil { return err } _, err := tx.ExecContext(ctx, `INSERT INTO resume_ops (attempt_id, operation_id, status, prepared_epoch, result_epoch, prepared_t, completed_t) VALUES ('att-1', 'op-1', 'done', 1, 1, 10, 20)`) return err }); err != nil { t.Fatal(err) } cols := `(attempt_id, launch_id, task_id, account_id, actor_key, purpose, spec_json, spec_sha256, state, launched_t, deadline_t, drain_t, stop_t)` for _, change := range []struct{ name, sql, want string }{ {"replace on the attempt ID", `INSERT OR REPLACE INTO jobs ` + cols + ` VALUES ('att-1', 'launch-att-1', 't', 'a', 'k', 'task', '{"image":"b"}', 'bbbb', 'waiting', 0, 1, 1, 1)`, "jobs are never deleted"}, {"replace on the launch ID", `REPLACE INTO jobs ` + cols + ` VALUES ('att-2', 'launch-att-1', 't', 'a', 'k', 'task', '{"image":"b"}', 'bbbb', 'waiting', 0, 1, 1, 1)`, "jobs are never deleted"}, {"upsert of the spec", `INSERT INTO jobs ` + cols + ` VALUES ('att-1', 'launch-att-1', 't', 'a', 'k', 'task', '{"image":"b"}', 'bbbb', 'waiting', 0, 1, 1, 1) ON CONFLICT (attempt_id) DO UPDATE SET spec_json = excluded.spec_json, spec_sha256 = excluded.spec_sha256`, "spec is immutable"}, {"delete", `DELETE FROM jobs WHERE attempt_id = 'att-1'`, "jobs are never deleted"}, } { err := s.Tx(ctx, func(tx *sql.Tx) error { _, err := tx.ExecContext(ctx, change.sql) return err }) if err == nil || !strings.Contains(err.Error(), change.want) { t.Errorf("%s = %v, want %q", change.name, err, change.want) } } var spec, sum, status string var ops int if err := s.Tx(ctx, func(tx *sql.Tx) error { if err := tx.QueryRowContext(ctx, `SELECT spec_json, spec_sha256 FROM jobs WHERE attempt_id = 'att-1'`).Scan(&spec, &sum); err != nil { return err } return tx.QueryRowContext(ctx, `SELECT count(*), max(status) FROM resume_ops WHERE attempt_id = 'att-1'`).Scan(&ops, &status) }); err != nil { t.Fatal(err) } if spec != `{"image":"a"}` || sum != "aaaa" || ops != 1 || status != "done" { t.Fatalf("after refused replaces: spec %q %q, %d resume rows (%s); want the original spec and its one done row", spec, sum, ops, status) } } func TestStoreOneOwner(t *testing.T) { ctx := context.Background() path := filepath.Join(t.TempDir(), "hosted.db") first, err := Open(ctx, path, isolatedjobtest.NewFakeClock(testWall)) if err != nil { t.Fatal(err) } start := time.Now() second, err := Open(ctx, path, isolatedjobtest.NewFakeClock(testWall)) if err == nil { _ = second.Close() _ = first.Close() t.Fatal("second Open while the first is open = nil error, want ErrStoreInUse") } if !errors.Is(err, ErrStoreInUse) { t.Fatalf("second Open while the first is open = %v, want ErrStoreInUse", err) } if took := time.Since(start); took > time.Second { t.Fatalf("second Open took %v to fail, want under 1s", took) } if err := first.Close(); err != nil { t.Fatal(err) } openStore(t, path, isolatedjobtest.NewFakeClock(testWall)) } // TestStoreOneOwnerThroughLinks: the lock belongs to the database file, not // the name it was opened by. func TestStoreOneOwnerThroughLinks(t *testing.T) { ctx := context.Background() dir := t.TempDir() path := filepath.Join(dir, "controller.db") first, err := Open(ctx, path, isolatedjobtest.NewFakeClock(testWall)) if err != nil { t.Fatal(err) } symlink, hardlink := filepath.Join(dir, "current.db"), filepath.Join(dir, "linked.db") if err := os.Symlink(path, symlink); err != nil { t.Fatal(err) } if err := os.Link(path, hardlink); err != nil { t.Fatal(err) } for _, other := range []string{symlink, hardlink} { start := time.Now() second, err := Open(ctx, other, isolatedjobtest.NewFakeClock(testWall)) if err == nil { _ = second.Close() t.Errorf("Open through %s while %s is open = nil error, want ErrStoreInUse", filepath.Base(other), filepath.Base(path)) continue } if !errors.Is(err, ErrStoreInUse) { t.Errorf("Open through %s while %s is open = %v, want ErrStoreInUse", filepath.Base(other), filepath.Base(path), err) } if took := time.Since(start); took > time.Second { t.Errorf("Open through %s took %v to fail, want under 1s", filepath.Base(other), took) } // Not only Open: any connection, by any name, is kept out while the // Store holds the file. reader, err := sql.Open("sqlite", (&url.URL{Scheme: "file", Path: other}).String()+"?_pragma=busy_timeout(100)") if err != nil { t.Fatal(err) } var n int err = reader.QueryRow(`SELECT count(*) FROM jobs`).Scan(&n) _ = reader.Close() if err == nil { t.Errorf("plain read through %s while the Store is open = nil error, want the database locked", filepath.Base(other)) } } if err := first.Close(); err != nil { t.Fatal(err) } openStore(t, symlink, isolatedjobtest.NewFakeClock(testWall)) } // TestStoreLostConnectionFailsStore: when database/sql discards the pinned // connection, its exclusive lock is gone, so the Store must stop for good // instead of carrying on with a fresh connection and a stale clock. func TestStoreLostConnectionFailsStore(t *testing.T) { ctx := context.Background() path := filepath.Join(t.TempDir(), "hosted.db") clk := isolatedjobtest.NewFakeClock(testWall) s := openStore(t, path, clk) // What database/sql does with a connection the driver calls bad. _ = s.conn.Raw(func(any) error { return driver.ErrBadConn }) other, err := Open(ctx, path, isolatedjobtest.NewFakeClock(testWall.Add(time.Hour))) if err != nil { t.Fatalf("Open after the first Store lost its connection = %v, want nil (the lock is gone)", err) } if err := other.Close(); err != nil { t.Fatal(err) } before := readCheckpoint(t, path) clk.AdvanceMono(time.Minute) err = s.Tx(ctx, func(tx *sql.Tx) error { return appendAudit(tx, Audit{Action: "stale"}) }) if !errors.Is(err, ErrStoreLost) { t.Fatalf("Tx on the Store whose connection was discarded = %v, want ErrStoreLost", err) } if err := s.Checkpoint(ctx); !errors.Is(err, ErrStoreLost) { t.Fatalf("a later Checkpoint = %v, want ErrStoreLost (the Store stays failed)", err) } if ok, err := s.Remember(ctx, "inst-1", "n1", testWall.Add(hostedwire.NonceTTL)); ok || !errors.Is(err, ErrStoreLost) { t.Fatalf("a later Remember = (%v, %v), want (false, ErrStoreLost)", ok, err) } if after := readCheckpoint(t, path); after != before { t.Fatalf("checkpoint after the stale Store's calls = %v, want the second Store's %v unchanged", after, before) } if err := s.Close(); err != nil { t.Fatalf("Close of a lost Store = %v, want nil", err) } } // readCheckpoint reads the clock row past the store, with a short timeout. func readCheckpoint(t *testing.T, path string) [2]int64 { t.Helper() db, err := sql.Open("sqlite", (&url.URL{Scheme: "file", Path: path}).String()+"?_pragma=busy_timeout(100)") if err != nil { t.Fatal(err) } defer db.Close() var cp [2]int64 if err := db.QueryRow(`SELECT t_ns, wall_unix_ns FROM clock WHERE id = 1`).Scan(&cp[0], &cp[1]); err != nil { t.Fatalf("read checkpoint: %v", err) } return cp } // TestStoreNonceReplayAcrossWallJump: the wall clock jumps forward between // Verify (which set until) and Remember (which prunes by the wall clock). func TestStoreNonceReplayAcrossWallJump(t *testing.T) { ctx := context.Background() clk := isolatedjobtest.NewFakeClock(testWall) // 12:00 s := openStore(t, filepath.Join(t.TempDir(), "hosted.db"), clk) until := testWall.Add(hostedwire.NonceTTL) // 12:10 if ok, err := s.Remember(ctx, "inst-1", "orig", until); err != nil || !ok { t.Fatalf("first Remember = (%v, %v), want (true, nil)", ok, err) } clk.SetWall(until.Add(time.Minute)) // 12:11, before the replay reaches Remember if ok, err := s.Remember(ctx, "inst-1", "orig", until); ok || err != nil { t.Fatalf("replay with until 12:10 at 12:11 = (%v, %v), want (false, nil): a held row is a replay whatever its expiry", ok, err) } // A new nonce whose window ends no later than the nonces this call // prunes (plus the skew margin) is denied too: the wall clock moved past // it. if ok, err := s.Remember(ctx, "inst-1", "new", until); ok || !errors.Is(err, ErrNoncePruned) { t.Fatalf("new nonce with until 12:10 at 12:11, pruning until 12:10 = (%v, %v), want (false, ErrNoncePruned)", ok, err) } } func TestStoreDeniesNonceAfterPruneAndRollback(t *testing.T) { ctx := context.Background() clk := isolatedjobtest.NewFakeClock(testWall) // 12:00 path := filepath.Join(t.TempDir(), "hosted.db") s := openStore(t, path, clk) until := testWall.Add(hostedwire.NonceTTL) // 12:10 if ok, err := s.Remember(ctx, "inst-1", "orig", until); err != nil || !ok { t.Fatalf("first Remember = (%v, %v), want (true, nil)", ok, err) } clk.SetWall(until.Add(time.Minute)) // 12:11: another request prunes "orig" if ok, err := s.Remember(ctx, "inst-1", "other", until.Add(11*time.Minute)); err != nil || !ok { t.Fatalf("Remember at 12:11 = (%v, %v), want (true, nil)", ok, err) } clk.SetWall(testWall) // back to 12:00: the replay would pass the skew check if ok, err := s.Remember(ctx, "inst-1", "orig", until); err == nil || ok { t.Fatalf("replay of a pruned nonce after the wall clock went back = (%v, %v), want (false, an error)", ok, err) } // A replay 90 s after the original still passes a 60 s skew check // against its own timestamp, and its window ends 90 s later. clk.SetWall(testWall.Add(90 * time.Second)) if ok, err := s.Remember(ctx, "inst-1", "orig", until.Add(90*time.Second)); !errors.Is(err, ErrNoncePruned) || ok { t.Fatalf("replay 90s after the original = (%v, %v), want (false, ErrNoncePruned)", ok, err) } _ = s.Close() s = openStore(t, path, clk) if ok, err := s.Remember(ctx, "inst-1", "orig", until); err == nil || ok { t.Fatalf("replay of a pruned nonce after a restart = (%v, %v), want (false, an error)", ok, err) } clk.SetWall(until.Add(time.Second)) // past the pruned window: new nonces are fine again if ok, err := s.Remember(ctx, "inst-1", "fresh", until.Add(hostedwire.NonceTTL)); err != nil || !ok { t.Fatalf("Remember once the wall clock is past the pruned window = (%v, %v), want (true, nil)", ok, err) } } func TestStoreRemembersNonces(t *testing.T) { ctx := context.Background() clk := isolatedjobtest.NewFakeClock(testWall) s := openStore(t, filepath.Join(t.TempDir(), "hosted.db"), clk) var _ hostedwire.NonceStore = s until := testWall.Add(hostedwire.NonceTTL) check := func(id hostedwire.KeyID, nonce string, want bool) { t.Helper() got, err := s.Remember(ctx, id, nonce, until) if err != nil || got != want { t.Fatalf("Remember(%s, %s) = (%v, %v), want (%v, nil)", id, nonce, got, err, want) } } check("inst-1", "n1", true) check("inst-1", "n1", false) // a replay check("inst-2", "n1", true) // nonces are per key check("inst-1", "n2", true) clk.SetWall(until.Add(time.Second)) until = until.Add(time.Hour) check("inst-1", "n1", false) // expired but still held: a replay, and nothing pruned check("inst-1", "n3", true) // prunes the three expired rows check("inst-1", "n1", true) // forgotten once pruned, and outside the pruned window check("inst-1", "n1", false) var left int if err := s.Tx(ctx, func(tx *sql.Tx) error { return tx.QueryRowContext(ctx, `SELECT count(*) FROM nonces`).Scan(&left) }); err != nil { t.Fatal(err) } if left != 2 { t.Fatalf("nonces held after expiry = %d, want 2 (n3 and the new n1): expired rows are pruned", left) } // Of concurrent calls with one pair, exactly one gets true. var wg sync.WaitGroup results := make(chan bool, 20) for range 20 { wg.Go(func() { ok, err := s.Remember(ctx, "inst-3", "race", until) if err != nil { t.Errorf("concurrent Remember = %v", err) } results <- ok }) } wg.Wait() close(results) fresh := 0 for ok := range results { if ok { fresh++ } } if fresh != 1 { t.Fatalf("20 concurrent Remember calls with one nonce: %d got true, want 1", fresh) } _ = s.Close() if ok, err := s.Remember(ctx, "inst-1", "n3", until); err == nil || ok { t.Fatalf("Remember on a closed store = (%v, %v), want (false, an error)", ok, err) } } type recordingAlerter struct { got []Alert fail error } func (r *recordingAlerter) Alert(_ context.Context, a Alert) error { if r.fail != nil { return r.fail } r.got = append(r.got, a) return nil } type nopRunner struct{ isolatedjob.Runner } type nopAuditor struct{ isolatedjob.NetworkAuditor } // testNamespace is the provider namespace test controllers are set up for. const testNamespace = "test:account-1:region-1" // testFingerprint is the test controllers' ProviderFingerprint. func testFingerprint(d isolatedjob.ImageDigest, s isolatedjob.Size) string { return "fp/" + string(d) + "/" + string(s) } // testConfig is a Config with only the required provider fields set. func testConfig() Config { return Config{ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint} } func TestNewRefusesNilDependency(t *testing.T) { s := openStore(t, filepath.Join(t.TempDir(), "hosted.db"), isolatedjobtest.NewFakeClock(testWall)) full := Deps{Store: s, Runner: nopRunner{}, Auditor: nopAuditor{}, Alerter: &recordingAlerter{}} if _, err := New(testConfig(), full); err != nil { t.Fatalf("New with every dependency = %v, want nil", err) } for _, c := range []struct { name, want string d Deps }{ {"no store", "store", Deps{Runner: full.Runner, Auditor: full.Auditor, Alerter: full.Alerter}}, {"no runner", "runner", Deps{Store: s, Auditor: full.Auditor, Alerter: full.Alerter}}, {"no auditor", "auditor", Deps{Store: s, Runner: full.Runner, Alerter: full.Alerter}}, {"no alerter", "alerter", Deps{Store: s, Runner: full.Runner, Auditor: full.Auditor}}, {"typed nil runner", "runner", Deps{Store: s, Runner: (*nopRunner)(nil), Auditor: full.Auditor, Alerter: full.Alerter}}, {"typed nil auditor", "auditor", Deps{Store: s, Runner: full.Runner, Auditor: (*nopAuditor)(nil), Alerter: full.Alerter}}, {"typed nil alerter", "alerter", Deps{Store: s, Runner: full.Runner, Auditor: full.Auditor, Alerter: (*recordingAlerter)(nil)}}, } { got, err := New(testConfig(), c.d) if err == nil || got != nil { t.Errorf("New with %s = (%v, %v), want (nil, an error)", c.name, got, err) } else if !strings.Contains(err.Error(), c.want) { t.Errorf("New with %s = %v, want the error to name the %s", c.name, err, c.want) } } } // TestProviderNamespaceBound: the first controller binds the database to its // provider namespace. After a restart, a controller set up for another (an // account or region where every saved Ref reads as not found) refuses to // start, so it never reconciles, proves or dispatches anything (R28); one // with no namespace or fingerprint refuses too; the right one starts. func TestProviderNamespaceBound(t *testing.T) { t.Parallel() e := newLaunchEnv(t) e.launchWith("att-1", 2*time.Hour) reads := e.fake.Calls(isolatedjob.OpGet) + e.fake.Calls(isolatedjob.OpList) e.down() e.store = openStore(t, e.path, e.clk) deps := Deps{Store: e.store, Runner: e.fake, Auditor: e.fake, Alerter: &recordingAlerter{}} other := e.cfg other.ProviderNamespace = "test:account-2:region-1" if c, err := New(other, deps); c != nil || !errors.Is(err, ErrProviderMismatch) { t.Fatalf("New for another namespace = (%v, %v), want ErrProviderMismatch", c, err) } for _, cfg := range []Config{{ProviderNamespace: testNamespace}, {ProviderFingerprint: testFingerprint}} { if c, err := New(cfg, deps); c != nil || err == nil { t.Fatalf("New with namespace %q and fingerprint set %v = (%v, %v), want an error", cfg.ProviderNamespace, cfg.ProviderFingerprint != nil, c, err) } } if n := e.fake.Calls(isolatedjob.OpGet) + e.fake.Calls(isolatedjob.OpList); n != reads { t.Fatalf("provider reads after the refused starts = %d, want %d", n, reads) } e.newController() e.refresh() if s := e.stopCols("att-1"); s.proof.Valid || s.notFoundSince.Valid { t.Fatalf("att-1 under its own namespace = %+v, want no proof and no not-found", s) } if !e.hasAudit("", "", "provider_bound", testNamespace) { t.Fatal("no provider_bound audit row for the first binding") } } func TestStoreRefusesNilClock(t *testing.T) { ctx := context.Background() for name, c := range map[string]isolatedjob.Clock{ "nil clock": nil, "typed nil clock": (*isolatedjobtest.FakeClock)(nil), } { var s *Store var err error func() { defer func() { if r := recover(); r != nil { err = nil t.Errorf("Open with a %s panicked (%v), want an error", name, r) } }() s, err = Open(ctx, filepath.Join(t.TempDir(), "hosted.db"), c) }() if err == nil || s != nil { if s != nil { _ = s.Close() } t.Errorf("Open with a %s = (%v, %v), want (nil, an error)", name, s, err) } } }