Skip to content
Merged
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
175 changes: 175 additions & 0 deletions graphql/server-test/__tests__/cors-per-api.integration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,175 @@
/**
* 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<void>;
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'));
});

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'));
});
});
87 changes: 87 additions & 0 deletions graphql/server-test/__tests__/strict-auth.integration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/**
* `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<void>;
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.status).toBe(503);
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' })
})
]);
});
});
9 changes: 9 additions & 0 deletions graphql/server/src/middleware/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(), { status: 503 });
return;
}

if (!rlsModule) {
log.info('[auth] No RLS module configured, skipping auth');
return next();
Expand Down
77 changes: 19 additions & 58 deletions graphql/server/src/middleware/cors.ts
Original file line number Diff line number Diff line change
@@ -1,75 +1,36 @@
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, 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.
*
* 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;
};
7 changes: 6 additions & 1 deletion graphql/server/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,12 +151,17 @@ 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);
// 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);
app.use(corsForRoutedApi);
app.use(authenticate);
app.use(createContextMiddleware({
pg: effectiveOpts.pg,
Expand Down
Loading
Loading