-
Notifications
You must be signed in to change notification settings - Fork 0
Enforce env-driven CORS origin allow-list on /graphql, /graphql/stream, and /export #25
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
24d224c
Initial plan
Copilot 93e3653
Enforce env-driven CORS origin allow-list
Copilot 17fbce8
test: add integration coverage for CORS on production mounts
Copilot 174cd29
test: avoid dangling SSE stream in CORS integration test
Copilot 640175b
test: simplify CORS integration test cleanup to a single abort mechanism
Copilot 8503d5c
test: guarantee CORS integration test cleanup with try/finally and as…
Copilot 57a7d25
test: simplify CORS integration test and cover requests without an Or…
Copilot File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,33 @@ | ||
| /** | ||
| * Environment-driven CORS configuration. | ||
| * | ||
| * `CORS_ALLOWED_ORIGINS` holds a comma-separated allow-list of origins that may | ||
| * read responses cross-origin (e.g. `https://app.example.com,https://admin.example.com`). | ||
| * Anything outside the list gets no `Access-Control-Allow-Origin` header, so the | ||
| * browser blocks the response; the wildcard `*` is never emitted. | ||
| */ | ||
| export function parseAllowedOrigins(value) { | ||
| return String(value ?? '') | ||
| .split(',') | ||
| .map((origin) => origin.trim()) | ||
| .filter(Boolean); | ||
| } | ||
|
|
||
| /** Builds the options object passed to the `cors()` middleware. */ | ||
| export function loadCorsOptions(env = process.env) { | ||
| const allowedOrigins = parseAllowedOrigins(env.CORS_ALLOWED_ORIGINS); | ||
|
|
||
| return { | ||
| // Requests without an `Origin` header (curl, server-to-server, same-origin | ||
| // navigations) are not subject to CORS, so they pass through unchanged and | ||
| // simply receive no CORS headers. | ||
| origin(origin, callback) { | ||
| if (!origin || allowedOrigins.includes(origin)) { | ||
| callback(null, origin ? [origin] : false); | ||
| return; | ||
| } | ||
| callback(null, false); | ||
| }, | ||
| credentials: true, | ||
| }; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,157 @@ | ||
| import assert from 'node:assert/strict'; | ||
| import { describe, it } from 'node:test'; | ||
|
|
||
| import { expressMiddleware } from '@as-integrations/express4'; | ||
| import cors from 'cors'; | ||
| import express from 'express'; | ||
|
|
||
| import { loadCorsOptions, parseAllowedOrigins } from '../src/config/cors.js'; | ||
| import { createStore } from '../src/data/store.js'; | ||
| import { createExportRouter } from '../src/export/router.js'; | ||
| import { createSchema } from '../src/schema.js'; | ||
| import { createFinanceService } from '../src/services/financeService.js'; | ||
| import { createApolloServer } from '../src/server.js'; | ||
| import { createPubSub } from '../src/streaming/pubsub.js'; | ||
| import { createStreamRouter } from '../src/streaming/sseRouter.js'; | ||
|
|
||
| /** Starts a throwaway app guarded by the allow-list CORS middleware. */ | ||
| async function withServer(env, run) { | ||
| const app = express(); | ||
| app.use(cors(loadCorsOptions(env))); | ||
| app.get('/probe', (_req, res) => res.json({ ok: true })); | ||
|
|
||
| const server = await new Promise((resolve) => { | ||
| const listener = app.listen(0, () => resolve(listener)); | ||
| }); | ||
| const { port } = server.address(); | ||
| try { | ||
| await run(`http://127.0.0.1:${port}/probe`); | ||
| } finally { | ||
| await new Promise((resolve) => server.close(resolve)); | ||
| } | ||
| } | ||
|
|
||
| /** Starts the actual /export, /graphql/stream, and /graphql mounts wired the same way as src/index.js. */ | ||
| async function withApp(env, run) { | ||
| const store = createStore(); | ||
| const finance = createFinanceService(); | ||
| const pubsub = createPubSub(); | ||
| const schema = createSchema(); | ||
| const apolloServer = createApolloServer({ schema }); | ||
| await apolloServer.start(); | ||
|
|
||
| const app = express(); | ||
| const corsOptions = loadCorsOptions(env); | ||
|
|
||
| app.use('/export', cors(corsOptions), createExportRouter({ store, finance })); | ||
| app.use( | ||
| '/graphql/stream', | ||
| cors(corsOptions), | ||
| express.json(), | ||
| createStreamRouter({ schema, contextValue: () => ({ store, finance, pubsub }) }) | ||
| ); | ||
| app.use( | ||
| '/graphql', | ||
| cors(corsOptions), | ||
| express.json(), | ||
| expressMiddleware(apolloServer, { context: async () => ({ store, finance, pubsub }) }) | ||
| ); | ||
|
|
||
| const server = await new Promise((resolve) => { | ||
| const listener = app.listen(0, () => resolve(listener)); | ||
| }); | ||
| const { port } = server.address(); | ||
| try { | ||
| await run(`http://127.0.0.1:${port}`); | ||
| } finally { | ||
| await new Promise((resolve) => server.close(resolve)); | ||
| await apolloServer.stop(); | ||
| } | ||
| } | ||
|
|
||
| describe('cors configuration', () => { | ||
| it('parses a comma-separated allow-list and ignores blanks', () => { | ||
| assert.deepEqual(parseAllowedOrigins(' https://a.example , ,https://b.example '), [ | ||
| 'https://a.example', | ||
| 'https://b.example', | ||
| ]); | ||
| assert.deepEqual(parseAllowedOrigins(undefined), []); | ||
| }); | ||
|
|
||
| it('echoes allowed origins and never emits a wildcard', async () => { | ||
| await withServer({ CORS_ALLOWED_ORIGINS: 'https://app.example' }, async (url) => { | ||
| const allowed = await fetch(url, { headers: { origin: 'https://app.example' } }); | ||
| assert.equal(allowed.headers.get('access-control-allow-origin'), 'https://app.example'); | ||
|
|
||
| const denied = await fetch(url, { headers: { origin: 'https://evil.example' } }); | ||
| assert.equal(denied.headers.get('access-control-allow-origin'), null); | ||
|
|
||
| const noOrigin = await fetch(url); | ||
| assert.equal(noOrigin.headers.get('access-control-allow-origin'), null); | ||
| assert.equal(noOrigin.status, 200); | ||
| }); | ||
| }); | ||
|
|
||
| it('denies every origin when the allow-list is unset', async () => { | ||
| await withServer({}, async (url) => { | ||
| const response = await fetch(url, { headers: { origin: 'https://app.example' } }); | ||
| assert.equal(response.headers.get('access-control-allow-origin'), null); | ||
| assert.equal(response.status, 200); | ||
| }); | ||
| }); | ||
|
|
||
| it('enforces the allow-list on the production /export, /graphql/stream, and /graphql mounts', async () => { | ||
| const env = { CORS_ALLOWED_ORIGINS: 'https://app.example' }; | ||
| await withApp(env, async (baseUrl) => { | ||
| const routes = [ | ||
| { path: '/export', init: {} }, | ||
| { | ||
| // A valid one-shot query completes and closes the response itself, | ||
| // instead of leaving an SSE stream open for the test to clean up. | ||
| path: `/graphql/stream?query=${encodeURIComponent('{ __typename }')}`, | ||
| init: { headers: { accept: 'text/event-stream' }, method: 'GET' }, | ||
| }, | ||
| { | ||
| path: '/graphql', | ||
| init: { | ||
| method: 'POST', | ||
| headers: { 'content-type': 'application/json' }, | ||
| body: JSON.stringify({ query: '{ __typename }' }), | ||
| }, | ||
| }, | ||
| ]; | ||
|
|
||
| for (const { path, init } of routes) { | ||
| const allowed = await fetch(`${baseUrl}${path}`, { | ||
| ...init, | ||
| headers: { ...init.headers, origin: 'https://app.example' }, | ||
| }); | ||
| assert.equal(allowed.status, 200, `${path} should succeed for an allowed origin`); | ||
| assert.equal( | ||
| allowed.headers.get('access-control-allow-origin'), | ||
| 'https://app.example', | ||
| `${path} should echo the allowed origin` | ||
| ); | ||
|
|
||
| const denied = await fetch(`${baseUrl}${path}`, { | ||
| ...init, | ||
| headers: { ...init.headers, origin: 'https://evil.example' }, | ||
| }); | ||
| assert.equal(denied.status, 200, `${path} should still respond for a denied origin`); | ||
| assert.equal( | ||
| denied.headers.get('access-control-allow-origin'), | ||
| null, | ||
| `${path} should not echo a denied origin` | ||
| ); | ||
|
|
||
| const noOrigin = await fetch(`${baseUrl}${path}`, init); | ||
| assert.equal(noOrigin.status, 200, `${path} should succeed without an Origin header`); | ||
| assert.equal( | ||
| noOrigin.headers.get('access-control-allow-origin'), | ||
| null, | ||
| `${path} should not emit a CORS header without an Origin header` | ||
| ); | ||
| } | ||
| }); | ||
| }); | ||
| }); | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.