Claude MCP skill CORS misconfiguration — GraphQL subscription and batch request endpoints — SA-SKL-CORS20
GraphQL's transport options — WebSocket subscriptions, batch queries, and Apollo's plugin-based CORS configuration — each introduce CORS bypass vectors that differ from REST API patterns. Browsers don't enforce the Same-Origin Policy on WebSocket upgrades, so a graphql-ws subscription server that relies on the browser for CORS protection gets none. Batch query endpoints apply CORS at the HTTP level but can bypass per-operation access checks in the batch handler. SA-SKL-CORS20 covers the four GraphQL-specific CORS patterns SkillAudit finds in MCP skill registry infrastructure.
graphql-ws subscription server has no Origin header check in context function; any attacker page opens a WebSocket to the endpoint and subscribes to all skill update events using the victim's session cookiecredentials: true and origin function that returns true for all origins; reflects any origin as ACAO with Allow-Credentials: trueACAO: *; combined with cross-origin XHR, attacker enumerates entire schema including private types and mutation inputs from any pageCORS20-001 — GraphQL WebSocket subscription with no Origin check
The browser's Same-Origin Policy applies to XMLHttpRequest and fetch() — it does not apply to the WebSocket upgrade request. A page at evil.com can open a WebSocket connection to wss://registry.example.com/graphql-ws without any preflight check, and the browser will include the victim's session cookies (if the WebSocket URL is a secure same-site context) or connection tokens in the initial handshake. The Origin header is present in the WebSocket upgrade request, but no browser policy prevents the connection — it's the server's responsibility to validate it.
// CORS20-001 — VULNERABLE
// graphql-ws server with no Origin validation in the context function.
// Any origin can subscribe to authenticated skill update events.
import { useServer } from 'graphql-ws/lib/use/ws';
import { WebSocketServer } from 'ws';
const wsServer = new WebSocketServer({ server: httpServer, path: '/graphql-ws' });
useServer({
schema,
context: async (ctx) => {
// VULNERABLE: Origin header from ctx.extra.request is never checked
const authToken = ctx.connectionParams?.authToken;
const user = await verifyToken(authToken);
return { user };
},
onSubscribe: async (ctx, msg) => {
// No origin check here either
return undefined; // proceed with subscription
},
}, wsServer);
// Attacker page at evil.com:
// const ws = new WebSocket('wss://registry.example.com/graphql-ws',
// ['graphql-transport-ws'], { headers: { Cookie: ... } });
// ws.send(JSON.stringify({
// id: '1', type: 'subscribe',
// payload: { query: 'subscription { skillUpdated { id secretApiKey } }' }
// }));
// Browser sends Origin: https://evil.com in the upgrade — server ignores it
// CORS20-001 — FIXED
// Origin check in the context function rejects connections from non-allowlisted origins.
import { useServer } from 'graphql-ws/lib/use/ws';
import { WebSocketServer } from 'ws';
const ALLOWED_ORIGINS = new Set([
'https://skillaudit.dev',
'https://app.skillaudit.dev',
]);
const wsServer = new WebSocketServer({ server: httpServer, path: '/graphql-ws' });
useServer({
schema,
context: async (ctx) => {
// Fix: validate Origin from the WebSocket upgrade request
const origin = ctx.extra.request.headers.origin;
if (!origin || !ALLOWED_ORIGINS.has(origin)) {
throw new Error('Forbidden: origin not allowed');
}
const authToken = ctx.connectionParams?.authToken;
const user = await verifyToken(authToken);
if (!user) throw new Error('Unauthorized');
return { user };
},
connectionInitWaitTimeout: 3000,
}, wsServer);
connectionInitWaitTimeout matters too: Without a connectionInitWaitTimeout, an attacker can open a WebSocket connection without sending a connection_init message, holding the connection open indefinitely. Combined with an origin bypass, this enables a denial-of-service on the subscription pool. Set a timeout (3000ms is reasonable) so unauthenticated connections are terminated promptly.
CORS20-002 — GraphQL batch query CORS bypass
GraphQL batch requests allow multiple operations to be sent in a single HTTP request as a JSON array. When a registry exposes a batch endpoint, the CORS middleware typically validates the HTTP request's origin once and then passes all operations to the GraphQL executor. If individual operations have different access control requirements (some public, some private), the batch handler must apply per-operation authorization — not just per-request. A CORS check at the HTTP level does not substitute for per-operation authorization inside the batch.
// CORS20-002 — VULNERABLE
// Batch endpoint applies CORS once at HTTP level but not per operation.
// Mixed public/private operations in one batch call bypass per-operation CORS.
app.post('/graphql-batch', corsMiddleware, async (req, res) => {
const batch = req.body; // array of operations
if (!Array.isArray(batch)) {
return res.status(400).json({ error: 'Expected array' });
}
// VULNERABLE: operations executed without per-operation origin check
const results = await Promise.all(
batch.map(operation => execute({ schema, ...operation, contextValue: req.context }))
);
res.json(results);
});
// Attacker from evil.com sends a mixed batch:
// [
// { query: '{ publicSkillCount }' }, // passes CORS on HTTP
// { query: '{ myPrivateAuditResults { ... } }' } // also executes despite private data
// ]
// CORS middleware saw the HTTP request as valid; both operations execute.
// CORS20-002 — FIXED
// CORS middleware applied before the batch router.
// Per-operation authentication check inside the batch handler.
const ALLOWED_ORIGINS = new Set(['https://skillaudit.dev', 'https://app.skillaudit.dev']);
function strictCors(req, res, next) {
const origin = req.headers.origin;
if (origin && ALLOWED_ORIGINS.has(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Vary', 'Origin');
} else if (origin) {
return res.status(403).json({ error: 'Forbidden' });
}
if (req.method === 'OPTIONS') return res.sendStatus(204);
next();
}
app.post('/graphql-batch', strictCors, async (req, res) => {
const batch = req.body;
if (!Array.isArray(batch) || batch.length > 10) { // cap batch size
return res.status(400).json({ error: 'Invalid batch' });
}
// Fix: apply per-operation context (including auth) for each operation
const results = await Promise.all(
batch.map(operation => execute({
schema,
...operation,
// Each operation gets its own context derived from req — includes auth check
contextValue: buildOperationContext(req, operation),
}))
);
res.json(results);
});
CORS20-003 — Apollo Server credentials:true with open origin function
Apollo Server's built-in CORS plugin accepts a cors option that maps to the cors npm package. The origin property can be set to a function: origin: (origin, callback) => callback(null, true). This pattern looks like it's doing something — it's a function, not a simple boolean — but calling callback(null, true) unconditionally reflects every origin exactly like setting origin: true. Combined with credentials: true, it creates a full unrestricted-origin-with-credentials vulnerability identical to CORS18-001.
// CORS20-003 — VULNERABLE
// Apollo Server cors origin function returns true for all origins.
// Equivalent to reflecting every origin unconditionally with credentials.
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
const server = new ApolloServer({ typeDefs, resolvers });
await server.start();
app.use('/graphql', expressMiddleware(server, {
cors: {
// VULNERABLE: origin function accepts every caller
origin: (origin, callback) => {
callback(null, true); // ← accepts any origin
},
credentials: true, // ← combined with any origin = CORS18-001 equivalent
methods: ['GET', 'POST'],
},
context: async ({ req }) => ({ user: await getUserFromToken(req) }),
}));
// CORS20-003 — FIXED
// origin function validates against allowlist before calling back with true.
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
const ALLOWED_ORIGINS = new Set([
'https://skillaudit.dev',
'https://app.skillaudit.dev',
]);
const server = new ApolloServer({ typeDefs, resolvers });
await server.start();
app.use('/graphql', expressMiddleware(server, {
cors: {
// Fix: validate origin before accepting
origin: (origin, callback) => {
if (!origin || ALLOWED_ORIGINS.has(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
},
credentials: true,
methods: ['GET', 'POST'],
},
context: async ({ req }) => ({ user: await getUserFromToken(req) }),
}));
!origin allows server-to-server requests: The check if (!origin || ALLOWED_ORIGINS.has(origin)) passes when origin is undefined — which happens for same-origin requests and for server-to-server requests (curl, Postman, server-side fetch). This is intentional: same-origin and server-side callers are not subject to CORS and should not be blocked. The browser always sends an Origin header for cross-origin requests, so an attacker page at evil.com will have origin = 'https://evil.com' and will be rejected.
CORS20-004 — Introspection endpoint ACAO:* schema enumeration
GraphQL introspection allows clients to query the schema itself — all type names, field names, argument names, and descriptions. By default, introspection is enabled in development and many production deployments. When the introspection endpoint returns Access-Control-Allow-Origin: *, an attacker page can query the schema cross-origin without credentials and discover the full type system: private mutation inputs, internal type names that reveal infrastructure, and argument names that hint at injection surfaces.
// CORS20-004 — VULNERABLE
// Introspection enabled in production + ACAO:* on /graphql endpoint.
// Attacker page enumerates entire schema cross-origin.
// No introspection disable, no origin restriction on introspection queries
app.use('/graphql', cors({ origin: '*' }), expressMiddleware(server));
// Attacker page:
// fetch('https://registry.example.com/graphql', {
// method: 'POST',
// headers: { 'Content-Type': 'application/json' },
// body: JSON.stringify({ query: '{ __schema { types { name fields { name } } } }' })
// }).then(r => r.json()).then(schema => exfiltrateSchema(schema));
// No credentials needed — ACAO:* allows the read without credentials
// CORS20-004 — FIXED
// Two options: disable introspection in production, or apply origin restriction.
import { ApolloServer } from '@apollo/server';
// Option A: disable introspection in production (recommended)
const server = new ApolloServer({
typeDefs,
resolvers,
introspection: process.env.NODE_ENV !== 'production', // Fix: disable in prod
});
// Option B: if introspection must be on (e.g. for external partners), restrict origin
app.use('/graphql', (req, res, next) => {
const { query } = req.body || {};
// Check if this is an introspection query
if (typeof query === 'string' && query.includes('__schema')) {
// Apply strict origin check for introspection
const origin = req.headers.origin;
if (origin && !ALLOWED_ORIGINS.has(origin)) {
return res.status(403).json({ errors: [{ message: 'Introspection not allowed' }] });
}
}
next();
}, strictCors, expressMiddleware(server));
Disable introspection in production by default: Introspection is valuable during development but rarely needed in production. Disabling it removes an entire class of reconnaissance opportunity. If you need to support third-party integrations that use introspection, add an authenticated introspection endpoint separate from the main GraphQL endpoint, protected by API key and strict origin validation. For more patterns on how CORS misconfigurations in MCP registries combine with other access control bugs, see SA-SKL-CORS19 (WebSocket and SSE CORS) and SA-SKL-CORS18 blog post (origin reflection to null-origin bypass).
How SkillAudit detects SA-SKL-CORS20
SkillAudit's GraphQL CORS scanner combines static analysis and active probing:
- CORS20-001: Static analysis finds
useServer(ormakeServer(from graphql-ws; checks whether thecontextfunction validatesctx.extra.request.headers.originagainst an allowlist; flags absence as CRITICAL. Active probe sends a WebSocket upgrade from a probe origin and checks whether the server completes the handshake. - CORS20-002: Finds batch endpoints (arrays accepted in body); checks for per-operation CORS/auth validation inside the batch handler; flags absence at HIGH.
- CORS20-003: Static analysis scans Apollo Server
cors.originvalues; detects functions that callcallback(null, true)unconditionally; flags CRITICAL when combined withcredentials: true. - CORS20-004: Active probe sends an introspection query with a probe origin (
https://evil-audit-probe.skillaudit.dev); if the response body contains__schemaand the CORS headers allow the read, flags HIGH.
| Pattern | Root cause | Fix | Severity |
|---|---|---|---|
| CORS20-001 | graphql-ws subscription server ignores Origin header | Origin allowlist check in context function; connectionInitWaitTimeout | CRITICAL |
| CORS20-002 | Batch endpoint CORS validation at HTTP level only, not per-operation | Per-operation auth context; cap batch size; strict CORS before batch router | HIGH |
| CORS20-003 | Apollo cors origin function returns true unconditionally with credentials:true | Allowlist check in origin function before callback(null, true) | CRITICAL |
| CORS20-004 | Introspection enabled in production with ACAO:* | Disable introspection in production; or restrict origin for introspection endpoint | HIGH |