From 368666df4fd943d68afed293df6edaf303fc874a Mon Sep 17 00:00:00 2001 From: yyyyaaa Date: Tue, 17 Nov 2026 23:44:45 +0700 Subject: [PATCH] fix(graphql-server): a flush makes rebuilt hosts read their settings again A host's API structure carries settings the loaders resolved: CORS origins, auth, RLS, database, pubkey and WebAuthn settings. Each loader keeps its own cache (5 minutes for CORS, 1 minute for the others), and flushService only evicted the host. A host rebuilt within that time took the loaders' old copy and kept it for as long as the host stays cached. So a database whose CORS list gained an origin kept refusing it on every host read in the 5 minutes before the write, even after a schema:update: a new app's deployed site could not sign up through its auth host (constructive-planning#2539). flushService, flushAllServices and the authenticated /flush now clear the settings loaders for the database (or for all) before they evict its hosts. --- .../src/middleware/__tests__/flush.test.ts | 54 ++++++++++++++++++- graphql/server/src/middleware/api.ts | 11 ++++ graphql/server/src/middleware/flush.ts | 12 ++++- 3 files changed, 74 insertions(+), 3 deletions(-) diff --git a/graphql/server/src/middleware/__tests__/flush.test.ts b/graphql/server/src/middleware/__tests__/flush.test.ts index 8186949917..a20436a2b6 100644 --- a/graphql/server/src/middleware/__tests__/flush.test.ts +++ b/graphql/server/src/middleware/__tests__/flush.test.ts @@ -1,3 +1,4 @@ +import { corsLoader } from '@constructive-io/express-context'; import { ConstructiveOptions } from '@constructive-io/graphql-types'; import { svcCache } from '@pgpmjs/server-utils'; import { EventEmitter } from 'events'; @@ -11,7 +12,7 @@ import { import type { PoolClient } from 'pg'; import { Server } from '../../server'; -import { createFlushMiddleware } from '../flush'; +import { createFlushMiddleware, flushAllServices } from '../flush'; const mockRoutingQuery = jest.fn(); jest.mock('pg-cache', () => ({ @@ -214,6 +215,57 @@ describe('createFlushMiddleware', () => { } ); + // A host evicted by a flush is rebuilt from the settings loaders. If their + // cached copy survived the flush, the rebuilt host would keep the old CORS + // list for as long as it stays cached (constructive-planning#2539). + it.each(['notification', 'authenticated HTTP', 'listener reconnect'])( + 'makes the next host build read the CORS origins again through the %s flush path', + async (path) => { + let origins = ['https://preview.example.com']; + const routingPool = { query: jest.fn(async () => ({ rows: [{ allowed_origins: origins }] })) }; + const otherPool = { query: jest.fn(async () => ({ rows: [{ allowed_origins: ['https://other.example.com'] }] })) }; + const ctx = (databaseId: string, pool: typeof routingPool) => + ({ routingPool: pool, tenantPool: pool, databaseId, apiId: 'auth-api' }) as any; + corsLoader.invalidate(); + await corsLoader.resolve(ctx(DATABASE_ID, routingPool)); + await corsLoader.resolve(ctx('other-database', otherPool)); + origins = ['https://preview.example.com', 'https://site.example.com']; + + if (path === 'notification') { + const server = Object.create(Server.prototype) as Server; + Object.assign(server, { opts: { api: { isPublic: true } } }); + await server.flush(DATABASE_ID); + } else if (path === 'authenticated HTTP') { + await createFlushMiddleware(opts(TOKEN))( + makeReq('/flush', `Bearer ${TOKEN}`), + makeRes(), + next + ); + } else { + flushAllServices(); + } + + expect(await corsLoader.resolve(ctx(DATABASE_ID, routingPool))).toEqual(origins); + expect(routingPool.query).toHaveBeenCalledTimes(2); + await corsLoader.resolve(ctx('other-database', otherPool)); + expect(otherPool.query).toHaveBeenCalledTimes(path === 'listener reconnect' ? 2 : 1); + } + ); + + it('does not let an unauthenticated flush invalidate the settings loaders', async () => { + const routingPool = { query: jest.fn(async () => ({ rows: [{ allowed_origins: ['https://preview.example.com'] }] })) }; + const ctx = { routingPool, tenantPool: routingPool, databaseId: DATABASE_ID, apiId: 'auth-api' } as any; + corsLoader.invalidate(); + await corsLoader.resolve(ctx); + await createFlushMiddleware(opts(TOKEN))( + makeReq('/flush', 'Bearer wrong'), + makeRes(), + next + ); + await corsLoader.resolve(ctx); + expect(routingPool.query).toHaveBeenCalledTimes(1); + }); + it('does not let an unauthenticated flush invalidate storage discovery', async () => { const client = { query: jest.fn(async () => ({ diff --git a/graphql/server/src/middleware/api.ts b/graphql/server/src/middleware/api.ts index 7d7d3dc781..e186bfbc24 100644 --- a/graphql/server/src/middleware/api.ts +++ b/graphql/server/src/middleware/api.ts @@ -26,6 +26,17 @@ const log = new Logger('api'); const defaultRegistry: LoaderRegistry = createDefaultRegistry(); +/** + * Drop the settings a host is built from (CORS origins, auth, RLS, database, + * pubkey and WebAuthn settings) for one database, or for all. Each loader + * keeps its own short-lived cache, so a host evicted by a flush and rebuilt + * within that time would otherwise take the old settings again, and keep them + * for as long as the host stays cached. + */ +export const invalidateApiSettings = (databaseId?: string): void => { + defaultRegistry.invalidate(databaseId); +}; + // ============================================================================= // SQL Queries (API resolution only — module queries now live in loaders) // ============================================================================= diff --git a/graphql/server/src/middleware/flush.ts b/graphql/server/src/middleware/flush.ts index e0c9597e72..cce169b153 100644 --- a/graphql/server/src/middleware/flush.ts +++ b/graphql/server/src/middleware/flush.ts @@ -9,6 +9,7 @@ import { graphileCache } from 'graphile-cache'; import { clearStorageModuleCache } from 'graphile-presigned-url-plugin'; import { getPgPool } from 'pg-cache'; +import { invalidateApiSettings } from './api'; import { evictAllServiceKeys, evictServiceKey } from './cache-generation'; @@ -64,7 +65,10 @@ export const createFlushMiddleware = ( } const databaseId = req.databaseId ?? req.api?.databaseId; - if (databaseId) clearStorageModuleCache(databaseId); + if (databaseId) { + clearStorageModuleCache(databaseId); + invalidateApiSettings(databaseId); + } evictServiceKey((req as any).svc_key); res.status(200).send('OK'); }; @@ -74,6 +78,7 @@ export const createFlushMiddleware = ( // every service, including hosts deleted while the listener was unavailable. export const flushAllServices = (): void => { clearStorageModuleCache(); + invalidateApiSettings(); evictAllServiceKeys(); }; @@ -82,8 +87,11 @@ export const flushService = async ( databaseId: string ): Promise => { // Do this before the routing lookup: an empty/removed domain must not leave - // module discovery alive after its schema has changed. + // module discovery alive after its schema has changed. The settings go + // before the hosts too, so a host rebuilt after its eviction reads them + // again instead of taking the loaders' cached copy. clearStorageModuleCache(databaseId); + invalidateApiSettings(databaseId); const pgPool = getPgPool(opts.pg); log.info('flushing db ' + databaseId);