SA-SKL-PRIVESC22 — Privilege Escalation

Privilege Escalation in MCP Skill Registry Organisation Billing and Subscription Management Endpoints

Billing and subscription management endpoints sit at the intersection of access control and revenue integrity. PRIVESC22 covers four patterns — storing the subscription tier as a JWT claim that any attacker with a leaked or guessable secret can self-elevate to Enterprise; applying a tier upgrade to the database before Stripe confirms payment, letting attackers receive Enterprise features for free; storing seat count limits in the JWT where they can be overridden to bypass plan enforcement; and a coupon redemption endpoint that checks only global use counts but not per-organisation redemption history, enabling multi-organisation coupon stacking that drains promotional budget without restriction.

SA-SKL-PRIVESC22 findings
CRITICALPRIVESC22-001 — subscriptionTier stored in JWT claim; attacker crafts subscriptionTier:'enterprise' using leaked or guessable JWT_SECRET; all feature gates return true unlocking unlimited audit runs, SSO, policy export, SBOM generation; fix: JWT carries only sub + orgId; tier fetched from subscriptions table with 60s server-side Map cache; invalidate on billing webhook events
CRITICALPRIVESC22-002 — POST /api/billing/upgrade writes org.subscriptionTier = newTier at payment-intent creation time before Stripe confirms payment; attacker calls endpoint and abandons payment flow, receiving Enterprise tier at no cost; fix: apply tier only inside invoice.paid Stripe webhook handler using atomic UPDATE after constructEvent() signature verification
HIGHPRIVESC22-003 — seatCount stored in JWT claim; attacker crafts seatCount:9999; seat limit middleware if (org.usedSeats >= req.user.seatCount) never fires; unlimited seats provisioned on Free plan; fix: fetch seat_limit from subscriptions table with 30s server-side Map cache; never trust any resource-limit claim from the token
HIGHPRIVESC22-004 — POST /api/billing/redeem-coupon checks only global coupon.usedCount < coupon.maxUses; attacker creates N orgs via email aliases and redeems same coupon N times; fix: coupon_redemptions(coupon_id, org_id) join table with unique index; atomic insert + increment transaction; unique constraint returns 409 on second redemption from the same org

PRIVESC22-001 — JWT subscriptionTier claim grants Enterprise access without payment

The MCP skill registry issues JWTs that embed a subscriptionTier claim alongside the standard sub and orgId identifiers. Every feature gate throughout the application evaluates req.user.subscriptionTier === 'enterprise' against the value decoded directly from the token. The intent was to avoid a database round-trip on every gated request, but the design means that anyone who can produce a validly signed JWT — for example by exploiting a leaked JWT_SECRET from a public repository commit, a misconfigured CI environment variable, or a development secret reused in production — can self-elevate to Enterprise tier with no payment interaction whatsoever. The affected features include unlimited audit runs, SSO provisioning, policy export, and SBOM generation.

Even without a fully leaked secret, low-entropy secrets derived from team names, product names, or simple numeric sequences are realistic targets for offline brute-force using tools like hashcat against captured JWTs. Once an attacker obtains a valid Enterprise JWT for their own orgId, they retain that access indefinitely because JWT expiry is typically set to 24 hours or longer, and the subscription tier is never re-verified against the database on each request. The correct architecture is to remove all authorization claims from JWTs entirely: the token identifies who the caller is, the database determines what they are allowed to do.

Vulnerable
// PRIVESC22-001 — VULNERABLE
// subscriptionTier embedded in JWT — attacker forges claim with any known secret.

const jwt = require('jsonwebtoken');

// Token issuance — tier baked into the payload
function issueToken(user, org) {
  return jwt.sign(
    {
      sub: user.id,
      orgId: org.id,
      subscriptionTier: org.subscriptionTier, // VULNERABLE: authorization claim in JWT
      seatCount: org.seatCount,               // VULNERABLE: resource limit in JWT
    },
    process.env.JWT_SECRET,
    { expiresIn: '24h' }
  );
}

// Feature gate middleware — trusts JWT claim directly
function requireEnterprise(req, res, next) {
  if (req.user.subscriptionTier !== 'enterprise') {
    return res.status(403).json({ error: 'Enterprise plan required' });
  }
  next();
}

// Gated routes — all bypass with a crafted JWT
router.post('/audit/run',         requireEnterprise, runAuditHandler);
router.post('/sso/provision',     requireEnterprise, ssoProvisionHandler);
router.get('/policy/export',      requireEnterprise, policyExportHandler);
router.post('/sbom/generate',     requireEnterprise, sbomGenerateHandler);
Fixed
// PRIVESC22-001 — FIXED
// 1. JWT carries only sub (userId) and orgId — no authorization claims.
// 2. subscriptionTier fetched from DB on each gated request via 60s server-side Map cache.
// 3. Cache invalidated on Stripe billing webhook events.

const jwt = require('jsonwebtoken');

// Minimal token — identity only, no entitlements
function issueToken(user, org) {
  return jwt.sign(
    { sub: user.id, orgId: org.id },
    process.env.JWT_SECRET,
    { expiresIn: '1h' }
  );
}

// Server-side tier cache — keyed on orgId, 60s TTL
const tierCache = new Map(); // orgId -> { tier, expiresAt }

async function getSubscriptionTier(orgId) {
  const cached = tierCache.get(orgId);
  if (cached && cached.expiresAt > Date.now()) return cached.tier;
  const row = await db.query(
    'SELECT tier FROM subscriptions WHERE org_id = $1 AND status = $2',
    [orgId, 'active']
  );
  const tier = row?.tier ?? 'free';
  tierCache.set(orgId, { tier, expiresAt: Date.now() + 60_000 });
  return tier;
}

// Cache invalidation on billing events
async function handleBillingWebhook(event) {
  const orgId = event.data.object.metadata?.orgId;
  if (orgId) tierCache.delete(orgId); // force fresh DB read on next gated request
}

// Feature gate middleware — always reads from DB (cached)
async function requireEnterprise(req, res, next) {
  const tier = await getSubscriptionTier(req.user.orgId);
  if (tier !== 'enterprise') {
    return res.status(403).json({ error: 'Enterprise plan required' });
  }
  next();
}

// Gated routes — unchanged interface, secure implementation
router.post('/audit/run',         requireEnterprise, runAuditHandler);
router.post('/sso/provision',     requireEnterprise, ssoProvisionHandler);
router.get('/policy/export',      requireEnterprise, policyExportHandler);
router.post('/sbom/generate',     requireEnterprise, sbomGenerateHandler);

PRIVESC22-002 — Subscription upgrade endpoint applies tier change before payment confirmation

The subscription upgrade endpoint POST /api/billing/upgrade was designed to follow a two-step flow: create a Stripe payment intent, then wait for the invoice.paid webhook to confirm that the payment completed before activating the new tier. In practice the implementation writes org.subscriptionTier = req.body.newTier to the database immediately after calling Stripe.paymentIntents.create(), trusting that the client will complete the payment UI step. An attacker calls the endpoint, receives the HTTP 200 response with the payment intent client secret, and simply never calls Stripe to complete the payment. The database already reflects the Enterprise tier upgrade at that point and there is no background job or webhook handler that reverts it on payment failure.

The Stripe webhook handler for invoice.paid was present in the codebase but only used to send a confirmation email, not to gate the actual tier activation. This is a classic time-of-check to time-of-use pattern applied to billing: the check (Stripe payment confirmation) and the use (setting the database tier) are separated in time and the application took the optimistic path, assuming payment would succeed. The fix requires inverting the control: the database tier must only ever be written from inside the invoice.paid and customer.subscription.updated webhook handlers, using an atomic conditional update that guards on stripe_subscription_id and status = 'active' to prevent replay attacks. The upgrade endpoint itself should return only the payment intent client secret and store the requested target tier as a pending field that the webhook then promotes to active.

Vulnerable
// PRIVESC22-002 — VULNERABLE
// Tier written to DB immediately at intent creation — payment step is never enforced.

router.post('/api/billing/upgrade', requireAuth, async (req, res) => {
  const { newTier } = req.body;
  const org = await db.orgs.findById(req.user.orgId);

  // Create payment intent first
  const paymentIntent = await stripe.paymentIntents.create({
    amount: TIER_PRICES[newTier],
    currency: 'usd',
    customer: org.stripeCustomerId,
    metadata: { orgId: org.id, newTier },
  });

  // VULNERABLE: tier applied immediately, payment not yet confirmed
  await db.orgs.update(
    { subscriptionTier: newTier }, // ← written before invoice.paid fires
    { where: { id: org.id } }
  );

  res.json({ clientSecret: paymentIntent.client_secret });
});

// Webhook handler only sends email — does NOT gate tier activation
router.post('/api/billing/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
  const event = stripe.webhooks.constructEvent(req.body, req.headers['stripe-signature'], process.env.STRIPE_WEBHOOK_SECRET);
  if (event.type === 'invoice.paid') {
    const orgId = event.data.object.metadata.orgId;
    await sendUpgradeConfirmationEmail(orgId); // ← does nothing to DB
  }
  res.json({ received: true });
});
Fixed
// PRIVESC22-002 — FIXED
// 1. Upgrade endpoint stores ONLY pending target tier — never writes active tier.
// 2. Active tier written exclusively inside invoice.paid webhook after constructEvent().
// 3. Atomic UPDATE with stripe_subscription_id guard prevents replay.

router.post('/api/billing/upgrade', requireAuth, async (req, res) => {
  const { newTier } = req.body;
  const org = await db.orgs.findById(req.user.orgId);

  if (!VALID_TIERS.includes(newTier)) {
    return res.status(400).json({ error: 'Invalid tier' });
  }

  const paymentIntent = await stripe.paymentIntents.create({
    amount: TIER_PRICES[newTier],
    currency: 'usd',
    customer: org.stripeCustomerId,
    metadata: { orgId: org.id, newTier },
  });

  // Store ONLY as pending — never activate before payment confirmed
  await db.subscriptions.update(
    { pendingTier: newTier, pendingIntentId: paymentIntent.id },
    { where: { org_id: org.id } }
  );

  res.json({ clientSecret: paymentIntent.client_secret });
});

// Webhook handler is the ONLY place where tier activation occurs
router.post('/api/billing/webhook', express.raw({ type: 'application/json' }), async (req, res) => {
  let event;
  try {
    event = stripe.webhooks.constructEvent(
      req.body,
      req.headers['stripe-signature'],
      process.env.STRIPE_WEBHOOK_SECRET // verifies signature — rejects replays
    );
  } catch (err) {
    return res.status(400).json({ error: 'Webhook signature invalid' });
  }

  if (event.type === 'invoice.paid' || event.type === 'customer.subscription.updated') {
    const { orgId, newTier } = event.data.object.metadata;
    const stripeSubId = event.data.object.subscription;

    // Atomic conditional update — only promotes if subscription is active
    await db.query(
      `UPDATE subscriptions
         SET tier = $1, pending_tier = NULL, pending_intent_id = NULL, updated_at = NOW()
       WHERE org_id = $2
         AND stripe_subscription_id = $3
         AND status = 'active'`,
      [newTier, orgId, stripeSubId]
    );

    // Invalidate server-side tier cache
    tierCache.delete(orgId);
  }

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

PRIVESC22-003 — JWT seatCount claim bypasses seat limit enforcement on Free plan

Seat count limits are the per-plan resource boundary that prevents Free-tier organisations from provisioning more user accounts than their plan allows. The seat limit middleware reads the allowed seat count from req.user.seatCount, which is decoded from the JWT in exactly the same way as the subscription tier in PRIVESC22-001. The guard condition if (org.usedSeats >= req.user.seatCount) return 403 never triggers when an attacker presents a JWT with seatCount: 9999, because usedSeats will never reach that threshold on a real organisation. The result is that any Free-plan organisation whose JWT secret is known or guessable can provision an arbitrary number of seats, consuming infrastructure resources and potentially using provisioned accounts to exceed audit-run rate limits as well.

The same architectural fix applies as for PRIVESC22-001: the JWT should carry only the caller’s identity, and resource limits must be fetched from the authoritative source — in this case the subscriptions table. A 30-second server-side cache is appropriate for seat limits because provisioning events are less frequent than arbitrary API calls and a brief lag between a plan downgrade and enforcement is an acceptable trade-off. The cache should be invalidated whenever a billing webhook event signals a subscription change so that limit reductions take effect within one cache TTL.

Vulnerable
// PRIVESC22-003 — VULNERABLE
// seatCount embedded in JWT — attacker forges seatCount:9999 to bypass limit.

// Token issuance — seat limit baked into payload
function issueToken(user, org) {
  return jwt.sign(
    {
      sub: user.id,
      orgId: org.id,
      subscriptionTier: org.subscriptionTier,
      seatCount: org.seatLimit, // VULNERABLE: resource limit in JWT
    },
    process.env.JWT_SECRET,
    { expiresIn: '24h' }
  );
}

// Seat limit middleware — trusts JWT claim directly
async function enforceSeatLimit(req, res, next) {
  const org = await db.orgs.findById(req.user.orgId);
  // VULNERABLE: req.user.seatCount comes from JWT — attacker controls this value
  if (org.usedSeats >= req.user.seatCount) {
    return res.status(403).json({ error: 'Seat limit reached. Upgrade your plan.' });
  }
  next();
}

router.post('/api/orgs/:orgId/members/invite', requireAuth, enforceSeatLimit, inviteMemberHandler);
Fixed
// PRIVESC22-003 — FIXED
// 1. JWT carries only sub and orgId — no resource-limit claims.
// 2. seat_limit fetched from subscriptions table with 30s server-side Map cache.
// 3. Cache invalidated on billing webhook events.

const seatCache = new Map(); // orgId -> { seatLimit, expiresAt }

async function getSeatLimit(orgId) {
  const cached = seatCache.get(orgId);
  if (cached && cached.expiresAt > Date.now()) return cached.seatLimit;
  const row = await db.query(
    'SELECT seat_limit FROM subscriptions WHERE org_id = $1 AND status = $2',
    [orgId, 'active']
  );
  const seatLimit = row?.seat_limit ?? FREE_PLAN_SEAT_LIMIT;
  seatCache.set(orgId, { seatLimit, expiresAt: Date.now() + 30_000 });
  return seatLimit;
}

// Cache invalidation reused from billing webhook handler
async function handleBillingWebhook(event) {
  const orgId = event.data.object.metadata?.orgId;
  if (orgId) {
    tierCache.delete(orgId);
    seatCache.delete(orgId); // invalidate seat limit cache as well
  }
}

// Seat limit middleware — always reads from DB (cached)
async function enforceSeatLimit(req, res, next) {
  const [org, seatLimit] = await Promise.all([
    db.orgs.findById(req.user.orgId),
    getSeatLimit(req.user.orgId), // authoritative value from subscriptions table
  ]);
  if (org.usedSeats >= seatLimit) {
    return res.status(403).json({ error: 'Seat limit reached. Upgrade your plan.' });
  }
  next();
}

router.post('/api/orgs/:orgId/members/invite', requireAuth, enforceSeatLimit, inviteMemberHandler);

PRIVESC22-004 — Coupon redemption endpoint missing per-org uniqueness check enables multi-org discount abuse

Promotional coupon codes issued by the SkillAudit billing system carry a maxUses limit that is intended to cap total redemptions across the entire customer base. The redemption endpoint POST /api/billing/redeem-coupon validates that coupon.usedCount < coupon.maxUses before applying the discount, then increments usedCount. However it performs no check for whether the redeeming organisation has already claimed this coupon. An attacker can register multiple organisations using email sub-addressing (e.g., attacker+1@gmail.com, attacker+2@gmail.com) and redeem the same promotional code from each organisation, applying the full discount to each org’s subscription. If maxUses is set to 100, a single attacker can drain all 100 uses, preventing any legitimate customer from benefiting from the promotion.

The correct fix is a normalised coupon_redemptions join table with columns coupon_id, org_id, and redeemed_at, protected by a unique index on (coupon_id, org_id). The insert into this table and the increment of coupon.usedCount must occur inside a single atomic database transaction so that a concurrent redemption from the same org cannot race past the uniqueness check. The database unique constraint will cause any second insert from the same org to fail with a constraint violation, which the application catches and returns as a 409 response with no discount applied. Additionally the endpoint should validate that the redeeming organisation’s billing email domain matches any domain restriction stored on the coupon record, preventing unintended redemption by organisations outside a targeted promotional campaign.

Vulnerable
// PRIVESC22-004 — VULNERABLE
// Only global usedCount checked — same coupon redeemable from N orgs via email aliases.

router.post('/api/billing/redeem-coupon', requireAuth, async (req, res) => {
  const { couponCode } = req.body;
  const org = await db.orgs.findById(req.user.orgId);

  const coupon = await db.coupons.findOne({ where: { code: couponCode, active: true } });
  if (!coupon) return res.status(404).json({ error: 'Coupon not found' });

  // VULNERABLE: only checks global usedCount — no per-org redemption history
  if (coupon.usedCount >= coupon.maxUses) {
    return res.status(409).json({ error: 'Coupon fully redeemed' });
  }

  // Apply discount to org subscription via Stripe
  await stripe.subscriptions.update(org.stripeSubscriptionId, {
    coupon: coupon.stripeId,
  });

  // Increment global counter — no record of which orgs have redeemed
  await db.coupons.increment('usedCount', { where: { id: coupon.id } });

  res.json({ applied: true, discountPercent: coupon.discountPercent });
});
Fixed
// PRIVESC22-004 — FIXED
// 1. coupon_redemptions(coupon_id, org_id) join table with unique index on (coupon_id, org_id).
// 2. Atomic transaction: insert redemption record + increment usedCount together.
// 3. Unique constraint violation on duplicate insert → 409 response, no discount applied.
// 4. Validate redeeming org's billing email domain against coupon domain restriction.

router.post('/api/billing/redeem-coupon', requireAuth, async (req, res) => {
  const { couponCode } = req.body;
  const org = await db.orgs.findById(req.user.orgId);

  const coupon = await db.coupons.findOne({ where: { code: couponCode, active: true } });
  if (!coupon) return res.status(404).json({ error: 'Coupon not found' });

  // Validate domain restriction if coupon targets a specific company domain
  if (coupon.allowedDomain) {
    const orgEmailDomain = org.billingEmail.split('@')[1]?.toLowerCase();
    if (orgEmailDomain !== coupon.allowedDomain.toLowerCase()) {
      return res.status(403).json({ error: 'Coupon not valid for your organisation' });
    }
  }

  // Atomic transaction: unique index on (coupon_id, org_id) prevents double-redemption
  const pgClient = await db.pool.connect();
  try {
    await pgClient.query('BEGIN');

    // Check global cap inside transaction for consistency
    const { rows } = await pgClient.query(
      'SELECT used_count, max_uses FROM coupons WHERE id = $1 FOR UPDATE',
      [coupon.id]
    );
    if (rows[0].used_count >= rows[0].max_uses) {
      await pgClient.query('ROLLBACK');
      return res.status(409).json({ error: 'Coupon fully redeemed' });
    }

    // Insert redemption record — unique index on (coupon_id, org_id) throws on duplicate
    await pgClient.query(
      'INSERT INTO coupon_redemptions (coupon_id, org_id, redeemed_at) VALUES ($1, $2, NOW())',
      [coupon.id, org.id]
      // Unique constraint: CREATE UNIQUE INDEX ON coupon_redemptions(coupon_id, org_id)
    );

    // Increment global counter atomically in the same transaction
    await pgClient.query(
      'UPDATE coupons SET used_count = used_count + 1 WHERE id = $1',
      [coupon.id]
    );

    await pgClient.query('COMMIT');
  } catch (err) {
    await pgClient.query('ROLLBACK');
    // Unique constraint violation code 23505 — org already redeemed this coupon
    if (err.code === '23505') {
      return res.status(409).json({ error: 'Your organisation has already redeemed this coupon' });
    }
    throw err;
  } finally {
    pgClient.release();
  }

  // Apply discount via Stripe only after DB transaction committed
  await stripe.subscriptions.update(org.stripeSubscriptionId, {
    coupon: coupon.stripeId,
  });

  res.json({ applied: true, discountPercent: coupon.discountPercent });
});

Related findings