Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 53 additions & 1 deletion graphql/server/src/middleware/__tests__/flush.test.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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', () => ({
Expand Down Expand Up @@ -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 () => ({
Expand Down
11 changes: 11 additions & 0 deletions graphql/server/src/middleware/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)
// =============================================================================
Expand Down
12 changes: 10 additions & 2 deletions graphql/server/src/middleware/flush.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';


Expand Down Expand Up @@ -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');
};
Expand All @@ -74,6 +78,7 @@ export const createFlushMiddleware = (
// every service, including hosts deleted while the listener was unavailable.
export const flushAllServices = (): void => {
clearStorageModuleCache();
invalidateApiSettings();
evictAllServiceKeys();
};

Expand All @@ -82,8 +87,11 @@ export const flushService = async (
databaseId: string
): Promise<void> => {
// 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);

Expand Down
Loading