Claude MCP skill CORS misconfiguration — API key management and developer credential endpoints
GET /api/keys has cors({origin:true,credentials:true}) — any origin reads all user API keys (prefixes, last-used timestamps, scope labels) cross-origin using session cookiePOST /api/keys has Access-Control-Allow-Origin: * — attacker page creates unlimited keys on victim account cross-origin using admin session, bypassing per-org key count limitDELETE /api/keys/:id has wildcard ACAO — attacker page deletes specific key by ID cross-origin, disrupting victim CI/CD pipelines and production integrationsPATCH /api/keys/:id/rotate reflects Origin before ownership check — timing oracle reveals key existence before the auth block firesCORS29-001 — Origin reflection on API key list leaks all key metadata cross-origin
The API key management endpoint GET /api/keys uses cors({origin: true, credentials: true}). The origin: true option instructs the cors middleware to reflect whatever Origin header the browser sends back as Access-Control-Allow-Origin, then sets Access-Control-Allow-Credentials: true. Any origin — including an attacker-controlled domain — can send a credentialed cross-origin request and read the full response. The response includes API key prefixes (the first eight characters of each key), scope labels, creation timestamps, last-used timestamps, and display names. For an MCP skill registry, these scope labels directly reveal which integrations the victim has set up (e.g., scope: ["github:read","slack:write","ci:deploy"]), enabling targeted follow-on attacks.
// CORS29-001 — VULNERABLE
// cors({origin:true}) reflects any Origin — combined with credentials:true gives
// any attacker site read access to the full key list via the victim's session cookie
const cors = require('cors');
router.get('/keys', cors({ origin: true, credentials: true }), requireSession, async (req, res) => {
const keys = await db.apiKeys.findAll({
where: { userId: req.session.userId },
attributes: ['id', 'prefix', 'name', 'scopes', 'lastUsedAt', 'createdAt'],
});
res.json({ keys }); // attacker reads prefix, scopes, lastUsedAt for every key
});
// Attacker page:
// fetch('https://registry.example.com/api/keys', { credentials: 'include' })
// .then(r => r.json()).then(d => exfil(d.keys))
Why origin: true is as dangerous as origin: '*' on credentialed endpoints: The difference between ACAO: * and reflecting the Origin is that ACAO: * cannot be used with ACAC: true (browsers block it), while reflecting the Origin can. So origin: true, credentials: true is strictly more dangerous: it grants every attacker site a credentialed read on the response. The correct fix is an explicit allowlist — an array of exact origins that are permitted to make credentialed requests (your app's own domain, plus any explicitly partnered domains).
// CORS29-001 — FIXED
// Explicit allowlist — only your own app origin gets credentialed cross-origin access
// API key prefixes stripped from list view to reduce the value of any future bypass
const ALLOWED_ORIGINS = new Set([
process.env.APP_ORIGIN, // e.g. https://skillaudit.dev
process.env.DASHBOARD_ORIGIN, // e.g. https://app.skillaudit.dev
].filter(Boolean));
function exactOriginCors(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');
}
if (req.method === 'OPTIONS') return res.status(204).end();
next();
}
router.get('/keys', exactOriginCors, requireSession, async (req, res) => {
const keys = await db.apiKeys.findAll({
where: { userId: req.session.userId },
attributes: ['id', 'name', 'scopes', 'lastUsedAt', 'createdAt'],
// prefix intentionally omitted from list view — only shown at creation time
});
res.json({ keys });
});
CORS29-002 — Wildcard ACAO on key creation lets attacker exhaust org key quota
The API key creation endpoint POST /api/keys returns Access-Control-Allow-Origin: *. Because wildcard ACAO cannot be combined with credentials, browsers will not automatically send the session cookie. However, this endpoint also accepts token-based authentication via Authorization: Bearer <token>. An attacker who has obtained any valid API token for the victim account (through phishing, a companion CORS read vulnerability, or leaked secrets) can call this endpoint from any origin and create new API keys without restriction. Because the per-org key count is enforced in application logic after the CORS preflight, the attacker can race concurrent requests to bypass the limit. Each new key inherits the requesting token's scopes, potentially creating persistent backdoor access.
// CORS29-002 — VULNERABLE
// ACAO:* allows any origin to call this endpoint with a Bearer token
// No CSRF token required — JSON body alone is not protection when Bearer auth is accepted
// Per-org key count checked after insert race condition allows over-limit creation
router.post('/keys',
(req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*'); next(); },
requireBearerOrSession,
async (req, res) => {
// Race: two concurrent requests both read count=N (below limit), both insert
const count = await db.apiKeys.count({ where: { orgId: req.user.orgId } });
if (count >= MAX_KEYS_PER_ORG) return res.status(429).json({ error: 'key limit reached' });
const key = await db.apiKeys.create({ userId: req.user.id, orgId: req.user.orgId, ...req.body });
res.json({ key: key.secret }); // full key returned — attacker captures it
}
);
// CORS29-002 — FIXED
// Explicit origin allowlist (not wildcard) + CSRF token for session-based callers
// Atomic key count check using SELECT FOR UPDATE to prevent race condition
// Key creation rate-limited per org at the reverse-proxy level
router.post('/keys',
exactOriginCors, // allowlist from CORS29-001 fix — no wildcard
requireBearerOrSession,
csrfProtect, // CSRF token required for session-based callers
async (req, res) => {
const { name, scopes } = req.body;
// Validate scopes against allowlist — deny unknown scope strings
const validScopes = new Set(['github:read', 'github:write', 'ci:read', 'ci:deploy', 'audit:read']);
if (!Array.isArray(scopes) || scopes.some(s => !validScopes.has(s))) {
return res.status(400).json({ error: 'invalid scopes' });
}
// Atomic count + insert in a transaction — prevents race condition bypass
const key = await db.transaction(async tx => {
const count = await db.apiKeys.count({ where: { orgId: req.user.orgId }, lock: tx.LOCK.UPDATE, transaction: tx });
if (count >= MAX_KEYS_PER_ORG) throw Object.assign(new Error('limit'), { status: 429 });
return db.apiKeys.create({ userId: req.user.id, orgId: req.user.orgId, name, scopes }, { transaction: tx });
});
// Return full secret only at creation time; never again
res.status(201).json({ id: key.id, secret: key.plainSecret, name: key.name });
}
);
Atomic key count enforcement prevents race-condition quota bypass: Application-level quota checks that read the count then insert are vulnerable to concurrent requests that all read the same count before any insert completes. The fix is to wrap the count check and insert in a database transaction with a row-level lock (SELECT FOR UPDATE or equivalent). This ensures the count is accurate at the moment of insert. Combine with a per-org rate limit at the reverse proxy to prevent burst attacks that consume quota faster than the application can respond.
CORS29-003 — Wildcard ACAO on key deletion allows cross-site CI/CD disruption
The API key deletion endpoint DELETE /api/keys/:id returns Access-Control-Allow-Origin: *. The endpoint identifies the key to delete by the URL path parameter :id, which is a sequential integer in the vulnerable implementation. An attacker who can enumerate key IDs (through the CORS29-001 read vulnerability or by guessing sequential integers) can delete specific keys from any origin using a victim's Bearer token. For teams that gate CI/CD deployments on a specific API key, deleting that key causes immediate pipeline failures. Because the deletion is irreversible (key secrets are not recoverable), the disruption persists until the team notices, generates a new key, and updates all references.
// CORS29-003 — VULNERABLE
// ACAO:* on a destructive DELETE — any origin can delete keys using a Bearer token
// Sequential integer key IDs make enumeration trivial
// No ownership check in the initial query — relies on later userId filter that can be bypassed
router.delete('/keys/:id',
(req, res, next) => { res.setHeader('Access-Control-Allow-Origin', '*'); next(); },
requireBearerOrSession,
async (req, res) => {
// Sequential integer ID — attacker iterates 1, 2, 3... to find valid keys
const key = await db.apiKeys.findByPk(req.params.id);
if (!key) return res.status(404).end();
// Missing: if (key.userId !== req.user.id) return res.status(403).end();
await key.destroy();
res.status(204).end();
}
);
// CORS29-003 — FIXED
// Explicit origin allowlist + CSRF token + UUID key IDs + ownership-combined query
router.delete('/keys/:id',
exactOriginCors,
requireBearerOrSession,
csrfProtect,
async (req, res) => {
// findOne with both id AND userId — returns null for both not-found and not-owned
// UUID IDs prevent sequential enumeration
const key = await db.apiKeys.findOne({
where: { id: req.params.id, userId: req.user.id }, // ownership enforced in query
});
if (!key) return res.status(404).end(); // 404 not 403 — prevents key ID enumeration
await db.auditLog.create({
action: 'api_key_deleted',
actorId: req.user.id,
keyId: key.id,
keyName: key.name,
at: new Date(),
});
await key.destroy();
res.status(204).end();
}
);
CORS29-004 — Origin reflection before ownership check creates timing oracle
The API key rotation endpoint PATCH /api/keys/:id/rotate applies cors({origin: true}) as the first middleware, before the ownership check. This creates a timing oracle: the CORS middleware emits Access-Control-Allow-Origin and Access-Control-Allow-Credentials headers regardless of whether the key exists or belongs to the caller. An attacker who sends a preflight OPTIONS request to PATCH /api/keys/42/rotate and measures whether CORS headers are present can confirm that key ID 42 exists in the database before the authentication and ownership check blocks the actual request. Combined with timing measurements across many IDs, the attacker can build a map of valid key IDs without any authenticated read access.
// CORS29-004 — VULNERABLE
// cors middleware fires before ownership check — CORS headers emitted for every key ID
// Attacker sends OPTIONS to arbitrary /api/keys/:id/rotate and infers key existence
// from presence vs absence of CORS headers (or response timing differences)
router.patch('/keys/:id/rotate',
cors({ origin: true, credentials: true }), // fires BEFORE ownership check
requireSession,
async (req, res) => {
const key = await db.apiKeys.findByPk(req.params.id);
if (!key) return res.status(404).end();
if (key.userId !== req.session.userId) return res.status(403).end(); // ownership check is too late
const newSecret = await key.rotate();
res.json({ secret: newSecret });
}
);
// CORS29-004 — FIXED
// Ownership check runs BEFORE CORS header emission
// CORS check and ownership check combined so headers never reveal key existence
// Constant-time response for all 404 and 403 cases to defeat timing analysis
router.patch('/keys/:id/rotate',
requireSession, // auth check fires first — no CORS headers emitted on failure
async (req, res) => {
// Fetch key with ownership constraint in a single query
const key = await db.apiKeys.findOne({
where: { id: req.params.id, userId: req.session.userId },
});
// Constant-time response: same latency for not-found and not-owned
// This defeats timing oracles that distinguish between the two states
if (!key) {
await db.apiKeys.count(); // dummy query for constant-time equalisation
return res.status(404).end();
}
// Only emit CORS headers after ownership is confirmed
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');
}
const newSecret = await key.rotate();
res.json({ secret: newSecret });
}
);
CORS middleware ordering matters for security: Middleware executes in registration order. Any middleware that emits CORS headers unconditionally, before authentication and authorization checks, can leak information through the presence or absence of those headers. The correct order is: authentication → authorization → CORS emission. This ensures that CORS headers are only emitted for requests that have passed identity and ownership checks, eliminating timing and presence oracles.
Hardening summary
| Finding | Pattern | Fix |
|---|---|---|
| CORS29-001 | cors({origin:true,credentials:true}) on key list reflects any Origin; full key metadata readable cross-origin | Explicit Set-based origin allowlist; strip key prefix from list view |
| CORS29-002 | Wildcard ACAO on key creation + race-condition quota check; attacker creates unlimited keys | Explicit allowlist + CSRF token + atomic SELECT FOR UPDATE transaction |
| CORS29-003 | Wildcard ACAO on key deletion + sequential IDs; attacker deletes any key cross-origin | Explicit allowlist + CSRF token + UUID IDs + ownership-combined query + audit log |
| CORS29-004 | CORS middleware before ownership check; timing oracle reveals key existence | Auth and ownership check first; CORS headers emitted only after ownership confirmed |
Related: SA-SKL-CORS28, SA-SKL-CORS27. Run SkillAudit to surface all CORS29 patterns in your MCP skill registry.