From 5d541cd8e259b0908a9a7e4532ced9573667e4ee Mon Sep 17 00:00:00 2001 From: Juan Fernando Castro Date: Fri, 13 Nov 2026 00:22:42 -0500 Subject: [PATCH] fix(auth): a just-minted read URL or token is found while the replica catches up (#4556) * fix(auth): a just-minted read URL or token is found while the replica catches up * fix(auth): a token's grants aren't cached when it's revoked mid-mint * fix(permissions): a mint succeeds when its grants cannot be read back to cache The grants are already stored at that point, so a failed read-back drops the cache key and the next read fills it. * test(auth): assert the grant list cached at mint; skip the sqlite-copy replica test on postgres * fix(auth): test that a token row is read from the primary only when both replica lookups miss * fix(auth): one-line comments on the replica-then-primary token row lookup * perf(auth): a mint caches the grants it stored without reading them back --------- Co-authored-by: Daniel Salazar --- .../clients/database/DatabaseClient.test.ts | 32 ++++ .../clients/database/DatabaseClient.ts | 28 ++++ .../auth/AuthController.http.test.ts | 99 ++++++++++++- src/backend/services/acl/ACLService.test.ts | 8 +- .../permission/PermissionService.test.ts | 11 +- .../stores/permission/PermissionStore.test.ts | 138 ++++++++++++++++-- .../stores/permission/PermissionStore.ts | 58 +++++--- src/backend/stores/session/SessionStore.js | 22 ++- .../stores/session/SessionStore.test.ts | 55 ++++++- src/backend/testUtil.ts | 55 +++++++ 10 files changed, 452 insertions(+), 54 deletions(-) diff --git a/src/backend/clients/database/DatabaseClient.test.ts b/src/backend/clients/database/DatabaseClient.test.ts index 2294dbd86..4b10f7aee 100644 --- a/src/backend/clients/database/DatabaseClient.test.ts +++ b/src/backend/clients/database/DatabaseClient.test.ts @@ -167,6 +167,38 @@ describe('AbstractDatabaseClient — replica-aware reads', () => { expect(client.reads).toEqual(['SELECT 1']); expect(client.preads).toEqual([]); }); + + describe('tryHardReadAll', () => { + const reads = [{ query: 'SELECT 1' }, { query: 'SELECT 2' }]; + + it('keeps replica rows without reading the primary', async () => { + const client = new FixtureDatabaseClient([{ id: 1 }], [{ id: 2 }]); + expect(await client.tryHardReadAll(reads)).toEqual([ + [{ id: 1 }], + [{ id: 1 }], + ]); + expect(client.preads).toEqual([]); + }); + + it.each([[], new Error('replica unavailable')])( + 'reads every query on the primary when the replica has none', + async (replica) => { + const client = new FixtureDatabaseClient(replica, [{ id: 2 }]); + expect(await client.tryHardReadAll(reads)).toEqual([ + [{ id: 2 }], + [{ id: 2 }], + ]); + expect(client.preads).toEqual(['SELECT 1', 'SELECT 2']); + }, + ); + + it('issues one read per query when there is no replica', async () => { + const client = new FixtureDatabaseClient([], [{ id: 2 }], false); + expect(await client.tryHardReadAll(reads)).toEqual([[], []]); + expect(client.reads).toEqual(['SELECT 1', 'SELECT 2']); + expect(client.preads).toEqual([]); + }); + }); }); describe('AbstractDatabaseClient — SQL generation', () => { diff --git a/src/backend/clients/database/DatabaseClient.ts b/src/backend/clients/database/DatabaseClient.ts index 0ca43f7b5..3aa933906 100644 --- a/src/backend/clients/database/DatabaseClient.ts +++ b/src/backend/clients/database/DatabaseClient.ts @@ -172,6 +172,34 @@ export class AbstractDatabaseClient extends PuterClient { return result.value; } + /** Reads the primary only when every replica read is empty or fails. */ + @Span('db.tryHardReadAll', (reads: unknown[]) => ({ + 'db.batch_size': reads.length, + })) + async tryHardReadAll( + reads: { query: string; params?: unknown[] }[], + ): Promise[][]> { + if (!this.hasReadReplica()) { + return Promise.all( + reads.map(({ query, params = [] }) => this.read(query, params)), + ); + } + const onReplica = await Promise.all( + reads.map(async ({ query, params = [] }) => { + try { + return await this.replicaRead(query, params); + } catch { + // A failed replica read counts as a miss. + return []; + } + }), + ); + if (onReplica.some((rows) => rows.length > 0)) return onReplica; + return Promise.all( + reads.map(({ query, params = [] }) => this.pread(query, params)), + ); + } + /** * Apply the `.sql` files named `*` in each configured migration * directory, in filename order. Files must be idempotent: nothing records diff --git a/src/backend/controllers/auth/AuthController.http.test.ts b/src/backend/controllers/auth/AuthController.http.test.ts index 9f5a247b4..6746cf74c 100644 --- a/src/backend/controllers/auth/AuthController.http.test.ts +++ b/src/backend/controllers/auth/AuthController.http.test.ts @@ -26,6 +26,7 @@ import { FULL_API_ACCESS } from '../../services/permission/consts.js'; import { tokenClaimsDigest } from '../../../gui/src/helpers/guiToken.js'; import { createTestUser, + lagReadReplica, setupPuterTestEnv, type PuterTestEnv, } from '../../testUtil.js'; @@ -351,6 +352,98 @@ describe('revoke-own-access-token over HTTP', () => { expect(await tokenReadStatus(file.uid, readToken)).not.toBe(200); }); + const ACCESS_TOKEN_QUERIES = + /FROM `access_token_permissions`|`access_token_uid` = \?/; + const tokenUidOf = (token: string) => + ( + env.server.services.token.verify('auth', token) as { + token_uid: string; + } + ).token_uid; + + it('serves a read URL fetched right after minting while the replica lags', async () => { + const owner = env.users.user; + const file = await makeFile(owner); + const replica = await lagReadReplica(env.server, ACCESS_TOKEN_QUERIES); + try { + const readToken = await mintReadToken(owner.token, file.uid); + expect(await tokenReadStatus(file.uid, readToken)).toBe(200); + const cached = await env.server.clients.redis.get( + `perms:token:${tokenUidOf(readToken)}`, + ); + expect(cached).toBe(JSON.stringify([`fs:${file.uid}:read`])); + } finally { + replica.catchUp(); + } + }); + + it('mints from a just-created personal API token while the replica lags', async () => { + const owner = env.users.user; + const file = await makeFile(owner); + const replica = await lagReadReplica(env.server, ACCESS_TOKEN_QUERIES); + try { + const pat = await mintPersonalToken(owner); + const readToken = await mintReadToken(pat, file.uid); + expect(await tokenReadStatus(file.uid, readToken)).toBe(200); + } finally { + replica.catchUp(); + } + }); + + it('revokes a just-created token by its uuid while the replica lags', async () => { + const owner = env.users.user; + const file = await makeFile(owner); + const { actor } = await env.server.services.auth.authenticate( + owner.token, + ); + const replica = await lagReadReplica(env.server, ACCESS_TOKEN_QUERIES); + let readToken: string; + try { + readToken = await mintReadToken(owner.token, file.uid); + await env.server.services.auth.revokeAccessToken( + actor!, + tokenUidOf(readToken), + ); + expect(await tokenReadStatus(file.uid, readToken)).not.toBe(200); + } finally { + replica.catchUp(); + } + expect(await tokenReadStatus(file.uid, readToken)).not.toBe(200); + expect(await whoamiStatus(readToken)).toBe(401); + }); + + it('keeps a revoked token dead while the replica still shows it live', async ({ + skip, + }) => { + // The frozen replica is a sqlite copy. + skip(process.env.PUTER_TEST_DB_ENGINE?.toLowerCase() === 'postgres'); + const owner = env.users.user; + const file = await makeFile(owner); + const { actor } = await env.server.services.auth.authenticate( + owner.token, + ); + const readToken = await mintReadToken(owner.token, file.uid); + const tokenUid = tokenUidOf(readToken); + const replica = await lagReadReplica(env.server, ACCESS_TOKEN_QUERIES, { + mode: 'frozen', + }); + try { + await env.server.services.auth.revokeAccessToken(actor!, tokenUid); + expect(await tokenReadStatus(file.uid, readToken)).not.toBe(200); + expect( + await env.server.stores.permission.listAccessTokenPerms( + tokenUid, + ), + ).toEqual([]); + expect( + await env.server.clients.redis.get(`perms:token:${tokenUid}`), + ).toBeNull(); + } finally { + replica.catchUp(); + } + expect(await whoamiStatus(readToken)).toBe(401); + }); + // These three run last in the file's shared `env.users.user`: each one // revokes a session belonging to `owner.token` / `owner.workerToken`, so // later tests can't rely on those credentials still being live. @@ -394,7 +487,10 @@ describe('revoke-own-access-token over HTTP', () => { it('a revoked GUI session still gets a reauth_token', async () => { const owner = env.users.user; - const decoded = env.server.services.token.verify('auth', owner.token) as { + const decoded = env.server.services.token.verify( + 'auth', + owner.token, + ) as { session_uid: string; }; await env.server.stores.session.removeByUuid(decoded.session_uid); @@ -560,7 +656,6 @@ describe('2FA enrollment over HTTP', () => { expect(enabled.status).toBe(200); expect((await otpState(account.userId)).enabled).toBe(true); }); - }); /** diff --git a/src/backend/services/acl/ACLService.test.ts b/src/backend/services/acl/ACLService.test.ts index 7a720648a..47237f5b8 100644 --- a/src/backend/services/acl/ACLService.test.ts +++ b/src/backend/services/acl/ACLService.test.ts @@ -1308,16 +1308,16 @@ describe('ACLService.statUserUser / setUserUser (integration)', () => { [tokenUid, top], ); - const get = vi.spyOn(server.clients.redis, 'get'); + const list = vi.spyOn(server.stores.permission, 'listAccessTokenPerms'); try { expect(await acl.check(token, deep, 'read')).toBe(true); expect(await acl.check(token, deep, 'write')).toBe(false); - const tokenReads = get.mock.calls.filter( - ([key]) => key === `perms:token:${tokenUid}`, + const tokenReads = list.mock.calls.filter( + ([uid]) => uid === tokenUid, ); expect(tokenReads).toHaveLength(2); } finally { - get.mockRestore(); + list.mockRestore(); } }); diff --git a/src/backend/services/permission/PermissionService.test.ts b/src/backend/services/permission/PermissionService.test.ts index aa392e144..9f2311dcb 100644 --- a/src/backend/services/permission/PermissionService.test.ts +++ b/src/backend/services/permission/PermissionService.test.ts @@ -2250,7 +2250,10 @@ describe('PermissionService — scan paths', () => { [tokenUid, permission, '{}'], ); - const get = vi.spyOn(server.clients.redis, 'get'); + const list = vi.spyOn( + server.stores.permission, + 'listAccessTokenPerms', + ); try { expect( await permService.check( @@ -2264,12 +2267,10 @@ describe('PermissionService — scan paths', () => { ), ).toBe(true); expect( - get.mock.calls.filter( - ([key]) => key === `perms:token:${tokenUid}`, - ), + list.mock.calls.filter(([uid]) => uid === tokenUid), ).toHaveLength(1); } finally { - get.mockRestore(); + list.mockRestore(); } }); diff --git a/src/backend/stores/permission/PermissionStore.test.ts b/src/backend/stores/permission/PermissionStore.test.ts index 177dbc30c..50ee0d681 100644 --- a/src/backend/stores/permission/PermissionStore.test.ts +++ b/src/backend/stores/permission/PermissionStore.test.ts @@ -23,7 +23,7 @@ import { v4 as uuidv4 } from 'uuid'; import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { PuterServer } from '../../server.ts'; import { PermissionUtil } from '../../services/permission/permissionUtil.ts'; -import { setupTestServer } from '../../testUtil.ts'; +import { lagReadReplica, setupTestServer } from '../../testUtil.ts'; import { decodeCursor } from '../../util/pagination.ts'; import { CACHE_TOMBSTONE_SUFFIX } from '../types.ts'; import { @@ -1433,7 +1433,7 @@ describe('PermissionStore', () => { // -- access token permissions -------------------------------------- describe('access token permissions', () => { - it('serves the grants cached, and every write through the store invalidates them', async () => { + it('serves the grants cached until the store deletes them', async () => { const tokenUid = `tok-${uuidv4()}`; const authorizer = { userId: null, appId: null }; await store.insertAccessTokenPerms(tokenUid, authorizer, [ @@ -1443,8 +1443,7 @@ describe('PermissionStore', () => { 'driver:kv', ]); - // A row written behind the store is invisible until a store - // write lands. + // A row written behind the store is invisible while the list is cached. await server.clients.db.write( 'INSERT INTO `access_token_permissions` (`token_uid`, `permission`) VALUES (?, ?)', [tokenUid, 'driver:fs'], @@ -1453,13 +1452,6 @@ describe('PermissionStore', () => { 'driver:kv', ]); - await store.insertAccessTokenPerms(tokenUid, authorizer, [ - { permission: 'driver:ai', extra: { note: 1 } }, - ]); - expect((await store.listAccessTokenPerms(tokenUid)).sort()).toEqual( - ['driver:ai', 'driver:fs', 'driver:kv'], - ); - await store.deleteAccessTokenPerms(tokenUid); expect(await store.listAccessTokenPerms(tokenUid)).toEqual([]); }); @@ -1516,6 +1508,130 @@ describe('PermissionStore', () => { ).toBe(false); expect(await store.hasAnyAccessTokenPerm(tokenUid, [])).toBe(false); }); + + const TOKEN_PERM_QUERIES = /FROM `access_token_permissions`/; + const cachedTokenPerms = (tokenUid: string) => + server.clients.redis.get(`perms:token:${tokenUid}`); + + it("finds a new token's grants while the replica lags, and caches no empty list", async () => { + const tokenUid = `tok-${uuidv4()}`; + const replica = await lagReadReplica(server, TOKEN_PERM_QUERIES); + try { + await store.insertAccessTokenPerms( + tokenUid, + { userId: 7, appId: null }, + [{ permission: 'fs:abc:read' }], + ); + expect(await store.listAccessTokenPerms(tokenUid)).toEqual([ + 'fs:abc:read', + ]); + + await server.clients.redis.del(`perms:token:${tokenUid}`); + expect(await store.listAccessTokenPerms(tokenUid)).toEqual([ + 'fs:abc:read', + ]); + await vi.waitFor(async () => + expect(await cachedTokenPerms(tokenUid)).toBe( + '["fs:abc:read"]', + ), + ); + expect(await store.getAccessTokenAuthorizerId(tokenUid)).toBe( + 7, + ); + } finally { + replica.catchUp(); + } + }); + + it('reads the primary only when the replica has no rows', async () => { + const tokenUid = `tok-${uuidv4()}`; + await store.insertAccessTokenPerms( + tokenUid, + { userId: 7, appId: null }, + [{ permission: 'fs:abc:read' }], + ); + await server.clients.redis.del(`perms:token:${tokenUid}`); + + const current = await lagReadReplica(server, TOKEN_PERM_QUERIES, { + mode: 'current', + }); + try { + expect(await store.listAccessTokenPerms(tokenUid)).toEqual([ + 'fs:abc:read', + ]); + expect(await store.getAccessTokenAuthorizerId(tokenUid)).toBe( + 7, + ); + expect(current.primaryReads()).toBe(0); + } finally { + current.catchUp(); + } + + const lagging = await lagReadReplica(server, TOKEN_PERM_QUERIES); + try { + expect(await store.getAccessTokenAuthorizerId(tokenUid)).toBe( + 7, + ); + expect(lagging.primaryReads()).toBe(1); + } finally { + lagging.catchUp(); + } + }); + + it('caches the grants it stores without reading them back', async () => { + const scoped = `tok-${uuidv4()}`; + const unscoped = `tok-${uuidv4()}`; + const pread = vi.spyOn(server.clients.db, 'pread'); + try { + await store.insertAccessTokenPerms( + scoped, + { userId: 7, appId: null }, + [ + { permission: 'fs:abc:read' }, + { permission: 'fs:def:read' }, + ], + ); + // A token with no stored grants, as a full-access one is. + await store.insertAccessTokenPerms( + unscoped, + { userId: 7, appId: null }, + [], + ); + expect(pread).not.toHaveBeenCalled(); + } finally { + pread.mockRestore(); + } + expect(await cachedTokenPerms(scoped)).toBe( + '["fs:abc:read","fs:def:read"]', + ); + expect(await cachedTokenPerms(unscoped)).toBe('[]'); + }); + + it('caches nothing when the token is deleted while its grants are being cached', async () => { + const tokenUid = `tok-${uuidv4()}`; + const db = server.clients.db; + const write = db.write.bind(db); + // The delete lands after the grants are stored, before they're cached. + const stored = vi + .spyOn(db, 'write') + .mockImplementationOnce(async (sql, params) => { + const result = await write(sql, params); + stored.mockRestore(); + await store.deleteAccessTokenPerms(tokenUid); + return result; + }); + try { + await store.insertAccessTokenPerms( + tokenUid, + { userId: 7, appId: null }, + [{ permission: 'fs:abc:read' }], + ); + } finally { + stored.mockRestore(); + } + expect(await cachedTokenPerms(tokenUid)).toBeNull(); + expect(await store.listAccessTokenPerms(tokenUid)).toEqual([]); + }); }); // -- cache generation + scan/check caches ---------------------------- diff --git a/src/backend/stores/permission/PermissionStore.ts b/src/backend/stores/permission/PermissionStore.ts index d648c9c26..485cc96e9 100644 --- a/src/backend/stores/permission/PermissionStore.ts +++ b/src/backend/stores/permission/PermissionStore.ts @@ -1617,25 +1617,31 @@ export class PermissionStore extends PuterStore { /** The token's whole grant list, so a check reads it once. */ async listAccessTokenPerms(tokenUid: string): Promise { const cacheKey = this.#tokenCacheKey(tokenUid); - try { - const raw = await this.clients.redis.get(cacheKey); - if (raw) { + const { tombstoned, raw } = await this.readCacheUnlessDeleted(cacheKey); + if (raw) { + try { const parsed = JSON.parse(raw); if (Array.isArray(parsed)) return parsed; + } catch { + // Fall through to DB. } - } catch { - // Fall through to DB. } - const rows = await this.clients.db.read( - 'SELECT `permission` FROM `access_token_permissions` WHERE `token_uid` = ?', - [tokenUid], - ); + // A replica can lag a mint (rows missing) or a revoke (rows still there). + const sql = + 'SELECT `permission` FROM `access_token_permissions` WHERE `token_uid` = ?'; + const rows = tombstoned + ? await this.clients.db.pread(sql, [tokenUid]) + : await this.clients.db.tryHardRead(sql, [tokenUid], { + race: false, + }); const perms = rows.map((r) => String(r.permission)); - this.clients.redis - .set(cacheKey, JSON.stringify(perms), 'EX', TOKEN_CACHE_TTL_SECONDS) - .catch(() => {}); + if (!tombstoned) { + void this.writeCacheUnlessDeleted([cacheKey], () => + this.#cacheAccessTokenPerms(tokenUid, perms, false), + ).catch(() => {}); + } return perms; } @@ -1648,7 +1654,10 @@ export class PermissionStore extends PuterStore { return permissions.some((permission) => all.includes(permission)); } - /** Record a new token's grants, chunked multi-row inserts. */ + /** + * Record a new token's grants, once per token, in chunked multi-row + * inserts. + */ async insertAccessTokenPerms( tokenUid: string, authorizer: { userId: number | null; appId: number | null }, @@ -1678,7 +1687,13 @@ export class PermissionStore extends PuterStore { ]), ); } - await this.#invalidateAccessTokenPerms(tokenUid); + // Seeded with what was just stored, so a check right after the mint + // finds it without a read. + const perms = grants.map(({ permission }) => permission); + await this.writeCacheUnlessDeleted( + [this.#tokenCacheKey(tokenUid)], + () => this.#cacheAccessTokenPerms(tokenUid, perms, true), + ); } /** Drop a token's grant manifest. */ @@ -1687,7 +1702,7 @@ export class PermissionStore extends PuterStore { 'DELETE FROM `access_token_permissions` WHERE `token_uid` = ?', [tokenUid], ); - await this.#invalidateAccessTokenPerms(tokenUid); + await this.tombstoneCacheKeys([this.#tokenCacheKey(tokenUid)]); } /** @@ -1695,17 +1710,24 @@ export class PermissionStore extends PuterStore { * none, which every full-access token is. */ async getAccessTokenAuthorizerId(tokenUid: string): Promise { - const rows = (await this.clients.db.read( + const rows = (await this.clients.db.tryHardRead( 'SELECT `authorizer_user_id` FROM `access_token_permissions` WHERE `token_uid` = ? LIMIT 1', [tokenUid], + { race: false }, )) as Array<{ authorizer_user_id?: number | null }>; return rows[0]?.authorizer_user_id ?? null; } - async #invalidateAccessTokenPerms(tokenUid: string): Promise { + async #cacheAccessTokenPerms( + tokenUid: string, + perms: string[], + broadcast: boolean, + ): Promise { await this.publishCacheKeys({ keys: [this.#tokenCacheKey(tokenUid)], - broadcast: true, + serializedData: JSON.stringify(perms), + ttlSeconds: TOKEN_CACHE_TTL_SECONDS, + broadcast, }); } diff --git a/src/backend/stores/session/SessionStore.js b/src/backend/stores/session/SessionStore.js index 13a9b2795..908030825 100644 --- a/src/backend/stores/session/SessionStore.js +++ b/src/backend/stores/session/SessionStore.js @@ -665,19 +665,15 @@ export class SessionStore extends PuterStore { mysql: 'legacy_token_unique_key', otherwise: 'legacy_token_uid', }); - const findBy = async (column) => { - const rows = await this.clients.db.read( - `SELECT * FROM \`sessions\` WHERE \`kind\` = 'access_token' AND \`${column}\` = ? AND \`revoked_at\` IS NULL AND (\`expires_at\` IS NULL OR \`expires_at\` > ?) ORDER BY \`id\` DESC LIMIT 1`, - [tokenUid, nowSeconds()], - ); - return this.#normalizeRow(rows[0]); - }; - // Sent together, so a miss on the first costs no second round trip. - const [own, legacy] = await Promise.all([ - findBy('access_token_uid'), - findBy(legacyColumn), - ]); - return own ?? legacy; + const now = nowSeconds(); + // A token minted moments ago is found while the replica catches up. + const [own, legacy] = await this.clients.db.tryHardReadAll( + ['access_token_uid', legacyColumn].map((column) => ({ + query: `SELECT * FROM \`sessions\` WHERE \`kind\` = 'access_token' AND \`${column}\` = ? AND \`revoked_at\` IS NULL AND (\`expires_at\` IS NULL OR \`expires_at\` > ?) ORDER BY \`id\` DESC LIMIT 1`, + params: [tokenUid, now], + })), + ); + return this.#normalizeRow(own[0]) ?? this.#normalizeRow(legacy[0]); } /** diff --git a/src/backend/stores/session/SessionStore.test.ts b/src/backend/stores/session/SessionStore.test.ts index c06f590b4..6a5a7fb6a 100644 --- a/src/backend/stores/session/SessionStore.test.ts +++ b/src/backend/stores/session/SessionStore.test.ts @@ -19,7 +19,7 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'; import { v4 as uuidv4 } from 'uuid'; -import { setupTestServer } from '../../testUtil.ts'; +import { lagReadReplica, setupTestServer } from '../../testUtil.ts'; import { PuterServer } from '../../server.ts'; import { APP_WINDOW_SECONDS, @@ -840,6 +840,59 @@ describe('SessionStore', () => { await target.findActiveByAccessTokenUid(tokenUid), ).toBeNull(); }); + + const TOKEN_UID_QUERIES = + /`(access_token_uid|legacy_token_uid|legacy_token_unique_key)` = \?/; + const byColumn = [ + ['access_token_uid', {}], + ['legacy_token_uid', { created_via: 'legacy_backfill' }], + ] as const; + + it.each(byColumn)( + 'finds a row just written under %s while the replica lags', + async (column, extra) => { + const user = await makeUser(); + const tokenUid = uuidv4(); + const row = await tokenRow(user.id, { + [column]: tokenUid, + ...extra, + }); + const replica = await lagReadReplica(server, TOKEN_UID_QUERIES); + try { + const found = + await target.findActiveByAccessTokenUid(tokenUid); + expect(found?.uuid).toBe(row.uuid); + expect(replica.primaryReads()).toBe(2); + } finally { + replica.catchUp(); + } + }, + ); + + it.each(byColumn)( + 'skips the primary when the replica has the row under %s', + async (column, extra) => { + const user = await makeUser(); + const tokenUid = uuidv4(); + const row = await tokenRow(user.id, { + [column]: tokenUid, + ...extra, + }); + const replica = await lagReadReplica( + server, + TOKEN_UID_QUERIES, + { mode: 'current' }, + ); + try { + const found = + await target.findActiveByAccessTokenUid(tokenUid); + expect(found?.uuid).toBe(row.uuid); + expect(replica.primaryReads()).toBe(0); + } finally { + replica.catchUp(); + } + }, + ); }); describe('getOrCreateGodmodeToken', () => { diff --git a/src/backend/testUtil.ts b/src/backend/testUtil.ts index da871a2cb..40cc54f83 100644 --- a/src/backend/testUtil.ts +++ b/src/backend/testUtil.ts @@ -1,6 +1,9 @@ import bcrypt from 'bcrypt'; +import { mkdtempSync, rmSync } from 'node:fs'; import { createServer } from 'node:net'; import type { AddressInfo } from 'node:net'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { v4 as uuidv4 } from 'uuid'; import { deepMerge } from '../../tools/lib/configMigration.mjs'; @@ -14,6 +17,7 @@ import { PostgresDatabaseClient, type PostgresPool, } from './clients/database/PostgresDatabaseClient'; +import { SqliteDatabaseClient } from './clients/database/SqliteDatabaseClient'; import type { PoolConfig } from 'pg'; import { ADMIN_GROUP_UID } from './services/selfhosted/DefaultUserService'; import { FULL_API_ACCESS } from './services/permission/consts'; @@ -470,3 +474,54 @@ export const inRequestScope = (controller: T): T => ); }, }); + +/** Adds a replica that, for `queries`, is empty, a copy from now, or current. */ +export const lagReadReplica = async ( + server: PuterServer, + queries: RegExp, + { mode = 'missing' }: { mode?: 'missing' | 'frozen' | 'current' } = {}, +) => { + type Read = (sql: string, params?: unknown[]) => Promise; + const db = server.clients.db as unknown as Record & { + read: Read; + }; + let frozen: SqliteDatabaseClient | null = null; + let frozenDir: string | null = null; + if (mode === 'frozen') { + frozenDir = mkdtempSync(join(tmpdir(), 'puter-replica-')); + const path = join(frozenDir, 'replica.sqlite'); + await server.clients.db.write('VACUUM INTO ?', [path]); + frozen = new SqliteDatabaseClient({ + port: 0, + extensions: [], + database: { engine: 'sqlite', path }, + } as IConfig); + await frozen.onServerStart(); + } + + const names = ['read', 'pread', 'hasReadReplica']; + const own = names.map((name) => Object.getOwnPropertyDescriptor(db, name)); + const read = db.read.bind(db); + let primaryReads = 0; + db.hasReadReplica = () => true; + db.read = async (sql: string, params: unknown[] = []) => { + if (mode === 'current' || !queries.test(sql)) return read(sql, params); + return frozen ? frozen.read(sql, params) : []; + }; + db.pread = async (sql: string, params: unknown[] = []) => { + if (queries.test(sql)) primaryReads++; + return read(sql, params); + }; + return { + primaryReads: () => primaryReads, + catchUp: () => { + names.forEach((name, i) => { + const descriptor = own[i]; + if (descriptor) Object.defineProperty(db, name, descriptor); + else delete db[name]; + }); + frozen?.onServerShutdown(); + if (frozenDir) rmSync(frozenDir, { recursive: true, force: true }); + }, + }; +};