Claude MCP skill CORS misconfiguration — webhook event delivery and SDK initialization — SA-SKL-CORS21
CORS misconfigurations in MCP skill registry APIs frequently appear in secondary endpoints — not in the main API but in webhook delivery receivers, SDK initialization routes, and event polling endpoints. These are often added late in development with minimal security review, then forgotten. SA-SKL-CORS21 covers four CORS patterns that expose API keys, pending events, and authenticated write endpoints to cross-origin access from attacker pages.
POST /api/webhooks/events) has no CORS middleware; attacker page on shared network POSTs to this endpoint with victim's session cookie via fetch({credentials:'include'}); forged webhook events trigger downstream actionsGET /api/sdk/init) returns ACAO:* and includes the user's API key in the JSON response; any attacker page can read the API key cross-origin with a simple fetch() callGET /api/events/poll) returns ACAO:*; victim's pending skill review events, notifications, and audit results are readable cross-origin while the victim's browser waitsCORS_ALLOW_ORIGIN env var set to comma-delimited list without trimming whitespace; " https://skillaudit.dev" (leading space) never matches the request Origin; some CORS middleware implementations fall back to wildcard on no-matchCORS21-001 — Webhook event delivery endpoint missing CORS middleware
When a MCP skill registry exposes a webhook event delivery endpoint — allowing external services to push events into the platform — that endpoint often lacks the CORS middleware applied to the main API. Developers assume that webhooks are only called by server-side systems, not by browsers. This assumption is wrong when CORS is the only access control. A browser fetch request from an attacker-controlled page sends the victim's session cookie with credentials: 'include'. If the browser sends the preflight OPTIONS and the server responds without CORS headers, modern browsers block the response — but if the endpoint also lacks CSRF protection and doesn't require a preflight (simple POST with Content-Type: text/plain), the browser sends the request without a preflight at all, and the POST lands with the victim's authentication.
// CORS21-001 — VULNERABLE
// Main API router has CORS middleware.
// Webhook event delivery router was added separately — no CORS applied.
import express from 'express';
import cors from 'cors';
const app = express();
// Main API has CORS configured correctly
app.use('/api/v1', cors({ origin: 'https://skillaudit.dev', credentials: true }), mainRouter);
// VULNERABLE: webhook router added later without CORS middleware
// Attacker page on same network can POST to this endpoint with victim's cookies
app.use('/api/webhooks', webhookRouter);
// webhookRouter.js
router.post('/events', authenticateWebhookSession, async (req, res) => {
const { skillId, event, payload } = req.body;
// No CORS check — attacker forges events (approve skill, trigger CI, etc.)
await processWebhookEvent(skillId, event, payload);
res.json({ ok: true });
});
// CORS21-001 — FIXED
// CORS middleware applied to ALL routes, including webhook endpoints.
// CSRF double-submit token required for state-changing webhook operations.
import cors from 'cors';
const corsOptions = {
origin: (origin, callback) => {
const allowed = new Set(['https://skillaudit.dev', 'https://app.skillaudit.dev']);
// Allow server-to-server calls (no Origin header) and known origins
if (!origin || allowed.has(origin)) return callback(null, true);
callback(new Error('CORS: origin not allowed'));
},
credentials: true,
};
// Apply CORS to ALL routes — not per-router
app.use(cors(corsOptions));
// Webhook endpoint additionally requires HMAC signature — mitigates even if CORS misconfigured
router.post('/events', verifyWebhookSignature, async (req, res) => {
// verifyWebhookSignature checks X-Webhook-Signature HMAC-SHA256 header
// Attacker cannot forge this — secret is only known to the registered webhook sender
const { skillId, event, payload } = req.body;
await processWebhookEvent(skillId, event, payload);
res.json({ ok: true });
});
Why CORS alone is not enough for webhook endpoints: Even with correct CORS, a webhook endpoint that relies solely on session cookies for authentication is vulnerable to CSRF. A well-designed webhook endpoint should validate a shared HMAC-SHA256 secret in a custom header (X-Webhook-Signature). This prevents both CSRF (custom headers require a preflight that CORS blocks) and replay attacks. CORS + HMAC = defence in depth. For related CORS patterns in GraphQL subscription and batch request endpoints, see SA-SKL-CORS20.
CORS21-002 — SDK initialization endpoint returns API key with wildcard CORS
Some MCP skill registry SDKs perform an initialization call when the client loads — a GET /api/sdk/init that returns configuration including the user's API key, feature flags, and account metadata. If this endpoint sets Access-Control-Allow-Origin: * for convenience (so the SDK can be loaded from any domain), any page on the internet can fetch this URL with the victim's session cookie and read the response — including the API key. The browser's same-origin policy is enforced per-document, not per-network: an attacker page at https://evil.com can call fetch('https://api.skillaudit.dev/api/sdk/init', {credentials:'include'}). With ACAO:* and credentials: true combined, the browser allows the cross-origin read.
// CORS21-002 — VULNERABLE
// SDK init endpoint returns API key with ACAO:* — any origin can read it.
router.get('/sdk/init', authenticate, (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*'); // VULNERABLE: wildcard
res.setHeader('Access-Control-Allow-Credentials', 'true'); // Double-broken: * + credentials
res.json({
userId: req.user.id,
apiKey: req.user.apiKey, // CRITICAL: attacker reads this cross-origin
plan: req.user.plan,
features: getFeatureFlags(req.user),
});
});
// CORS21-002 — FIXED
// SDK init endpoint uses origin allowlist — never wildcards credentials responses.
// API key is not returned in init response — fetched via separate authenticated call.
const ALLOWED_ORIGINS = new Set([
'https://skillaudit.dev',
'https://app.skillaudit.dev',
'https://docs.skillaudit.dev',
]);
router.get('/sdk/init', authenticate, (req, res) => {
const origin = req.headers.origin;
// Fix 1: allowlist-based CORS — never wildcard when credentials are involved
if (origin && ALLOWED_ORIGINS.has(origin)) {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Vary', 'Origin'); // Required when ACAO is dynamic
}
// If origin not in allowlist: no ACAO header — browser blocks cross-origin read
// Fix 2: never return raw API key in init response
// SDK fetches API key via POST /api/keys/reveal which requires re-authentication
res.json({
userId: req.user.id,
plan: req.user.plan,
features: getFeatureFlags(req.user),
// apiKey intentionally omitted
});
});
CORS21-003 — Long-poll event subscription endpoint with wildcard CORS
Long-polling is an alternative to WebSockets for server-push notifications: the client opens a GET /api/events/poll request that hangs open until an event is ready, then returns the event and immediately issues another poll. If this endpoint sets Access-Control-Allow-Origin: *, an attacker page can run the same polling loop against the victim's session. While the victim's browser holds an authenticated poll connection, the attacker's page holds its own — and because CORS wildcard allows cross-origin reads, the attacker reads every event the victim's account generates: skill review results, audit reports, billing notifications, and invitation emails.
// CORS21-003 — VULNERABLE
// Long-poll event subscription returns ACAO:* — victim's events readable cross-origin.
router.get('/events/poll', authenticate, async (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*'); // VULNERABLE
res.setHeader('Cache-Control', 'no-store');
// Hangs open for up to 30s waiting for an event
const event = await waitForEvent(req.user.id, { timeout: 30000 });
if (event) {
res.json(event); // Attacker page reads skill audit results, notifications, etc.
} else {
res.json({ type: 'keepalive' });
}
});
// CORS21-003 — FIXED
// Long-poll endpoint requires origin allowlist — no wildcard on authenticated endpoints.
// Also adds Vary: Origin so CDN/proxy does not serve cached ACAO to wrong origin.
router.get('/events/poll', authenticate, async (req, res) => {
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');
}
res.setHeader('Cache-Control', 'no-store');
const event = await waitForEvent(req.user.id, { timeout: 30000 });
res.json(event ?? { type: 'keepalive' });
});
Prefer Server-Sent Events or WebSockets with explicit origin checks over long-polling: Long-polling is harder to secure than SSE or WebSockets because every poll is a fresh HTTP request with its own CORS handshake. SSE (EventSource) and WebSocket both allow explicit origin validation at the upgrade/connection stage. For WebSocket and SSE CORS patterns, see SA-SKL-CORS19.
CORS21-004 — CORS_ALLOW_ORIGIN whitespace forces wildcard fallback
Environment variables passed through container orchestration systems (Docker Compose, Kubernetes ConfigMaps, CI/CD secrets) often pick up accidental whitespace — leading spaces, trailing newlines, or Windows-style \r\n line endings. A CORS_ALLOW_ORIGIN value of " https://skillaudit.dev" (note leading space) never matches the browser's Origin: https://skillaudit.dev header because string comparison is exact. Some CORS middleware implementations treat a no-match as "allow all" (wildcard fallback) rather than "deny". The result: the registry intended to allow only its own domain but every origin passes.
// CORS21-004 — VULNERABLE
// CORS_ALLOW_ORIGIN env var not trimmed — whitespace causes no-match fallback to wildcard.
// In Docker Compose or CI the env var picks up a leading space:
// CORS_ALLOW_ORIGIN=" https://skillaudit.dev,https://app.skillaudit.dev"
const allowedOrigins = process.env.CORS_ALLOW_ORIGIN?.split(',') ?? [];
// allowedOrigins = [' https://skillaudit.dev', 'https://app.skillaudit.dev']
// ^-- leading space here
app.use(cors({
origin: (origin, callback) => {
if (allowedOrigins.includes(origin)) return callback(null, true);
// VULNERABLE: fallback to wildcard instead of reject
// Some teams add this to avoid breaking dev environments
callback(null, true); // <-- every origin passes
},
credentials: true,
}));
// CORS21-004 — FIXED
// Trim every entry when parsing CORS_ALLOW_ORIGIN.
// Fail-closed on no-match — deny unknown origins, do not fall back to wildcard.
// Log rejected origins to aid debugging without opening the door.
const allowedOrigins = new Set(
(process.env.CORS_ALLOW_ORIGIN ?? '')
.split(',')
.map(s => s.trim()) // Fix 1: trim each entry
.filter(s => s.length > 0), // Filter empty strings from trailing commas
);
// Fail fast at startup if no origins configured
if (allowedOrigins.size === 0) {
throw new Error('CORS_ALLOW_ORIGIN is not configured — refusing to start');
}
app.use(cors({
origin: (origin, callback) => {
// Server-to-server calls have no Origin — allow
if (!origin) return callback(null, true);
if (allowedOrigins.has(origin)) return callback(null, true);
// Fix 2: deny unknown origins — never fall back to wildcard
logger.warn({ origin }, 'CORS: rejected unknown origin');
callback(new Error('CORS: origin not permitted'));
},
credentials: true,
}));
Validate CORS config at startup, not per-request: Add a startup assertion that parses CORS_ALLOW_ORIGIN and verifies every entry is a valid https:// URL with no whitespace. Log the parsed allowlist at INFO level so the first deploy surfaces misconfiguration immediately. A one-line startup check prevents hours of debugging a production incident where "CORS is configured but everything still passes." For whitespace-trimming patterns in related config env vars, also check ALLOWED_REDIRECT_URIS in SA-SKL-AUTH15.
How SkillAudit detects SA-SKL-CORS21
SkillAudit's CORS scanner applies four checks for the SA-SKL-CORS21 family:
- CORS21-001: Identifies Express router subtrees (via route prefix analysis) that do not have CORS middleware in the middleware chain; flags CRITICAL when the router handles POST/PUT/DELETE endpoints that use session authentication.
- CORS21-002: Finds
res.setHeader('Access-Control-Allow-Origin', '*')calls on endpoints that return fields namedapiKey,token,secret, orcredentialin their response serialization; flags CRITICAL. - CORS21-003: Detects long-poll pattern (
await waitForEventorawait db.queryinside a GET handler with a timeout parameter) with ACAO:*; flags HIGH. - CORS21-004: Finds
process.env.CORS_ALLOW_ORIGIN?.split(',')without a.map(s => s.trim())call; also flags CORS middleware callbacks that callcallback(null, true)in the no-match branch; flags MEDIUM.
| Pattern | Root cause | Fix | Severity |
|---|---|---|---|
| CORS21-001 | Webhook router added without CORS middleware; POST with session cookie forged cross-origin | Apply CORS middleware globally; require HMAC signature on webhook endpoints | CRITICAL |
| CORS21-002 | SDK init endpoint returns API key with ACAO:* — any origin reads it | Allowlist-based CORS; never return API key in init response | CRITICAL |
| CORS21-003 | Long-poll subscription with ACAO:* — victim's events readable cross-origin | Allowlist-based CORS + Vary: Origin on all authenticated endpoints | HIGH |
| CORS21-004 | CORS_ALLOW_ORIGIN whitespace prevents match; fallback to wildcard opens all origins | Trim env var entries; fail-closed on no-match; validate at startup | MEDIUM |