Claude MCP skill privilege escalation via role confusion in multi-tenant authorization — SA-SKL-PRIVESC1
Multi-tenant MCP skills frequently embed a user's role in the JWT access token to avoid a database round-trip on every request. This design creates a gap: the role in the token reflects the user's role at login time, not their current role. Combining stale token claims with ORM-level validation hook bypasses, mass assignment vulnerabilities, and GraphQL input type confusion produces four distinct privilege escalation paths — each allowing a regular user to perform admin operations without valid admin credentials. The SA-SKL-PRIVESC1 patterns cover all four paths found in real MCP skill repositories.
The authentication vs authorisation confusion in JWT-based MCP skills
JWTs are designed to prove identity — they tell the server who made the request. When developers also embed authorization data (roles, permissions, plan tier) inside the JWT, the token starts to serve two purposes, and the second one breaks down over the token's lifetime. A role in a JWT is a snapshot of the user's role at the moment of token issuance. If an admin revokes a user's admin role after the token is issued, every subsequent request using that token still passes role checks until the token expires. In skills with long-lived access tokens (24 hours or more), this window is large enough to be exploited deliberately.
The correct model is: use the JWT for authentication only (verify the signature and extract the user ID), then re-fetch the user's current role from the database on requests that require role checks. The extra database query is cheap — a single indexed primary-key lookup — and eliminates the stale-claim class of vulnerabilities entirely.
admin before expiry window; role check passes on stale claim; full admin access grantedpre('save') validates role field; attacker uses findByIdAndUpdate() which skips pre-save hooks; role validation bypassed; role overwritten to admin in DBWHERE userId = req.user.id provides row isolation; attacker includes userId in PATCH body; Prisma spreads body into data object; overwrites another user's record via IDORrole field; resolver spreads input into Prisma update(); attacker passes role: "admin" in mutation body; role overwritten in DB on own accountPRIVESC1-001 — Stale JWT role claim grants admin access after role revocation
When an MCP skill's authorization middleware reads the user's role from req.user.role (populated from the decoded JWT) rather than querying the database, any user who was an admin at token issuance time retains admin access until their token expires — even after an operator downgrades their role. More dangerously, in some implementations developers make role checks against decoded.role before they have verified the JWT signature, or they issue tokens with long expiry times and no revocation list, meaning a leaked token continues to pass role checks indefinitely. The fix is straightforward: use the JWT only for userId extraction, then load the full user record — including the current role — from the database in the middleware.
// VULNERABLE — role read from JWT claim without DB re-fetch
import jwt from 'jsonwebtoken';
export function requireAdmin(req, res, next) {
const token = req.headers.authorization?.split(' ')[1];
const decoded = jwt.verify(token, process.env.JWT_SECRET);
// VULNERABLE: role comes from the token, not from the database
// Attacker who had admin role at token issuance retains admin access
// until token expires, even after operator downgrades their role
if (decoded.role !== 'admin') {
return res.status(403).json({ error: 'Forbidden' });
}
req.user = decoded;
next();
}
// FIXED — verify JWT for userId only; re-fetch role from DB
import jwt from 'jsonwebtoken';
import { db } from './db.js';
export async function requireAdmin(req, res, next) {
try {
const token = req.headers.authorization?.split(' ')[1];
// JWT proves identity only — we extract userId from the token
const { userId } = jwt.verify(token, process.env.JWT_SECRET) as { userId: string };
// Re-fetch current role from DB on every admin-required request
const user = await db.user.findUnique({
where: { id: userId },
select: { id: true, role: true, active: true },
});
if (!user || !user.active || user.role !== 'admin') {
return res.status(403).json({ error: 'Forbidden' });
}
req.user = user; // populated from DB, not from token
next();
} catch (err) {
return res.status(401).json({ error: 'Unauthorized' });
}
}
PRIVESC1-002 — Mongoose pre-save hook bypass via findByIdAndUpdate()
Mongoose's document middleware — pre('save') and post('save') hooks — only fires when a document is saved using the .save() method on a Mongoose document instance. Query middleware like findByIdAndUpdate(), updateOne(), and updateMany() bypasses document middleware entirely. If a developer adds role validation to a pre('save') hook expecting it to protect the role field from mutation, any code path that uses a query update method silently skips that validation. An attacker who finds a user update endpoint that uses findByIdAndUpdate() can include role: "admin" in the update body and have it written to the database without triggering the hook.
// VULNERABLE — pre-save hook validates role but findByIdAndUpdate bypasses it
import mongoose from 'mongoose';
const userSchema = new mongoose.Schema({
email: String,
name: String,
role: { type: String, default: 'user' },
});
// Hook validates role on save() calls only — does NOT fire for query updates
userSchema.pre('save', function(next) {
const allowedRoles = ['user', 'viewer'];
if (!allowedRoles.includes(this.role)) {
return next(new Error(`Invalid role: ${this.role}`));
}
next();
});
const User = mongoose.model('User', userSchema);
// VULNERABLE update route — uses findByIdAndUpdate which skips the pre-save hook
export async function updateUserProfile(userId: string, body: any) {
// attacker sends: { name: "Alice", role: "admin" }
// findByIdAndUpdate skips pre('save') — role validation never runs
return User.findByIdAndUpdate(userId, body, { new: true });
}
// FIXED — explicit field allowlist; use save() for sensitive field changes
import mongoose from 'mongoose';
const User = mongoose.model('User', userSchema);
export async function updateUserProfile(userId: string, body: any) {
// Approach 1: explicit field extraction — role never comes from body
const user = await User.findById(userId);
if (!user) throw new Error('User not found');
// Only allow safe fields; role is NOT in this list
if (body.name !== undefined) user.name = String(body.name).slice(0, 100);
if (body.bio !== undefined) user.bio = String(body.bio).slice(0, 500);
// role, email, passwordHash are NOT settable via this endpoint
// .save() triggers pre('save') hook — role validation fires for all changes
return user.save();
}
// Approach 2: if you must use findByIdAndUpdate, add runValidators and
// replicate role protection as a query middleware
userSchema.pre('findOneAndUpdate', function(next) {
const update = this.getUpdate() as any;
// Strip role from any query-based update
if (update?.role !== undefined) delete update.role;
if (update?.$set?.role !== undefined) delete update.$set.role;
next();
});
PRIVESC1-003 — Prisma mass assignment IDOR via userId in PATCH body
Prisma's update() method requires explicit where and data arguments. Developers commonly write row-level security as where: { id: params.id, userId: req.user.id } — the dual-field WHERE clause ensures a user can only update their own records. The vulnerability appears when the data argument is populated by spreading the entire request body: data: req.body. If req.body contains a userId field, Prisma writes that value to the userId column, overwriting the row's ownership to point at a different user. A subsequent request from the attacker using the victim's userId in the where clause then successfully reads or modifies the victim's record. The fix is to never spread request body into the Prisma data argument — always extract fields explicitly.
// VULNERABLE — req.body spread into Prisma data; userId overwritten via IDOR
import { prisma } from './prisma.js';
export async function updateAudit(req, res) {
const { id } = req.params;
// WHERE clause looks correct — only own records
// But data: req.body lets attacker write userId: "victim-uuid"
// Next request with where: { id: ..., userId: "victim-uuid" } reads victim's record
const audit = await prisma.audit.update({
where: { id, userId: req.user.id },
data: req.body, // VULNERABLE: attacker sends { name: "x", userId: "victim-uuid" }
});
return res.json(audit);
}
// FIXED — explicit field extraction; userId never from request body
import { prisma } from './prisma.js';
import { z } from 'zod';
const UpdateAuditSchema = z.object({
name: z.string().max(200).optional(),
notes: z.string().max(5000).optional(),
status: z.enum(['pending', 'in_progress', 'complete']).optional(),
// userId is intentionally absent — never settable by the user
});
export async function updateAudit(req, res) {
const { id } = req.params;
const parsed = UpdateAuditSchema.safeParse(req.body);
if (!parsed.success) return res.status(400).json({ error: parsed.error });
const audit = await prisma.audit.update({
where: { id, userId: req.user.id }, // userId always from token, never from body
data: parsed.data, // only validated, explicitly typed fields
});
return res.json(audit);
}
PRIVESC1-004 — GraphQL mutation input accepts role field overwriting DB value
GraphQL resolvers that spread the mutation input directly into an ORM update call are vulnerable to any field present in the input type that also maps to a sensitive column. If the UpdateUserInput type includes a role field (perhaps left in during development or copied from an admin mutation type), any authenticated user can call the mutation with role: "admin" and have it written to the database. The GraphQL type system does not enforce field-level authorization — it only validates types and nullability. The resolver must explicitly exclude sensitive fields from the data passed to the ORM, or use a separate input type for each permission level.
# VULNERABLE GraphQL schema — UpdateUserInput includes role field
type Mutation {
updateUser(input: UpdateUserInput!): User!
}
# VULNERABLE: role is in the input type — any user can pass role:"admin"
input UpdateUserInput {
name: String
bio: String
role: String # should not be here for user-facing mutations
}
// VULNERABLE resolver — input spread into Prisma update
export const resolvers = {
Mutation: {
updateUser: async (_: any, { input }: { input: any }, ctx: Context) => {
// attacker sends: mutation { updateUser(input: { name: "x", role: "admin" }) { id role } }
// Prisma writes role: "admin" to the DB row
return ctx.prisma.user.update({
where: { id: ctx.user.id },
data: input, // VULNERABLE: role from input overwrites DB value
});
},
},
};
# FIXED GraphQL schema — separate input types by permission level
type Mutation {
updateUser(input: UpdateUserInput!): User!
adminUpdateUser(input: AdminUpdateUserInput!): User! # admin-only resolver
}
# User-facing input: role is NOT present
input UpdateUserInput {
name: String
bio: String
}
# Admin-only input: includes role, but resolver checks admin role
input AdminUpdateUserInput {
userId: ID!
role: String
active: Boolean
}
// FIXED resolver — explicit field extraction; role derived from session only
export const resolvers = {
Mutation: {
updateUser: async (_: any, { input }: { input: UpdateUserInput }, ctx: Context) => {
// UpdateUserInput type does not include role — TypeScript enforces this
const data: Prisma.UserUpdateInput = {};
if (input.name !== undefined) data.name = input.name.slice(0, 100);
if (input.bio !== undefined) data.bio = input.bio.slice(0, 500);
return ctx.prisma.user.update({
where: { id: ctx.user.id },
data, // role is NOT in data — only user-controlled safe fields
});
},
adminUpdateUser: async (_: any, { input }: any, ctx: Context) => {
// Role derived from DB, not from token — see PRIVESC1-001 fix
if (ctx.user.role !== 'admin') throw new ForbiddenError('Admin only');
return ctx.prisma.user.update({
where: { id: input.userId },
data: {
role: input.role,
active: input.active,
},
});
},
},
};
Detection with SkillAudit
SkillAudit's SA-SKL-PRIVESC1 rule set detects privilege escalation patterns through static analysis of JWT decode call sites, Mongoose and Prisma ORM usage, and GraphQL schema + resolver pairs. The JWT check identifies decoded.role reads without a subsequent DB query before the role comparison. The Mongoose check flags pre('save') hooks that protect sensitive fields while sibling code paths use query update methods on the same model. The Prisma check flags data: req.body or data: input spreads where the source object contains fields that map to ownership or role columns. The GraphQL check identifies input types used in user-facing mutations that share field names with admin input types. See also SA-SKL-AUTH4 for JWT claim confusion patterns in access and refresh token flows.
Run SA-SKL-PRIVESC1 on your skill: Paste your MCP skill's GitHub URL at skillaudit.dev to get a full scan. The free tier covers public repositories and returns a shareable security badge.
| Finding | Severity | Vulnerable pattern | Fix |
|---|---|---|---|
PRIVESC1-001 | Critical | JWT role claim read in authorization check without DB re-fetch; stale admin claim grants access after revocation | Use JWT for userId only; re-fetch user role from DB on every admin-gated request |
PRIVESC1-002 | High | Mongoose pre('save') validates role; findByIdAndUpdate() on same model skips hook; role overwritten | Explicit field extraction before .save(); add pre('findOneAndUpdate') to strip role from query updates |
PRIVESC1-003 | High | Prisma data: req.body spread; attacker includes userId to reassign record ownership (IDOR) | Zod schema for update input that excludes userId; data: parsed.data never raw body |
PRIVESC1-004 | High | GraphQL UpdateUserInput includes role field; resolver spreads input into ORM update; role overwritten | Separate input types per permission level; user-facing input must not include role; admin mutation has own type + role check |