Claude MCP skill privilege escalation — organisation role assignment and permission delegation endpoints

SA-SKL-PRIVESC20 documents four privilege escalation vulnerabilities in MCP skill registry organisation role assignment and permission delegation endpoints. PRIVESC20-001 reads the org role from a mutable JWT claim instead of the database, allowing any user to forge a JWT with orgRole:'owner' and bypass all owner-only operation checks; PRIVESC20-002 allows any member to demote the current owner to 'viewer' without a minimum-owner count check, leaving the org with no owners and the attacker as the de facto controller; PRIVESC20-003 allows a user to delegate permissions they do not themselves hold by omitting a scope validation check on the delegating user’s own permission set; and PRIVESC20-004 creates time-limited access grants but enforces the expiry only at login time, so any session minted before the grant’s expiry remains fully valid after the expiry, granting indefinite access.

Critical PRIVESC20-001 — Role assignment reads orgRole from JWT claim; forging a JWT with orgRole:'owner' bypasses all owner-level operation checks without compromising a real owner account
Critical PRIVESC20-002 — PATCH /api/orgs/:id/members/:userId/role missing self-protection; any member demotes the current owner to 'viewer', leaving the org with zero owners and the attacker as de facto controller
High PRIVESC20-003 — POST /api/orgs/:id/permissions/delegate missing scope validation; attacker delegates admin:all permission they do not hold, escalating another account to full admin without possessing those rights
High PRIVESC20-004 — POST /api/orgs/:id/access/temporary creates time-limited grants but expiry is checked only at login; sessions minted before grant expiry remain valid indefinitely after the grant expires

PRIVESC20-001 — JWT orgRole claim bypass grants owner-level access via forged token

Role-based access control systems that embed the user’s organization role in the JWT payload allow any user who can forge or modify a JWT to escalate to any role. If the JWT signing secret is weak, reused across environments, or accidentally exposed (e.g., via SSRF or environment variable leakage), an attacker can mint a token with orgRole: 'owner' and pass all subsequent owner checks without compromising a real owner account. Even with a strong secret, embedding mutable state like role in the JWT means that a role downgrade (from owner to member) is not reflected until the token expires, and that any token theft during the owner role period grants owner access for the full token lifetime.

Vulnerable
// PRIVESC20-001 — VULNERABLE
function requireOwner(req, res, next) {
  const decoded = jwt.verify(req.headers.authorization?.split(' ')[1], JWT_SECRET);
  // Reads role from JWT claim — attacker who can forge token gets owner access
  if (decoded.orgRole !== 'owner') {
    return res.status(403).json({ error: 'Owner role required' });
  }
  req.user = decoded;
  next();
}

router.delete('/orgs/:id', requireOwner, async (req, res) => {
  await db.orgs.delete(req.params.id);
  res.json({ deleted: req.params.id });
});

JWTs should carry identity, not authorization state: The JWT payload should contain only the user’s stable identity (sub, orgId, jti). Role and permission lookups must happen server-side on every request, with a short-lived in-memory or Redis cache (30–60 seconds) to avoid per-request database round-trips. This ensures that role changes take effect immediately after the cache TTL, regardless of token lifetime.

Fixed
// PRIVESC20-001 — FIXED
// Role fetched from DB; JWT carries orgId + userId only; server-side cache with 30s TTL.
const roleCache = new Map(); // Map

async function getOrgRole(orgId, userId) {
  const key = `${orgId}:${userId}`;
  const cached = roleCache.get(key);
  if (cached && cached.expiresAt > Date.now()) return cached.role;

  const member = await db.orgMembers.findByOrgAndUser(orgId, userId);
  if (!member) return null;

  roleCache.set(key, { role: member.role, expiresAt: Date.now() + 30_000 });
  return member.role;
}

async function requireOwner(req, res, next) {
  const decoded = jwt.verify(req.headers.authorization?.split(' ')[1], JWT_SECRET);
  const role = await getOrgRole(decoded.orgId, decoded.sub);
  if (role !== 'owner') return res.status(403).json({ error: 'Owner role required' });
  req.user = { ...decoded, orgRole: role };
  next();
}

PRIVESC20-002 — Owner self-demotion enables full org takeover via zero-owner state

Role assignment endpoints that allow members to modify roles without a minimum-owner count check create an org takeover vector. An attacker who is any member of the org (not necessarily an admin) calls PATCH /api/orgs/:id/members/:ownerId/role with { role: "viewer" } targeting the current owner. The endpoint modifies the owner’s role to viewer without checking whether this leaves the org with zero owners. After the demotion, the org has no owner, the former owner loses all owner-level access, and the attacker — as the only remaining member who understands the org structure — can submit a POST /api/orgs/:id/members/:selfId/role request to claim ownership, since the endpoint may allow any member to assign the owner role when no owner exists.

Vulnerable
// PRIVESC20-002 — VULNERABLE
router.patch('/orgs/:id/members/:userId/role',
  requireSession, requireRole('admin'),
  async (req, res) => {
    const { role } = req.body;
    // No check: does this leave org with zero owners?
    // No check: is req.user trying to demote the last owner?
    await db.orgMembers.updateRole(req.params.id, req.params.userId, role);
    res.json({ updated: true });
  }
);

Owner role changes require invariant enforcement: Before any role change that could reduce the owner count, verify that the org will still have at least one owner after the change. Owner self-demotion is the most common case; additionally guard against bulk role changes that target all owners simultaneously. Treat the owner count invariant (minimum 1) as a database constraint enforced in an atomic transaction, not just an application-level check.

Fixed
// PRIVESC20-002 — FIXED
// requireRole('owner') for owner-level assignments; atomic transaction checks minimum owner count.
router.patch('/orgs/:id/members/:userId/role',
  requireSession, requireOwner, // only owners can reassign roles
  async (req, res) => {
    const { role } = req.body;
    const targetMember = await db.orgMembers.findByOrgAndUser(req.params.id, req.params.userId);
    if (!targetMember) return res.status(404).json({ error: 'Member not found' });

    await db.transaction(async (tx) => {
      // Count owners before change
      const ownerCount = await tx.orgMembers.countByRole(req.params.id, 'owner');
      const targetIsCurrentOwner = targetMember.role === 'owner';
      const demotingToNonOwner = role !== 'owner';

      // Prevent last owner demotion
      if (targetIsCurrentOwner && demotingToNonOwner && ownerCount <= 1) {
        throw new Error('Cannot demote the last owner. Assign another owner first.');
      }

      await tx.orgMembers.updateRole(req.params.id, req.params.userId, role);
    });
    res.json({ updated: true });
  }
);

PRIVESC20-003 — Permission delegation scope bypass escalates unpossessed permissions

Permission delegation systems that allow users to grant subsets of their own permissions to other users are vulnerable to privilege escalation when the delegation endpoint does not verify that the delegating user actually holds all the permissions they are attempting to delegate. An attacker who holds only skills:read calls POST /api/orgs/:id/permissions/delegate with a payload requesting delegation of admin:all to a second account under their control. If the endpoint only checks that the delegating user is authenticated (not that they hold admin:all), the target account receives admin:all and can perform all administrative operations — deleting skills, managing billing, exporting audit logs — without the delegating user having ever possessed those rights.

Vulnerable
// PRIVESC20-003 — VULNERABLE
router.post('/orgs/:id/permissions/delegate',
  requireSession,
  async (req, res) => {
    const { targetUserId, permissions } = req.body;
    // No scope validation — attacker delegates admin:all they don't hold
    await db.permissionGrants.create({
      orgId: req.params.id,
      grantedBy: req.session.userId,
      grantedTo: targetUserId,
      permissions, // could be ['admin:all'] even if grantedBy only has ['skills:read']
      createdAt: new Date(),
    });
    res.json({ granted: true });
  }
);
Fixed
// PRIVESC20-003 — FIXED
// Verify delegating user holds every permission they are attempting to delegate.
router.post('/orgs/:id/permissions/delegate',
  requireSession,
  async (req, res) => {
    const { targetUserId, permissions } = req.body;

    // Fetch the delegating user's actual permission set from DB
    const delegatorPerms = await db.permissionGrants.getEffectivePermissions(
      req.params.id, req.session.userId
    );
    const delegatorPermSet = new Set(delegatorPerms);

    // Validate every requested permission is held by the delegator
    const unpossessedPerms = permissions.filter(p => !delegatorPermSet.has(p));
    if (unpossessedPerms.length > 0) {
      return res.status(403).json({
        error: 'You cannot delegate permissions you do not hold',
        invalid: unpossessedPerms,
      });
    }

    await db.permissionGrants.create({
      orgId: req.params.id,
      grantedBy: req.session.userId,
      grantedTo: targetUserId,
      permissions,
      createdAt: new Date(),
    });

    await auditLog.write({
      action: 'permission_delegated',
      orgId: req.params.id,
      by: req.session.userId,
      to: targetUserId,
      permissions,
    });

    res.json({ granted: true });
  }
);

PRIVESC20-004 — Temporal access grant expiry not enforced per-request allows indefinite access

Time-limited access grants are commonly used to give contractors or on-call responders temporary elevated access to an organization. The grant is created with an expiresAt timestamp, and the expectation is that access is revoked automatically when the timestamp is reached. When expiry is checked only at login time (at session creation), a user who logs in one minute before the grant expires receives a full-lifetime session token. For a 24-hour session JWT, this means the user retains elevated access for the remaining 23 hours and 59 minutes after the grant expires. The gap between grant expiry and session expiry is an indefinite access window that the grant mechanism was designed to prevent.

Vulnerable
// PRIVESC20-004 — VULNERABLE
// Grant expiry checked at login only — session remains valid after grant expires
async function createSession(userId, orgId) {
  const grant = await db.tempGrants.findActive(userId, orgId);
  if (!grant || new Date(grant.expiresAt) < new Date()) {
    throw new Error('No valid grant');
  }
  // Session token minted here — valid for 24h regardless of grant expiry
  return jwt.sign({ sub: userId, orgId, role: grant.role }, JWT_SECRET, { expiresIn: '24h' });
}

// No per-request grant check — expired grant, active session
router.get('/orgs/:id/admin/members', requireSession, async (req, res) => {
  // Returns admin data even after grant has expired — expiry not re-checked
  const members = await db.orgMembers.findAll(req.params.id);
  res.json(members);
});

Temporal grants require per-request enforcement: The session JWT lifetime and the grant expiry are independent clocks. For temporal grants to work as intended, every request that uses a temporally-granted role must re-verify that the underlying grant has not expired. The simplest implementation is a middleware that checks grant.expiresAt > now on every request for roles sourced from temporary grants, with a short cache TTL (10–30 seconds) to avoid per-request database lookups on hot paths. Grant revocation (early termination) must also invalidate associated sessions — store session IDs in the grant record and revoke on demand.

Fixed
// PRIVESC20-004 — FIXED
// Per-request grant expiry validation via middleware; grant revocation invalidates sessions.
async function requireValidGrant(req, res, next) {
  const decoded = jwt.verify(req.headers.authorization?.split(' ')[1], JWT_SECRET);
  if (!decoded.tempGrantId) return next(); // permanent role — no grant to check

  // Re-validate grant on every request (cached 15s to avoid DB hit on every call)
  const cacheKey = `grant:${decoded.tempGrantId}`;
  let grant = grantCache.get(cacheKey);
  if (!grant) {
    grant = await db.tempGrants.findById(decoded.tempGrantId);
    grantCache.set(cacheKey, grant, 15_000); // 15s TTL
  }

  if (!grant || grant.revokedAt || new Date(grant.expiresAt) < new Date()) {
    return res.status(401).json({ error: 'Temporary access grant has expired or been revoked' });
  }

  req.user = decoded;
  next();
}

router.get('/orgs/:id/admin/members',
  requireSession, requireValidGrant,
  async (req, res) => {
    const members = await db.orgMembers.findAll(req.params.id);
    res.json(members);
  }
);

Related advisories: For privilege escalation in skill publication and verification status endpoints, see SA-SKL-PRIVESC19. For privilege escalation in admin console and system configuration endpoints, see SA-SKL-PRIVESC18. For CORS misconfigurations in skill search and autocomplete suggestion endpoints, see SA-SKL-CORS37.

Scan your MCP server or Claude skill

SkillAudit checks for PRIVESC20, PRIVESC19, CORS, SSRF, injection, and 50+ more vulnerability patterns — in 60 seconds, with a shareable grade badge.

Get early access