← Blog

Claude MCP skill privilege escalation — API key management and service account permissions — SA-SKL-PRIVESC10

API key management and service account permissions form the programmatic access layer of a MCP skill registry — they govern which automated workflows, CI/CD pipelines, and third-party integrations can perform audits, read results, and manage skills. SA-SKL-PRIVESC10 covers four privilege escalation patterns: an API key scope validation that uses includes() allowing a wildcard scope "*" to match any permission check; a service account JWT that shares an issuer with regular user JWTs and lacks sub claim type validation, allowing personal JWTs to authenticate as service accounts at service-only endpoints; an API key rotation endpoint missing an ownership check that allows any authenticated user to rotate any user's API key; and an API key creation endpoint that checks the plan-tier limit only after the first key already exists, allowing an attacker to create an unlimited number of keys by racing the check.

By SkillAudit  |  13 Nov 2026
SA-SKL-PRIVESC10 findings at a glance
HIGHPRIVESC10-001 — API key scope validation checks req.apiKey.scope array using includes() — attacker API key with scope:["*"] matches includes("audits:read") returning true; wildcard scope grants all permissions; fix: explicit allowlist of valid scope strings, reject "*" at key creation
HIGHPRIVESC10-002 — service account JWT missing sub claim type validation — regular user JWT and service account JWT share same issuer; attacker uses personal JWT at service account endpoint /api/service/batch; endpoint reads req.user.id from JWT sub without checking account type
HIGHPRIVESC10-003 — API key rotation endpoint PATCH /api/keys/:id/rotate missing ownership check — attacker rotates any user's API key by ID, invalidating their access and issuing new key to attacker
MEDIUMPRIVESC10-004 — API key creation endpoint POST /api/keys missing plan-tier limit — free plan allows 1 API key per account; attacker creates 1000 API keys by hitting endpoint 1000 times before first key is counted in plan check; each key valid for 90 days

Background: privilege escalation in API key management and service account permissions

API keys in a MCP skill registry are the primary access mechanism for programmatic integrations — CI/CD pipelines, audit automation scripts, third-party tools. The scope system that governs what each key can do, the ownership model that determines who can manage keys, and the plan-tier limits that control how many keys a user can create are all potential privilege escalation surfaces. PRIVESC10-001 exploits a subtle JavaScript array method behavior: Array.includes() returns true when the searched value is a member of the array. If the scope check logic is scope.includes(requiredPermission) || scope.includes("*"), the wildcard grants everything. When the allowlist check is omitted entirely and only includes() is used with a wildcard shortcut, an attacker with a key scoped to ["*"] passes all permission checks.

PRIVESC10-002 is a JWT claim confusion attack: when two token types share the same issuer and the endpoint only checks the issuer, an attacker can use a personal JWT at a service account endpoint. PRIVESC10-003 is an IDOR on the key rotation endpoint — a classic missing ownership check. PRIVESC10-004 is a TOCTOU race condition at plan limit enforcement: the check reads the current key count and the creation writes a new key, but if many concurrent requests fire before the first key's write completes, all pass the check at zero keys and all create new keys. The fix for PRIVESC10-004 is a database-level SELECT FOR UPDATE or atomic counter that prevents concurrent creation beyond the plan limit.

Related patterns: SA-SKL-PRIVESC9 (privilege escalation in audit plan management and subscription enforcement), SA-SKL-PRIVESC8 (privilege escalation in role-based access control enforcement), SA-SKL-INJECTION17 (command injection in static analysis and linting tool execution).

PRIVESC10-001 — HIGH — API key scope "*" matches includes() check granting all permissions

The API key authorization middleware checks whether the key's scope array includes the required permission string using req.apiKey.scope.includes(requiredPermission). An attacker creates an API key and sets the scope to ["*"]. At key creation time, the API accepts any array of strings as valid scopes — there is no validation against an allowlist of permitted scope values and no rejection of the wildcard string. The authorization code has a parallel check: scope.includes("*") which returns true for any key holding the wildcard value. The combined check scope.includes(permission) || scope.includes("*") grants full access to any permission to any key scoped with "*".

An attacker who can create API keys (even on the free tier with limited permissions) creates a wildcard-scoped key and gains access to all API endpoints regardless of plan tier — audit submission, report export, webhook management, and skill publication. The same technique works against any permission string. The fix requires validating all requested scope strings against an explicit allowlist at key creation time and rejecting "*" explicitly. The authorization check then uses only scope.includes(requiredPermission) against the validated stored scopes with no wildcard branch.

Vulnerable
// VULNERABLE — PRIVESC10-001
// middleware/apiKeyAuth.js

// BUG: scope check includes wildcard shortcut scope.includes('*')
// Attacker creates key with scope:["*"] — matches all permission checks
function requireApiKeyScope(requiredPermission) {
  return async (req, res, next) => {
    const apiKey = req.headers['x-api-key'];
    if (!apiKey) return res.status(401).json({ error: 'API key required' });

    const keyRecord = await ApiKey.findByValue(apiKey);
    if (!keyRecord || keyRecord.revokedAt) {
      return res.status(401).json({ error: 'Invalid or revoked API key' });
    }

    // BUG: wildcard scope ["*"] passes all permission checks
    // Attacker sets scope:["*"] at key creation → unlimited access
    const hasPermission = keyRecord.scope.includes(requiredPermission)
      || keyRecord.scope.includes('*');  // <- BUG: wildcard bypass

    if (!hasPermission) {
      return res.status(403).json({
        error: `API key missing required scope: ${requiredPermission}`,
      });
    }

    req.apiKey = keyRecord;
    next();
  };
}
Fixed
// FIXED — PRIVESC10-001
// middleware/apiKeyAuth.js

// Explicit allowlist of valid scope strings — no wildcard permitted
const VALID_SCOPES = new Set([
  'audits:read',
  'audits:write',
  'audits:delete',
  'skills:read',
  'skills:write',
  'reports:read',
  'reports:export',
  'webhooks:read',
  'webhooks:write',
]);

// At key creation: validate all requested scopes against allowlist
function validateScopes(requestedScopes) {
  if (!Array.isArray(requestedScopes) || requestedScopes.length === 0) {
    throw new Error('At least one scope is required');
  }
  for (const scope of requestedScopes) {
    if (!VALID_SCOPES.has(scope)) {
      throw new Error(`Invalid scope: "${scope}" — must be one of: ${[...VALID_SCOPES].join(', ')}`);
    }
    if (scope === '*') {
      throw new Error('Wildcard scope "*" is not permitted — specify explicit scopes');
    }
  }
  return requestedScopes;
}

function requireApiKeyScope(requiredPermission) {
  return async (req, res, next) => {
    const apiKey = req.headers['x-api-key'];
    if (!apiKey) return res.status(401).json({ error: 'API key required' });

    const keyRecord = await ApiKey.findByValue(apiKey);
    if (!keyRecord || keyRecord.revokedAt) {
      return res.status(401).json({ error: 'Invalid or revoked API key' });
    }

    // Explicit scope membership check — no wildcard support
    const hasPermission = Array.isArray(keyRecord.scope)
      && keyRecord.scope.includes(requiredPermission)
      && VALID_SCOPES.has(requiredPermission); // double-check permission is valid

    if (!hasPermission) {
      logger.warn('PRIVESC10-001: API key missing scope', {
        keyId: keyRecord.id,
        requiredPermission,
        keyScopes: keyRecord.scope,
      });
      return res.status(403).json({
        error: `API key missing required scope: ${requiredPermission}`,
      });
    }

    req.apiKey = keyRecord;
    next();
  };
}

PRIVESC10-001 impact: A single wildcard-scoped API key grants unlimited programmatic access to all API endpoints — audit submission, report export, webhook management, and skill publication — regardless of the user's plan tier. Free-tier users who create a wildcard key can run unlimited deep audits, export all reports, and manage webhooks that should require paid plans. SkillAudit detects this by identifying API key scope authorization checks that include a scope.includes('*') branch or any form of wildcard matching that bypasses the explicit permission check.

PRIVESC10-002 — HIGH — Service account JWT missing sub claim type validation

The service account endpoint /api/service/batch is designed for machine-to-machine batch audit submission and accepts service account JWTs with elevated rate limits and batch processing capabilities not available to regular user JWTs. The endpoint's authentication middleware verifies the JWT signature and issuer (iss: "skillaudit.dev") but does not check the accountType claim or validate that the JWT sub matches a service account record. Regular user JWTs are issued by the same issuer with the same signing secret and use the same sub format (a UUID).

An attacker presents their regular user JWT at the /api/service/batch endpoint. The middleware validates the signature and issuer (both match) and reads req.user.id from decoded.sub. Because the endpoint does not check decoded.accountType === "service" and does not look up whether decoded.sub corresponds to a service account record, the attacker's regular JWT authenticates successfully to the service account endpoint, gaining access to batch processing with elevated rate limits. JWT claim confusion attacks are common when multiple token types share an issuer and signing secret. The fix requires checking the accountType claim and performing a database lookup to confirm the service account exists and is active.

Vulnerable
// VULNERABLE — PRIVESC10-002
// middleware/serviceAccountAuth.js

const jwt = require('jsonwebtoken');

// BUG: authenticates any JWT with matching issuer — does not check accountType claim
// Regular user JWT and service account JWT share same issuer and signing secret
// Attacker uses personal JWT at /api/service/batch → elevated batch rate limits
function authenticateServiceAccount(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Service account token required' });

  let decoded;
  try {
    decoded = jwt.verify(token, process.env.JWT_SECRET, {
      issuer: 'skillaudit.dev',
    });
  } catch {
    return res.status(401).json({ error: 'Invalid token' });
  }

  // BUG: no accountType check — regular user JWT passes here
  req.user = { id: decoded.sub, orgId: decoded.orgId };
  next();
}
Fixed
// FIXED — PRIVESC10-002
// middleware/serviceAccountAuth.js

const jwt = require('jsonwebtoken');
const { getServiceAccount } = require('../db/serviceAccounts');

async function authenticateServiceAccount(req, res, next) {
  const token = req.headers.authorization?.split(' ')[1];
  if (!token) return res.status(401).json({ error: 'Service account token required' });

  let decoded;
  try {
    decoded = jwt.verify(token, process.env.JWT_SECRET, {
      issuer: 'skillaudit.dev',
    });
  } catch {
    return res.status(401).json({ error: 'Invalid token' });
  }

  // Check accountType claim from JWT payload
  if (decoded.accountType !== 'service') {
    logger.warn('PRIVESC10-002: non-service-account JWT at service endpoint', {
      sub: decoded.sub, accountType: decoded.accountType,
    });
    return res.status(403).json({ error: 'Service account token required — personal JWTs not accepted at this endpoint' });
  }

  // Verify the sub matches an active service account record in the DB
  const serviceAccount = await getServiceAccount(decoded.sub);
  if (!serviceAccount || serviceAccount.revokedAt) {
    return res.status(401).json({ error: 'Service account not found or revoked' });
  }

  // Confirm the service account has batch access enabled
  if (!serviceAccount.batchEnabled) {
    return res.status(403).json({ error: 'Batch processing not enabled for this service account' });
  }

  req.user = {
    id: serviceAccount.id,
    orgId: serviceAccount.orgId,
    accountType: 'service',
    batchRateLimit: serviceAccount.batchRateLimit,
  };
  next();
}

PRIVESC10-002 impact: Regular users gain access to the service account batch processing endpoint with elevated rate limits (typically 100× the per-request rate limit), bypassing per-user API quotas and enabling high-volume audit submission at free-tier cost. JWT claim confusion attacks are common when multiple token types share an issuer and signing secret — the fix is to issue service account JWTs with a distinct accountType claim and validate it at service account endpoints, combined with a DB lookup to confirm the account exists and is active. SkillAudit detects this by identifying service account authentication middleware that verifies JWT signature and issuer but does not check the accountType claim and does not perform a DB lookup for the service account record.

PRIVESC10-003 — HIGH — API key rotation endpoint missing ownership check

The API key rotation endpoint PATCH /api/keys/:id/rotate invalidates the existing key and issues a new key value for the specified key ID. The endpoint authenticates the requesting user but does not verify that the key being rotated belongs to the authenticated user. An attacker can rotate any user's API key by supplying its ID. Key IDs are sequential integers or short UUIDs discoverable by incrementing from the attacker's own key ID. When the attacker rotates a victim's key, the victim's existing key is immediately invalidated — their CI/CD pipelines, audit automation scripts, and third-party integrations that use the key begin failing.

The new key value is returned to the attacker, who now holds the active API key for the victim's account and can perform any action the victim's key was authorized for. This is a classic Insecure Direct Object Reference (IDOR) vulnerability on a key management endpoint. The fix requires checking that key.userId === req.user.id before performing the rotation, and returning a 404 (not 403) to avoid confirming that the key exists for a different user. An audit log entry should record every successful key rotation.

Vulnerable
// VULNERABLE — PRIVESC10-003
// routes/apiKeys.js

// BUG: no ownership check — any authenticated user can rotate any key by ID
// Attacker PATCH /api/keys/42/rotate invalidates victim's key, receives new value
app.patch('/api/keys/:id/rotate',
  authenticate,
  async (req, res) => {
    const keyId = req.params.id;

    // BUG: finds key by ID only — does not check userId === req.user.id
    const key = await ApiKey.findById(keyId);
    if (!key) return res.status(404).json({ error: 'Key not found' });

    // Rotate: invalidate old key, issue new one
    const newKeyValue = crypto.randomBytes(32).toString('hex');
    await ApiKey.update(keyId, {
      value: newKeyValue,
      rotatedAt: new Date(),
    });

    // Returns new key value to whoever called this endpoint — not necessarily the owner
    res.json({ id: keyId, key: newKeyValue, rotatedAt: new Date() });
  }
);
Fixed
// FIXED — PRIVESC10-003
// routes/apiKeys.js

app.patch('/api/keys/:id/rotate',
  authenticate,
  async (req, res) => {
    const keyId = req.params.id;

    // Ownership check: key must belong to the authenticated user
    const key = await ApiKey.findById(keyId);
    if (!key) return res.status(404).json({ error: 'Key not found' });

    if (key.userId !== req.user.id) {
      logger.warn('PRIVESC10-003: API key rotation ownership check failed', {
        requestorUserId: req.user.id,
        keyOwnerId: key.userId,
        keyId,
      });
      // Return 404 not 403 to avoid revealing that the key exists
      return res.status(404).json({ error: 'Key not found' });
    }

    // Additional check: key must not already be revoked
    if (key.revokedAt) {
      return res.status(400).json({ error: 'Cannot rotate a revoked key' });
    }

    const newKeyValue = crypto.randomBytes(32).toString('hex');
    await ApiKey.update(keyId, {
      value: newKeyValue,
      rotatedAt: new Date(),
      previousKeyHash: crypto.createHash('sha256').update(key.value).digest('hex'),
    });

    await AuditLog.record({
      action: 'api_key_rotated',
      userId: req.user.id,
      keyId,
    });

    res.json({ id: keyId, key: newKeyValue, rotatedAt: new Date() });
  }
);

PRIVESC10-003 impact: The attacker invalidates the victim's API key (causing immediate outage of all integrations using that key) and receives the new key value, gaining programmatic access to the victim's account. CI/CD pipeline failures, automated audit scripts, and third-party integrations break immediately on key invalidation. Recovery requires the victim to notice the outage, generate a new key manually, and update all integrations — typically an hours-long incident. SkillAudit detects this by identifying API key management endpoints that perform update or rotation operations without a key.userId === req.user.id ownership check before the write.

PRIVESC10-004 — MEDIUM — API key creation endpoint missing atomic plan-tier limit allows key flooding

The API key creation endpoint POST /api/keys enforces a plan-tier limit of 1 API key per free-tier account. The enforcement logic reads the current key count with a SELECT query and compares it against the limit: if (count >= FREE_TIER_MAX_KEYS) return 403. An attacker on the free tier sends 1000 concurrent POST requests to /api/keys. All 1000 requests execute the SELECT count query before any of them have completed the INSERT — all 1000 reads return a count of 0, all 1000 pass the limit check, and all 1000 proceed to create a new key.

The result is 1000 API keys all valid for 90 days on a free-tier account. The attacker can distribute these keys across attack infrastructure or use them to bypass per-key rate limiting, since each key gets its own rate limit bucket. At 10 requests/minute per key × 1000 keys, the attacker executes 10,000 requests/minute against the SkillAudit API — consuming significant compute and LLM API budget for free. The fix requires a database-level SELECT FOR UPDATE within a transaction to serialize concurrent key creation for the same user, combined with a per-user rate limit on the key creation endpoint itself to prevent rapid-fire concurrent requests.

Vulnerable
// VULNERABLE — PRIVESC10-004
// routes/apiKeys.js

const FREE_TIER_MAX_KEYS = 1;

// BUG: SELECT count then INSERT — TOCTOU race condition
// 1000 concurrent requests all read count=0 before any INSERT completes
// 1000 keys created on a free-tier account
app.post('/api/keys',
  authenticate,
  async (req, res) => {
    const { name, scope } = req.body;

    // BUG: non-atomic check-then-create — race condition allows unlimited key creation
    const [{ count }] = await db.query(
      'SELECT count(*) AS count FROM api_keys WHERE userId = ? AND revokedAt IS NULL',
      [req.user.id]
    );

    if (req.user.plan === 'free' && count >= FREE_TIER_MAX_KEYS) {
      return res.status(403).json({ error: 'Free plan allows only 1 API key' });
    }

    const keyValue = crypto.randomBytes(32).toString('hex');
    await db.query(
      'INSERT INTO api_keys (userId, name, value, scope, expiresAt) VALUES (?, ?, ?, ?, ?)',
      [req.user.id, name, keyValue, JSON.stringify(scope), new Date(Date.now() + 90 * 86400000)]
    );

    res.status(201).json({ key: keyValue });
  }
);
Fixed
// FIXED — PRIVESC10-004
// routes/apiKeys.js

const PLAN_MAX_KEYS = { free: 1, pro: 5, team: 25, enterprise: 100 };

app.post('/api/keys',
  authenticate,
  // Per-user rate limit on key creation — prevents rapid-fire concurrent requests
  rateLimit({ windowMs: 60000, max: 10, keyGenerator: req => req.user.id }),
  async (req, res) => {
    const { name, scope } = req.body;

    // Validate scopes before attempting to create
    const validatedScopes = validateScopes(scope);

    // Fetch plan from authoritative subscription record
    const sub = await getSubscription(req.user.id);
    const plan = sub?.stripeStatus === 'active' ? sub.plan : 'free';
    const maxKeys = PLAN_MAX_KEYS[plan] ?? 1;

    // Atomic insert with plan-limit guard using SELECT FOR UPDATE (MySQL) /
    // advisory lock (Postgres) to prevent TOCTOU race condition
    await db.transaction(async (trx) => {
      // Lock the user's key count for this transaction
      const [{ count }] = await trx.query(
        'SELECT count(*) AS count FROM api_keys WHERE userId = ? AND revokedAt IS NULL FOR UPDATE',
        [req.user.id]
      );

      if (count >= maxKeys) {
        const err = new Error(`Plan ${plan} allows a maximum of ${maxKeys} API key(s)`);
        err.statusCode = 403;
        throw err;
      }

      const keyValue = crypto.randomBytes(32).toString('hex');
      await trx.query(
        'INSERT INTO api_keys (userId, name, value_hash, scope, expiresAt) VALUES (?, ?, ?, ?, ?)',
        [
          req.user.id,
          name,
          crypto.createHash('sha256').update(keyValue).digest('hex'),
          JSON.stringify(validatedScopes),
          new Date(Date.now() + 90 * 86400000),
        ]
      );

      res.status(201).json({ key: keyValue, name, scope: validatedScopes, expiresIn: '90 days' });
    });
  }
);

PRIVESC10-004 impact: A free-tier attacker creates up to 1000 valid 90-day API keys, each with its own rate limit bucket, enabling distributed high-volume API access that is effectively unlimited. At 10 requests/minute per key × 1000 keys, the attacker executes 10,000 requests/minute against the SkillAudit API — consuming significant compute and LLM API budget for free. The rate-limiting and plan quota systems are both bypassed because they track per-key usage, not aggregate per-user usage. SkillAudit detects this by identifying API key creation endpoints that use a non-transactional SELECT count then INSERT pattern for plan limit enforcement, flagging the absence of SELECT FOR UPDATE or advisory lock atomicity.

Detection with SkillAudit

SkillAudit's static analysis scans API key management and service account permission modules for all four SA-SKL-PRIVESC10 patterns. For PRIVESC10-001 it identifies scope authorization checks that include scope.includes('*') or similar wildcard bypass branches, and flags key creation endpoints that do not validate requested scope strings against an explicit allowlist. For PRIVESC10-002 it identifies service account authentication middleware that verifies JWT signature and issuer but does not check the accountType claim and does not perform a database lookup to confirm the service account exists. For PRIVESC10-003 it identifies API key rotation and revocation endpoints that perform write operations without a key.userId === req.user.id ownership check. For PRIVESC10-004 it identifies key creation endpoints that use a non-transactional count-then-insert pattern for plan limit enforcement without SELECT FOR UPDATE or advisory lock atomicity.

FindingSeverityRoot causeFix
PRIVESC10-001HIGHScope check scope.includes('*') accepts wildcard — free-tier user creates key with scope:["*"] granting all permissionsExplicit scope allowlist at key creation; reject "*"; authorization check uses only scope.includes(permission) against allowlisted values
PRIVESC10-002HIGHService account JWT missing accountType claim check — personal JWT authenticates at service batch endpoint sharing same issuer and signing keyCheck decoded.accountType === 'service'; DB lookup to confirm service account exists and is active; consider separate signing keys for service vs user tokens
PRIVESC10-003HIGHAPI key rotation PATCH /api/keys/:id/rotate missing key.userId === req.user.id ownership check — attacker rotates any key by IDAdd ownership check before any update; return 404 (not 403) to avoid confirming key existence; audit log on rotation
PRIVESC10-004MEDIUMKey creation SELECT count then INSERT TOCTOU race — 1000 concurrent requests all read count=0 before first INSERT; 1000 keys createdSELECT FOR UPDATE in transaction; per-user creation rate limit; store key hash not plaintext; plan limit from DB not JWT

Related findings: SA-SKL-PRIVESC9 (privilege escalation in audit plan management and subscription enforcement), SA-SKL-PRIVESC8 (privilege escalation in role-based access control enforcement), SA-SKL-INJECTION17 (command injection in static analysis and linting tool execution).

Catch API key privilege escalation before it compromises your registry

SkillAudit scans your MCP skill registry for all SA-SKL-PRIVESC10 patterns — wildcard scope bypass, service account JWT claim confusion, API key rotation IDOR, and plan-limit TOCTOU race — and delivers a prioritized fix report in minutes.

Join the waitlist →