| 1 | package hostedctl |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "database/sql" |
| 6 | "database/sql/driver" |
| 7 | "errors" |
| 8 | "net/url" |
| 9 | "os" |
| 10 | "path/filepath" |
| 11 | "strings" |
| 12 | "sync" |
| 13 | "testing" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/oficina/equipo/internal/hostedwire" |
| 17 | "amadan.net/oficina/equipo/internal/isolatedjob" |
| 18 | "amadan.net/oficina/equipo/internal/isolatedjob/isolatedjobtest" |
| 19 | "amadan.net/rastrillo/rastrillo/budget" |
| 20 | ) |
| 21 | |
| 22 | func TestMain(m *testing.M) { os.Exit(budget.Main(m)) } |
| 23 | |
| 24 | var testWall = time.Date(2026, 11, 22, 12, 0, 0, 0, time.UTC) |
| 25 | |
| 26 | // openStore opens the store at path and closes it when the test ends. |
| 27 | func openStore(t *testing.T, path string, c isolatedjob.Clock) *Store { |
| 28 | t.Helper() |
| 29 | s, err := Open(context.Background(), path, c) |
| 30 | if err != nil { |
| 31 | t.Fatalf("Open(%s) = %v", path, err) |
| 32 | } |
| 33 | t.Cleanup(func() { _ = s.Close() }) |
| 34 | return s |
| 35 | } |
| 36 | |
| 37 | // rawDB opens path directly, past the store, to look at or tamper with it. |
| 38 | func rawDB(t *testing.T, path string) *sql.DB { |
| 39 | t.Helper() |
| 40 | db, err := sql.Open("sqlite", (&url.URL{Scheme: "file", Path: path}).String()+"?_pragma=busy_timeout(5000)") |
| 41 | if err != nil { |
| 42 | t.Fatal(err) |
| 43 | } |
| 44 | t.Cleanup(func() { _ = db.Close() }) |
| 45 | return db |
| 46 | } |
| 47 | |
| 48 | func insertJob(ctx context.Context, tx *sql.Tx, attempt string) error { |
| 49 | _, err := tx.ExecContext(ctx, `INSERT INTO jobs (attempt_id, launch_id, task_id, account_id, actor_key, purpose, |
| 50 | spec_json, spec_sha256, state, launched_t, deadline_t, drain_t, stop_t) |
| 51 | VALUES (?, ?, 'task-1', 'acct-1', 'inst-1', 'task', '{"image":"a"}', 'aaaa', 'waiting', 0, 100, 50, 90)`, |
| 52 | attempt, "launch-"+attempt) |
| 53 | return err |
| 54 | } |
| 55 | |
| 56 | func TestStoreMigratesTwice(t *testing.T) { |
| 57 | ctx := context.Background() |
| 58 | path := filepath.Join(t.TempDir(), "hosted.db") |
| 59 | |
| 60 | s, err := Open(ctx, path, isolatedjobtest.NewFakeClock(testWall)) |
| 61 | if err != nil { |
| 62 | t.Fatalf("first Open = %v", err) |
| 63 | } |
| 64 | if s.Restarted() { |
| 65 | t.Fatal("first Open of a fresh database: Restarted() = true, want false") |
| 66 | } |
| 67 | if err := s.Tx(ctx, func(tx *sql.Tx) error { return insertJob(ctx, tx, "att-1") }); err != nil { |
| 68 | t.Fatalf("insert job = %v", err) |
| 69 | } |
| 70 | if err := s.Close(); err != nil { |
| 71 | t.Fatal(err) |
| 72 | } |
| 73 | |
| 74 | s2 := openStore(t, path, isolatedjobtest.NewFakeClock(testWall)) |
| 75 | if !s2.Restarted() { |
| 76 | t.Fatal("second Open: Restarted() = false, want true") |
| 77 | } |
| 78 | var n int |
| 79 | if err := s2.Tx(ctx, func(tx *sql.Tx) error { |
| 80 | return tx.QueryRowContext(ctx, `SELECT count(*) FROM jobs WHERE attempt_id = 'att-1'`).Scan(&n) |
| 81 | }); err != nil { |
| 82 | t.Fatal(err) |
| 83 | } |
| 84 | if n != 1 { |
| 85 | t.Fatalf("jobs after a second Open = %d rows, want 1: the second Open must not reapply the schema", n) |
| 86 | } |
| 87 | _ = s2.Close() |
| 88 | |
| 89 | var version int |
| 90 | if err := rawDB(t, path).QueryRow(`PRAGMA user_version`).Scan(&version); err != nil { |
| 91 | t.Fatal(err) |
| 92 | } |
| 93 | if version != schemaVersion() { |
| 94 | t.Fatalf("user_version = %d, want %d", version, schemaVersion()) |
| 95 | } |
| 96 | for _, table := range []string{"jobs", "resume_ops", "unmatched_vms", "nonces", "audit", "clock"} { |
| 97 | var name string |
| 98 | err := rawDB(t, path).QueryRow(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?`, table).Scan(&name) |
| 99 | if err != nil { |
| 100 | t.Fatalf("table %s missing: %v", table, err) |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | func TestStoreRefusesNewerSchema(t *testing.T) { |
| 106 | ctx := context.Background() |
| 107 | path := filepath.Join(t.TempDir(), "hosted.db") |
| 108 | s, err := Open(ctx, path, isolatedjobtest.NewFakeClock(testWall)) |
| 109 | if err != nil { |
| 110 | t.Fatal(err) |
| 111 | } |
| 112 | _ = s.Close() |
| 113 | db := rawDB(t, path) |
| 114 | if _, err := db.Exec(`PRAGMA user_version = 99`); err != nil { |
| 115 | t.Fatal(err) |
| 116 | } |
| 117 | _ = db.Close() |
| 118 | |
| 119 | s, err = Open(ctx, path, isolatedjobtest.NewFakeClock(testWall)) |
| 120 | if err == nil { |
| 121 | _ = s.Close() |
| 122 | t.Fatal("Open of a database at schema 99 = nil error, want ErrSchemaNewer") |
| 123 | } |
| 124 | if !errors.Is(err, ErrSchemaNewer) { |
| 125 | t.Fatalf("Open of a database at schema 99 = %v, want ErrSchemaNewer", err) |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | func auditRows(t *testing.T, s *Store) []Audit { |
| 130 | t.Helper() |
| 131 | ctx := context.Background() |
| 132 | var out []Audit |
| 133 | err := s.Tx(ctx, func(tx *sql.Tx) error { |
| 134 | rows, err := tx.QueryContext(ctx, `SELECT actor_key, account_id, task_id, attempt_id, action, reason, at_t FROM audit ORDER BY id`) |
| 135 | if err != nil { |
| 136 | return err |
| 137 | } |
| 138 | defer rows.Close() |
| 139 | for rows.Next() { |
| 140 | var a Audit |
| 141 | var actor string |
| 142 | var at int64 |
| 143 | if err := rows.Scan(&actor, &a.Account, &a.Task, &a.Attempt, &a.Action, &a.Reason, &at); err != nil { |
| 144 | return err |
| 145 | } |
| 146 | a.Actor, a.At = hostedwire.KeyID(actor), T(at) |
| 147 | out = append(out, a) |
| 148 | } |
| 149 | return rows.Err() |
| 150 | }) |
| 151 | if err != nil { |
| 152 | t.Fatalf("read audit = %v", err) |
| 153 | } |
| 154 | return out |
| 155 | } |
| 156 | |
| 157 | func TestAuditRollsBackWithTx(t *testing.T) { |
| 158 | ctx := context.Background() |
| 159 | s := openStore(t, filepath.Join(t.TempDir(), "hosted.db"), isolatedjobtest.NewFakeClock(testWall)) |
| 160 | a := Audit{Actor: "inst-1", Account: "acct-1", Task: "task-1", Attempt: "att-1", Action: "launch", Reason: "asked", At: 5} |
| 161 | |
| 162 | failed := errors.New("later step failed") |
| 163 | err := s.Tx(ctx, func(tx *sql.Tx) error { |
| 164 | if err := appendAudit(tx, a); err != nil { |
| 165 | return err |
| 166 | } |
| 167 | return failed |
| 168 | }) |
| 169 | if !errors.Is(err, failed) { |
| 170 | t.Fatalf("Tx = %v, want the function's own error", err) |
| 171 | } |
| 172 | func() { |
| 173 | defer func() { _ = recover() }() |
| 174 | _ = s.Tx(ctx, func(tx *sql.Tx) error { |
| 175 | if err := appendAudit(tx, a); err != nil { |
| 176 | return err |
| 177 | } |
| 178 | panic("boom") |
| 179 | }) |
| 180 | }() |
| 181 | if got := auditRows(t, s); len(got) != 0 { |
| 182 | t.Fatalf("audit after a failed and a panicking Tx = %v, want no rows", got) |
| 183 | } |
| 184 | |
| 185 | if err := s.Tx(ctx, func(tx *sql.Tx) error { return appendAudit(tx, a) }); err != nil { |
| 186 | t.Fatalf("Tx = %v", err) |
| 187 | } |
| 188 | if got := auditRows(t, s); len(got) != 1 || got[0] != a { |
| 189 | t.Fatalf("audit after a committed Tx = %v, want [%v]", got, a) |
| 190 | } |
| 191 | |
| 192 | if err := s.Tx(ctx, func(tx *sql.Tx) error { return appendAudit(tx, Audit{Actor: "inst-1"}) }); err == nil { |
| 193 | t.Fatal("appendAudit with no action = nil, want an error") |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | func TestSpecImmutable(t *testing.T) { |
| 198 | ctx := context.Background() |
| 199 | s := openStore(t, filepath.Join(t.TempDir(), "hosted.db"), isolatedjobtest.NewFakeClock(testWall)) |
| 200 | if err := s.Tx(ctx, func(tx *sql.Tx) error { return insertJob(ctx, tx, "att-1") }); err != nil { |
| 201 | t.Fatal(err) |
| 202 | } |
| 203 | if err := s.Tx(ctx, func(tx *sql.Tx) error { |
| 204 | _, err := tx.ExecContext(ctx, `UPDATE jobs SET state = 'starting', vm_ref = 'vm-1', revision = revision + 1 WHERE attempt_id = 'att-1'`) |
| 205 | return err |
| 206 | }); err != nil { |
| 207 | t.Fatalf("update of state and vm_ref = %v, want nil", err) |
| 208 | } |
| 209 | for _, change := range []string{ |
| 210 | `UPDATE jobs SET spec_json = '{"image":"b"}' WHERE attempt_id = 'att-1'`, |
| 211 | `UPDATE jobs SET spec_sha256 = 'bbbb' WHERE attempt_id = 'att-1'`, |
| 212 | `UPDATE jobs SET spec_json = NULL WHERE attempt_id = 'att-1'`, |
| 213 | `UPDATE jobs SET provider_fingerprint = 'other' WHERE attempt_id = 'att-1'`, |
| 214 | } { |
| 215 | err := s.Tx(ctx, func(tx *sql.Tx) error { |
| 216 | _, err := tx.ExecContext(ctx, change) |
| 217 | return err |
| 218 | }) |
| 219 | if err == nil || !strings.Contains(err.Error(), "spec is immutable") { |
| 220 | t.Errorf("%s = %v, want 'spec is immutable'", change, err) |
| 221 | } |
| 222 | } |
| 223 | var spec, sum string |
| 224 | if err := s.Tx(ctx, func(tx *sql.Tx) error { |
| 225 | return tx.QueryRowContext(ctx, `SELECT spec_json, spec_sha256 FROM jobs WHERE attempt_id = 'att-1'`).Scan(&spec, &sum) |
| 226 | }); err != nil { |
| 227 | t.Fatal(err) |
| 228 | } |
| 229 | if spec != `{"image":"a"}` || sum != "aaaa" { |
| 230 | t.Fatalf("spec after refused updates = %q %q, want the original", spec, sum) |
| 231 | } |
| 232 | } |
| 233 | |
| 234 | // TestJobsNeverReplaced: no statement removes a jobs row, so neither its spec |
| 235 | // nor its resume history can be swapped out by a replace. |
| 236 | func TestJobsNeverReplaced(t *testing.T) { |
| 237 | ctx := context.Background() |
| 238 | s := openStore(t, filepath.Join(t.TempDir(), "hosted.db"), isolatedjobtest.NewFakeClock(testWall)) |
| 239 | if err := s.Tx(ctx, func(tx *sql.Tx) error { |
| 240 | if err := insertJob(ctx, tx, "att-1"); err != nil { |
| 241 | return err |
| 242 | } |
| 243 | _, err := tx.ExecContext(ctx, `INSERT INTO resume_ops (attempt_id, operation_id, status, prepared_epoch, result_epoch, prepared_t, completed_t) |
| 244 | VALUES ('att-1', 'op-1', 'done', 1, 1, 10, 20)`) |
| 245 | return err |
| 246 | }); err != nil { |
| 247 | t.Fatal(err) |
| 248 | } |
| 249 | 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)` |
| 250 | for _, change := range []struct{ name, sql, want string }{ |
| 251 | {"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"}, |
| 252 | {"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"}, |
| 253 | {"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) |
| 254 | ON CONFLICT (attempt_id) DO UPDATE SET spec_json = excluded.spec_json, spec_sha256 = excluded.spec_sha256`, "spec is immutable"}, |
| 255 | {"delete", `DELETE FROM jobs WHERE attempt_id = 'att-1'`, "jobs are never deleted"}, |
| 256 | } { |
| 257 | err := s.Tx(ctx, func(tx *sql.Tx) error { |
| 258 | _, err := tx.ExecContext(ctx, change.sql) |
| 259 | return err |
| 260 | }) |
| 261 | if err == nil || !strings.Contains(err.Error(), change.want) { |
| 262 | t.Errorf("%s = %v, want %q", change.name, err, change.want) |
| 263 | } |
| 264 | } |
| 265 | var spec, sum, status string |
| 266 | var ops int |
| 267 | if err := s.Tx(ctx, func(tx *sql.Tx) error { |
| 268 | if err := tx.QueryRowContext(ctx, `SELECT spec_json, spec_sha256 FROM jobs WHERE attempt_id = 'att-1'`).Scan(&spec, &sum); err != nil { |
| 269 | return err |
| 270 | } |
| 271 | return tx.QueryRowContext(ctx, `SELECT count(*), max(status) FROM resume_ops WHERE attempt_id = 'att-1'`).Scan(&ops, &status) |
| 272 | }); err != nil { |
| 273 | t.Fatal(err) |
| 274 | } |
| 275 | if spec != `{"image":"a"}` || sum != "aaaa" || ops != 1 || status != "done" { |
| 276 | 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) |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | func TestStoreOneOwner(t *testing.T) { |
| 281 | ctx := context.Background() |
| 282 | path := filepath.Join(t.TempDir(), "hosted.db") |
| 283 | first, err := Open(ctx, path, isolatedjobtest.NewFakeClock(testWall)) |
| 284 | if err != nil { |
| 285 | t.Fatal(err) |
| 286 | } |
| 287 | start := time.Now() |
| 288 | second, err := Open(ctx, path, isolatedjobtest.NewFakeClock(testWall)) |
| 289 | if err == nil { |
| 290 | _ = second.Close() |
| 291 | _ = first.Close() |
| 292 | t.Fatal("second Open while the first is open = nil error, want ErrStoreInUse") |
| 293 | } |
| 294 | if !errors.Is(err, ErrStoreInUse) { |
| 295 | t.Fatalf("second Open while the first is open = %v, want ErrStoreInUse", err) |
| 296 | } |
| 297 | if took := time.Since(start); took > time.Second { |
| 298 | t.Fatalf("second Open took %v to fail, want under 1s", took) |
| 299 | } |
| 300 | if err := first.Close(); err != nil { |
| 301 | t.Fatal(err) |
| 302 | } |
| 303 | openStore(t, path, isolatedjobtest.NewFakeClock(testWall)) |
| 304 | } |
| 305 | |
| 306 | // TestStoreOneOwnerThroughLinks: the lock belongs to the database file, not |
| 307 | // the name it was opened by. |
| 308 | func TestStoreOneOwnerThroughLinks(t *testing.T) { |
| 309 | ctx := context.Background() |
| 310 | dir := t.TempDir() |
| 311 | path := filepath.Join(dir, "controller.db") |
| 312 | first, err := Open(ctx, path, isolatedjobtest.NewFakeClock(testWall)) |
| 313 | if err != nil { |
| 314 | t.Fatal(err) |
| 315 | } |
| 316 | symlink, hardlink := filepath.Join(dir, "current.db"), filepath.Join(dir, "linked.db") |
| 317 | if err := os.Symlink(path, symlink); err != nil { |
| 318 | t.Fatal(err) |
| 319 | } |
| 320 | if err := os.Link(path, hardlink); err != nil { |
| 321 | t.Fatal(err) |
| 322 | } |
| 323 | for _, other := range []string{symlink, hardlink} { |
| 324 | start := time.Now() |
| 325 | second, err := Open(ctx, other, isolatedjobtest.NewFakeClock(testWall)) |
| 326 | if err == nil { |
| 327 | _ = second.Close() |
| 328 | t.Errorf("Open through %s while %s is open = nil error, want ErrStoreInUse", filepath.Base(other), filepath.Base(path)) |
| 329 | continue |
| 330 | } |
| 331 | if !errors.Is(err, ErrStoreInUse) { |
| 332 | t.Errorf("Open through %s while %s is open = %v, want ErrStoreInUse", filepath.Base(other), filepath.Base(path), err) |
| 333 | } |
| 334 | if took := time.Since(start); took > time.Second { |
| 335 | t.Errorf("Open through %s took %v to fail, want under 1s", filepath.Base(other), took) |
| 336 | } |
| 337 | // Not only Open: any connection, by any name, is kept out while the |
| 338 | // Store holds the file. |
| 339 | reader, err := sql.Open("sqlite", (&url.URL{Scheme: "file", Path: other}).String()+"?_pragma=busy_timeout(100)") |
| 340 | if err != nil { |
| 341 | t.Fatal(err) |
| 342 | } |
| 343 | var n int |
| 344 | err = reader.QueryRow(`SELECT count(*) FROM jobs`).Scan(&n) |
| 345 | _ = reader.Close() |
| 346 | if err == nil { |
| 347 | t.Errorf("plain read through %s while the Store is open = nil error, want the database locked", filepath.Base(other)) |
| 348 | } |
| 349 | } |
| 350 | if err := first.Close(); err != nil { |
| 351 | t.Fatal(err) |
| 352 | } |
| 353 | openStore(t, symlink, isolatedjobtest.NewFakeClock(testWall)) |
| 354 | } |
| 355 | |
| 356 | // TestStoreLostConnectionFailsStore: when database/sql discards the pinned |
| 357 | // connection, its exclusive lock is gone, so the Store must stop for good |
| 358 | // instead of carrying on with a fresh connection and a stale clock. |
| 359 | func TestStoreLostConnectionFailsStore(t *testing.T) { |
| 360 | ctx := context.Background() |
| 361 | path := filepath.Join(t.TempDir(), "hosted.db") |
| 362 | clk := isolatedjobtest.NewFakeClock(testWall) |
| 363 | s := openStore(t, path, clk) |
| 364 | |
| 365 | // What database/sql does with a connection the driver calls bad. |
| 366 | _ = s.conn.Raw(func(any) error { return driver.ErrBadConn }) |
| 367 | |
| 368 | other, err := Open(ctx, path, isolatedjobtest.NewFakeClock(testWall.Add(time.Hour))) |
| 369 | if err != nil { |
| 370 | t.Fatalf("Open after the first Store lost its connection = %v, want nil (the lock is gone)", err) |
| 371 | } |
| 372 | if err := other.Close(); err != nil { |
| 373 | t.Fatal(err) |
| 374 | } |
| 375 | before := readCheckpoint(t, path) |
| 376 | |
| 377 | clk.AdvanceMono(time.Minute) |
| 378 | err = s.Tx(ctx, func(tx *sql.Tx) error { return appendAudit(tx, Audit{Action: "stale"}) }) |
| 379 | if !errors.Is(err, ErrStoreLost) { |
| 380 | t.Fatalf("Tx on the Store whose connection was discarded = %v, want ErrStoreLost", err) |
| 381 | } |
| 382 | if err := s.Checkpoint(ctx); !errors.Is(err, ErrStoreLost) { |
| 383 | t.Fatalf("a later Checkpoint = %v, want ErrStoreLost (the Store stays failed)", err) |
| 384 | } |
| 385 | if ok, err := s.Remember(ctx, "inst-1", "n1", testWall.Add(hostedwire.NonceTTL)); ok || !errors.Is(err, ErrStoreLost) { |
| 386 | t.Fatalf("a later Remember = (%v, %v), want (false, ErrStoreLost)", ok, err) |
| 387 | } |
| 388 | if after := readCheckpoint(t, path); after != before { |
| 389 | t.Fatalf("checkpoint after the stale Store's calls = %v, want the second Store's %v unchanged", after, before) |
| 390 | } |
| 391 | if err := s.Close(); err != nil { |
| 392 | t.Fatalf("Close of a lost Store = %v, want nil", err) |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | // readCheckpoint reads the clock row past the store, with a short timeout. |
| 397 | func readCheckpoint(t *testing.T, path string) [2]int64 { |
| 398 | t.Helper() |
| 399 | db, err := sql.Open("sqlite", (&url.URL{Scheme: "file", Path: path}).String()+"?_pragma=busy_timeout(100)") |
| 400 | if err != nil { |
| 401 | t.Fatal(err) |
| 402 | } |
| 403 | defer db.Close() |
| 404 | var cp [2]int64 |
| 405 | if err := db.QueryRow(`SELECT t_ns, wall_unix_ns FROM clock WHERE id = 1`).Scan(&cp[0], &cp[1]); err != nil { |
| 406 | t.Fatalf("read checkpoint: %v", err) |
| 407 | } |
| 408 | return cp |
| 409 | } |
| 410 | |
| 411 | // TestStoreNonceReplayAcrossWallJump: the wall clock jumps forward between |
| 412 | // Verify (which set until) and Remember (which prunes by the wall clock). |
| 413 | func TestStoreNonceReplayAcrossWallJump(t *testing.T) { |
| 414 | ctx := context.Background() |
| 415 | clk := isolatedjobtest.NewFakeClock(testWall) // 12:00 |
| 416 | s := openStore(t, filepath.Join(t.TempDir(), "hosted.db"), clk) |
| 417 | until := testWall.Add(hostedwire.NonceTTL) // 12:10 |
| 418 | if ok, err := s.Remember(ctx, "inst-1", "orig", until); err != nil || !ok { |
| 419 | t.Fatalf("first Remember = (%v, %v), want (true, nil)", ok, err) |
| 420 | } |
| 421 | clk.SetWall(until.Add(time.Minute)) // 12:11, before the replay reaches Remember |
| 422 | if ok, err := s.Remember(ctx, "inst-1", "orig", until); ok || err != nil { |
| 423 | 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) |
| 424 | } |
| 425 | // A new nonce whose window ends no later than the nonces this call |
| 426 | // prunes (plus the skew margin) is denied too: the wall clock moved past |
| 427 | // it. |
| 428 | if ok, err := s.Remember(ctx, "inst-1", "new", until); ok || !errors.Is(err, ErrNoncePruned) { |
| 429 | t.Fatalf("new nonce with until 12:10 at 12:11, pruning until 12:10 = (%v, %v), want (false, ErrNoncePruned)", ok, err) |
| 430 | } |
| 431 | } |
| 432 | |
| 433 | func TestStoreDeniesNonceAfterPruneAndRollback(t *testing.T) { |
| 434 | ctx := context.Background() |
| 435 | clk := isolatedjobtest.NewFakeClock(testWall) // 12:00 |
| 436 | path := filepath.Join(t.TempDir(), "hosted.db") |
| 437 | s := openStore(t, path, clk) |
| 438 | until := testWall.Add(hostedwire.NonceTTL) // 12:10 |
| 439 | if ok, err := s.Remember(ctx, "inst-1", "orig", until); err != nil || !ok { |
| 440 | t.Fatalf("first Remember = (%v, %v), want (true, nil)", ok, err) |
| 441 | } |
| 442 | clk.SetWall(until.Add(time.Minute)) // 12:11: another request prunes "orig" |
| 443 | if ok, err := s.Remember(ctx, "inst-1", "other", until.Add(11*time.Minute)); err != nil || !ok { |
| 444 | t.Fatalf("Remember at 12:11 = (%v, %v), want (true, nil)", ok, err) |
| 445 | } |
| 446 | clk.SetWall(testWall) // back to 12:00: the replay would pass the skew check |
| 447 | if ok, err := s.Remember(ctx, "inst-1", "orig", until); err == nil || ok { |
| 448 | t.Fatalf("replay of a pruned nonce after the wall clock went back = (%v, %v), want (false, an error)", ok, err) |
| 449 | } |
| 450 | // A replay 90 s after the original still passes a 60 s skew check |
| 451 | // against its own timestamp, and its window ends 90 s later. |
| 452 | clk.SetWall(testWall.Add(90 * time.Second)) |
| 453 | if ok, err := s.Remember(ctx, "inst-1", "orig", until.Add(90*time.Second)); !errors.Is(err, ErrNoncePruned) || ok { |
| 454 | t.Fatalf("replay 90s after the original = (%v, %v), want (false, ErrNoncePruned)", ok, err) |
| 455 | } |
| 456 | _ = s.Close() |
| 457 | s = openStore(t, path, clk) |
| 458 | if ok, err := s.Remember(ctx, "inst-1", "orig", until); err == nil || ok { |
| 459 | t.Fatalf("replay of a pruned nonce after a restart = (%v, %v), want (false, an error)", ok, err) |
| 460 | } |
| 461 | clk.SetWall(until.Add(time.Second)) // past the pruned window: new nonces are fine again |
| 462 | if ok, err := s.Remember(ctx, "inst-1", "fresh", until.Add(hostedwire.NonceTTL)); err != nil || !ok { |
| 463 | t.Fatalf("Remember once the wall clock is past the pruned window = (%v, %v), want (true, nil)", ok, err) |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | func TestStoreRemembersNonces(t *testing.T) { |
| 468 | ctx := context.Background() |
| 469 | clk := isolatedjobtest.NewFakeClock(testWall) |
| 470 | s := openStore(t, filepath.Join(t.TempDir(), "hosted.db"), clk) |
| 471 | var _ hostedwire.NonceStore = s |
| 472 | |
| 473 | until := testWall.Add(hostedwire.NonceTTL) |
| 474 | check := func(id hostedwire.KeyID, nonce string, want bool) { |
| 475 | t.Helper() |
| 476 | got, err := s.Remember(ctx, id, nonce, until) |
| 477 | if err != nil || got != want { |
| 478 | t.Fatalf("Remember(%s, %s) = (%v, %v), want (%v, nil)", id, nonce, got, err, want) |
| 479 | } |
| 480 | } |
| 481 | check("inst-1", "n1", true) |
| 482 | check("inst-1", "n1", false) // a replay |
| 483 | check("inst-2", "n1", true) // nonces are per key |
| 484 | check("inst-1", "n2", true) |
| 485 | |
| 486 | clk.SetWall(until.Add(time.Second)) |
| 487 | until = until.Add(time.Hour) |
| 488 | check("inst-1", "n1", false) // expired but still held: a replay, and nothing pruned |
| 489 | check("inst-1", "n3", true) // prunes the three expired rows |
| 490 | check("inst-1", "n1", true) // forgotten once pruned, and outside the pruned window |
| 491 | check("inst-1", "n1", false) |
| 492 | |
| 493 | var left int |
| 494 | if err := s.Tx(ctx, func(tx *sql.Tx) error { |
| 495 | return tx.QueryRowContext(ctx, `SELECT count(*) FROM nonces`).Scan(&left) |
| 496 | }); err != nil { |
| 497 | t.Fatal(err) |
| 498 | } |
| 499 | if left != 2 { |
| 500 | t.Fatalf("nonces held after expiry = %d, want 2 (n3 and the new n1): expired rows are pruned", left) |
| 501 | } |
| 502 | |
| 503 | // Of concurrent calls with one pair, exactly one gets true. |
| 504 | var wg sync.WaitGroup |
| 505 | results := make(chan bool, 20) |
| 506 | for range 20 { |
| 507 | wg.Go(func() { |
| 508 | ok, err := s.Remember(ctx, "inst-3", "race", until) |
| 509 | if err != nil { |
| 510 | t.Errorf("concurrent Remember = %v", err) |
| 511 | } |
| 512 | results <- ok |
| 513 | }) |
| 514 | } |
| 515 | wg.Wait() |
| 516 | close(results) |
| 517 | fresh := 0 |
| 518 | for ok := range results { |
| 519 | if ok { |
| 520 | fresh++ |
| 521 | } |
| 522 | } |
| 523 | if fresh != 1 { |
| 524 | t.Fatalf("20 concurrent Remember calls with one nonce: %d got true, want 1", fresh) |
| 525 | } |
| 526 | |
| 527 | _ = s.Close() |
| 528 | if ok, err := s.Remember(ctx, "inst-1", "n3", until); err == nil || ok { |
| 529 | t.Fatalf("Remember on a closed store = (%v, %v), want (false, an error)", ok, err) |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | type recordingAlerter struct { |
| 534 | got []Alert |
| 535 | fail error |
| 536 | } |
| 537 | |
| 538 | func (r *recordingAlerter) Alert(_ context.Context, a Alert) error { |
| 539 | if r.fail != nil { |
| 540 | return r.fail |
| 541 | } |
| 542 | r.got = append(r.got, a) |
| 543 | return nil |
| 544 | } |
| 545 | |
| 546 | type nopRunner struct{ isolatedjob.Runner } |
| 547 | type nopAuditor struct{ isolatedjob.NetworkAuditor } |
| 548 | |
| 549 | // testNamespace is the provider namespace test controllers are set up for. |
| 550 | const testNamespace = "test:account-1:region-1" |
| 551 | |
| 552 | // testFingerprint is the test controllers' ProviderFingerprint. |
| 553 | func testFingerprint(d isolatedjob.ImageDigest, s isolatedjob.Size) string { |
| 554 | return "fp/" + string(d) + "/" + string(s) |
| 555 | } |
| 556 | |
| 557 | // testConfig is a Config with only the required provider fields set. |
| 558 | func testConfig() Config { |
| 559 | return Config{ProviderNamespace: testNamespace, ProviderFingerprint: testFingerprint} |
| 560 | } |
| 561 | |
| 562 | func TestNewRefusesNilDependency(t *testing.T) { |
| 563 | s := openStore(t, filepath.Join(t.TempDir(), "hosted.db"), isolatedjobtest.NewFakeClock(testWall)) |
| 564 | full := Deps{Store: s, Runner: nopRunner{}, Auditor: nopAuditor{}, Alerter: &recordingAlerter{}} |
| 565 | if _, err := New(testConfig(), full); err != nil { |
| 566 | t.Fatalf("New with every dependency = %v, want nil", err) |
| 567 | } |
| 568 | for _, c := range []struct { |
| 569 | name, want string |
| 570 | d Deps |
| 571 | }{ |
| 572 | {"no store", "store", Deps{Runner: full.Runner, Auditor: full.Auditor, Alerter: full.Alerter}}, |
| 573 | {"no runner", "runner", Deps{Store: s, Auditor: full.Auditor, Alerter: full.Alerter}}, |
| 574 | {"no auditor", "auditor", Deps{Store: s, Runner: full.Runner, Alerter: full.Alerter}}, |
| 575 | {"no alerter", "alerter", Deps{Store: s, Runner: full.Runner, Auditor: full.Auditor}}, |
| 576 | {"typed nil runner", "runner", Deps{Store: s, Runner: (*nopRunner)(nil), Auditor: full.Auditor, Alerter: full.Alerter}}, |
| 577 | {"typed nil auditor", "auditor", Deps{Store: s, Runner: full.Runner, Auditor: (*nopAuditor)(nil), Alerter: full.Alerter}}, |
| 578 | {"typed nil alerter", "alerter", Deps{Store: s, Runner: full.Runner, Auditor: full.Auditor, Alerter: (*recordingAlerter)(nil)}}, |
| 579 | } { |
| 580 | got, err := New(testConfig(), c.d) |
| 581 | if err == nil || got != nil { |
| 582 | t.Errorf("New with %s = (%v, %v), want (nil, an error)", c.name, got, err) |
| 583 | } else if !strings.Contains(err.Error(), c.want) { |
| 584 | t.Errorf("New with %s = %v, want the error to name the %s", c.name, err, c.want) |
| 585 | } |
| 586 | } |
| 587 | } |
| 588 | |
| 589 | // TestProviderNamespaceBound: the first controller binds the database to its |
| 590 | // provider namespace. After a restart, a controller set up for another (an |
| 591 | // account or region where every saved Ref reads as not found) refuses to |
| 592 | // start, so it never reconciles, proves or dispatches anything (R28); one |
| 593 | // with no namespace or fingerprint refuses too; the right one starts. |
| 594 | func TestProviderNamespaceBound(t *testing.T) { |
| 595 | t.Parallel() |
| 596 | e := newLaunchEnv(t) |
| 597 | e.launchWith("att-1", 2*time.Hour) |
| 598 | reads := e.fake.Calls(isolatedjob.OpGet) + e.fake.Calls(isolatedjob.OpList) |
| 599 | e.down() |
| 600 | e.store = openStore(t, e.path, e.clk) |
| 601 | deps := Deps{Store: e.store, Runner: e.fake, Auditor: e.fake, Alerter: &recordingAlerter{}} |
| 602 | other := e.cfg |
| 603 | other.ProviderNamespace = "test:account-2:region-1" |
| 604 | if c, err := New(other, deps); c != nil || !errors.Is(err, ErrProviderMismatch) { |
| 605 | t.Fatalf("New for another namespace = (%v, %v), want ErrProviderMismatch", c, err) |
| 606 | } |
| 607 | for _, cfg := range []Config{{ProviderNamespace: testNamespace}, {ProviderFingerprint: testFingerprint}} { |
| 608 | if c, err := New(cfg, deps); c != nil || err == nil { |
| 609 | t.Fatalf("New with namespace %q and fingerprint set %v = (%v, %v), want an error", |
| 610 | cfg.ProviderNamespace, cfg.ProviderFingerprint != nil, c, err) |
| 611 | } |
| 612 | } |
| 613 | if n := e.fake.Calls(isolatedjob.OpGet) + e.fake.Calls(isolatedjob.OpList); n != reads { |
| 614 | t.Fatalf("provider reads after the refused starts = %d, want %d", n, reads) |
| 615 | } |
| 616 | e.newController() |
| 617 | e.refresh() |
| 618 | if s := e.stopCols("att-1"); s.proof.Valid || s.notFoundSince.Valid { |
| 619 | t.Fatalf("att-1 under its own namespace = %+v, want no proof and no not-found", s) |
| 620 | } |
| 621 | if !e.hasAudit("", "", "provider_bound", testNamespace) { |
| 622 | t.Fatal("no provider_bound audit row for the first binding") |
| 623 | } |
| 624 | } |
| 625 | |
| 626 | func TestStoreRefusesNilClock(t *testing.T) { |
| 627 | ctx := context.Background() |
| 628 | for name, c := range map[string]isolatedjob.Clock{ |
| 629 | "nil clock": nil, |
| 630 | "typed nil clock": (*isolatedjobtest.FakeClock)(nil), |
| 631 | } { |
| 632 | var s *Store |
| 633 | var err error |
| 634 | func() { |
| 635 | defer func() { |
| 636 | if r := recover(); r != nil { |
| 637 | err = nil |
| 638 | t.Errorf("Open with a %s panicked (%v), want an error", name, r) |
| 639 | } |
| 640 | }() |
| 641 | s, err = Open(ctx, filepath.Join(t.TempDir(), "hosted.db"), c) |
| 642 | }() |
| 643 | if err == nil || s != nil { |
| 644 | if s != nil { |
| 645 | _ = s.Close() |
| 646 | } |
| 647 | t.Errorf("Open with a %s = (%v, %v), want (nil, an error)", name, s, err) |
| 648 | } |
| 649 | } |
| 650 | } |
| 651 | |