| 1 | // Package hostedctl is the core of equipo-hosted-controller: the job table, |
| 2 | // controller time, launch intents, stop proof, pause generations, resume |
| 3 | // epochs and the reaper. It talks to VMs only through isolatedjob.Runner. |
| 4 | package hostedctl |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "database/sql" |
| 9 | "database/sql/driver" |
| 10 | "embed" |
| 11 | "errors" |
| 12 | "fmt" |
| 13 | "math" |
| 14 | "net/url" |
| 15 | "sync" |
| 16 | "sync/atomic" |
| 17 | "time" |
| 18 | |
| 19 | "amadan.net/oficina/equipo/internal/hostedwire" |
| 20 | "amadan.net/oficina/equipo/internal/isolatedjob" |
| 21 | |
| 22 | "modernc.org/sqlite" |
| 23 | ) |
| 24 | |
| 25 | // ErrSchemaNewer: the database was written by a newer controller. Open |
| 26 | // refuses it rather than guess what the newer columns mean. |
| 27 | var ErrSchemaNewer = errors.New("hostedctl: database schema is newer than this controller") |
| 28 | |
| 29 | // ErrStoreInUse: another Store, in this process or another, has the |
| 30 | // database open. One controller owns a database at a time. |
| 31 | var ErrStoreInUse = errors.New("hostedctl: database is open in another controller") |
| 32 | |
| 33 | // ErrNoncePruned: the nonce's validity window reaches back into a window |
| 34 | // whose nonces were already pruned, which happens when the wall clock went |
| 35 | // back. A replay there could not be told from a new request, so Remember |
| 36 | // denies it. |
| 37 | var ErrNoncePruned = errors.New("hostedctl: nonce window already pruned (wall clock went back)") |
| 38 | |
| 39 | // ErrStoreLost: the Store's one connection, and with it the exclusive lock, |
| 40 | // is gone. The Store stays failed and never reconnects, because another |
| 41 | // controller may own the database since. Close it and Open afresh, which |
| 42 | // takes the lock again and restores controller time. |
| 43 | var ErrStoreLost = errors.New("hostedctl: store connection lost; close and reopen") |
| 44 | |
| 45 | // AlertClockRollback is the alert kind, and the audit action, raised when |
| 46 | // Open finds the wall clock behind the last checkpoint. |
| 47 | const AlertClockRollback = "clock_rollback" |
| 48 | |
| 49 | //go:embed schema/*.sql |
| 50 | var schemaFS embed.FS |
| 51 | |
| 52 | // migrations are applied in order; version n is migrations[n-1]. Add a file, |
| 53 | // never edit one. |
| 54 | var migrations = []string{"schema/0001_jobs.sql"} |
| 55 | |
| 56 | // schemaVersion is the newest schema this code knows. |
| 57 | func schemaVersion() int { return len(migrations) } |
| 58 | |
| 59 | // Store is the controller's SQLite database and its controller time. |
| 60 | type Store struct { |
| 61 | db *sql.DB |
| 62 | conn *sql.Conn // the one connection, pinned at Open; it holds the exclusive lock |
| 63 | txMu sync.Mutex // one transaction at a time on conn |
| 64 | lost atomic.Bool |
| 65 | host isolatedjob.Clock |
| 66 | clock *CtlClock |
| 67 | restarted bool |
| 68 | |
| 69 | mu sync.Mutex |
| 70 | pending []outboxAlert // undelivered rows of alert_outbox, oldest first |
| 71 | closed bool |
| 72 | } |
| 73 | |
| 74 | // outboxAlert is one undelivered alert_outbox row. |
| 75 | type outboxAlert struct { |
| 76 | id int64 |
| 77 | alert Alert |
| 78 | } |
| 79 | |
| 80 | // Audit is one audit row. Actor is the verified key that asked, or empty for |
| 81 | // the controller itself. Reason never holds credentials. |
| 82 | type Audit struct { |
| 83 | Actor hostedwire.KeyID |
| 84 | Account, Task, Attempt, Action, Reason string |
| 85 | At T |
| 86 | } |
| 87 | |
| 88 | // Open opens or creates the store at path, applies any missing schema |
| 89 | // migrations, and restores controller time from the last checkpoint. |
| 90 | // |
| 91 | // Open holds SQLite's exclusive lock on the database file for the Store's |
| 92 | // whole life, so a second Open of the same file, by any name (a symlink or |
| 93 | // a hard link included), fails at once with ErrStoreInUse until the first is |
| 94 | // closed. |
| 95 | // |
| 96 | // On a fresh database controller time starts at 0 and Restarted is false. |
| 97 | // Otherwise T starts at the checkpoint's T plus the wall time since the |
| 98 | // checkpoint, or the checkpoint's T alone when the wall clock is behind it; |
| 99 | // Restarted is true; and a wall clock behind the checkpoint is audited and |
| 100 | // queued in alert_outbox, in the same transaction, for New to deliver. |
| 101 | // Either way Open writes a fresh checkpoint, so T never falls below a T |
| 102 | // already restored, and loads every undelivered alert. |
| 103 | func Open(ctx context.Context, path string, c isolatedjob.Clock) (*Store, error) { |
| 104 | if path == "" { |
| 105 | return nil, errors.New("hostedctl: store path is empty") |
| 106 | } |
| 107 | if isNil(c) { |
| 108 | return nil, errors.New("hostedctl: store needs a clock") |
| 109 | } |
| 110 | // _txlock=immediate makes every transaction BEGIN IMMEDIATE: it takes the |
| 111 | // write lock up front, so a read-check-write sequence is never |
| 112 | // interleaved with another writer. recursive_triggers makes the implicit |
| 113 | // delete of INSERT OR REPLACE fire jobs_never_deleted. |
| 114 | // |
| 115 | // locking_mode(EXCLUSIVE) makes the connection keep SQLite's lock on the |
| 116 | // database file, taken at Open's first write, until it closes. The lock |
| 117 | // follows the file, not the name, and is SQLite's own, so it cannot clash |
| 118 | // with SQLite's locking the way a separate flock on the file can (BSD, |
| 119 | // NFS). No other connection may touch the database while a Store holds |
| 120 | // it, so busy_timeout is 0: a second Open fails at once instead of |
| 121 | // waiting. (modernc runs busy_timeout first and the other pragmas in name |
| 122 | // order, so WAL is entered before EXCLUSIVE; SQLite allows that switch.) |
| 123 | dsn := (&url.URL{Scheme: "file", Path: path}).String() + |
| 124 | "?_pragma=busy_timeout(0)&_pragma=journal_mode(WAL)&_pragma=locking_mode(EXCLUSIVE)" + |
| 125 | "&_pragma=synchronous(FULL)&_pragma=foreign_keys(1)&_pragma=recursive_triggers(1)&_txlock=immediate" |
| 126 | db, err := sql.Open("sqlite", dsn) |
| 127 | if err != nil { |
| 128 | return nil, fmt.Errorf("hostedctl: open store: %w", err) |
| 129 | } |
| 130 | // One connection, pinned for the Store's life: it takes the exclusive |
| 131 | // lock at Open's first write and every Store operation runs on it. If |
| 132 | // database/sql discards it, nothing reconnects (see ErrStoreLost). |
| 133 | db.SetMaxOpenConns(1) |
| 134 | conn, err := db.Conn(ctx) |
| 135 | if err != nil { |
| 136 | _ = db.Close() |
| 137 | return nil, inUse(fmt.Errorf("hostedctl: open store: %w", err), path) |
| 138 | } |
| 139 | s := &Store{db: db, conn: conn, host: c} |
| 140 | if err := s.migrate(ctx); err != nil { |
| 141 | _ = s.release() |
| 142 | return nil, inUse(err, path) |
| 143 | } |
| 144 | if err := s.restoreClock(ctx); err != nil { |
| 145 | _ = s.release() |
| 146 | return nil, err |
| 147 | } |
| 148 | return s, nil |
| 149 | } |
| 150 | |
| 151 | // inUse turns SQLite's "busy" or "locked" at Open into ErrStoreInUse: |
| 152 | // another connection holds the database. |
| 153 | func inUse(err error, path string) error { |
| 154 | var e *sqlite.Error |
| 155 | if errors.As(err, &e) { |
| 156 | switch e.Code() & 0xff { |
| 157 | case 5, 6: // SQLITE_BUSY, SQLITE_LOCKED |
| 158 | return fmt.Errorf("%w: %s: %w", ErrStoreInUse, path, err) |
| 159 | } |
| 160 | } |
| 161 | return err |
| 162 | } |
| 163 | |
| 164 | // migrate applies the missing migrations in one transaction. The version is |
| 165 | // read inside the transaction, so two Opens racing apply each one once. |
| 166 | func (s *Store) migrate(ctx context.Context) error { |
| 167 | tx, err := s.conn.BeginTx(ctx, nil) |
| 168 | if err != nil { |
| 169 | return fmt.Errorf("hostedctl: migrate: %w", err) |
| 170 | } |
| 171 | defer func() { _ = tx.Rollback() }() |
| 172 | var version int |
| 173 | if err := tx.QueryRowContext(ctx, `PRAGMA user_version`).Scan(&version); err != nil { |
| 174 | return fmt.Errorf("hostedctl: read schema version: %w", err) |
| 175 | } |
| 176 | if version > schemaVersion() { |
| 177 | return fmt.Errorf("%w: database at version %d, this controller knows %d", ErrSchemaNewer, version, schemaVersion()) |
| 178 | } |
| 179 | if version == schemaVersion() { |
| 180 | return nil |
| 181 | } |
| 182 | for v := version; v < schemaVersion(); v++ { |
| 183 | body, err := schemaFS.ReadFile(migrations[v]) |
| 184 | if err != nil { |
| 185 | return fmt.Errorf("hostedctl: read migration %s: %w", migrations[v], err) |
| 186 | } |
| 187 | if _, err := tx.ExecContext(ctx, string(body)); err != nil { |
| 188 | return fmt.Errorf("hostedctl: apply migration %s: %w", migrations[v], err) |
| 189 | } |
| 190 | if _, err := tx.ExecContext(ctx, fmt.Sprintf(`PRAGMA user_version = %d`, v+1)); err != nil { |
| 191 | return fmt.Errorf("hostedctl: record schema version %d: %w", v+1, err) |
| 192 | } |
| 193 | } |
| 194 | if err := tx.Commit(); err != nil { |
| 195 | return fmt.Errorf("hostedctl: migrate: %w", err) |
| 196 | } |
| 197 | return nil |
| 198 | } |
| 199 | |
| 200 | // restoreClock sets controller time from the last checkpoint and writes a |
| 201 | // new one, in one transaction with any clock_rollback audit row. |
| 202 | func (s *Store) restoreClock(ctx context.Context) error { |
| 203 | tx, err := s.conn.BeginTx(ctx, nil) |
| 204 | if err != nil { |
| 205 | return fmt.Errorf("hostedctl: restore clock: %w", err) |
| 206 | } |
| 207 | defer func() { _ = tx.Rollback() }() |
| 208 | |
| 209 | wallNow := s.host.Wall().UnixNano() |
| 210 | monoNow := s.host.Mono() |
| 211 | var cpT, cpWall int64 |
| 212 | var base T |
| 213 | var rollback time.Duration |
| 214 | restarted := false |
| 215 | err = tx.QueryRowContext(ctx, `SELECT t_ns, wall_unix_ns FROM clock WHERE id = 1`).Scan(&cpT, &cpWall) |
| 216 | switch { |
| 217 | case errors.Is(err, sql.ErrNoRows): // a fresh database: T starts at 0 |
| 218 | case err != nil: |
| 219 | return fmt.Errorf("hostedctl: read clock checkpoint: %w", err) |
| 220 | default: |
| 221 | restarted = true |
| 222 | if base, rollback, err = restoreBase(T(cpT), cpWall, wallNow); err != nil { |
| 223 | return err |
| 224 | } |
| 225 | } |
| 226 | |
| 227 | if rollback > 0 { |
| 228 | detail := fmt.Sprintf("wall clock %v behind the last checkpoint at start; controller time kept at %v", rollback, time.Duration(base)) |
| 229 | if err := appendAudit(tx, Audit{Action: AlertClockRollback, Reason: detail, At: base}); err != nil { |
| 230 | return err |
| 231 | } |
| 232 | if _, err := tx.ExecContext(ctx, `INSERT INTO alert_outbox (kind, detail, at_t) VALUES (?, ?, ?)`, |
| 233 | AlertClockRollback, detail, int64(base)); err != nil { |
| 234 | return fmt.Errorf("hostedctl: queue %s alert: %w", AlertClockRollback, err) |
| 235 | } |
| 236 | } |
| 237 | if _, err := tx.ExecContext(ctx, `INSERT INTO clock (id, t_ns, wall_unix_ns) VALUES (1, ?, ?) |
| 238 | ON CONFLICT (id) DO UPDATE SET t_ns = excluded.t_ns, wall_unix_ns = excluded.wall_unix_ns`, |
| 239 | int64(base), wallNow); err != nil { |
| 240 | return fmt.Errorf("hostedctl: write clock checkpoint: %w", err) |
| 241 | } |
| 242 | pending, err := undeliveredAlerts(ctx, tx) |
| 243 | if err != nil { |
| 244 | return err |
| 245 | } |
| 246 | if err := tx.Commit(); err != nil { |
| 247 | return fmt.Errorf("hostedctl: restore clock: %w", err) |
| 248 | } |
| 249 | s.clock = &CtlClock{base: base, monoAtOpen: monoNow, c: s.host} |
| 250 | s.restarted = restarted |
| 251 | s.pending = pending |
| 252 | return nil |
| 253 | } |
| 254 | |
| 255 | // undeliveredAlerts reads alert_outbox rows not yet delivered, oldest first. |
| 256 | // Each alert's detail starts with its stable event ID, "alert <id>: ". |
| 257 | func undeliveredAlerts(ctx context.Context, tx *sql.Tx) ([]outboxAlert, error) { |
| 258 | rows, err := tx.QueryContext(ctx, `SELECT id, kind, detail, at_t FROM alert_outbox WHERE delivered = 0 ORDER BY id`) |
| 259 | if err != nil { |
| 260 | return nil, fmt.Errorf("hostedctl: read alert outbox: %w", err) |
| 261 | } |
| 262 | defer rows.Close() |
| 263 | var out []outboxAlert |
| 264 | for rows.Next() { |
| 265 | var o outboxAlert |
| 266 | var detail string |
| 267 | var at int64 |
| 268 | if err := rows.Scan(&o.id, &o.alert.Kind, &detail, &at); err != nil { |
| 269 | return nil, fmt.Errorf("hostedctl: read alert outbox: %w", err) |
| 270 | } |
| 271 | o.alert.Detail = fmt.Sprintf("alert %d: %s", o.id, detail) |
| 272 | o.alert.At = T(at) |
| 273 | out = append(out, o) |
| 274 | } |
| 275 | if err := rows.Err(); err != nil { |
| 276 | return nil, fmt.Errorf("hostedctl: read alert outbox: %w", err) |
| 277 | } |
| 278 | return out, nil |
| 279 | } |
| 280 | |
| 281 | // Close checkpoints controller time, closes the database and releases the |
| 282 | // exclusive lock. A second Close does nothing. A lost Store skips the |
| 283 | // checkpoint (it no longer owns the database) and just lets go. |
| 284 | func (s *Store) Close() error { |
| 285 | s.mu.Lock() |
| 286 | if s.closed { |
| 287 | s.mu.Unlock() |
| 288 | return nil |
| 289 | } |
| 290 | s.closed = true |
| 291 | s.mu.Unlock() |
| 292 | var cpErr error |
| 293 | if !s.lost.Load() { |
| 294 | cpErr = s.Checkpoint(context.Background()) |
| 295 | } |
| 296 | return errors.Join(cpErr, s.release()) |
| 297 | } |
| 298 | |
| 299 | // release closes the pinned connection and the database, which drops the |
| 300 | // exclusive lock. |
| 301 | func (s *Store) release() error { |
| 302 | err := s.conn.Close() |
| 303 | if errors.Is(err, sql.ErrConnDone) { |
| 304 | err = nil // already discarded |
| 305 | } |
| 306 | return errors.Join(err, s.db.Close()) |
| 307 | } |
| 308 | |
| 309 | // Clock returns the store's controller clock. |
| 310 | func (s *Store) Clock() *CtlClock { return s.clock } |
| 311 | |
| 312 | // Restarted reports whether Open found state from an earlier run. When it |
| 313 | // is true, the time that passed while the controller was down is unknown. |
| 314 | // The wall delta Open added to T is untrusted in either direction: the |
| 315 | // downtime may be longer or shorter, so it is never proof of how long a job |
| 316 | // has lived. |
| 317 | func (s *Store) Restarted() bool { return s.restarted } |
| 318 | |
| 319 | // OpenedAt returns controller time at Open. Every T stored before Open is at |
| 320 | // or below it, so after a restart a job launched at or before OpenedAt |
| 321 | // existed before this process opened the store. |
| 322 | func (s *Store) OpenedAt() T { return s.clock.base } |
| 323 | |
| 324 | // StartupAlerts returns the undelivered alerts from alert_outbox, as loaded |
| 325 | // by Open and not yet delivered by New, oldest first. |
| 326 | func (s *Store) StartupAlerts() []Alert { |
| 327 | s.mu.Lock() |
| 328 | defer s.mu.Unlock() |
| 329 | out := make([]Alert, 0, len(s.pending)) |
| 330 | for _, p := range s.pending { |
| 331 | out = append(out, p.alert) |
| 332 | } |
| 333 | return out |
| 334 | } |
| 335 | |
| 336 | // deliverStartupAlerts sends each undelivered alert, in order, and marks its |
| 337 | // outbox row delivered. It stops at the first failure; that alert stays |
| 338 | // queued, in memory and in the database, and is tried again by the next New |
| 339 | // or after a restart. Delivery is at least once: a crash, or a failed mark, |
| 340 | // after the Alerter accepted an alert sends it again with the same ID. |
| 341 | func (s *Store) deliverStartupAlerts(ctx context.Context, a Alerter) error { |
| 342 | s.mu.Lock() |
| 343 | defer s.mu.Unlock() |
| 344 | for len(s.pending) > 0 { |
| 345 | p := s.pending[0] |
| 346 | if err := a.Alert(ctx, p.alert); err != nil { |
| 347 | return fmt.Errorf("hostedctl: deliver %s alert %d: %w", p.alert.Kind, p.id, err) |
| 348 | } |
| 349 | if err := s.Tx(ctx, func(tx *sql.Tx) error { |
| 350 | _, err := tx.ExecContext(ctx, `UPDATE alert_outbox SET delivered = 1 WHERE id = ?`, p.id) |
| 351 | return err |
| 352 | }); err != nil { |
| 353 | return fmt.Errorf("hostedctl: mark alert %d delivered: %w", p.id, err) |
| 354 | } |
| 355 | s.pending = s.pending[1:] |
| 356 | } |
| 357 | return nil |
| 358 | } |
| 359 | |
| 360 | // bindProvider binds the database to provider namespace ns, with an audit |
| 361 | // row, when it has no binding yet, and returns ErrProviderMismatch when it is |
| 362 | // bound to another (ruling R28). |
| 363 | func (s *Store) bindProvider(ctx context.Context, ns string) error { |
| 364 | return s.Tx(ctx, func(tx *sql.Tx) error { |
| 365 | var bound string |
| 366 | err := tx.QueryRowContext(ctx, `SELECT namespace FROM provider_binding WHERE id = 1`).Scan(&bound) |
| 367 | switch { |
| 368 | case errors.Is(err, sql.ErrNoRows): |
| 369 | if _, err := tx.ExecContext(ctx, `INSERT INTO provider_binding (id, namespace) VALUES (1, ?)`, ns); err != nil { |
| 370 | return fmt.Errorf("hostedctl: bind provider namespace: %w", err) |
| 371 | } |
| 372 | return appendAudit(tx, Audit{Action: "provider_bound", Reason: "database bound to provider namespace " + ns, At: s.clock.Now()}) |
| 373 | case err != nil: |
| 374 | return fmt.Errorf("hostedctl: read provider binding: %w", err) |
| 375 | case bound != ns: |
| 376 | return fmt.Errorf("%w: bound to %q, configured for %q", ErrProviderMismatch, bound, ns) |
| 377 | } |
| 378 | return nil |
| 379 | }) |
| 380 | } |
| 381 | |
| 382 | // Tx runs fn in one write transaction, which holds SQLite's write lock from |
| 383 | // the start. It rolls back when fn returns an error (returned as is) or |
| 384 | // panics, and otherwise checkpoints controller time and commits. Use the tx |
| 385 | // handle for every statement inside fn, audit rows included. Never call Tx, |
| 386 | // Checkpoint or Remember from inside fn: transactions run one at a time on |
| 387 | // the one connection, so the inner call would wait forever. Do provider |
| 388 | // calls outside fn. |
| 389 | // |
| 390 | // When a call fails and the pinned connection turns out to be gone (the |
| 391 | // error says so, or a ping on it fails), the Store is marked lost: this and |
| 392 | // every later call returns ErrStoreLost. |
| 393 | // |
| 394 | // The checkpoint is sampled after fn returns, so it is at least every T fn |
| 395 | // read or wrote, and it commits with fn's writes: no committed row holds a T |
| 396 | // later than the checkpoint, so T after any restart is at least every |
| 397 | // stored T even when the wall clock went back. A T only read and never |
| 398 | // stored may appear to step back after a crash (ruling R10). |
| 399 | func (s *Store) Tx(ctx context.Context, fn func(*sql.Tx) error) error { |
| 400 | s.txMu.Lock() |
| 401 | defer s.txMu.Unlock() |
| 402 | if s.lost.Load() { |
| 403 | return ErrStoreLost |
| 404 | } |
| 405 | err := s.runTx(ctx, fn) |
| 406 | if err != nil && s.connGone(ctx, err) { |
| 407 | s.lost.Store(true) |
| 408 | return fmt.Errorf("%w: %w", ErrStoreLost, err) |
| 409 | } |
| 410 | return err |
| 411 | } |
| 412 | |
| 413 | // connGone reports whether err, or a ping on the pinned connection, shows |
| 414 | // the connection was discarded. |
| 415 | func (s *Store) connGone(ctx context.Context, err error) bool { |
| 416 | if errors.Is(err, driver.ErrBadConn) || errors.Is(err, sql.ErrConnDone) { |
| 417 | return true |
| 418 | } |
| 419 | return s.conn.PingContext(context.WithoutCancel(ctx)) != nil |
| 420 | } |
| 421 | |
| 422 | // runTx is one transaction on the pinned connection; see Tx. |
| 423 | func (s *Store) runTx(ctx context.Context, fn func(*sql.Tx) error) error { |
| 424 | tx, err := s.conn.BeginTx(ctx, nil) |
| 425 | if err != nil { |
| 426 | return fmt.Errorf("hostedctl: begin: %w", err) |
| 427 | } |
| 428 | done := false |
| 429 | defer func() { |
| 430 | if !done { |
| 431 | _ = tx.Rollback() |
| 432 | } |
| 433 | }() |
| 434 | if err := fn(tx); err != nil { |
| 435 | return err |
| 436 | } |
| 437 | if err := s.checkpoint(ctx, tx); err != nil { |
| 438 | return err |
| 439 | } |
| 440 | if err := tx.Commit(); err != nil { |
| 441 | return fmt.Errorf("hostedctl: commit: %w", err) |
| 442 | } |
| 443 | done = true |
| 444 | return nil |
| 445 | } |
| 446 | |
| 447 | // Checkpoint records (controller time, wall time) so a restart can carry T |
| 448 | // on. The reaper calls it every pass; every Tx commit does it too. |
| 449 | func (s *Store) Checkpoint(ctx context.Context) error { |
| 450 | return s.Tx(ctx, func(*sql.Tx) error { return nil }) |
| 451 | } |
| 452 | |
| 453 | func (s *Store) checkpoint(ctx context.Context, tx *sql.Tx) error { |
| 454 | res, err := tx.ExecContext(ctx, `UPDATE clock SET t_ns = ?, wall_unix_ns = ? WHERE id = 1`, |
| 455 | int64(s.clock.Now()), s.host.Wall().UnixNano()) |
| 456 | if err != nil { |
| 457 | return fmt.Errorf("hostedctl: clock checkpoint: %w", err) |
| 458 | } |
| 459 | if n, err := res.RowsAffected(); err != nil || n != 1 { |
| 460 | return fmt.Errorf("hostedctl: clock checkpoint row missing (%d rows, %v)", n, err) |
| 461 | } |
| 462 | return nil |
| 463 | } |
| 464 | |
| 465 | // Remember implements hostedwire.NonceStore. It records (id, nonce) until the |
| 466 | // given wall time. In one transaction it: |
| 467 | // 1. reports false (a replay) when a row for the pair exists, whatever its |
| 468 | // expiry, before anything is pruned; |
| 469 | // 2. finds the bound: the larger of the durable pruned-through mark and the |
| 470 | // latest expiry this call is about to prune (by this host's wall clock); |
| 471 | // 3. denies with ErrNoncePruned when until <= bound + 2*hostedwire.MaxSkew. |
| 472 | // The wall clock moved past this window, forward between Verify and |
| 473 | // Remember or back after a prune, and a forgotten nonce's replay could |
| 474 | // pass the skew check there. The margin covers a replay sent up to |
| 475 | // 2 MaxSkew later than the original; |
| 476 | // 4. prunes the expired rows, raises the mark, and inserts the nonce. |
| 477 | // |
| 478 | // Any database error returns false with the error, so the request is denied. |
| 479 | func (s *Store) Remember(ctx context.Context, id hostedwire.KeyID, nonce string, until time.Time) (bool, error) { |
| 480 | if id == "" || nonce == "" { |
| 481 | return false, errors.New("hostedctl: nonce needs a key ID and a value") |
| 482 | } |
| 483 | untilNs := until.UnixNano() |
| 484 | fresh := false |
| 485 | err := s.Tx(ctx, func(tx *sql.Tx) error { |
| 486 | var held int |
| 487 | if err := tx.QueryRowContext(ctx, `SELECT count(*) FROM nonces WHERE key_id = ? AND nonce = ?`, string(id), nonce).Scan(&held); err != nil { |
| 488 | return fmt.Errorf("hostedctl: look up nonce: %w", err) |
| 489 | } |
| 490 | if held > 0 { |
| 491 | return nil // a replay |
| 492 | } |
| 493 | var through sql.NullInt64 |
| 494 | err := tx.QueryRowContext(ctx, `SELECT through_unix_ns FROM nonce_pruned WHERE id = 1`).Scan(&through) |
| 495 | if err != nil && !errors.Is(err, sql.ErrNoRows) { |
| 496 | return fmt.Errorf("hostedctl: read nonce prune mark: %w", err) |
| 497 | } |
| 498 | wallNow := s.host.Wall().UnixNano() |
| 499 | var pruned sql.NullInt64 |
| 500 | if err := tx.QueryRowContext(ctx, `SELECT max(until_unix_ns) FROM nonces WHERE until_unix_ns < ?`, wallNow).Scan(&pruned); err != nil { |
| 501 | return fmt.Errorf("hostedctl: find expired nonces: %w", err) |
| 502 | } |
| 503 | bound := through |
| 504 | if pruned.Valid && (!bound.Valid || pruned.Int64 > bound.Int64) { |
| 505 | bound = pruned |
| 506 | } |
| 507 | if bound.Valid && (bound.Int64 > math.MaxInt64-int64(2*hostedwire.MaxSkew) || untilNs <= bound.Int64+int64(2*hostedwire.MaxSkew)) { |
| 508 | return fmt.Errorf("%w: until %d, pruned through %d", ErrNoncePruned, untilNs, bound.Int64) |
| 509 | } |
| 510 | if pruned.Valid { |
| 511 | if _, err := tx.ExecContext(ctx, `DELETE FROM nonces WHERE until_unix_ns < ?`, wallNow); err != nil { |
| 512 | return fmt.Errorf("hostedctl: prune nonces: %w", err) |
| 513 | } |
| 514 | if _, err := tx.ExecContext(ctx, `INSERT INTO nonce_pruned (id, through_unix_ns) VALUES (1, ?) |
| 515 | ON CONFLICT (id) DO UPDATE SET through_unix_ns = max(through_unix_ns, excluded.through_unix_ns)`, pruned.Int64); err != nil { |
| 516 | return fmt.Errorf("hostedctl: record nonce prune mark: %w", err) |
| 517 | } |
| 518 | } |
| 519 | res, err := tx.ExecContext(ctx, `INSERT INTO nonces (key_id, nonce, until_unix_ns) VALUES (?, ?, ?) |
| 520 | ON CONFLICT (key_id, nonce) DO NOTHING`, string(id), nonce, untilNs) |
| 521 | if err != nil { |
| 522 | return fmt.Errorf("hostedctl: remember nonce: %w", err) |
| 523 | } |
| 524 | n, err := res.RowsAffected() |
| 525 | if err != nil { |
| 526 | return fmt.Errorf("hostedctl: remember nonce: %w", err) |
| 527 | } |
| 528 | fresh = n == 1 |
| 529 | return nil |
| 530 | }) |
| 531 | if err != nil { |
| 532 | return false, err |
| 533 | } |
| 534 | return fresh, nil |
| 535 | } |
| 536 | |
| 537 | // appendAudit adds one audit row inside tx, so it commits or rolls back with |
| 538 | // the change it records. a must name an action and must not hold |
| 539 | // credentials. |
| 540 | func appendAudit(tx *sql.Tx, a Audit) error { |
| 541 | if a.Action == "" { |
| 542 | return errors.New("hostedctl: audit row needs an action") |
| 543 | } |
| 544 | _, err := tx.Exec(`INSERT INTO audit (actor_key, account_id, task_id, attempt_id, action, reason, at_t) |
| 545 | VALUES (?, ?, ?, ?, ?, ?, ?)`, |
| 546 | string(a.Actor), a.Account, a.Task, a.Attempt, a.Action, a.Reason, int64(a.At)) |
| 547 | if err != nil { |
| 548 | return fmt.Errorf("hostedctl: append audit: %w", err) |
| 549 | } |
| 550 | return nil |
| 551 | } |
| 552 | |