LifeMate — Personal, Family & Learning Companion
fix(auth): reject tokens expiring during database lock waits
Quinn White committed
Oct 15, 2026 at 22:18 UTC
34bc9de5459cae059931d868f99931ad3296908c
2 files changed
+116
-8
backend/src/auth_router.js
+17
-8
@@ -45,8 +45,13 @@ export function createAuthRouter({ pool, jwtSecret, auth, env = process.env,
45
if (!owner.rowCount) return null;
46
const active = await client.query('select 1 from app_user where id=$1 and disabled_at is null for update', [owner.rows[0].user_id]);
47
if (!active.rowCount) return null;
48
- const token = await client.query('select user_id from auth_token where token_digest=$1 and kind=$2 and used_at is null and expires_at>now() for update', [tokenDigest, kind]);
49
- return token.rows[0] ?? null;
48
+ const token = await client.query('select user_id from auth_token where token_digest=$1 and kind=$2 and used_at is null for update', [tokenDigest, kind]);
49
+ if (!token.rowCount) return null;
50
+ // now() is the transaction start, and predicates in FOR UPDATE can be
51
+ // evaluated before a row-lock wait. Check wall time in a NEW statement
52
+ // after both account and token locks have actually been acquired.
53
+ const fresh = await client.query('select 1 from auth_token where token_digest=$1 and kind=$2 and used_at is null and expires_at>clock_timestamp()', [tokenDigest, kind]);
54
+ return fresh.rowCount ? token.rows[0] : null;
55
}
56
57
async function session(client, userId) {
@@ -67,16 +72,16 @@ export function createAuthRouter({ pool, jwtSecret, auth, env = process.env,
72
await client.query('select pg_advisory_xact_lock(hashtextextended($1,0))', [recipientDigest + ':' + purpose]);
73
const recent = await client.query(
74
`select count(*)::int as n,
70
- ceil(extract(epoch from (max(requested_at)+interval '60 seconds'-now()))) as cooldown,
71
- ceil(extract(epoch from (min(requested_at)+interval '1 hour'-now()))) as window_wait
75
+ ceil(extract(epoch from (max(requested_at)+interval '60 seconds'-statement_timestamp()))) as cooldown,
76
+ ceil(extract(epoch from (min(requested_at)+interval '1 hour'-statement_timestamp()))) as window_wait
77
from auth_delivery_attempt where recipient_digest=$1 and purpose=$2
73
- and requested_at>now()-interval '1 hour'`, [recipientDigest, purpose],
78
+ and requested_at>statement_timestamp()-interval '1 hour'`, [recipientDigest, purpose],
79
);
80
const row = recent.rows[0];
81
const wait = row.n >= 3 ? Number(row.window_wait) : Number(row.cooldown);
82
if (wait > 0) return { retryAfter: Math.max(1, wait) };
83
const inserted = await client.query(
79
- 'insert into auth_delivery_attempt(recipient_digest,purpose,user_id) values($1,$2,$3) returning id',
84
+ 'insert into auth_delivery_attempt(recipient_digest,purpose,user_id,requested_at) values($1,$2,$3,clock_timestamp()) returning id',
85
[recipientDigest, purpose, userId],
86
);
87
return { attemptId: inserted.rows[0].id };
@@ -207,8 +212,10 @@ export function createAuthRouter({ pool, jwtSecret, auth, env = process.env,
212
// Account-first locking is shared with password/OTP recovery.
213
const active = await client.query('select 1 from app_user where id=$1 and disabled_at is null for update', [preliminary.rows[0].user_id]);
214
if (!active.rowCount) return null;
210
- const current = await client.query('select id,user_id from auth_session where refresh_digest=$1 and revoked_at is null and expires_at>now() for update', [sha256(String(req.body?.refreshToken ?? ''))]);
215
+ const current = await client.query('select id,user_id from auth_session where refresh_digest=$1 and revoked_at is null for update', [sha256(String(req.body?.refreshToken ?? ''))]);
216
if (!current.rowCount) return null;
217
+ const fresh = await client.query('select 1 from auth_session where id=$1 and revoked_at is null and expires_at>clock_timestamp()', [current.rows[0].id]);
218
+ if (!fresh.rowCount) return null;
219
await client.query('update auth_session set revoked_at=now() where id=$1', [current.rows[0].id]);
220
return session(client, current.rows[0].user_id);
221
});
@@ -313,8 +320,10 @@ export function createAuthRouter({ pool, jwtSecret, auth, env = process.env,
320
user = await client.query('select phone_verified_at from app_user where id=$1 and disabled_at is null for update', [owner.rows[0].user_id]);
321
if (!user.rowCount) return null;
322
}
316
- const challenge = await client.query('select * from auth_phone_challenge where id=$1 and used_at is null and expires_at>now() and attempts<5 for update', [challengeId]);
323
+ const challenge = await client.query('select * from auth_phone_challenge where id=$1 and used_at is null and attempts<5 for update', [challengeId]);
324
if (!challenge.rowCount) return null;
325
+ const fresh = await client.query('select 1 from auth_phone_challenge where id=$1 and used_at is null and attempts<5 and expires_at>clock_timestamp()', [challengeId]);
326
+ if (!fresh.rowCount) return null;
327
const row = challenge.rows[0];
328
await client.query('update auth_phone_challenge set attempts=attempts+1 where id=$1', [challengeId]);
329
const provided = Buffer.from(digest(`otp:${challengeId}:${code}`), 'hex');
backend/tests/auth_post_lock_expiry.test.js
new
+99
@@ -0,0 +1,99 @@
1
+// Only loopback PostgreSQL and synthetic identities; no delivery provider is called.
2
+import test, { after } from 'node:test';
3
+import assert from 'node:assert/strict';
4
+import crypto from 'node:crypto';
5
+import express from 'express';
6
+import pg from 'pg';
7
+import { createAuthRouter } from '../src/auth_router.js';
8
+
9
+const url = new URL(process.env.DATABASE_URL);
10
+assert.ok(['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname));
11
+assert.match(url.pathname, /^\/(?:lifeguide_roles_source_[a-f0-9]{16}|lifemate_ci|lifeguide_\w*test\w*)$/);
12
+const marker = 'auth-expiry-' + crypto.randomUUID();
13
+const pool = new pg.Pool({ connectionString: url.href, application_name: marker });
14
+const secret = 'synthetic-auth-expiry-fixture-not-a-live-key-2026';
15
+const users = [];
16
+const app = express();
17
+app.use(express.json());
18
+app.use('/auth', createAuthRouter({ pool, jwtSecret: secret, env: { NODE_ENV: 'test' },
19
+ auth: (_req, _res, next) => next(),
20
+ emailProvider: { configured: false },
21
+ smsProvider: { configured: true, status: 'TEST_ONLY', async sendOtp() { assert.fail('No SMS should be sent'); } },
22
+}));
23
+const server = app.listen(0, '127.0.0.1');
24
+await new Promise(resolve => server.once('listening', resolve));
25
+const base = 'http://127.0.0.1:' + server.address().port + '/auth';
26
+after(async () => {
27
+ await new Promise(resolve => server.close(resolve));
28
+ await pool.query('delete from app_user where id=any($1::uuid[])', [users]);
29
+ await pool.end();
30
+});
31
+
32
+async function owner() {
33
+ const id = crypto.randomUUID(); users.push(id);
34
+ await pool.query("insert into app_user(id,identity_subject,email_normalized,phone_verified_at) values($1,$2,$3,now())",
35
+ [id, 'synthetic-expiry:' + id, 'expiry-' + id + '@example.test']);
36
+ return id;
37
+}
38
+async function request(path, body) {
39
+ return fetch(base + path, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), signal: AbortSignal.timeout(10000) });
40
+}
41
+async function observedWait() {
42
+ for (let n = 0; n < 250; n++) {
43
+ const r = await pool.query("select 1 from pg_stat_activity where application_name=$1 and wait_event_type='Lock'", [marker]);
44
+ if (r.rowCount) return;
45
+ await new Promise(resolve => setTimeout(resolve, 10));
46
+ }
47
+ assert.fail('Expected an actual PostgreSQL row-lock wait');
48
+}
49
+async function blockedRequest(userId, operation, expire) {
50
+ const blocker = await pool.connect();
51
+ try {
52
+ await blocker.query('begin');
53
+ await blocker.query('select 1 from app_user where id=$1 for update', [userId]);
54
+ const response = operation();
55
+ await observedWait();
56
+ // Expire after the request transaction began, without a timing-sensitive sleep.
57
+ await expire();
58
+ await blocker.query('commit');
59
+ return await response;
60
+ } finally { await blocker.query('rollback'); blocker.release(); }
61
+}
62
+
63
+for (const kind of ['email_verification', 'password_reset']) {
64
+ test(kind + ' expires during an observed account-row wait and cannot be consumed', async () => {
65
+ const userId = await owner(), token = crypto.randomBytes(32).toString('base64url');
66
+ await pool.query("insert into auth_token(user_id,kind,token_digest,expires_at) values($1,$2,$3,now()+interval '1 hour')",
67
+ [userId, kind, crypto.createHash('sha256').update(token).digest('hex')]);
68
+ const response = await blockedRequest(userId,
69
+ () => request(kind === 'email_verification' ? '/verify-email' : '/reset-password', { token, newPassword: 'SyntheticReplacement123!' }),
70
+ () => pool.query("update auth_token set expires_at=clock_timestamp() where user_id=$1", [userId]));
71
+ assert.equal(response.status, 400);
72
+ assert.equal((await response.json()).error, 'invalid_or_expired_token');
73
+ assert.equal((await pool.query('select used_at from auth_token where user_id=$1', [userId])).rows[0].used_at, null);
74
+ });
75
+}
76
+
77
+test('refresh expiry after an observed account-row wait cannot mint a replacement session', async () => {
78
+ const userId = await owner(), raw = crypto.randomBytes(32).toString('base64url');
79
+ await pool.query("insert into auth_session(user_id,refresh_digest,expires_at) values($1,$2,now()+interval '1 hour')",
80
+ [userId, crypto.createHash('sha256').update(raw).digest('hex')]);
81
+ const response = await blockedRequest(userId, () => request('/refresh', { refreshToken: raw }),
82
+ () => pool.query("update auth_session set expires_at=clock_timestamp() where user_id=$1", [userId]));
83
+ assert.equal(response.status, 401);
84
+ const rows = await pool.query('select revoked_at from auth_session where user_id=$1', [userId]);
85
+ assert.equal(rows.rowCount, 1);
86
+ assert.equal(rows.rows[0].revoked_at, null);
87
+});
88
+
89
+test('OTP expiry after an observed account-row wait neither authenticates nor consumes the challenge', async () => {
90
+ const userId = await owner(), id = crypto.randomUUID(), code = '123456';
91
+ const digest = crypto.createHmac('sha256', secret).update(`otp:${id}:${code}`).digest('hex');
92
+ await pool.query("insert into auth_phone_challenge(id,user_id,purpose,code_digest,expires_at) values($1,$2,'login',$3,now()+interval '5 minutes')", [id, userId, digest]);
93
+ const response = await blockedRequest(userId, () => request('/phone/verify-otp', { challengeId: id, code }),
94
+ () => pool.query("update auth_phone_challenge set expires_at=clock_timestamp() where id=$1", [id]));
95
+ assert.equal(response.status, 401);
96
+ const row = (await pool.query('select attempts,used_at from auth_phone_challenge where id=$1', [id])).rows[0];
97
+ assert.equal(row.used_at, null);
98
+ assert.equal(row.attempts, 0);
99
+});