← Security advisories

Claude MCP skill privilege escalation — skill analytics and metrics access control endpoints — SA-SKL-PRIVESC43

SA-SKL-PRIVESC43 documents four privilege escalation vulnerabilities in MCP skill registry skill analytics and metrics access control endpoints. Analytics and metrics access control systems determine which users can read usage data, revenue figures, churn indicators, and PII-containing behavioral analytics for skills across the registry. PRIVESC43 identifies four distinct escalation paths: JWT analyticsAccessLevel claim forgery granting access to all organizations' commercial metrics; analytics access level self-assignment without boundary enforcement enabling any user to grant themselves analytics_admin; global analytics configuration modification without ownership check allowing any authenticated user to disable PII masking and alter data retention policies; and analytics access level cache key collision enabling privilege bleed across organizational membership changes.

SA-SKL-PRIVESC43 findings at a glance
CRITICALPRIVESC43-001 — analytics access level read from JWT analyticsAccessLevel claim — craft JWT with analyticsAccessLevel:'analytics_admin' grants access to all organizations' usage metrics, revenue data, and churn indicators; fix: DB-backed 60s Map cache keyed on userId; JWT carries only sub; invalidate on level change event
HIGHPRIVESC43-002 — POST /api/analytics/access missing level boundary check — any analytics user assigns analytics_admin level to themselves or others exceeding their own access level; fix: requireSession; validate assigned level does not exceed assigning user's own level; Zod AnalyticsAccessLevelSchema; audit log
HIGHPRIVESC43-003 — PATCH /api/registry/analytics/config missing ownership check — any authenticated user modifies global analytics configuration including data retention periods, PII masking rules, and cross-org data sharing policies; fix: require analytics_admin level; requireSession; audit log
HIGHPRIVESC43-004 — analytics access level cache key uses userId without orgId — cache entries bleed across org membership changes; previously assigned analytics_admin level for org A served when user moves to org B with same sequential integer userId sequence; fix: cache key = orgId:userId; invalidate on org membership change; strict 60s TTL

PRIVESC43-001 — JWT analyticsAccessLevel claim forgery granting cross-org revenue data access

Severity: CRITICAL

The analytics access control middleware reads the user's analytics access level directly from the analyticsAccessLevel claim in the JWT access token. Because the JWT signature verification only ensures that the token was signed by the issuer's private key, any attacker who can obtain a valid JWT (through legitimate authentication) and forge a modified token with an elevated analyticsAccessLevel claim — using a weak or leaked signing key, an algorithm confusion attack on the JWT library, or a misconfigured JWT verification endpoint — can grant themselves analytics_admin level. At analytics_admin level, the middleware grants access to aggregated usage metrics, monthly revenue totals, subscription churn rate indicators, and geographic distribution data for all skills across all organizations in the registry.

Even without a compromised signing key, storing authorization claims in the JWT itself creates a stale data problem: if the actual access level in the database is revoked, the JWT continues to carry the old elevated claim until it expires. The database-backed cache approach (the fix) provides real-time revocability — revoking access in the database immediately prevents access on the next request, without requiring JWT expiry or token blacklisting infrastructure.

The revenue data, churn indicators, and cross-org usage metrics accessible at analytics_admin level represent commercially sensitive information that skill publishers use to make business decisions. An attacker who reads this data can identify skills that are losing users (acquisition targets), skills with high revenue but poor security posture (extortion targets), and skills with declining churn rates (market timing signals) across the entire registry ecosystem.

Never store authorization levels in JWT claims. JWT claims are readable and potentially forgeable — they should carry only the user's identity (sub) and authentication metadata. Authorization levels must be resolved from the database or a database-backed cache on each request, using the JWT sub as the lookup key. This provides real-time revocability and prevents privilege escalation via token claim manipulation.

Vulnerable
// analytics access control reads analyticsAccessLevel from JWT claim
function requireAnalyticsAccess(requiredLevel) {
  return (req, res, next) => {
    const token = req.headers.authorization?.split(' ')[1];
    const decoded = jwt.verify(token, process.env.JWT_SECRET);
    // attacker forges JWT with analyticsAccessLevel: 'analytics_admin'
    const userLevel = decoded.analyticsAccessLevel;
    if (!hasRequiredLevel(userLevel, requiredLevel)) {
      return res.status(403).json({ error: 'Insufficient analytics access level' });
    }
    req.userId = decoded.sub;
    next();
  };
}
Fixed
// analytics access control reads level from DB-backed cache — JWT carries only sub
import { z } from 'zod';

const ANALYTICS_LEVELS = ['none', 'read_own', 'read_org', 'analytics_admin'] as const;
type AnalyticsLevel = typeof ANALYTICS_LEVELS[number];

// DB-backed Map cache: key = userId, value = { level, expiresAt }
const analyticsLevelCache = new Map();

async function resolveAnalyticsLevel(userId: string): Promise {
  const cached = analyticsLevelCache.get(userId);
  if (cached && cached.expiresAt > Date.now()) return cached.level;

  const record = await AnalyticsAccess.findOne({ userId }).select('level');
  const level = (record?.level ?? 'none') as AnalyticsLevel;

  analyticsLevelCache.set(userId, { level, expiresAt: Date.now() + 60_000 }); // 60s TTL
  return level;
}

function requireAnalyticsAccess(requiredLevel: AnalyticsLevel) {
  return async (req: Request, res: Response, next: NextFunction) => {
    const token = req.headers.authorization?.split(' ')[1];
    if (!token) return res.status(401).json({ error: 'Unauthorized' });

    const decoded = jwt.verify(token, process.env.JWT_SECRET!);
    const userId = z.string().parse((decoded as any).sub);
    req.userId = userId;

    const userLevel = await resolveAnalyticsLevel(userId);
    if (!hasRequiredLevel(userLevel, requiredLevel)) {
      return res.status(403).json({ error: 'Insufficient analytics access level' });
    }
    next();
  };
}

PRIVESC43-002 — Analytics access level self-assignment without boundary check

Severity: HIGH

The analytics access level assignment endpoint allows any authenticated user with analytics read access to assign analytics access levels to other users — or to themselves — without checking whether the assigned level exceeds the assigning user's own level. An attacker with read_own level (the default for skill publishers) sends a POST request to /api/analytics/access with targetUserId: <their own userId> and level: 'analytics_admin'. The endpoint creates or updates the target user's access record without enforcing the invariant that you cannot grant a permission you do not yourself hold. The attacker now has analytics_admin level in the database, circumventing the PRIVESC43-001 JWT path and granting persistent elevated access that survives token rotation.

The absence of an audit log on this endpoint makes it difficult to detect after the fact. Without audit records, the registry operators have no way to determine when the escalation occurred, what actions were taken at the elevated level, or which user accounts were involved in the escalation chain. An attacker who escalates their own access and then assigns elevated access to multiple additional accounts creates a privilege escalation fan-out that is not visible until a full database audit is performed.

Access level assignment endpoints must enforce the boundary invariant: you cannot grant a level you do not hold. This is a fundamental authorization principle. All access level assignment endpoints must resolve the assigning user's current access level from the database, compare it to the requested assignment level, and reject any assignment that would grant a level exceeding the assigning user's own. Every successful and failed assignment must be written to an immutable audit log.

Vulnerable
// POST /api/analytics/access — no boundary check, no audit log
router.post('/analytics/access', requireSession, async (req, res) => {
  const { targetUserId, level } = req.body;
  // no check that req.session.userId's level >= level being assigned
  // no check that req.session.userId can assign to targetUserId
  await AnalyticsAccess.findOneAndUpdate(
    { userId: targetUserId },
    { level },
    { upsert: true, new: true }
  );
  return res.json({ assigned: true });
});
Fixed
// POST /api/analytics/access — boundary check + requireSession + Zod + audit log
import { z } from 'zod';

const AnalyticsAccessLevelSchema = z.object({
  targetUserId: z.string().uuid(),
  level: z.enum(ANALYTICS_LEVELS),
});

const LEVEL_ORDER: Record = {
  none: 0, read_own: 1, read_org: 2, analytics_admin: 3,
};

router.post(
  '/analytics/access',
  requireSession,
  requireAnalyticsAccess('analytics_admin'), // only analytics_admin can assign
  async (req: Request, res: Response) => {
    const parsed = AnalyticsAccessLevelSchema.safeParse(req.body);
    if (!parsed.success) return res.status(400).json({ error: parsed.error });

    const actorLevel = await resolveAnalyticsLevel(req.userId);
    if (LEVEL_ORDER[parsed.data.level] > LEVEL_ORDER[actorLevel]) {
      return res.status(403).json({ error: 'Cannot assign level exceeding your own' });
    }

    await AnalyticsAccess.findOneAndUpdate(
      { userId: parsed.data.targetUserId },
      { level: parsed.data.level, assignedBy: req.userId, assignedAt: new Date() },
      { upsert: true, new: true }
    );

    // invalidate cache for the target user
    analyticsLevelCache.delete(parsed.data.targetUserId);

    await AuditLog.create({
      action: 'analytics.access.assigned', actorId: req.userId,
      targetUserId: parsed.data.targetUserId, level: parsed.data.level, at: new Date(),
    });

    return res.json({ assigned: true });
  }
);

PRIVESC43-003 — Global analytics config modification without ownership check

Severity: HIGH

The global analytics configuration endpoint accepts PATCH requests from any authenticated user without checking whether the user has analytics_admin level. Any user with a valid session can modify the global analytics configuration, which controls data retention periods for all organizations in the registry, PII masking rules that determine whether reviewer email addresses and purchase identifiers appear in raw analytics exports, and cross-org data sharing policies that govern whether aggregated usage data can be accessed by research integrations. An attacker who disables PII masking and reduces the data retention period to zero can cause the registry to retroactively expose PII in existing analytics records while simultaneously preventing future records from being retained long enough for auditing.

Modifying cross-org data sharing policies can enable unauthorized third-party integrations to access usage metrics across organizations — an impact equivalent to PRIVESC43-001 but achieved through policy configuration rather than access control bypass. The configuration endpoint represents a lateral escalation path for users who cannot directly reach analytics_admin level through PRIVESC43-001 or PRIVESC43-002 but can still cause registry-wide impact through configuration manipulation.

Global configuration endpoints must enforce the highest access level in the system. Any endpoint that modifies registry-wide configuration — including data retention periods, PII masking rules, and cross-org sharing policies — must require analytics_admin level (or equivalent), enforce session authentication, and write every configuration change to an immutable audit log with the full before and after state of the modified fields.

Vulnerable
// PATCH /api/registry/analytics/config — no ownership check, any authenticated user
router.patch('/registry/analytics/config', requireSession, async (req, res) => {
  const { retentionDays, piiMasking, crossOrgSharing } = req.body;
  // no analytics_admin check — any user can modify global analytics config
  await AnalyticsConfig.findOneAndUpdate(
    { registry: 'default' },
    { retentionDays, piiMasking, crossOrgSharing, updatedAt: new Date() },
    { new: true }
  );
  return res.json({ updated: true });
});
Fixed
// PATCH /api/registry/analytics/config — analytics_admin required + Zod + before/after audit
import { z } from 'zod';

const AnalyticsConfigSchema = z.object({
  retentionDays: z.number().int().min(1).max(730).optional(),
  piiMasking: z.object({
    maskEmail: z.boolean(),
    maskUserId: z.boolean(),
    maskPurchaseId: z.boolean(),
  }).optional(),
  crossOrgSharing: z.object({
    enabled: z.boolean(),
    allowedIntegrationIds: z.array(z.string().uuid()).max(20),
  }).optional(),
});

router.patch(
  '/registry/analytics/config',
  requireSession,
  requireAnalyticsAccess('analytics_admin'),
  async (req: Request, res: Response) => {
    const parsed = AnalyticsConfigSchema.safeParse(req.body);
    if (!parsed.success) return res.status(400).json({ error: parsed.error });

    const before = await AnalyticsConfig.findOne({ registry: 'default' }).lean();
    const after = await AnalyticsConfig.findOneAndUpdate(
      { registry: 'default' },
      { ...parsed.data, updatedBy: req.userId, updatedAt: new Date() },
      { new: true }
    );

    await AuditLog.create({
      action: 'analytics.config.updated', actorId: req.userId,
      before, after, at: new Date(),
    });

    return res.json({ updated: true });
  }
);

PRIVESC43-004 — Analytics access level cache key collision across org membership changes

Severity: HIGH

The analytics access level cache uses only userId as the cache key, without including the current orgId context. When a user is assigned analytics_admin level within organization A and then moves to organization B — through job change, account transfer, or the organization merging with another registry tenant — the cache entry keyed on userId alone continues to serve the previously assigned analytics_admin level for the new organizational context. If organization B uses a sequential integer userId sequence that reuses IDs previously assigned in organization A, a newly registered user in org B may receive a cache hit from a previous user's elevated analytics level before the cache entry expires.

The 60-second TTL on the cache entries means the window for exploitation is bounded, but 60 seconds is sufficient for an attacker who can predict the userId sequence to time a request to coincide with the cache population window. Additionally, if the cache invalidation logic (triggered on access level change) uses only userId as the deletion key, moving a user from one org to another without changing their userId in the access record will not trigger cache invalidation, causing the stale elevated level to persist until natural TTL expiry.

Cache keys for access control data must include all context dimensions that affect the authorization decision. When authorization is org-scoped, the cache key must include both orgId and userId. Cache invalidation must be triggered by all events that change the access control state — including org membership changes, not only direct access level modifications. TTL must be short (60 seconds or less) for all access control caches.

Vulnerable
// analytics access level cache keyed on userId only — bleeds across org membership changes
const analyticsLevelCache = new Map();

async function resolveAnalyticsLevel(userId: string): Promise {
  // cache key = userId only — no orgId context
  const cached = analyticsLevelCache.get(userId);
  if (cached && cached.expiresAt > Date.now()) return cached.level;

  const record = await AnalyticsAccess.findOne({ userId }).select('level');
  const level = (record?.level ?? 'none') as AnalyticsLevel;

  analyticsLevelCache.set(userId, { level, expiresAt: Date.now() + 60_000 });
  return level;
}

// invalidation triggered only on direct access level change — not on org membership change
eventBus.on('analytics.access.level.changed', ({ userId }) => {
  analyticsLevelCache.delete(userId); // only userId key — orgId context not invalidated
});
Fixed
// analytics access level cache keyed on orgId:userId + invalidation on org membership change
const analyticsLevelCache = new Map();

function cacheKey(orgId: string, userId: string): string {
  return `${orgId}:${userId}`;
}

async function resolveAnalyticsLevel(orgId: string, userId: string): Promise {
  const key = cacheKey(orgId, userId);
  const cached = analyticsLevelCache.get(key);
  if (cached && cached.expiresAt > Date.now()) return cached.level;

  // query must scope to both orgId and userId to prevent cross-org bleed
  const record = await AnalyticsAccess.findOne({ orgId, userId }).select('level');
  const level = (record?.level ?? 'none') as AnalyticsLevel;

  analyticsLevelCache.set(key, { level, expiresAt: Date.now() + 60_000 }); // strict 60s TTL
  return level;
}

// invalidate on BOTH access level change AND org membership change
eventBus.on('analytics.access.level.changed', ({ orgId, userId }) => {
  analyticsLevelCache.delete(cacheKey(orgId, userId));
});

eventBus.on('org.membership.changed', ({ orgId, userId }) => {
  // also invalidate old org cache entries for this user
  for (const key of analyticsLevelCache.keys()) {
    if (key.endsWith(`:${userId}`)) analyticsLevelCache.delete(key);
  }
  // force fresh DB lookup for new org context
  analyticsLevelCache.delete(cacheKey(orgId, userId));
});

All four SA-SKL-PRIVESC43 vulnerabilities reflect a consistent pattern of analytics access control decisions that rely on forgeable tokens, miss boundary enforcement, omit ownership checks, or use incomplete cache keys — resulting in privilege escalation paths that grant access to commercially sensitive cross-organizational metrics data. SkillAudit detects PRIVESC43-001 by flagging JWT claim reads used as authorization level values in middleware; PRIVESC43-002 by detecting access level assignment endpoints that do not compare the assigned level against the assigning user's level in the same handler scope; PRIVESC43-003 by detecting PATCH endpoints on configuration routes that lack a requireAnalyticsAccess('analytics_admin') or equivalent middleware call; and PRIVESC43-004 by detecting cache key construction patterns that use only userId without additional scoping dimensions in authorization cache implementations. See also SA-SKL-PRIVESC42 on billing and subscription access control endpoints for the companion escalation chain.

Compound attack chain: PRIVESC43-001 → PRIVESC43-002 → PRIVESC43-003 → PRIVESC43-004

The four PRIVESC43 findings compose into a layered privilege escalation and persistence chain. An attacker with a legitimate skill publisher account first exploits PRIVESC43-001 by crafting a JWT with a forged analyticsAccessLevel: 'analytics_admin' claim. If JWT signing key compromise is not feasible, the attacker alternatively exploits PRIVESC43-002 to self-assign analytics_admin level through the access assignment endpoint's missing boundary check, achieving the same elevated access through the database-backed authorization path rather than the token path.

With analytics_admin level achieved via either PRIVESC43-001 or PRIVESC43-002, the attacker uses PRIVESC43-003 to modify the global analytics configuration — disabling PII masking on existing records to expose reviewer identities and purchase history, reducing data retention periods to destroy evidence of the attack, and enabling cross-org data sharing to a third-party integration ID they control. This provides ongoing access to registry-wide analytics data through a registered integration rather than a compromised user account.

Finally, the attacker exploits PRIVESC43-004 by creating a new account in a different organization and timing the request to coincide with the cache population window for a recently elevated user ID, gaining a brief window of analytics_admin access in the new org context. Combined with the cross-org sharing policy enabled in the previous step, this allows the attacker to establish persistent multi-org analytics access that persists even after their original account is suspended.

SkillAudit detection

SkillAudit's static analysis rules detect all four PRIVESC43 vulnerability classes during CI pipeline scanning. The JWT authorization claim detector flags any expression that reads an authorization-related property (matching patterns like accessLevel, role, permission, admin) from a JWT decoded payload object used in a middleware authorization check. The access level boundary detector flags POST handlers on paths matching /access or /role that do not contain a comparison between the assigned level value and the assigning user's resolved level within the same handler scope. The config ownership detector flags PATCH handlers on paths matching /config or /settings that do not contain a call to requireAnalyticsAccess, requireRole, or an equivalent authorization middleware. The cache key completeness detector flags Map.set() calls in authorization resolvers where the key is a single-dimension user ID string rather than a composite key containing an organizational scope identifier. All findings include remediation snippets and links to this advisory.