Claude MCP skill privilege escalation — team invitation and role assignment — SA-SKL-PRIVESC7
Role management is one of the highest-impact surfaces in a multi-tenant skill registry: a single missing authorization check on the team invitation or role assignment endpoint hands any low-privileged member the ability to crown themselves or a colluding account as org admin. SA-SKL-PRIVESC7 covers four patterns across the invitation and role-assignment lifecycle — missing role cap on invitations, unsecured role assignment accessible to all members, JWT role claim tampering at invite accept, and a concurrent seat-limit race that defeats plan enforcement.
POST /api/orgs/:orgId/invitations with { "role": "admin" } and invite a colluding second account as a full admin, then accept via that account to gain org-level controlPATCH /api/orgs/:orgId/members/:userId checks only that req.user.orgId === orgId (org membership), not admin status; any org member can send { "role": "admin" } for their own userId and become an admin immediately with a single API callrole field directly from verified JWT claims (jwt.verify(token).role) and writes it to the DB without cross-checking the invitation record; the JWT is signed on the invitationId field but the role claim is not part of the signed payload, allowing an attacker to modify role in the token header and escalate to admin at accept timeBackground: role escalation in team invitation flows
MCP skill registries that support multi-tenant organizations commonly expose three tightly-coupled endpoints: one to send invitations, one to accept them, and one to change the role of an existing member. Each of these endpoints must independently enforce the authorization invariant that only an admin may grant admin-level access. When any one of these checks is missing, an attacker with a basic org membership can traverse the entire trust boundary between member and admin. The findings in SA-SKL-PRIVESC7 represent a complete privilege escalation kill-chain: PRIVESC7-001 and PRIVESC7-002 each provide a direct path to admin; PRIVESC7-003 provides an alternative path through the invite-accept flow; and PRIVESC7-004 undermines billing controls independently of role.
These issues differ from the cross-tenant patterns in SA-SKL-PRIVESC6 in that they target the authorization rules within a single organization rather than across organization boundaries. They are also closely related to OAuth2 misconfigurations documented in SA-SKL-AUTH15, where tokens issued with overly broad scopes can be used to call the same role assignment APIs described here without an interactive session at all.
PRIVESC7-001 — CRITICAL — Team invitation endpoint missing role cap
The POST /api/orgs/:orgId/invitations endpoint is designed to let admins invite new team members to an organization. The implementation checks that the invitee email domain matches the organization's configured domain — a reasonable anti-spam guard — but it does not verify that the requesting user holds a role that permits inviting at the requested level. Because the request body carries the target role directly ({ "email": "attacker2@org.example.com", "role": "admin" }), and because the server never inspects req.user.role, any authenticated org member can POST this body and produce a valid admin invitation. The attacker controls a second email address at the organization domain, accepts the invitation, and now has admin access. Because the invitation is a legitimate server-issued invite, it bypasses any front-end role guards entirely.
The fix requires two guards applied together. First, the route must be protected by a middleware that asserts req.user.role === 'admin' before the handler runs at all. Second, as a defense-in-depth measure, the handler should cap the maximum invitable role to the requesting user's own role: a member-level caller (if the middleware is somehow bypassed) should never be able to issue an invitation at a higher level than their own. The role must be read from the database on every request, not from the JWT claims, because JWT claims can be stale or forged.
// VULNERABLE — PRIVESC7-001
// routes/invitations.js
router.post('/api/orgs/:orgId/invitations', requireAuth, async (req, res) => {
const { orgId } = req.params;
const { email, role } = req.body;
// Only checks that the requesting user belongs to this org
if (req.user.orgId !== orgId) {
return res.status(403).json({ error: 'Not a member of this org' });
}
// Validates email domain matches the org domain — good idea, but incomplete
const org = await db.query(
'SELECT domain FROM orgs WHERE id = $1',
[orgId]
);
const emailDomain = email.split('@')[1];
if (emailDomain !== org.rows[0].domain) {
return res.status(400).json({ error: 'Email domain does not match org domain' });
}
// BUG: never checks req.user.role — any org member can invite as admin
// BUG: role comes directly from request body with no cap enforcement
const invite = await db.query(
`INSERT INTO invitations (org_id, email, role, token, expires_at)
VALUES ($1, $2, $3, $4, NOW() + INTERVAL '7 days')
RETURNING id`,
[orgId, email, role, generateInviteToken()]
);
await sendInvitationEmail(email, invite.rows[0].id);
res.status(201).json({ invitationId: invite.rows[0].id });
});
// FIXED — PRIVESC7-001
// middleware/requireRole.js
function requireRole(minRole) {
const hierarchy = { member: 0, admin: 1, owner: 2 };
return async (req, res, next) => {
// Always read role from DB — never trust JWT claims for authorization decisions
const result = await db.query(
'SELECT role FROM org_members WHERE org_id = $1 AND user_id = $2',
[req.params.orgId, req.user.id]
);
if (!result.rows.length) {
return res.status(403).json({ error: 'Not a member of this org' });
}
req.dbRole = result.rows[0].role;
if (hierarchy[req.dbRole] < hierarchy[minRole]) {
return res.status(403).json({ error: `Requires ${minRole} role` });
}
next();
};
}
// routes/invitations.js
router.post(
'/api/orgs/:orgId/invitations',
requireAuth,
requireRole('admin'), // only admins may invite
async (req, res) => {
const { orgId } = req.params;
const { email, role } = req.body;
const org = await db.query(
'SELECT domain FROM orgs WHERE id = $1',
[orgId]
);
const emailDomain = email.split('@')[1];
if (emailDomain !== org.rows[0].domain) {
return res.status(400).json({ error: 'Email domain does not match org domain' });
}
// Cap the invitable role to at most the requester's own role
const hierarchy = { member: 0, admin: 1, owner: 2 };
const allowedRole = hierarchy[role] <= hierarchy[req.dbRole] ? role : req.dbRole;
const invite = await db.query(
`INSERT INTO invitations (org_id, email, role, token, expires_at)
VALUES ($1, $2, $3, $4, NOW() + INTERVAL '7 days')
RETURNING id`,
[orgId, email, allowedRole, generateInviteToken()]
);
await sendInvitationEmail(email, invite.rows[0].id);
res.status(201).json({ invitationId: invite.rows[0].id });
}
);
PRIVESC7-001 impact: Any authenticated org member can produce a valid admin invitation for a colluding second account at the same email domain. The attack requires only one API call and one email acceptance. SkillAudit detects this pattern by calling the invitation endpoint as a member-role test account with { "role": "admin" } in the body and verifying whether the resulting invitation record stores role admin.
PRIVESC7-002 — CRITICAL — Role assignment accessible to any org member
The PATCH /api/orgs/:orgId/members/:userId endpoint is intended to let admins update an existing member's role. The authorization gate checks only that the requesting user's orgId claim matches the URL parameter, confirming they are a member of the organization but not that they hold the admin role required to modify other members' roles. Because the endpoint also does not restrict self-modification, an attacker can send PATCH /api/orgs/org123/members/attacker-user-id with body { "role": "admin" } and immediately escalate their own role. The write succeeds, the JWT issued at next login will carry role: admin, and the attacker has full org control. No second account is needed; the entire exploit is a single authenticated PATCH request.
The fix is to apply the same requireRole('admin') middleware from PRIVESC7-001 to all role assignment routes. Additionally, only the organization owner should be able to assign the owner role, so the middleware should be parameterized by the target role in the body, not just the caller's role. For self-modification, the simplest safe policy is to disallow it entirely: an admin may not demote or promote themselves, only another admin or owner may change their role. This prevents both privilege escalation and accidental lockout.
// VULNERABLE — PRIVESC7-002
// routes/members.js
router.patch('/api/orgs/:orgId/members/:userId', requireAuth, async (req, res) => {
const { orgId, userId } = req.params;
const { role } = req.body;
// BUG: only checks org membership — not admin status
if (req.user.orgId !== orgId) {
return res.status(403).json({ error: 'Not a member of this org' });
}
// BUG: allows self-promotion — attacker sets userId === their own id
// BUG: role value comes from body with no cap
await db.query(
'UPDATE org_members SET role = $1 WHERE org_id = $2 AND user_id = $3',
[role, orgId, userId]
);
res.json({ updated: true });
});
// FIXED — PRIVESC7-002
// routes/members.js
router.patch(
'/api/orgs/:orgId/members/:userId',
requireAuth,
requireRole('admin'), // only admins may change roles
async (req, res) => {
const { orgId, userId } = req.params;
const { role } = req.body;
const VALID_ROLES = ['member', 'admin'];
if (!VALID_ROLES.includes(role)) {
return res.status(400).json({ error: 'Invalid role value' });
}
// Disallow self-modification — prevents self-promotion and accidental lockout
if (userId === req.user.id) {
return res.status(403).json({ error: 'Cannot modify your own role' });
}
// Fetch current role of target from DB to prevent privilege escalation above own level
const target = await db.query(
'SELECT role FROM org_members WHERE org_id = $1 AND user_id = $2',
[orgId, userId]
);
if (!target.rows.length) {
return res.status(404).json({ error: 'Member not found' });
}
// An admin cannot promote someone to owner or demote an owner
const hierarchy = { member: 0, admin: 1, owner: 2 };
if (hierarchy[role] > hierarchy[req.dbRole]) {
return res.status(403).json({ error: 'Cannot assign a role higher than your own' });
}
if (hierarchy[target.rows[0].role] >= hierarchy[req.dbRole]) {
return res.status(403).json({ error: 'Cannot modify a member with equal or higher role' });
}
await db.query(
'UPDATE org_members SET role = $1 WHERE org_id = $2 AND user_id = $3',
[role, orgId, userId]
);
res.json({ updated: true });
}
);
PRIVESC7-002 impact: A single authenticated PATCH request is sufficient for a member-role attacker to become an org admin. No invitation, no second account, no social engineering required. SkillAudit detects this by issuing the PATCH as a member-role session and asserting the response status is 403, then verifying the DB role did not change.
PRIVESC7-003 — HIGH — JWT role claim used at invite accept without DB cross-check
When a user clicks an invitation link, the accept endpoint (POST /api/invitations/accept) receives a signed JWT and calls jwt.verify(token) to authenticate it. The implementation then reads decoded.role from the JWT claims and writes that value directly into the org_members table as the new member's role. The flaw is that the JWT is signed over the invitationId field (a UUID), but the role claim sits in the JWT header or unprotected payload section and is not covered by the same HMAC. An attacker who receives a legitimate member-level invitation can decode the token (Base64), change "role":"member" to "role":"admin" in the claims portion, re-encode the Base64 without altering the signature bytes, and submit it. The server verifies the signature (which covers the invitationId), considers the token valid, and uses the attacker-supplied role to create the new membership record.
The correct fix is to never derive security-relevant attributes from JWT claims when those attributes can be fetched from the database. The JWT should carry only the invitationId UUID. At accept time the server verifies the token's signature, extracts the invitationId, looks up the invitation record in the DB (SELECT role, email, org_id FROM invitations WHERE id = $1 AND used_at IS NULL AND expires_at > NOW()), and uses only the DB-sourced role. The JWT is a bearer token proving the holder was sent the email; all authorization data lives in the server.
// VULNERABLE — PRIVESC7-003
// routes/invitations.js — accept endpoint
router.post('/api/invitations/accept', requireAuth, async (req, res) => {
const { inviteToken } = req.body;
let decoded;
try {
// jwt.verify checks signature — but only the invitationId is part of the signed payload
decoded = jwt.verify(inviteToken, process.env.JWT_SECRET);
} catch (err) {
return res.status(400).json({ error: 'Invalid or expired invitation token' });
}
// BUG: role is read directly from JWT claims
// Attacker can Base64-decode, change role to 'admin', re-encode — signature still valid
// because the signature covers only the invitationId, not the full payload
const { invitationId, role } = decoded;
// Marks invitation as used
const invite = await db.query(
'UPDATE invitations SET used_at = NOW() WHERE id = $1 AND used_at IS NULL RETURNING org_id',
[invitationId]
);
if (!invite.rows.length) {
return res.status(400).json({ error: 'Invitation already used or not found' });
}
// BUG: attacker-controlled role written to org_members
await db.query(
'INSERT INTO org_members (org_id, user_id, role) VALUES ($1, $2, $3)',
[invite.rows[0].org_id, req.user.id, role]
);
res.json({ joined: true, role });
});
// FIXED — PRIVESC7-003
// Token creation: sign a minimal payload — only the UUID
function createInvitationToken(invitationId) {
// The secret covers the entire payload including the invitationId
return jwt.sign({ invitationId }, process.env.INVITE_JWT_SECRET, { expiresIn: '7d' });
}
// routes/invitations.js — accept endpoint
router.post('/api/invitations/accept', requireAuth, async (req, res) => {
const { inviteToken } = req.body;
let decoded;
try {
decoded = jwt.verify(inviteToken, process.env.INVITE_JWT_SECRET);
} catch (err) {
return res.status(400).json({ error: 'Invalid or expired invitation token' });
}
const { invitationId } = decoded;
// Fetch ALL security-relevant attributes from the DB — never from the JWT
const invite = await db.query(
`UPDATE invitations
SET used_at = NOW()
WHERE id = $1
AND used_at IS NULL
AND expires_at > NOW()
RETURNING org_id, role, email`,
[invitationId]
);
if (!invite.rows.length) {
return res.status(400).json({ error: 'Invitation not found, already used, or expired' });
}
const { org_id, role, email } = invite.rows[0];
// Optionally verify the accepting user's email matches the invitation email
if (req.user.email !== email) {
return res.status(403).json({ error: 'This invitation was issued to a different email address' });
}
// Role sourced entirely from DB record — not from JWT claims
await db.query(
'INSERT INTO org_members (org_id, user_id, role) VALUES ($1, $2, $3)',
[org_id, req.user.id, role]
);
res.json({ joined: true, role });
});
PRIVESC7-003 impact: An attacker who receives any legitimate invitation (even as a member) can flip the role claim in the JWT and join as admin. This requires only Base64 manipulation — no JWT secret is needed if the signature covers only the UUID field. SkillAudit detects this by issuing a member-level invitation to a test account, modifying the role claim in the token, and verifying that the accept endpoint rejects it or ignores the modified claim.
PRIVESC7-004 — MEDIUM — Seat-limit race condition at invite accept time
Organizations on the Team plan are capped at 10 seats. The seat count check is implemented in the invitation creation handler: before inserting an invitation record, the endpoint reads COUNT(*) FROM org_members WHERE org_id = $1 and returns 402 if the count is already at the plan limit. The check is not repeated when invitations are accepted. An attacker (or a fast-acting legitimate admin) can send 20 invitation emails to 20 different addresses within the same second. Each POST to the invitation creation endpoint runs in a separate database transaction; each independently reads 10 current members, computes 10 available seats, and approves the invitation creation. All 20 invitations are stored. When all 20 invitees accept, the organization grows to 30 members on a 10-seat plan, bypassing billing controls and potentially causing revenue loss or resource exhaustion on shared infrastructure.
The fix is to enforce the seat limit at the moment of acceptance, not (only) at invite creation. This requires a serializable transaction that acquires a row-level lock on the org's member count before inserting: SELECT COUNT(*) FROM org_members WHERE org_id = $1 FOR UPDATE inside a BEGIN/COMMIT block. The FOR UPDATE clause causes each concurrent accept transaction to queue behind the previous one, ensuring that the count read and the insert are atomic. As an additional safeguard, a CHECK constraint or a database trigger on the org_members table can enforce the hard cap at the storage layer, so no application-level bug can bypass it.
// VULNERABLE — PRIVESC7-004
// routes/invitations.js — creation handler (seat check)
router.post('/api/orgs/:orgId/invitations', requireAuth, requireRole('admin'), async (req, res) => {
const { orgId } = req.params;
// Seat check at invite CREATION time only
const countResult = await db.query(
'SELECT COUNT(*) FROM org_members WHERE org_id = $1',
[orgId]
);
const currentSeats = parseInt(countResult.rows[0].count, 10);
const planLimit = await getPlanSeatLimit(orgId); // returns 10 for Team plan
if (currentSeats >= planLimit) {
return res.status(402).json({ error: 'Seat limit reached. Please upgrade your plan.' });
}
// BUG: 20 concurrent requests all read currentSeats=10 and planLimit=10 above
// All pass the check; all 20 invitations are created.
// No check at accept time — 20 accepts bring org to 30 seats.
const { email, role } = req.body;
// ... (domain check, insert invitation, send email)
});
// routes/invitations.js — accept handler (no seat check)
router.post('/api/invitations/accept', requireAuth, async (req, res) => {
// ... token verification ...
// BUG: no seat limit check here — unlimited accepts possible
await db.query(
'INSERT INTO org_members (org_id, user_id, role) VALUES ($1, $2, $3)',
[org_id, req.user.id, role]
);
res.json({ joined: true });
});
// FIXED — PRIVESC7-004
// routes/invitations.js — accept handler with serializable seat check
router.post('/api/invitations/accept', requireAuth, async (req, res) => {
const { inviteToken } = req.body;
let decoded;
try {
decoded = jwt.verify(inviteToken, process.env.INVITE_JWT_SECRET);
} catch (err) {
return res.status(400).json({ error: 'Invalid or expired invitation token' });
}
const { invitationId } = decoded;
// Use a serializable transaction so the seat count check and the insert are atomic
const client = await db.pool.connect();
try {
await client.query('BEGIN');
// Fetch and lock the invitation record
const invite = await client.query(
`UPDATE invitations
SET used_at = NOW()
WHERE id = $1
AND used_at IS NULL
AND expires_at > NOW()
RETURNING org_id, role, email`,
[invitationId]
);
if (!invite.rows.length) {
await client.query('ROLLBACK');
return res.status(400).json({ error: 'Invitation not found, already used, or expired' });
}
const { org_id, role, email } = invite.rows[0];
if (req.user.email !== email) {
await client.query('ROLLBACK');
return res.status(403).json({ error: 'Invitation issued to a different email address' });
}
// FOR UPDATE acquires a row-level lock — concurrent accepts queue here
// preventing two transactions from both reading seatCount=9 and both inserting
const countResult = await client.query(
'SELECT COUNT(*) FROM org_members WHERE org_id = $1 FOR UPDATE',
[org_id]
);
const currentSeats = parseInt(countResult.rows[0].count, 10);
const planLimit = await getPlanSeatLimit(org_id);
if (currentSeats >= planLimit) {
await client.query('ROLLBACK');
return res.status(402).json({ error: 'Org seat limit reached. Please ask an admin to upgrade the plan.' });
}
await client.query(
'INSERT INTO org_members (org_id, user_id, role) VALUES ($1, $2, $3)',
[org_id, req.user.id, role]
);
await client.query('COMMIT');
res.json({ joined: true, role });
} catch (err) {
await client.query('ROLLBACK');
throw err;
} finally {
client.release();
}
});
Defense in depth for PRIVESC7-004: In addition to the application-level serializable transaction, add a database-level trigger that enforces the seat cap hard: CREATE CONSTRAINT TRIGGER enforce_seat_limit AFTER INSERT ON org_members DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION check_org_seat_limit();. This prevents any application code path — including future endpoints — from bypassing the cap, even if the transaction-level check is accidentally removed.
Summary table
| ID | Severity | Location | Root cause | Fix |
|---|---|---|---|---|
| PRIVESC7-001 | CRITICAL | POST /api/orgs/:orgId/invitations |
No check that requesting user is admin; role in body accepted without cap | Apply requireRole('admin') middleware; cap invitable role to req.dbRole |
| PRIVESC7-002 | CRITICAL | PATCH /api/orgs/:orgId/members/:userId |
Authorization checks only org membership, not admin status; self-modification allowed | Apply requireRole('admin'); forbid self-modification; cap assignable role to caller's role |
| PRIVESC7-003 | HIGH | POST /api/invitations/accept |
Role read from JWT claims; role not included in signed payload; claims can be altered without breaking signature | JWT carries only invitationId; role and all attributes fetched from DB record keyed on that UUID |
| PRIVESC7-004 | MEDIUM | POST /api/invitations/accept |
Seat limit enforced only at invite creation, not at accept; concurrent creates all pass the check | Enforce seat limit at accept time with SELECT … FOR UPDATE inside a serializable transaction; add DB-level trigger as hard cap |
Detection with SkillAudit
SkillAudit's automated scanner covers all four SA-SKL-PRIVESC7 patterns. For PRIVESC7-001 and PRIVESC7-002, SkillAudit provisions a test org with two accounts — one admin and one member — then issues the invitation and role assignment requests from the member session, asserting that both return HTTP 403. For PRIVESC7-003, SkillAudit requests a member-level invitation token, modifies the role claim in the JWT payload, and verifies the accept endpoint does not honor the modified role. For PRIVESC7-004, SkillAudit sends concurrent invitation creation requests at the plan limit boundary using a thread-pool, then attempts to accept all invitations, verifying that the organization's final seat count does not exceed the plan cap.
These checks run as part of the standard SkillAudit role and invitation security suite alongside the cross-tenant checks in SA-SKL-PRIVESC6 and the OAuth2 scope checks in SA-SKL-AUTH15. All findings include reproduction steps, severity ratings, and patch-ready code snippets that map directly to the vulnerable endpoint.
Takeaway: The four PRIVESC7 patterns share a single root cause: authorization decisions are deferred to application code that runs after the data is already committed, or is based on client-supplied values rather than server-side DB state. The universal fix is to enforce every authorization invariant as close to the data layer as possible — preferably at both the middleware layer and the database layer — and to treat the JWT as an identity proof only, never as a source of entitlement data.