From 04af3fdde53d23ec1fe2bbc0b07b721dea6ca226 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Sat, 7 Nov 2026 04:16:15 +0000 Subject: [PATCH 1/2] fix(graphql-server): decide CORS per routed API and fail strictAuth closed --- .../cors-per-api.integration.test.ts | 138 ++++++++++++++++++ .../__tests__/strict-auth.integration.test.ts | 86 +++++++++++ graphql/server/src/middleware/auth.ts | 9 ++ graphql/server/src/middleware/cors.ts | 75 +++------- graphql/server/src/server.ts | 3 +- packages/errors/src/registry.ts | 6 + 6 files changed, 258 insertions(+), 59 deletions(-) create mode 100644 graphql/server-test/__tests__/cors-per-api.integration.test.ts create mode 100644 graphql/server-test/__tests__/strict-auth.integration.test.ts diff --git a/graphql/server-test/__tests__/cors-per-api.integration.test.ts b/graphql/server-test/__tests__/cors-per-api.integration.test.ts new file mode 100644 index 0000000000..20bb5bc1a9 --- /dev/null +++ b/graphql/server-test/__tests__/cors-per-api.integration.test.ts @@ -0,0 +1,138 @@ +/** + * CORS is decided per resolved API: the routed API's typed + * routing_public.cors_settings origins (exact match) plus the global + * `server.origin` platform fallback. Nothing else gets credentialed CORS. + */ + +import path from 'path'; +import type { PgTestClient } from 'pgsql-test/test-client'; +import type supertest from 'supertest'; + +import { getConnections, seed } from '../src'; + +jest.setTimeout(60000); + +const sharedSeedRoot = path.join(__dirname, '..', '..', '..', '__fixtures__', 'seed'); +const pgpmWorkspace = path.join(sharedSeedRoot, '..', '..'); +const schemas = ['simple-pets-public', 'simple-pets-pets-public']; +const metaSchemas = [ + 'catalog_private', + 'routing_public', + 'apps_public', + 'metaschema_public', + 'metaschema_modules_public' +]; + +const HOST = 'app.test.constructive.io'; +const DATABASE_ID = '80a2eaaf-f77e-4bfe-8506-df929ef1b8d9'; +const APP_API_ID = '6c9997a4-591b-4cb3-9313-4ef45d6f134e'; +const PRIVATE_API_ID = 'e257c53d-6ba6-40de-b679-61b37188a316'; + +const PLATFORM_ORIGIN = 'https://dashboard.platform.test'; +const APP_ORIGIN = 'https://tenant-app.example'; +const PRIVATE_ORIGIN = 'https://tenant-private.example'; + +describe('per-API CORS', () => { + let pg: PgTestClient; + let request: supertest.Agent; + let teardown: () => Promise; + const previousOrigin = process.env.SERVER_ORIGIN; + + const preflight = (origin: string) => + request + .options('/graphql') + .set('Host', HOST) + .set('Origin', origin) + .set('Access-Control-Request-Method', 'POST') + .set('Access-Control-Request-Headers', 'content-type'); + + const post = (origin: string) => + request + .post('/graphql') + .set('Host', HOST) + .set('Origin', origin) + .send({ query: '{ __typename }' }); + + const expectAllowed = (res: supertest.Response, origin: string) => { + expect(res.headers['access-control-allow-origin']).toBe(origin); + expect(res.headers['access-control-allow-credentials']).toBe('true'); + }; + + const expectRefused = (res: supertest.Response) => { + expect(res.headers['access-control-allow-origin']).toBeUndefined(); + expect(res.headers['access-control-allow-credentials']).toBeUndefined(); + }; + + beforeAll(async () => { + process.env.SERVER_ORIGIN = PLATFORM_ORIGIN; + ({ pg, request, teardown } = await getConnections( + { + schemas, + authRole: 'anonymous', + server: { useRouting: true, api: { isPublic: true, metaSchemas } } + }, + [ + seed.pgpm(pgpmWorkspace), + seed.sqlfile([ + path.join(sharedSeedRoot, 'app-schemas', 'simple-pets', 'schema.sql'), + path.join(sharedSeedRoot, 'scoped', 'test-data.sql') + ]) + ] + )); + await pg.query( + `INSERT INTO routing_public.cors_settings (database_id, api_id, allowed_origins) + VALUES ($1, $2, ARRAY[$3]), ($1, $4, ARRAY[$5])`, + [DATABASE_ID, APP_API_ID, APP_ORIGIN, PRIVATE_API_ID, PRIVATE_ORIGIN] + ); + }); + + afterAll(async () => { + if (previousOrigin === undefined) delete process.env.SERVER_ORIGIN; + else process.env.SERVER_ORIGIN = previousOrigin; + await teardown(); + }); + + it('answers a preflight from an origin in the routed API cors_settings', async () => { + const res = await preflight(APP_ORIGIN); + expect(res.status).toBe(200); + expectAllowed(res, APP_ORIGIN); + }); + + it('allows a request from an origin in the routed API cors_settings', async () => { + const res = await post(APP_ORIGIN); + expect(res.status).toBe(200); + expectAllowed(res, APP_ORIGIN); + }); + + it('allows the platform fallback origin', async () => { + expectAllowed(await preflight(PLATFORM_ORIGIN), PLATFORM_ORIGIN); + expectAllowed(await post(PLATFORM_ORIGIN), PLATFORM_ORIGIN); + }); + + it('refuses an origin listed only for another API', async () => { + expectRefused(await preflight(PRIVATE_ORIGIN)); + expectRefused(await post(PRIVATE_ORIGIN)); + }); + + it('refuses origins that only resemble a listed one', async () => { + for (const origin of [ + `${APP_ORIGIN}.evil.test`, + `${APP_ORIGIN}:8443`, + APP_ORIGIN.replace('https://', 'http://'), + APP_ORIGIN.toUpperCase() + ]) { + expectRefused(await preflight(origin)); + expectRefused(await post(origin)); + } + }); + + it('refuses a localhost origin that is not listed', async () => { + expectRefused(await preflight('http://localhost:5173')); + expectRefused(await post('http://localhost:5173')); + }); + + it('refuses an unrelated origin', async () => { + expectRefused(await preflight('https://evil.example')); + expectRefused(await post('https://evil.example')); + }); +}); diff --git a/graphql/server-test/__tests__/strict-auth.integration.test.ts b/graphql/server-test/__tests__/strict-auth.integration.test.ts new file mode 100644 index 0000000000..d2d04a809e --- /dev/null +++ b/graphql/server-test/__tests__/strict-auth.integration.test.ts @@ -0,0 +1,86 @@ +/** + * `server.strictAuth` fails closed: when it is on and the routed API has no + * `authenticate_strict` function, the request is refused instead of running + * without authentication. + */ + +import path from 'path'; +import type { PgTestClient } from 'pgsql-test/test-client'; +import type supertest from 'supertest'; + +import { getConnections, seed } from '../src'; + +jest.setTimeout(60000); + +const sharedSeedRoot = path.join(__dirname, '..', '..', '..', '__fixtures__', 'seed'); +const authSeed = path.join(__dirname, '..', '__fixtures__', 'seed', 'auth-cookie', 'schema.sql'); +const pgpmWorkspace = path.join(sharedSeedRoot, '..', '..'); +const schemas = ['simple-pets-public', 'simple-pets-pets-public']; +const metaSchemas = [ + 'catalog_private', + 'routing_public', + 'apps_public', + 'metaschema_public', + 'metaschema_modules_public' +]; + +const HOST = 'app.test.constructive.io'; +const DATABASE_ID = '80a2eaaf-f77e-4bfe-8506-df929ef1b8d9'; + +describe('strictAuth without an authenticate_strict function', () => { + let request: supertest.Agent; + let teardown: () => Promise; + const previous = process.env.SERVER_STRICT_AUTH; + + beforeAll(async () => { + process.env.SERVER_STRICT_AUTH = 'true'; + let pg: PgTestClient; + ({ pg, request, teardown } = await getConnections( + { + schemas, + authRole: 'anonymous', + server: { useRouting: true, api: { isPublic: true, metaSchemas } } + }, + [ + seed.pgpm(pgpmWorkspace), + seed.sqlfile([ + path.join(sharedSeedRoot, 'app-schemas', 'simple-pets', 'schema.sql'), + path.join(sharedSeedRoot, 'scoped', 'test-data.sql'), + authSeed + ]) + ] + )); + // The auth-cookie seed registers `authenticate` for both slots; drop the strict one. + await pg.query( + `SET session_replication_role TO replica; + UPDATE routing_public.rls_settings SET authenticate_strict_function_id = NULL + WHERE database_id = '${DATABASE_ID}'; + SET session_replication_role TO DEFAULT;` + ); + }); + + afterAll(async () => { + if (previous === undefined) delete process.env.SERVER_STRICT_AUTH; + else process.env.SERVER_STRICT_AUTH = previous; + await teardown(); + }); + + it.each([ + ['anonymous', {}], + ['bearer', { Authorization: 'Bearer some-token' }], + ['cookie', { Cookie: 'constructive_session=some-token' }] + ])('refuses a %s request instead of skipping authentication', async (_kind, headers) => { + const res = await request + .post('/graphql') + .set('Host', HOST) + .set(headers) + .send({ query: '{ __typename }' }); + expect(res.body.data).toBeUndefined(); + expect(res.body.errors).toEqual([ + expect.objectContaining({ + message: expect.stringMatching(/strict authentication/i), + extensions: expect.objectContaining({ code: 'STRICT_AUTH_UNAVAILABLE' }) + }) + ]); + }); +}); diff --git a/graphql/server/src/middleware/auth.ts b/graphql/server/src/middleware/auth.ts index 5a4f8a37a9..921cb867a4 100644 --- a/graphql/server/src/middleware/auth.ts +++ b/graphql/server/src/middleware/auth.ts @@ -63,6 +63,15 @@ export const createAuthenticateMiddleware = ( `privateSchema=${rlsModule?.privateSchema?.schemaName ?? 'none'}` ); + if ( + opts.server?.strictAuth && + !(rlsModule?.authenticateStrict && rlsModule.privateSchema?.schemaName) + ) { + log.error(`[auth] strictAuth is on but API ${api.apiId ?? 'unknown'} has no authenticateStrict; refusing`); + respondWithGraphQLError(res, errors.STRICT_AUTH_UNAVAILABLE()); + return; + } + if (!rlsModule) { log.info('[auth] No RLS module configured, skipping auth'); return next(); diff --git a/graphql/server/src/middleware/cors.ts b/graphql/server/src/middleware/cors.ts index 8bb7cefebb..63e54b8da7 100644 --- a/graphql/server/src/middleware/cors.ts +++ b/graphql/server/src/middleware/cors.ts @@ -1,75 +1,34 @@ import './types'; // for Request type -import { parseUrl } from '@constructive-io/url-domains'; import corsPlugin from 'cors'; import type { Request, RequestHandler } from 'express'; -import type { ApiStructure } from '../types'; - /** - * Unified CORS middleware for Constructive API + * CORS for the routed API. Mount after the `api` middleware: the decision is + * made against `req.api`, the API the request's host resolved to. * - * Feature parity + compatibility: - * - Respects a global fallback origin (e.g. from env/CLI) for quick overrides. - * - Reads per-API CORS origins from typed cors_settings table (via req.api.corsOrigins). - * - Always allows localhost to ease development. + * An origin is allowed, with credentials, when it is exactly: + * - one of the routed API's typed `cors_settings` origins (`req.api.corsOrigins`, + * the API row first and the database default otherwise), or + * - the global fallback origin (`server.origin`), the platform's own origin. + * A fallback of `*` reflects any origin. * - * Usage: - * app.use(cors(fallbackOrigin)); + * Every other origin, localhost included, gets no CORS headers. */ export const cors = (fallbackOrigin?: string): RequestHandler => { - // Use the cors library's dynamic origin function to decide per request - const dynamicOrigin = (origin: string | undefined, callback: (err: Error | null, allow?: boolean | string) => void, req: Request) => { - // 1) Global fallback (fast path) - if (fallbackOrigin && fallbackOrigin.trim().length) { - if (fallbackOrigin.trim() === '*') { - // Reflect whatever Origin the caller sent - return callback(null, true); - } - if (origin && origin.trim() === fallbackOrigin.trim()) { - return callback(null, true); - } - // If a strict fallback origin is provided and does not match, - // continue to per-API checks below (do not immediately deny). - } - - // 2) Per-API allowlist sourced from req.api (if available) - // createApiMiddleware runs before this in server.ts, so req.api should be set - const api = (req as any).api as ApiStructure | undefined; - if (api) { - // Typed cors_settings origins - const typedOrigins = api.corsOrigins || []; - const siteUrls = api.domains || []; - const listOfDomains = [...typedOrigins, ...siteUrls]; - - if (origin && listOfDomains.includes(origin)) { - return callback(null, true); - } - } + const fallback = fallbackOrigin?.trim(); - // 3) Localhost is always allowed - if (origin) { - try { - const parsed = parseUrl(new URL(origin)); - if (parsed.domain === 'localhost') { - return callback(null, true); - } - } catch { - // ignore invalid origin - } - } - - // Default: not allowed - return callback(null, false); + const isAllowed = (origin: string | undefined, req: Request): boolean => { + if (fallback === '*') return true; + if (!origin) return false; + if (origin === fallback) return true; + return req.api?.corsOrigins?.includes(origin) ?? false; }; - // Wrap in the cors plugin with our dynamic origin resolver - const handler: RequestHandler = (req, res, next) => + return (req, res, next) => corsPlugin({ - origin: (reqOrigin, cb) => dynamicOrigin(reqOrigin, cb as any, req), + origin: (origin, callback) => callback(null, isAllowed(origin, req)), credentials: true, - optionsSuccessStatus: 200, + optionsSuccessStatus: 200 })(req, res, next); - - return handler; }; diff --git a/graphql/server/src/server.ts b/graphql/server/src/server.ts index ca935be3d5..1f4adbb20c 100644 --- a/graphql/server/src/server.ts +++ b/graphql/server/src/server.ts @@ -151,12 +151,13 @@ class Server { app.use(poweredBy('constructive')); app.use(cookieParser()); - app.use(cors(fallbackOrigin)); app.use(parseDomains() as RequestHandler); app.use(clientIpMiddleware); app.use(requestIdMiddleware()); app.use(requestLogger); app.use(api); + // CORS is decided against the API the host resolved to (req.api). + app.use(cors(fallbackOrigin)); app.use(authenticate); app.use(createContextMiddleware({ pg: effectiveOpts.pg, diff --git a/packages/errors/src/registry.ts b/packages/errors/src/registry.ts index ce660050c9..1beeb24bea 100644 --- a/packages/errors/src/registry.ts +++ b/packages/errors/src/registry.ts @@ -327,6 +327,12 @@ export const registry = { http: 401, message: 'You must be signed in to do that.' }), + STRICT_AUTH_UNAVAILABLE: defineError({ + code: 'STRICT_AUTH_UNAVAILABLE', + class: 'internal', + http: 503, + message: 'Strict authentication is enabled but this API has no strict authentication function, so the request was refused.' + }), CAPTCHA_REQUIRED: defineError({ code: 'CAPTCHA_REQUIRED', class: 'public', From baf7eb31edcf36d882fb905b50b240a38775cb35 Mon Sep 17 00:00:00 2001 From: Dan Lynch Date: Mon, 9 Nov 2026 04:14:09 +0000 Subject: [PATCH 2/2] fix(graphql-server): keep CORS on routing errors and send strictAuth refusal as 503 --- .../cors-per-api.integration.test.ts | 37 +++++++++++++++++++ .../__tests__/strict-auth.integration.test.ts | 1 + graphql/server/src/middleware/auth.ts | 2 +- graphql/server/src/middleware/cors.ts | 6 ++- graphql/server/src/server.ts | 8 +++- 5 files changed, 49 insertions(+), 5 deletions(-) diff --git a/graphql/server-test/__tests__/cors-per-api.integration.test.ts b/graphql/server-test/__tests__/cors-per-api.integration.test.ts index 20bb5bc1a9..643799fdbe 100644 --- a/graphql/server-test/__tests__/cors-per-api.integration.test.ts +++ b/graphql/server-test/__tests__/cors-per-api.integration.test.ts @@ -131,6 +131,43 @@ describe('per-API CORS', () => { expectRefused(await post('http://localhost:5173')); }); + describe('on a host that resolves to no API', () => { + const UNKNOWN_HOST = 'nothing-here.test.constructive.io'; + + it('answers a preflight from the platform fallback origin', async () => { + const res = await request + .options('/graphql') + .set('Host', UNKNOWN_HOST) + .set('Origin', PLATFORM_ORIGIN) + .set('Access-Control-Request-Method', 'POST') + .set('Access-Control-Request-Headers', 'content-type'); + expect(res.status).toBe(200); + expectAllowed(res, PLATFORM_ORIGIN); + }); + + it('sends the 404 with CORS headers for the platform fallback origin', async () => { + const res = await request + .post('/graphql') + .set('Host', UNKNOWN_HOST) + .set('Origin', PLATFORM_ORIGIN) + .send({ query: '{ __typename }' }); + expect(res.status).toBe(404); + expectAllowed(res, PLATFORM_ORIGIN); + }); + + it('sends the 404 without CORS headers for any other origin', async () => { + for (const origin of [APP_ORIGIN, 'https://evil.example']) { + const res = await request + .post('/graphql') + .set('Host', UNKNOWN_HOST) + .set('Origin', origin) + .send({ query: '{ __typename }' }); + expect(res.status).toBe(404); + expectRefused(res); + } + }); + }); + it('refuses an unrelated origin', async () => { expectRefused(await preflight('https://evil.example')); expectRefused(await post('https://evil.example')); diff --git a/graphql/server-test/__tests__/strict-auth.integration.test.ts b/graphql/server-test/__tests__/strict-auth.integration.test.ts index d2d04a809e..3c0ba5c876 100644 --- a/graphql/server-test/__tests__/strict-auth.integration.test.ts +++ b/graphql/server-test/__tests__/strict-auth.integration.test.ts @@ -75,6 +75,7 @@ describe('strictAuth without an authenticate_strict function', () => { .set('Host', HOST) .set(headers) .send({ query: '{ __typename }' }); + expect(res.status).toBe(503); expect(res.body.data).toBeUndefined(); expect(res.body.errors).toEqual([ expect.objectContaining({ diff --git a/graphql/server/src/middleware/auth.ts b/graphql/server/src/middleware/auth.ts index 921cb867a4..f9c3475bf7 100644 --- a/graphql/server/src/middleware/auth.ts +++ b/graphql/server/src/middleware/auth.ts @@ -68,7 +68,7 @@ export const createAuthenticateMiddleware = ( !(rlsModule?.authenticateStrict && rlsModule.privateSchema?.schemaName) ) { log.error(`[auth] strictAuth is on but API ${api.apiId ?? 'unknown'} has no authenticateStrict; refusing`); - respondWithGraphQLError(res, errors.STRICT_AUTH_UNAVAILABLE()); + respondWithGraphQLError(res, errors.STRICT_AUTH_UNAVAILABLE(), { status: 503 }); return; } diff --git a/graphql/server/src/middleware/cors.ts b/graphql/server/src/middleware/cors.ts index 63e54b8da7..fbc3d0bb42 100644 --- a/graphql/server/src/middleware/cors.ts +++ b/graphql/server/src/middleware/cors.ts @@ -4,8 +4,10 @@ import corsPlugin from 'cors'; import type { Request, RequestHandler } from 'express'; /** - * CORS for the routed API. Mount after the `api` middleware: the decision is - * made against `req.api`, the API the request's host resolved to. + * CORS for the routed API, decided against `req.api`, the API the request's + * host resolved to. Mount it both before and after the `api` middleware: + * before routing `req.api` is unset, so only the fallback origin is allowed, + * which keeps routing 404/500 responses readable for the platform origin. * * An origin is allowed, with credentials, when it is exactly: * - one of the routed API's typed `cors_settings` origins (`req.api.corsOrigins`, diff --git a/graphql/server/src/server.ts b/graphql/server/src/server.ts index 1f4adbb20c..a3cf6bca13 100644 --- a/graphql/server/src/server.ts +++ b/graphql/server/src/server.ts @@ -155,9 +155,13 @@ class Server { app.use(clientIpMiddleware); app.use(requestIdMiddleware()); app.use(requestLogger); + // CORS runs twice. Before routing it can only allow the platform fallback, + // so a 404/500 from `api` still reaches that origin readably. After routing + // it decides against the API the host resolved to (req.api). + const corsForRoutedApi = cors(fallbackOrigin); + app.use(corsForRoutedApi); app.use(api); - // CORS is decided against the API the host resolved to (req.api). - app.use(cors(fallbackOrigin)); + app.use(corsForRoutedApi); app.use(authenticate); app.use(createContextMiddleware({ pg: effectiveOpts.pg,