package store import ( "context" "database/sql" ) // Commit the attempt before checking the approval code. A wrong code must not // roll back its attempt counter. The row lock replaces UPDATE ... RETURNING. func (s *Store) consumeCLIAuthAttemptMySQL(ctx context.Context, domain, origin, id, browser string, now int64) (code string, err error) { err = s.groupWrite(ctx, func(ctx context.Context, tx *sql.Tx) error { if e := tx.QueryRowContext(ctx, `SELECT code_hash FROM auth_cli_requests WHERE id=? AND domain_uuid=? AND origin=? AND state='pending' AND browser_hash=? AND attempts<5 AND expires_ms>? FOR UPDATE`, id, domain, origin, hashAuthToken(browser), now).Scan(&code); e != nil { return e } _, e := tx.ExecContext(ctx, `UPDATE auth_cli_requests SET attempts=attempts+1 WHERE id=?`, id) return e }) return } // The caller holds the administrative lock and commits polling/consumption // together with session creation. Failed issuance rolls back consumption. func (s *Store) pollCLIAuthMySQL(ctx context.Context, tx *sql.Tx, domain, origin, device, verifier string, now int64) (id, state, browser string, remember bool, err error) { err = tx.QueryRowContext(ctx, `SELECT id,state,browser_hash,remember FROM auth_cli_requests WHERE device_hash=? AND challenge=? AND domain_uuid=? AND origin=? AND expires_ms>? AND next_poll_ms<=? AND state IN ('pending','approved','denied') FOR UPDATE`, hashAuthToken(device), hashAuthToken(verifier), domain, origin, now, now).Scan(&id, &state, &browser, &remember) if err != nil { return } if state == "approved" { state = "consumed" } _, err = tx.ExecContext(ctx, `UPDATE auth_cli_requests SET next_poll_ms=?,state=? WHERE id=?`, now+5000, state, id) return }