CORS Misconfigurations in MCP Skill Registry API Key Management and Developer Credential Endpoints
API keys are the primary programmatic authentication mechanism in a multi-tenant MCP skill registry: they gate CI/CD pipeline access, webhook delivery signing, audit automation, and all machine-to-machine integrations. The four SA-SKL-CORS29 patterns demonstrate how CORS misconfigurations on key management endpoints transform a credential management surface into an attacker-controlled credential factory — culminating in a chain where scope labels are harvested cross-origin, the legitimate CI/CD key is deleted cross-origin, and a backdoor key with identical scopes is quietly created on the victim account using the same admin session, leaving automated pipelines silently re-authenticated to attacker-controlled infrastructure.
In this post
- Why API key management endpoints are CORS critical surfaces
- CORS29-001 — Origin reflection on key list GET leaks scope labels and usage metadata
- CORS29-002 — Wildcard ACAO on key creation POST enables unlimited key generation + quota bypass
- CORS29-003 — Wildcard ACAO on key deletion DELETE disrupts CI/CD pipelines
- CORS29-004 — Origin reflection before ownership check on key rotation creates timing oracle
- Compound attack chain: scope recon → CI key deletion → backdoor key creation
- Detection with AST queries
- Summary and checklist
GET /api/keys uses cors({origin:true,credentials:true}) reflecting any Origin as ACAO; attacker page reads all key prefixes, scope labels, last-used timestamps, and creation dates cross-origin using the victim's session cookiePOST /api/keys has ACAO: *; attacker page creates unlimited keys on victim account cross-origin using admin session; per-account key count is a TOCTOU race: 1 000 concurrent requests all read count=0 and each creates a key, blowing past the free-tier quota capDELETE /api/keys/:id has ACAO: * with sequential integer IDs; attacker deletes any specific key cross-origin by ID, disabling the victim's CI/CD pipeline or webhook signingPATCH /api/keys/:id/rotate reflects Origin before ownership check; timing difference between owned-key and unowned-key responses acts as an oracle revealing key existence and account ownership without authenticationWhy API key management endpoints are CORS critical surfaces
API key management occupies an unusual position in the CORS threat model. Unlike session-cookie authentication, API keys are designed to be passed programmatically — in Authorization: Bearer headers, in query strings, or in webhook HMAC signatures. This design intent often leads developers to treat key management endpoints as inherently "API-first" and therefore safe to open with permissive CORS, reasoning that "it's just for the developer console." That reasoning is exactly backwards.
The developer console that manages API keys is loaded in a browser with a session cookie. That session cookie authenticates the same endpoints as any other authenticated browser session. An attacker who can inject cross-origin JavaScript into any page the victim developer visits — or who can trick the victim into visiting an attacker-controlled page while logged into the registry — can leverage the session cookie to interact with every API key management endpoint that CORS permits. The result is not a theoretical information-disclosure concern: it is a live credential management interface that the attacker can read from, write to, and delete from, without any indication in the victim's audit log that the actions were taken cross-origin.
Three design patterns in MCP registry codebases recur as root causes for the CORS29 class. The first is using cors({origin:true}) on the key list endpoint specifically because the team wants their VS Code extension and other first-party desktop tools to be able to fetch the key list without a preflight. The correct fix is to list those tool origins explicitly in the allowlist; the common mistake is to use origin:true which is equivalent to allowing every origin in the world. The second pattern is applying ACAO: * to the entire keys router during a debugging session for a third-party OAuth integration and forgetting to remove it. The third is emitting CORS headers inside the route handler rather than via middleware, which creates ordering bugs where headers are emitted before authorization checks have run.
CORS29-001 — Origin reflection on key list GET leaks scope labels and usage metadata
The API key list endpoint GET /api/keys returns all keys belonging to the authenticated user, including the key prefix (the first 8 characters shown in the console for identification), the scope labels (which define what operations each key is permitted to perform), the last-used timestamp, the creation date, and the display name the developer assigned to the key. This combination of data is not the key secret itself — the actual secret is never returned after creation — but it is a highly useful reconnaissance payload for an attacker planning a targeted key management attack.
The endpoint uses cors({origin:true,credentials:true}) to serve both the web dashboard at skillaudit.dev and an internal tooling dashboard at internal.skillaudit.dev. The developer used origin:true to avoid hardcoding both origins, planning to refactor to an explicit allowlist later. As with all CORS29-class findings, later never arrived.
// CORS29-001 — VULNERABLE
// cors({origin:true,credentials:true}) reflects any Origin as ACAO.
// Attacker page reads all key metadata including scope labels cross-origin.
// keys/router.js
const cors = require('cors');
router.get(
'/',
cors({ origin: true, credentials: true }), // VULNERABLE: origin:true reflects all origins
requireSession,
async (req, res) => {
const keys = await db.apiKeys.findByUserId(req.session.userId);
res.json(keys.map(k => ({
id: k.id, // sequential integer ID — exploited in CORS29-003
prefix: k.prefix, // first 8 chars of the key — attacker harvests for identification
name: k.name, // display name — reveals purpose ("ci-cd-prod", "webhook-signer")
scopes: k.scopes, // array of scope strings — attacker targets high-privilege scopes
lastUsedAt: k.lastUsedAt,
createdAt: k.createdAt,
})));
}
);
// Attacker page (any origin):
// fetch('https://registry.example.com/api/keys', { credentials: 'include' })
// .then(r => r.json())
// .then(keys => {
// const ciKey = keys.find(k => k.name.includes('ci') || k.name.includes('prod'));
// // Record ciKey.id for deletion in CORS29-003 step
// // Record ciKey.scopes for backdoor key creation in CORS29-002 step
// });
Why key prefixes and scope labels are sensitive even without the secret: Key prefixes identify specific keys in log entries, support tickets, and audit trails. An attacker who knows a key prefix can correlate registry audit logs with external logs to determine when and how the key is used without possessing the key itself. Scope labels are more directly valuable: they reveal exactly which operations each key is authorized to perform. A key with scopes: ["skills:publish","webhooks:manage","audit:read"] tells the attacker this key can publish new skill versions and manage webhooks — both high-value targets. The attacker can use this information to construct a backdoor key with an identical scope profile that will not appear anomalous to anyone reviewing the key list.
// CORS29-001 — FIXED
// Replace origin:true with an explicit Set-based allowlist.
// Strip key prefix from the list view (prefix only needed in the create response).
// Use UUIDs for key IDs to prevent enumeration (see CORS29-003).
// config/cors.js
const ALLOWED_ORIGINS = new Set([
'https://skillaudit.dev',
'https://app.skillaudit.dev',
'https://internal.skillaudit.dev',
]);
const keyCorsOptions = {
origin: (origin, callback) => {
if (!origin || ALLOWED_ORIGINS.has(origin)) return callback(null, true);
callback(Object.assign(new Error('CORS: origin not allowed'), { status: 403 }));
},
credentials: true,
methods: ['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-CSRF-Token'],
};
module.exports = { keyCorsOptions };
// keys/router.js
const { keyCorsOptions } = require('../config/cors');
router.get(
'/',
cors(keyCorsOptions), // explicit allowlist — not origin:true
requireSession,
async (req, res) => {
const keys = await db.apiKeys.findByUserId(req.session.userId);
res.json(keys.map(k => ({
id: k.id, // UUID — not sequential integer
name: k.name,
scopes: k.scopes,
lastUsedAt: k.lastUsedAt,
createdAt: k.createdAt,
// prefix is NOT included — only shown in the create response (once)
})));
}
);
Separating the browser key-management API from the CLI/machine API: A cleaner architectural fix is to serve the developer console's key-management UI from a dedicated route (/api/keys/browser/) that explicitly carries CORS headers for allowed browser origins, while keeping the main /api/keys route accessible only via Authorization: Bearer header with no CORS headers at all. This eliminates the ambiguity between "which callers are browsers and which are machines" that produces the origin:true temptation in the first place.
CVSS 3.1 approximate score for CORS29-001: 7.4 (HIGH) — AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:N/A:N. Scope is Changed because the leaked scope labels affect the security posture of downstream systems that rely on the key's granted permissions.
CORS29-002 — Wildcard ACAO on key creation POST enables unlimited key generation + quota bypass
The key creation endpoint POST /api/keys creates a new API key with specified scopes and stores it in the database, returning the full key secret once (and only once) in the creation response. The endpoint has ACAO: * applied via a blanket res.header call that was added during the integration of a third-party OAuth flow and never removed when that flow was replaced.
The wildcard on a creation endpoint produces two compounding problems. First, any attacker origin can send a POST to create a key using the victim's session cookie — and because this is a mutation, the key is created before the browser evaluates whether to surface the response. The attacker does not need to read the key secret from the creation response; creating the key itself is sufficient to displace the victim's existing authentication or to provision a parallel access path. Second, the per-account key quota is enforced with a non-atomic SELECT-then-INSERT pattern: the endpoint reads the current key count, checks it against the plan limit, and then inserts a new row. Under concurrent load, every racing request reads the same count value before any of them has committed an insert, allowing the quota check to be bypassed entirely by sending many concurrent creation requests.
// CORS29-002 — VULNERABLE
// ACAO:* allows any origin to POST the creation endpoint.
// Non-atomic count check allows quota bypass under concurrent load.
// keys/router.js
router.post(
'/',
requireSession,
async (req, res) => {
res.header('Access-Control-Allow-Origin', '*'); // VULNERABLE: wildcard on creation endpoint
const { name, scopes } = req.body;
// TOCTOU: SELECT then INSERT — not atomic
const existingCount = await db.apiKeys.countByUserId(req.session.userId);
const plan = await db.plans.findByUserId(req.session.userId);
if (existingCount >= plan.keyLimit) {
return res.status(429).json({ error: 'Key limit reached' });
}
// Multiple concurrent requests all read existingCount=0 before any INSERT commits.
// Each then passes the limit check and inserts — quota enforcement is bypassed.
const keySecret = crypto.randomBytes(32).toString('hex');
const keyPrefix = keySecret.slice(0, 8);
const { id } = await db.apiKeys.create({
userId: req.session.userId,
name,
scopes,
prefix: keyPrefix,
secretHash: await bcrypt.hash(keySecret, 12),
});
res.json({ id, prefix: keyPrefix, secret: keySecret }); // browser blocked by wildcard + credentials rule but POST already fired
}
);
// Attacker page:
// const promises = Array.from({length: 1000}, () =>
// fetch('https://registry.example.com/api/keys', {
// method: 'POST', credentials: 'include',
// headers: {'Content-Type': 'application/json'},
// body: JSON.stringify({name:'backdoor', scopes:['skills:publish','webhooks:manage']})
// })
// );
// await Promise.all(promises); // 1000 keys created past quota limit
CORS-enabled quota bypass as a denial-of-service vector: The quota bypass does not require the attacker to receive the key creation response — the creation fires before the browser blocks the response. An attacker page that fires 1 000 concurrent creation requests will produce up to 1 000 keys on the victim account, each consuming database row capacity, potentially triggering rate-limit locks on the account, and flooding the victim's key list with attacker-named keys that obscure the legitimate CI/CD key. Recovery requires the victim to identify and delete all attacker-created keys, during which their own automated pipelines are disrupted by the account-level rate limit applied to the bloated key count.
// CORS29-002 — FIXED
// 1. Explicit allowlist — not wildcard.
// 2. Atomic SELECT FOR UPDATE to enforce quota without TOCTOU race.
// 3. Require application/json (forces preflight, eliminating simple-request gap).
// 4. CSRF token as defence-in-depth.
// 5. Per-user rate limit on key creation.
const cors = require('cors');
const { keyCorsOptions } = require('../config/cors');
const rateLimit = require('express-rate-limit');
const keyCreationRateLimit = rateLimit({
windowMs: 60 * 60 * 1000,
max: 20,
keyGenerator: (req) => `keycreate:${req.session.userId}`,
message: { error: 'Too many key creation requests' },
});
router.post(
'/',
cors(keyCorsOptions),
keyCreationRateLimit,
requireSession,
requireContentType('application/json'),
verifyCsrfToken,
async (req, res) => {
const { name, scopes } = req.body;
// Validate scopes against allowlist — do not accept arbitrary scope strings
const VALID_SCOPES = new Set([
'skills:read','skills:publish','audits:run','audits:read',
'webhooks:manage','keys:read'
]);
if (!Array.isArray(scopes) || !scopes.every(s => VALID_SCOPES.has(s))) {
return res.status(422).json({ error: 'Invalid scopes' });
}
// Atomic count enforcement using SELECT FOR UPDATE in a transaction
const result = await db.transaction(async (trx) => {
const { count } = await trx.raw(
'SELECT COUNT(*) as count FROM api_keys WHERE user_id = ? FOR UPDATE',
[req.session.userId]
).then(r => r[0]);
const plan = await trx('plans').where({ userId: req.session.userId }).first();
if (parseInt(count) >= plan.keyLimit) {
return { limitReached: true };
}
const keySecret = crypto.randomBytes(32).toString('hex');
const keyPrefix = keySecret.slice(0, 8);
const [id] = await trx('api_keys').insert({
id: crypto.randomUUID(), // UUID — not sequential integer
userId: req.session.userId,
name,
scopes: JSON.stringify(scopes),
prefix: keyPrefix,
secretHash: await bcrypt.hash(keySecret, 12),
createdAt: new Date(),
}).returning('id');
return { id, prefix: keyPrefix, secret: keySecret };
});
if (result.limitReached) {
return res.status(429).json({ error: 'Key limit reached for current plan' });
}
res.json({ id: result.id, prefix: result.prefix, secret: result.secret });
}
);
CVSS 3.1 approximate score for CORS29-002: 9.3 (CRITICAL) — AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:H. The scope is Changed because newly created keys authorize access to downstream systems (CI/CD, webhook endpoints, audit APIs) that exist outside the registry boundary. All three impact dimensions are high: the attacker gains access to the victim's key-protected resources (confidentiality), can publish skills and manage webhooks using the backdoor key (integrity), and the concurrent creation storm disrupts the victim's legitimate key operations (availability).
CORS29-003 — Wildcard ACAO on key deletion DELETE disrupts CI/CD pipelines
The key deletion endpoint DELETE /api/keys/:id removes a key from the database and immediately invalidates it for all in-flight requests. The endpoint uses sequential integer IDs in the :id path parameter — a design decision inherited from the initial schema that made debugging easier but that creates a trivially enumerable ID space. Combined with ACAO: * (added after a cross-origin error appeared in a support ticket), the endpoint allows any attacker origin to delete any key by integer ID, regardless of whether the key belongs to the victim or to another user.
The practical impact is not just that the attacker can delete a key they know. The impact is that an attacker who runs CORS29-001 to harvest key IDs and display names can then identify the key labelled "ci-prod" or "deploy-webhook" — the keys that gate automated deployment pipelines — and delete them cross-origin using the victim's session. The pipeline fails at its next scheduled run, and the on-call developer must rotate and redeploy credentials before service resumes. The attacker can repeat this deletion on each rotation, sustaining the outage until the CORS vulnerability is discovered and patched.
// CORS29-003 — VULNERABLE
// ACAO:* on DELETE allows any origin to delete any key by sequential integer ID.
// No ownership check prevents cross-user key deletion if ID is guessed.
// No CSRF token — credentialed simple-method DELETE fires without preflight on some configurations.
// keys/router.js
router.delete(
'/:id',
requireSession,
async (req, res) => {
res.header('Access-Control-Allow-Origin', '*'); // VULNERABLE: wildcard on deletion endpoint
res.header('Vary', 'Origin');
const keyId = parseInt(req.params.id, 10); // sequential integer — trivially enumerable
// Missing ownership check: deletes any key by ID regardless of who owns it
const deleted = await db.apiKeys.deleteById(keyId);
if (!deleted) {
return res.status(404).json({ error: 'Key not found' });
}
// No audit log: deletion happens silently
res.json({ ok: true });
}
);
// Attacker page (after harvesting key IDs from CORS29-001):
// const ciKeyId = harvestedKeys.find(k => k.name.includes('ci-prod')).id; // e.g. 4821
// fetch(`https://registry.example.com/api/keys/${ciKeyId}`, {
// method: 'DELETE', credentials: 'include'
// }); // CI/CD key deleted — pipeline starts failing
The asymmetric timing of CI/CD pipeline failures: CI/CD pipelines typically run on schedules (nightly builds, deployment windows, PR checks). An attacker who deletes a CI/CD key at 2 AM will often not be detected until the morning deployment window, when multiple pipeline runs fail simultaneously and the error messages show 401 Unauthorized rather than key not found (because the pipeline has cached the key reference, not the validation result). The gap between deletion and detection gives the attacker time to execute the CORS29-002 backdoor creation step and establish a parallel access path before the victim rotates credentials.
// CORS29-003 — FIXED
// 1. Explicit allowlist — not wildcard.
// 2. UUID key IDs — not sequential integers.
// 3. Ownership check: DELETE query includes userId constraint — 404 if not owned.
// 4. CSRF token.
// 5. Audit log on every deletion.
const cors = require('cors');
const { keyCorsOptions } = require('../config/cors');
router.options('/:id', cors(keyCorsOptions)); // explicit preflight response
router.delete(
'/:id',
cors(keyCorsOptions),
requireSession,
verifyCsrfToken,
async (req, res) => {
const keyId = req.params.id; // UUID — not an integer
// Ownership enforced at the query level: DELETE WHERE id = ? AND userId = ?
// Returns 0 rows affected (not an error) if key belongs to another user — 404 to caller
const deleted = await db.apiKeys.deleteByIdAndUserId(keyId, req.session.userId);
if (!deleted) {
return res.status(404).json({ error: 'Key not found' }); // same response for not-found and not-owned
}
// Audit log: who deleted what key, when, from which IP
await db.keyAudit.create({
action: 'key_deleted',
keyId,
userId: req.session.userId,
ip: req.ip,
at: new Date(),
});
res.json({ ok: true });
}
);
CVSS 3.1 approximate score for CORS29-003: 7.5 (HIGH) — AV:N/AC:L/PR:N/UI:R/S:U/C:N/I:H/A:H. Integrity is high (CI/CD pipeline credentials destroyed), availability is high (automated pipelines disabled until key rotation completes).
CORS29-004 — Origin reflection before ownership check on key rotation creates timing oracle
The key rotation endpoint PATCH /api/keys/:id/rotate generates a new secret for an existing key, invalidating the old secret and returning the new one. The CORS headers are emitted inside the route handler, before the ownership check runs, to avoid a code path where CORS errors would appear in the browser console when a 403 is returned. This ordering means that the endpoint emits an Access-Control-Allow-Origin header reflecting the attacker's origin before determining whether the requesting user owns the key being rotated — creating a timing oracle.
An attacker who sends rotation requests from a cross-origin page observes two distinct response timing profiles: requests for key IDs that exist and belong to the authenticated user produce a full ownership check path plus the rotation logic; requests for key IDs that exist but belong to a different user produce a shorter path that terminates at the ownership check; requests for key IDs that do not exist produce the shortest path that terminates at the not-found lookup. Because the CORS headers are emitted before these checks, the attacker can read the Access-Control-Allow-Origin header in the preflight response timing, correlate it with response time, and use the timing delta to enumerate which key IDs exist and which user accounts own them — without possessing any credentials at all.
// CORS29-004 — VULNERABLE
// CORS headers emitted before ownership check — timing oracle via ACAO header emission.
// Attacker measures preflight response time to enumerate key existence and ownership.
// keys/router.js
router.patch(
'/:id/rotate',
requireSession,
async (req, res) => {
// VULNERABLE: CORS header emitted before any authorization check
// Timing from ACAO emission to 403 reveals key-exists-but-not-owned path
res.header('Access-Control-Allow-Origin', req.headers.origin || '*');
res.header('Access-Control-Allow-Credentials', 'true');
res.header('Vary', 'Origin');
const key = await db.apiKeys.findById(req.params.id); // DB lookup timing varies
if (!key) {
return res.status(404).json({ error: 'Key not found' });
}
if (key.userId !== req.session.userId) {
return res.status(403).json({ error: 'Forbidden' }); // shorter path after ACAO emitted
}
const newSecret = crypto.randomBytes(32).toString('hex');
await db.apiKeys.rotateSecret(key.id, await bcrypt.hash(newSecret, 12));
res.json({ id: key.id, prefix: key.prefix, secret: newSecret });
}
);
CORS header timing as an enumeration channel: Timing oracles via CORS headers are subtler than typical timing side-channels because the measurement does not require the attacker to receive a response body. The attacker measures time-to-preflight-response-emission, which is observable even when the actual response body is blocked by the browser. For sequential integer key IDs (see CORS29-003), this oracle allows the attacker to build a map of which IDs are valid keys and which are gaps, then correlate with display names harvested from CORS29-001 to produce a complete inventory of key-to-owner mappings across the entire platform — not just for the authenticated user.
// CORS29-004 — FIXED
// 1. Apply cors() middleware BEFORE the route handler — headers controlled by middleware, not handler.
// 2. Auth and ownership check happen inside the route; CORS headers are set by middleware before any
// application logic runs, eliminating the timing delta between ACAO emission and auth result.
// 3. Return 404 for both not-found and not-owned (constant-time response profile).
// 4. CSRF token.
const cors = require('cors');
const { keyCorsOptions } = require('../config/cors');
router.options('/:id/rotate', cors(keyCorsOptions));
router.patch(
'/:id/rotate',
cors(keyCorsOptions), // CORS headers set by middleware before handler runs
requireSession,
verifyCsrfToken,
requireContentType('application/json'),
async (req, res) => {
// Auth and ownership check BEFORE any differentiating logic
const key = await db.apiKeys.findByIdAndUserId(req.params.id, req.session.userId);
if (!key) {
// Constant-time 404 for both not-found and not-owned — no timing oracle
return res.status(404).json({ error: 'Key not found' });
}
const newSecret = crypto.randomBytes(32).toString('hex');
await db.apiKeys.rotateSecret(key.id, await bcrypt.hash(newSecret, 12));
await db.keyAudit.create({
action: 'key_rotated',
keyId: key.id,
userId: req.session.userId,
ip: req.ip,
at: new Date(),
});
res.json({ id: key.id, prefix: key.prefix, secret: newSecret });
}
);
Why cors() middleware ordering matters: When CORS headers are set inside a route handler rather than via middleware, every conditional branch in the handler creates a potential timing difference observable before the CORS header is emitted. When cors() middleware is applied to the route at registration time (as a middleware argument), the middleware executes before the route handler begins, the CORS headers are set unconditionally, and no timing signal is available to the caller. This is a secondary reason — beyond the allowlist vs. wildcard distinction — to always use router.use(cors(options)) or router.get('/path', cors(options), handler) rather than res.header() calls inside handlers.
CVSS 3.1 approximate score for CORS29-004: 5.3 (MEDIUM) — AV:N/AC:H/PR:N/UI:N/S:U/C:L/I:N/A:N. Attack Complexity is High because exploiting the timing oracle requires statistical measurement across many requests and a controlled network environment. Confidentiality impact is Low (key existence and ownership metadata, not key secrets).
Compound attack chain: scope recon → CI key deletion → backdoor key creation
The three state-affecting CORS29 misconfigurations compose into a targeted credential takeover attack that can be executed from a single attacker-controlled page while the victim developer is logged into the registry console. The chain uses each finding sequentially: the read misconfiguration provides intelligence, the deletion misconfiguration removes the legitimate credential, and the creation misconfiguration establishes the backdoor. The attacker can then wait for the pipeline rotation cycle to surface the attack, or proceed immediately to use the newly created key.
GET /api/keys with victim's session cookie via Origin-reflecting CORS. Response returns all key IDs, display names, and scope arrays. Attacker identifies the CI/CD key (e.g. {"id":4821,"name":"ci-prod","scopes":["skills:publish","audits:run"]}) and records the ID and scopes for subsequent steps.DELETE /api/keys/4821 using the victim's session cookie via wildcard ACAO. The CI/CD key is deleted before the browser can block the response. All automated pipeline runs using this key will start failing with 401 Unauthorized at their next execution.POST /api/keys with {"name":"ci-prod","scopes":["skills:publish","audits:run"]} using the victim's session cookie. Wildcard ACAO allows the POST from any origin. A new key is created on the victim account. The attacker does not receive the key secret (browser blocks the credentialed read from wildcard ACAO), but the key exists and can be observed via CORS29-001 again. The attacker then uses CORS29-004 to rotate the backdoor key with their own authenticated session and receives the new secret in the rotation response.skills:publish scope and can publish malicious skill versions to the victim's published skill namespace — a supply-chain attack against every consumer of the victim's skills.The particularly dangerous aspect of this chain from an incident-response perspective is that the backdoor key looks legitimate in the registry console: it has the same display name and scope labels as the original CI/CD key, and the creation timestamp appears to be a legitimate key rotation. The victim developer, investigating why the CI/CD pipeline failed, may interpret the backdoor key as an accidental double-creation during a previous rotation and simply update the pipeline environment variable to point at the new key — at which point the attacker's key is now actively in use in production pipelines.
Detection with AST queries
SkillAudit detects all four CORS29 patterns using static analysis and dynamic CORS probing. The AST queries target the specific implementation patterns that produce each vulnerability class in Express.js codebases.
; CORS29-001 — Detect cors({origin:true}) — reflects all origins
; tree-sitter query for JavaScript
(call_expression
function: (identifier) @fn (#eq? @fn "cors")
arguments: (arguments
(object
(pair
key: (property_identifier) @key (#eq? @key "origin")
value: (true) @val))))
; CORS29-002 and CORS29-003 — Detect res.header ACAO:* on non-GET routes
; Used to find wildcard applied directly in handler (not via middleware)
(call_expression
function: (member_expression
object: (identifier) @res (#eq? @res "res")
property: (property_identifier) @method
(#match? @method "^(header|setHeader|set)$"))
arguments: (arguments
(string) @header_name
(#match? @header_name "(?i)access-control-allow-origin")
(string) @header_value
(#eq? @header_value "*")))
; CORS29-004 — Detect res.header ACAO with request-origin before an auth check
; SkillAudit walks the AST to find res.header(ACAO, req.headers.origin) calls that
; appear before any requireSession/verifyJWT/requireAuth middleware or await db call.
(call_expression
function: (member_expression
object: (identifier) @res (#eq? @res "res")
property: (property_identifier) @method (#match? @method "^(header|setHeader)$"))
arguments: (arguments
(string) @name (#match? @name "(?i)access-control-allow-origin")
(member_expression
object: (member_expression
object: (identifier) @req (#eq? @req "req")
property: (property_identifier) @headers (#eq? @headers "headers"))
property: (property_identifier) @field (#eq? @field "origin"))))
; Supplementary: detect sequential integer ID usage in key/secret management routes
; Flags parseInt(req.params.id) or +req.params.id patterns in DELETE/PATCH handlers
(call_expression
function: (identifier) @fn (#eq? @fn "parseInt")
arguments: (arguments
(member_expression
object: (member_expression
object: (identifier) @req (#eq? @req "req")
property: (property_identifier) @params (#eq? @params "params"))
property: (property_identifier) @id (#eq? @id "id"))))
Beyond AST analysis, SkillAudit's dynamic CORS probe fires four test requests against each key management endpoint: a cross-origin preflight from a synthetic attacker origin, a credentialed GET with credentials:include from an unlisted origin, a cross-origin DELETE with the victim's session cookie from a sandboxed browser context, and a timing-differential measurement of the rotation endpoint response latency across key-exists and key-not-exists ID variants. Any endpoint that returns an ACAO header permitting the probe origin on a credentialed or mutation request is flagged as a CORS29-class finding. See SA-SKL-CORS28 and SA-SKL-CORS27 for related CORS patterns in webhook configuration and org management endpoints.
Summary and checklist
| Finding | Pattern | Impact | Fix |
|---|---|---|---|
| CORS29-001 | cors({origin:true,credentials:true}) on key list GET | Key prefixes, scope labels, usage timestamps read cross-origin | Explicit Set-based allowlist; strip key prefix from list response |
| CORS29-002 | ACAO: * on key creation POST; non-atomic quota check | Unlimited keys created cross-origin; free-tier quota bypassed | Explicit allowlist; require JSON; CSRF token; SELECT FOR UPDATE in transaction |
| CORS29-003 | ACAO: * on key deletion DELETE; sequential integer IDs | Specific CI/CD key deleted cross-origin; pipeline disabled | Explicit allowlist; CSRF token; UUID IDs; ownership-combined query; audit log |
| CORS29-004 | Origin reflection before ownership check on rotation PATCH | Timing oracle reveals key existence and ownership without auth | CORS middleware before handler; constant-time 404 for not-found and not-owned |
- Use an explicit
ALLOWED_ORIGINSSet for all key management endpoints; never usecors({origin:true})orACAO: *. - Apply
cors()as middleware at route registration, not inside the handler; handler-levelres.header()calls create ordering-dependent timing oracles. - Use UUID identifiers for API keys, not sequential integers; sequential IDs are enumerable even when CORS is properly restricted.
- Strip the key prefix from list responses; return the prefix only in the creation response (once) and the rotation response (once).
- Enforce key creation quota with
SELECT FOR UPDATEinside a database transaction; never use a SELECT-then-INSERT pattern for quota enforcement. - Apply per-user rate limits to key creation and rotation endpoints to limit concurrent-request quota-bypass and abuse window.
- Require
application/jsonon all mutation endpoints (POST,PATCH,DELETE); form-encoded content types qualify as CORS simple requests and bypass preflight. - Add CSRF token verification to all key management mutation endpoints as defence-in-depth behind CORS controls.
- Return
404(not403) for both not-found and not-owned key operations to prevent cross-user key existence probing via error code differentiation. - Write every key creation, deletion, and rotation to an immutable key audit log with actor ID, key ID, IP address, timestamp, and origin header value.
Related findings: SA-SKL-CORS28 (webhook secret rotation and audit configuration CORS), SA-SKL-CORS27 (organization management and member invitation CORS), SA-SKL-PRIVESC10 (API key management and service account privilege escalation). Run SkillAudit on your MCP skill registry to surface all four CORS29 patterns alongside the full SA-SKL catalog of injection, deserialization, SSRF, and privilege escalation findings.