← Blog

Claude MCP skill privilege escalation — team management and permission inheritance

SA-SKL-PRIVESC12  |  SkillAudit Security Catalog  |  14 Nov 2026
SA-SKL-PRIVESC12 findings
CRITICALPRIVESC12-001 — Team permission check reads permissions from JWT teams[] array — attacker crafts JWT with teams:[{id:any-team-id,role:"admin"}] gaining team admin for any team without DB membership
HIGHPRIVESC12-002 — Permission inheritance walk is depth-unlimited — attacker creates cyclic group A inherits from B inherits from A; permission check loops forever consuming CPU until OOM or worker timeout (denial of service)
HIGHPRIVESC12-003 — Team member add endpoint POST /api/teams/:id/members missing team-ownership check — any team member adds new members including with role:admin, escalating team-level access
HIGHPRIVESC12-004 — Permission cache key is userId+teamId without orgId — cached permission for user in org A bleeds to same userId+teamId in org B after org-level team rename

PRIVESC12-001 — JWT teams[] claim used for team authorization without DB lookup

When users log in, their JWT includes a teams array: {"teams": [{"id": "team-123", "role": "member"}]}. The team permission middleware reads req.user.teams (populated from the decoded JWT) to determine the caller's role in the requested team, without querying the database. An attacker who obtains the JWT signing secret (or who exploits a JWT algorithm confusion vulnerability) can craft a token with {"teams": [{"id": "target-team-id", "role": "admin"}]} for any team ID in the registry. This grants the attacker admin-level access to that team — including the ability to add or remove team members, modify team access policies for skills, and approve or reject skill deployments — without ever being added to the team in the database.

Vulnerable
// PRIVESC12-001 — VULNERABLE
// Team role read from JWT teams[] array — no DB lookup
// Attacker crafts JWT with any team ID and role:admin
function requireTeamRole(minRole) {
  return (req, res, next) => {
    const teamId = req.params.teamId;
    // req.user.teams comes from JWT payload — attacker can set any team + role
    const membership = req.user.teams?.find(t => t.id === teamId);
    if (!membership) return res.status(403).end();
    const roles = ['viewer', 'member', 'admin'];
    if (roles.indexOf(membership.role) < roles.indexOf(minRole)) {
      return res.status(403).end();
    }
    next(); // attacker passes with crafted JWT claim
  };
}

JWTs are signed, not encrypted — the payload is readable and forgeable with the signing key: Any application that trusts JWT claims for authorization (not just identity) is vulnerable the moment the signing key is leaked. JWT signing keys are frequently found in environment variable dumps, CI/CD logs, error stack traces, and GitHub search results. The correct pattern is to use the JWT subject (sub) claim to identify the user, then fetch that user's current team memberships from the database on every request. The database is the source of truth for permissions; the JWT is a transport mechanism for identity.

Fixed
// PRIVESC12-001 — FIXED
// Team role fetched from DB on every request — JWT used for identity (sub) only
// DB query includes both userId and teamId for a single atomic authorization check

function requireTeamRole(minRole) {
  return async (req, res, next) => {
    const teamId = req.params.teamId;
    const userId = req.user.id; // req.user.id comes from JWT sub — identity only

    // Always fetch current membership from DB — never trust JWT teams[] claim
    const membership = await db.teamMembers.findOne({
      where: { teamId, userId },
      attributes: ['role'],
    });

    if (!membership) return res.status(403).end();

    const roles = ['viewer', 'member', 'admin'];
    if (roles.indexOf(membership.role) < roles.indexOf(minRole)) {
      return res.status(403).end();
    }

    req.teamMembership = membership; // set from DB, not from JWT
    next();
  };
}

PRIVESC12-002 — Depth-unlimited permission walk on cyclic group achieves CPU denial of service

The permission inheritance system allows groups to inherit permissions from parent groups. The permission resolution function recursively walks the inheritance chain without tracking visited nodes or enforcing a maximum depth. An attacker who is a member of any team can create two groups (Group A inheriting from Group B, Group B inheriting from Group A) through the team management API. When the permission system resolves effective permissions for a user in Group A, it recursively resolves Group B, then Group A again, then Group B — entering an infinite loop. The loop runs until the Node.js call stack is exhausted (stack overflow) or the worker process runs out of memory. Because each permission check in the team management UI triggers this resolution, the attacker can initiate a sustained denial of service against the permission resolution worker by creating cyclic group chains.

Vulnerable
// PRIVESC12-002 — VULNERABLE
// Recursive permission walk without visited-set or depth limit
// Cyclic group chain (A→B→A) causes infinite recursion → stack overflow
async function resolveEffectivePermissions(groupId, userId) {
  const group = await db.groups.findById(groupId);
  if (!group) return [];

  const directPerms = await db.groupPermissions.findAll({ where: { groupId, userId } });

  // No visited-set check — if group.parentId creates a cycle, this recurses forever
  const inheritedPerms = group.parentId
    ? await resolveEffectivePermissions(group.parentId, userId) // infinite recursion
    : [];

  return [...directPerms, ...inheritedPerms];
}
Fixed
// PRIVESC12-002 — FIXED
// BFS traversal with visited set — each groupId visited at most once
// Maximum depth of 10 to prevent excessively deep (but non-cyclic) chains
// Cycle detected → error logged + partial permissions returned (fail-open would be worse)

async function resolveEffectivePermissions(startGroupId, userId) {
  const MAX_DEPTH = 10;
  const visited = new Set();
  const queue = [{ groupId: startGroupId, depth: 0 }];
  const allPerms = [];

  while (queue.length > 0) {
    const { groupId, depth } = queue.shift();

    if (visited.has(groupId)) {
      // Cycle detected — log for security monitoring, skip this node
      logger.warn('permission_cycle_detected', { groupId, userId, startGroupId });
      continue;
    }

    if (depth > MAX_DEPTH) {
      logger.warn('permission_depth_exceeded', { groupId, userId, depth });
      break; // stop traversal — do not grant permissions beyond max depth
    }

    visited.add(groupId);

    const group = await db.groups.findById(groupId);
    if (!group) continue;

    const perms = await db.groupPermissions.findAll({ where: { groupId, userId } });
    allPerms.push(...perms);

    if (group.parentId && !visited.has(group.parentId)) {
      queue.push({ groupId: group.parentId, depth: depth + 1 });
    }
  }

  return allPerms;
}

Hierarchical permission systems must enforce cycle detection at both write and read time: The best fix for cyclic permission inheritance is to prevent cycles from being created in the first place (write-time enforcement: before adding a parent group, check that the proposed parent is not already a descendant of the current group). This is a DFS or BFS ancestor check at group creation or parent-assignment time. Combining write-time prevention with read-time visited-set protection gives defence in depth: even if write-time prevention is bypassed, the read-time check prevents infinite loops from causing service outage.

PRIVESC12-003 — Missing team-ownership check on member add enables privilege escalation

The team member add endpoint POST /api/teams/:id/members requires the caller to be a team member (via session authentication) but does not verify that the caller has the admin role within the team. Any team member — including those with the basic member role — can call this endpoint to add new users to the team, including with the admin role. A member role user can therefore escalate themselves to admin by adding themselves with the admin role: they simply call the endpoint with their own user ID and {"role": "admin"}. Because team admins have authority to approve skill deployments, modify team access policies, and add further members, this is a full privilege escalation to team admin from any team member account.

Vulnerable
// PRIVESC12-003 — VULNERABLE
// Any team member can add new members — no admin role check
// Member can add themselves with role:admin → full privilege escalation
router.post('/teams/:id/members',
  requireSession,
  requireTeamMember, // only checks membership, not role
  async (req, res) => {
    const { userId, role } = req.body;
    // No check: if (req.teamMembership.role !== 'admin') return res.status(403).end();
    await db.teamMembers.create({ teamId: req.params.id, userId, role });
    res.status(201).end();
  }
);
Fixed
// PRIVESC12-003 — FIXED
// Admin role required to add members — not just membership
// Cannot add a member with a role higher than your own
// Cannot add yourself (self-escalation prevention)
// Audit log on every member addition

router.post('/teams/:id/members',
  requireSession,
  requireTeamRole('admin'), // from PRIVESC12-001 fix — fetches role from DB
  async (req, res) => {
    const { userId, role } = req.body;

    // Validate role is a valid value
    const validRoles = ['viewer', 'member', 'admin'];
    if (!validRoles.includes(role)) {
      return res.status(400).json({ error: 'invalid role' });
    }

    // Prevent privilege escalation via member-add:
    // Cannot grant a role higher than your own (admin can add admin, but member cannot add admin)
    const callerRoleIndex = validRoles.indexOf(req.teamMembership.role);
    const newMemberRoleIndex = validRoles.indexOf(role);
    if (newMemberRoleIndex > callerRoleIndex) {
      return res.status(403).json({ error: 'cannot grant higher role than your own' });
    }

    // Self-escalation prevention: cannot add yourself to the team you're already in
    if (userId === req.session.userId) {
      return res.status(403).json({ error: 'cannot add yourself' });
    }

    await db.teamMembers.create({ teamId: req.params.id, userId, role });

    await db.auditLog.create({
      action: 'team_member_added',
      actorId: req.session.userId,
      teamId: req.params.id,
      targetUserId: userId,
      grantedRole: role,
      at: new Date(),
    });

    res.status(201).end();
  }
);

PRIVESC12-004 — orgId-less permission cache key bleeds permissions across organizations

The permission cache stores resolved team permissions keyed by `perms:${userId}:${teamId}`. In a multi-tenant skill registry, teams are scoped to organizations — the same teamId UUID could refer to different teams in different organizations if UUIDs are reused (or if an org rename causes a team slug collision). An attacker in organization A who is an admin of team T can ensure their permissions are cached under perms:{userId}:{teamId}. If the same user is subsequently added to organization B which has a team with the same UUID (possible through org transfer or team import), the cache returns the organization A permissions (admin) instead of the organization B permissions (member). The attacker retains admin permissions in organization B without being granted them.

Vulnerable
// PRIVESC12-004 — VULNERABLE
// Cache key missing orgId — permissions cached for userId+teamId bleed across orgs
// If same teamId exists in two orgs (possible via import or UUID reuse),
// org A admin permissions are served for org B membership lookups
async function getCachedPermissions(userId, teamId) {
  const cacheKey = `perms:${userId}:${teamId}`; // missing orgId component
  const cached = await redis.get(cacheKey);
  if (cached) return JSON.parse(cached);

  const perms = await resolveEffectivePermissions(teamId, userId);
  await redis.set(cacheKey, JSON.stringify(perms), 'EX', 300);
  return perms;
}
Fixed
// PRIVESC12-004 — FIXED
// Cache key includes orgId — prevents cross-org permission cache bleed
// orgId fetched from team record in DB — never from request parameter
// Cache invalidated on team membership change, org transfer, and team delete

async function getCachedPermissions(userId, teamId) {
  // Fetch team to get its orgId — this is the authoritative org for this team
  const team = await db.teams.findById(teamId, { attributes: ['id', 'orgId'] });
  if (!team) return [];

  // Include orgId in cache key — prevents bleed if same teamId appears in two orgs
  const cacheKey = `perms:${team.orgId}:${teamId}:${userId}`;
  const cached = await redis.get(cacheKey);
  if (cached) return JSON.parse(cached);

  const perms = await resolveEffectivePermissions(teamId, userId);
  await redis.set(cacheKey, JSON.stringify(perms), 'EX', 300);
  return perms;
}

// Cache invalidation must happen on all membership-changing events:
async function invalidatePermissionCache(orgId, teamId, userId) {
  const pattern = `perms:${orgId}:${teamId}:${userId}`;
  await redis.del(pattern);
  // Also invalidate org-wide cache entries if org-level permissions change
  const orgPattern = `perms:${orgId}:*:${userId}`;
  const keys = await redis.keys(orgPattern);
  if (keys.length > 0) await redis.del(keys);
}

Multi-tenant cache keys must include every tenant dimension: A permission cache entry is only safe to reuse when all dimensions of its identity are the same: user, team, and organization. If any dimension is omitted from the cache key, entries from one tenant context can be served in another. The rule is: if you would include a field in the SQL WHERE clause for the authorization query, include it in the cache key. For team permissions, that means WHERE userId=? AND teamId=? AND orgId=? — and the cache key must reflect all three.

Hardening summary

FindingPatternFix
PRIVESC12-001JWT teams[] claim used for team role authorization without DB lookupFetch team membership and role from DB on every request; JWT for sub identity only
PRIVESC12-002Depth-unlimited recursive permission inheritance walk; cyclic group achieves CPU DoSBFS with visited Set; maximum depth 10; write-time cycle prevention at group creation
PRIVESC12-003Team member add endpoint missing admin role check; any member adds admin-role memberAdmin role required; cannot grant higher role than own; self-escalation prevention; audit log
PRIVESC12-004Permission cache key userId+teamId without orgId; permissions bleed across orgsInclude orgId in cache key; invalidate on membership change, org transfer, team delete

Related: SA-SKL-PRIVESC11, SA-SKL-PRIVESC10. Run SkillAudit to surface all PRIVESC12 patterns in your MCP skill registry.