SA-SKL-PRIVESC21 — Privilege Escalation

Privilege Escalation in MCP Skill Registry API Key and Credential Management Endpoints

API keys are the primary authentication mechanism for programmatic access to skill registries — CI/CD pipelines, CLI tools, and integration partners all use them. When scope checks are based on JWT claims rather than live database lookups, when rotation endpoints lack ownership checks, and when service account creation is not gated behind admin role verification, the entire API key credential plane becomes a lateral movement surface. SA-SKL-PRIVESC21 documents four patterns that together allow an unprivileged user to gain full API access, rotate any organization’s keys, and enumerate active credentials via timing analysis.

SA-SKL-PRIVESC21 findings
CRITICALPRIVESC21-001 — API key scope read from JWT apiKeyScopes claim — craft JWT with apiKeyScopes:['admin:all'] bypasses all API key scope checks without compromising a real admin key; fix: fetch scopes from API key record in DB; JWT carries keyId only
CRITICALPRIVESC21-002 — POST /api/keys/:id/rotate missing ownership check — any authenticated user rotates any org’s API key, gains access to the new key value, and silently revokes the legitimate holder’s access; fix: verify key belongs to req.session.orgId; requireRole('admin'); audit log
HIGHPRIVESC21-003 — POST /api/service-accounts missing admin check — any member creates a service account with elevated scopes exceeding their own permissions; fix: requireRole('admin'); scope must be a subset of requestor’s own permissions; audit log
HIGHPRIVESC21-004 — API key lastUsedAt updated on every request — timing side-channel allows enumeration of which key IDs are actively used across all orgs; fix: update at most every 60 s per key via Redis TTL guard; never return exact lastUsedAt to non-owner callers

PRIVESC21-001 — JWT apiKeyScopes claim bypass grants admin:all without a real key

The API key scope verification middleware reads the allowed scopes from the JWT apiKeyScopes claim embedded in the token at key creation time. Because JWTs are signed but not encrypted, any user who can craft a valid JWT (using the same signing secret, which is recoverable if it’s weak or exposed) can include apiKeyScopes: ['admin:all'] to bypass all scope checks. Even without key compromise, any attacker who obtains a valid JWT for any scope can call the registry’s key-creation endpoint to mint a new JWT — and the JWT’s claims are taken at face value.

Vulnerable
// PRIVESC21-001 — VULNERABLE
// API key scopes read from JWT claim — attacker crafts JWT with admin:all scope.

// middleware/api-key-auth.js
async function requireApiKeyScope(requiredScope) {
  return async (req, res, next) => {
    const token = req.headers['x-api-key'];
    const decoded = jwt.verify(token, process.env.JWT_SECRET);

    // VULNERABLE: scopes come from JWT claim — attacker controls these
    const scopes = decoded.apiKeyScopes || [];
    if (!scopes.includes(requiredScope) && !scopes.includes('admin:all')) {
      return res.status(403).json({ error: 'Insufficient scope' });
    }
    req.apiKey = decoded;
    next();
  };
}
Fixed
// PRIVESC21-001 — FIXED
// 1. JWT carries only keyId — scopes fetched from DB on every request.
// 2. 30s server-side cache (Map with TTL) to avoid per-request DB round-trips.
// 3. If key is revoked in DB, cache miss forces re-fetch and returns 401.

const keyCache = new Map(); // keyId → { scopes, expiresAt }

async function requireApiKeyScope(requiredScope) {
  return async (req, res, next) => {
    const token = req.headers['x-api-key'];
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    const keyId = decoded.keyId; // JWT carries ONLY keyId — no scope claims

    // Check cache first
    const cached = keyCache.get(keyId);
    let scopes;
    if (cached && cached.expiresAt > Date.now()) {
      scopes = cached.scopes;
    } else {
      const keyRecord = await db.apiKeys.findOne({
        where: { id: keyId, revokedAt: null }, // reject revoked keys
      });
      if (!keyRecord) return res.status(401).json({ error: 'Invalid or revoked key' });
      scopes = keyRecord.scopes; // source of truth: DB only
      keyCache.set(keyId, { scopes, expiresAt: Date.now() + 30_000 });
    }

    if (!scopes.includes(requiredScope) && !scopes.includes('admin:all'))
      return res.status(403).json({ error: 'Insufficient scope' });

    req.apiKeyId = keyId;
    req.apiKeyScopes = scopes;
    next();
  };
}

PRIVESC21-002 — API key rotation missing ownership check lets any user rotate any org's key

The API key rotation endpoint POST /api/keys/:id/rotate generates a new key value for the specified key ID and returns the new value in the response. The endpoint requires a valid session but does not verify that the key belongs to the requesting user’s organization. Any authenticated user can rotate any org’s API key by guessing or enumerating the key ID. The old key is immediately invalidated, locking out the legitimate holder, and the new key value is returned to the attacker.

Vulnerable
// PRIVESC21-002 — VULNERABLE
// No ownership check — any authenticated user rotates any org's API key.

router.post('/:id/rotate', requireSession, async (req, res) => {
  const newSecret = crypto.randomBytes(32).toString('hex');
  await db.apiKeys.update(
    { secret: newSecret, rotatedAt: new Date() },
    { where: { id: req.params.id } } // VULNERABLE: no orgId ownership check
  );
  res.json({ newKey: `ska_${newSecret}` }); // new key returned to attacker
});
Fixed
// PRIVESC21-002 — FIXED
// 1. Verify key.orgId === req.session.orgId before rotation.
// 2. requireRole('admin') — only admins rotate keys.
// 3. Audit log every rotation.
// 4. Return new key value only once; subsequent reads are forbidden.

router.post('/:id/rotate', requireSession, requireRole('admin'), async (req, res) => {
  const keyRecord = await db.apiKeys.findOne({
    where: { id: req.params.id, orgId: req.session.orgId, revokedAt: null },
  });
  if (!keyRecord) return res.status(404).json({ error: 'Key not found' });

  const newSecret = crypto.randomBytes(32).toString('hex');
  const newKeyValue = `ska_${newSecret}`;

  await db.apiKeys.update(
    { secret: bcrypt.hashSync(newSecret, 10), rotatedAt: new Date() },
    { where: { id: req.params.id, orgId: req.session.orgId } }
  );

  await auditLog.write({
    action: 'api_key.rotate',
    keyId: req.params.id,
    orgId: req.session.orgId,
    rotatedBy: req.session.userId,
  });

  // Invalidate scope cache for this key
  keyCache.delete(req.params.id);

  res.json({ newKey: newKeyValue }); // shown exactly once
});

PRIVESC21-003 — Service account creation missing admin check lets members create elevated-scope accounts

The service account creation endpoint POST /api/service-accounts allows any authenticated member to create a new service account with arbitrary scopes. Because there is no check that the requesting user holds the scopes they are assigning to the service account, a viewer-role member can create a service account with admin:all scope — and then use that service account’s API key for full administrative access.

Vulnerable
// PRIVESC21-003 — VULNERABLE
// No admin check; member creates service account with scopes exceeding their own.

router.post('/service-accounts', requireSession, async (req, res) => {
  const { name, scopes } = req.body; // VULNERABLE: scopes not validated against caller's perms
  const secret = crypto.randomBytes(32).toString('hex');
  const account = await db.serviceAccounts.create({
    name,
    orgId: req.session.orgId,
    scopes,          // ← caller-controlled scopes, no ceiling check
    apiKey: `ska_${secret}`,
    createdBy: req.session.userId,
  });
  res.json({ id: account.id, apiKey: `ska_${secret}` });
});
Fixed
// PRIVESC21-003 — FIXED
// 1. requireRole('admin') — only admins create service accounts.
// 2. Requested scopes must be a subset of the requestor's own effective permissions.
// 3. Audit log every creation.

router.post('/service-accounts', requireSession, requireRole('admin'), async (req, res) => {
  const { name, scopes } = req.body;

  // Fetch requestor's current effective permissions from DB
  const requestorPerms = await db.orgMembers.getEffectiveScopes(
    req.session.userId, req.session.orgId
  );

  // Validate every requested scope is in requestor's permission set
  const invalidScopes = scopes.filter(s => !requestorPerms.includes(s) && s !== 'admin:all');
  if (invalidScopes.length > 0)
    return res.status(403).json({
      error: 'Cannot grant scopes exceeding your own permissions',
      invalidScopes,
    });

  const secret = crypto.randomBytes(32).toString('hex');
  const account = await db.serviceAccounts.create({
    name,
    orgId: req.session.orgId,
    scopes,
    apiKeyHash: bcrypt.hashSync(secret, 10),
    createdBy: req.session.userId,
  });

  await auditLog.write({
    action: 'service_account.create',
    accountId: account.id,
    scopes,
    createdBy: req.session.userId,
    orgId: req.session.orgId,
  });

  res.status(201).json({ id: account.id, apiKey: `ska_${secret}` }); // key shown once
});

PRIVESC21-004 — API key lastUsedAt timing side-channel enables active key enumeration

The API key management page shows the lastUsedAt timestamp for each key, updated on every authenticated request. By making repeated requests using different guessed key IDs and observing the update lag for each key’s lastUsedAt, an attacker can enumerate which key IDs are actively in use across any organization — including keys belonging to other orgs if the management endpoint lacks an ownership filter. Active keys are higher-value targets for brute-force or session hijacking attacks.

Vulnerable
// PRIVESC21-004 — VULNERABLE
// lastUsedAt updated on every request — timing side-channel for active key enumeration.

// middleware/api-key-auth.js
async function recordKeyUsage(keyId) {
  // VULNERABLE: DB write on every request — precise timestamp available to attacker
  await db.apiKeys.update(
    { lastUsedAt: new Date() }, // exact timestamp updated per-request
    { where: { id: keyId } }
  );
}

// management/keys.router.js — VULNERABLE: no orgId filter on listing
router.get('/', requireSession, async (req, res) => {
  const keys = await db.apiKeys.findAll({ /* no orgId filter */ });
  res.json(keys.map(k => ({ id: k.id, lastUsedAt: k.lastUsedAt }))); // exact timestamps returned
});
Fixed
// PRIVESC21-004 — FIXED
// 1. Update lastUsedAt at most every 60 seconds per key via Redis TTL guard.
// 2. Return only "within last hour" / "today" / "this week" buckets to non-owner callers.
// 3. Keys listing is strictly filtered to req.session.orgId.

const { redis } = require('../lib/redis');

async function recordKeyUsage(keyId) {
  // Redis SETNX with 60s TTL — only updates DB if the guard key has expired
  const guardKey = `key:usage-guard:${keyId}`;
  const set = await redis.set(guardKey, '1', 'EX', 60, 'NX');
  if (set) {
    // Guard was not set — update DB and reset guard
    await db.apiKeys.update(
      { lastUsedAt: new Date() },
      { where: { id: keyId } }
    );
  }
  // If guard was already set, skip DB update — lastUsedAt lags by up to 60s
}

// management/keys.router.js — FIXED
router.get('/', requireSession, async (req, res) => {
  const keys = await db.apiKeys.findAll({
    where: { orgId: req.session.orgId }, // ownership filter — own org only
  });
  res.json(keys.map(k => ({
    id: k.id,
    name: k.name,
    // Return bucketed relative time, not exact timestamp — reduces timing side-channel value
    lastUsedAt: bucketTimestamp(k.lastUsedAt), // e.g. "within last hour", "today", ">30 days"
  })));
});

function bucketTimestamp(ts) {
  if (!ts) return 'never';
  const ageMs = Date.now() - new Date(ts).getTime();
  if (ageMs < 3600_000) return 'within-last-hour';
  if (ageMs < 86400_000) return 'today';
  if (ageMs < 7 * 86400_000) return 'this-week';
  if (ageMs < 30 * 86400_000) return 'this-month';
  return 'more-than-30-days';
}

API key credential plane principle: JWTs should carry identity tokens (key ID, org ID, user ID) but never authorization claims (scopes, roles, permissions). Authorization must always be fetched from the database using the identity in the token, with a short-lived server-side cache to amortize the read cost. Any JWT claim that is used for authorization rather than identity is a scope-claim bypass waiting to happen when the JWT signing secret is rotated incorrectly, weak, or exposed.

Related findings