SA-SKL-DESER17 — Insecure Deserialization

Insecure deserialization in MCP skill registry webhook event queue and delivery retry pipeline

SA-SKL-DESER17 documents four deserialization vulnerabilities across the webhook infrastructure of an MCP skill registry. A MessagePack prototype pollution vector in the BullMQ event queue allows Redis-level write access to escalate request context privileges; an unchecked retry job schema enables infinite delivery loops that exhaust webhook endpoint rate limits; a BSON type coercion bug in the S3 archive path silently deletes webhook payloads on ingest; and an unsigned base64 replay token allows an attacker to replay arbitrary past webhook events with attacker-controlled metadata.

SA-SKL-DESER17 findings at a glance
Critical DESER17-001 — MessagePack BullMQ queue event merged via Object.assign into request context — attacker with Redis write access injects __proto__.isAdmin:true, escalating MCP skill worker privilege
High DESER17-002 — Redis stream retry job read via JSON.parse + spread without schema validation — attacker injects retryCount:-9999 and nextRetryAt:0, triggering infinite immediate retries that exhaust webhook rate limits
High DESER17-003 — Failed webhook payload archived to S3 as BSON — BSON Timestamp at createdAt returns unexpected integer value; negative age calculation triggers immediate TTL expiry deletion of valid payloads
High DESER17-004 — Webhook replay token is base64-encoded JSON with no HMAC — attacker crafts token with arbitrary eventId and far-future expiresAt to replay any past webhook event without restriction

DESER17-001: MessagePack prototype pollution via BullMQ queue Object.assign

The MCP skill registry stores webhook events in a BullMQ queue backed by Redis, serialized as MessagePack for compactness. When the worker dequeues a job it unpacks the MessagePack bytes back into a JavaScript object and merges that object into the request context using Object.assign(ctx, decodedEvent). MessagePack does not enforce a schema — any key-value pair valid in the encoding is accepted. An attacker who gains Redis write access (via a compromised internal service, a misconfigured Redis ACL, or a Redis SSRF) can insert a specially crafted MessagePack payload containing the key __proto__ with a nested object {"isAdmin": true}. When this payload is decoded and merged via Object.assign, the prototype chain of the target object is poisoned, causing every subsequent ctx.isAdmin check in the worker process to return true.

The practical impact is worker-level privilege escalation. After a successful poison payload is processed, every subsequent webhook job processed by that worker instance inherits the poisoned prototype, meaning all authorization checks that test ctx.isAdmin will pass for all events until the worker is restarted. In a horizontally scaled deployment, an attacker who can inject into the Redis queue can eventually poison all worker instances. Privileged worker operations in MCP skill registries often include issuing new skill signing certificates, modifying skill metadata records, and triggering registry-wide re-audits — all of which become accessible to the attacker's injected events.

// VULNERABLE — deser17-001
// workers/webhookWorker.js
const { decode } = require('@msgpack/msgpack');

worker.process(async (job) => {
  // Decode MessagePack bytes from Redis queue
  const decodedEvent = decode(job.data.payload);

  // Object.assign with untrusted data — prototype pollution vector
  // If decodedEvent contains __proto__: {isAdmin: true}, all future
  // ctx.isAdmin checks in this process will return true
  const ctx = {};
  Object.assign(ctx, decodedEvent);

  if (ctx.isAdmin) {
    await issueSkillSigningCert(ctx);  // reached by any poisoned event
  }
  await deliverWebhook(ctx);
});

Fix DESER17-001: Never use Object.assign or spread (...decoded) to merge deserialized queue data into a context object. Instead, create the context object using Object.create(null) to produce a null-prototype target that cannot be polluted, then validate the decoded payload with a strict Zod schema before reading any fields. The Zod schema must reject unknown keys (.strict()) and must not include __proto__, constructor, or prototype as valid field names. Explicitly extract only the required fields by name.

// FIXED — deser17-001
// workers/webhookWorker.js
const { decode } = require('@msgpack/msgpack');
const { z } = require('zod');

const WebhookEventSchema = z.object({
  eventId: z.string().uuid(),
  orgId: z.string().uuid(),
  skillId: z.string().uuid(),
  eventType: z.enum(['audit.complete', 'finding.new', 'skill.published']),
  payload: z.record(z.unknown()),
  triggeredAt: z.number().int().positive(),
}).strict(); // reject unknown keys including __proto__

worker.process(async (job) => {
  const raw = decode(job.data.payload);
  // Null-prototype target prevents prototype pollution
  const safeRaw = Object.assign(Object.create(null), raw);
  const event = WebhookEventSchema.parse(safeRaw); // throws on invalid shape

  // isAdmin is never part of the queue payload — derived from DB only
  const isAdmin = await db.users.checkAdminRole(event.orgId);
  if (isAdmin) await issueSkillSigningCert(event);
  await deliverWebhook(event);
});

DESER17-002: Unchecked retry context injection causes infinite delivery loop

When a webhook delivery fails, the MCP skill registry pushes a retry job to a Redis stream. The retry worker reads these jobs by calling xread on the stream, parses the stored JSON with JSON.parse, and spreads the result into a retry context object: const retryCtx = { ...JSON.parse(jobData) }. The retry context carries two fields that control delivery scheduling: retryCount (how many deliveries have been attempted so far) and nextRetryAt (the Unix timestamp in milliseconds at which the next attempt should fire). Neither field is validated after deserialization. An attacker who can write to the Redis stream injects a job with retryCount: -9999 and nextRetryAt: 0 — a timestamp in the past, January 1 1970.

The retry worker's scheduling logic tests whether Date.now() >= retryCtx.nextRetryAt before delivering, which is immediately true for nextRetryAt: 0. After delivery it increments retryCount from -9999, so it reaches the maximum allowed retry count (typically 10) only after 10,009 iterations. During those iterations the worker hammers the target webhook endpoint at the maximum possible rate, consuming the endpoint's rate limit budget and preventing legitimate events from being delivered. In multi-tenant MCP registries the attack can target a specific organization's webhook endpoint, causing a selective denial of service against that organization's audit notification pipeline while the attacker's own events continue to deliver normally.

// VULNERABLE — deser17-002
// workers/retryWorker.js
const redis = require('../lib/redis');

async function processRetryStream() {
  const entries = await redis.xread('COUNT', 10, 'STREAMS', 'webhook:retry', '$');
  for (const [, messages] of entries) {
    for (const [id, fields] of messages) {
      // No schema validation — retryCount and nextRetryAt are trusted as-is
      const retryCtx = { ...JSON.parse(fields.job) };

      if (Date.now() >= retryCtx.nextRetryAt) {
        await deliverWebhook(retryCtx);
        retryCtx.retryCount++;  // -9999 + 1 = -9998, never reaches max
        await scheduleNextRetry(retryCtx);
      }
    }
  }
}

Fix DESER17-002: Apply a Zod RetryJobSchema that uses z.number().int().min(0).max(10) for retryCount and z.number().int().min(Date.now()) for nextRetryAt. The minimum for nextRetryAt should be evaluated at parse time as current time + 1000ms to prevent immediate retries. Any job that fails schema validation must be moved to a dead-letter queue rather than retried. Additionally, enforce a hard cap of 10 retries by checking against a DB-stored canonical attempt count, never the value that arrived from the queue.

// FIXED — deser17-002
// workers/retryWorker.js
const redis = require('../lib/redis');
const { z } = require('zod');

const RetryJobSchema = z.object({
  eventId: z.string().uuid(),
  orgId: z.string().uuid(),
  webhookUrl: z.string().url(),
  // retryCount must be 0–10; never negative, never attacker-controlled max
  retryCount: z.number().int().min(0).max(10),
  // nextRetryAt must be at least 1 second in the future
  nextRetryAt: z.number().int().refine(
    (v) => v >= Date.now() + 1000,
    { message: 'nextRetryAt must be at least 1 second in the future' }
  ),
}).strict();

async function processRetryStream() {
  const entries = await redis.xread('COUNT', 10, 'STREAMS', 'webhook:retry', '$');
  for (const [, messages] of entries) {
    for (const [id, fields] of messages) {
      let job;
      try {
        job = RetryJobSchema.parse(JSON.parse(fields.job));
      } catch {
        await redis.xadd('webhook:dlq', '*', 'job', fields.job, 'reason', 'schema_invalid');
        continue;
      }
      if (Date.now() >= job.nextRetryAt) {
        await deliverWebhook(job);
      }
    }
  }
}

DESER17-003: BSON Timestamp type coercion causes negative age and silent TTL deletion

When a webhook delivery fails permanently after all retries are exhausted, the MCP skill registry archives the original payload to S3 as a BSON document for post-mortem analysis. The archive pipeline reads these BSON documents back and applies a TTL policy: payloads older than 90 days are deleted. The age calculation is const ageMs = Date.now() - doc.createdAt. The bug is that BSON's Timestamp type — distinct from BSON's Date type — does not convert to a Unix millisecond epoch when coerced to a number. Instead, it converts to a combined 64-bit value encoding an increment counter in the low 32 bits and a seconds-since-epoch value in the high 32 bits. When the BSON library deserializes a Timestamp and the JavaScript code reads .createdAt, it receives a large integer — often larger than Date.now() — producing a negative age.

When ageMs is negative, the condition ageMs > TTL_MS is false, so the payload should be retained. However, a secondary branch in the archival code uses Math.abs(ageMs) > ANOMALY_THRESHOLD_MS to detect clock skew and flags those documents for immediate deletion as "corrupted". A BSON Timestamp with a high combined value will trigger this anomaly branch, causing valid webhook payloads to be silently deleted within seconds of archival. This means failed webhooks that should be preserved for investigation disappear immediately, eliminating the organization's ability to audit or replay the events. The root cause is that the ingest pipeline never normalizes BSON types to plain JavaScript primitives before storing to S3.

// VULNERABLE — deser17-003
// workers/archiveWorker.js
const BSON = require('bson');
const s3 = require('../lib/s3');

const TTL_MS = 90 * 24 * 60 * 60 * 1000;         // 90 days
const ANOMALY_THRESHOLD_MS = 30 * 24 * 60 * 60 * 1000; // 30 days

async function applyTTL(s3Key) {
  const buf = await s3.getObject(s3Key);
  // BSON.deserialize returns Timestamp objects, not plain numbers
  const doc = BSON.deserialize(buf);

  // doc.createdAt may be a BSON Timestamp — not a Unix ms integer
  // Combined 64-bit value is >> Date.now(), so ageMs goes negative
  const ageMs = Date.now() - doc.createdAt;

  if (ageMs > TTL_MS) {
    await s3.deleteObject(s3Key);
  } else if (Math.abs(ageMs) > ANOMALY_THRESHOLD_MS) {
    // Silently deletes valid payloads with BSON Timestamp at createdAt
    await s3.deleteObject(s3Key);
  }
}

Fix DESER17-003: Store webhook archive payloads as plain JSON, never as BSON. If BSON is required at the storage layer, convert all BSON types to primitives at ingest time before writing to S3: use doc.createdAt instanceof BSON.Timestamp ? doc.createdAt.toNumber() * 1000 : Number(doc.createdAt) to normalize timestamps. Apply a Zod schema post-parse to enforce that createdAt is a plain number within a plausible range (e.g. after 2020 and not in the future) before any TTL arithmetic is performed. Remove the anomaly-deletion branch entirely — invalid documents should be quarantined to a review prefix, not silently deleted.

// FIXED — deser17-003
// workers/archiveWorker.js
const BSON = require('bson');
const s3 = require('../lib/s3');
const { z } = require('zod');

const TTL_MS = 90 * 24 * 60 * 60 * 1000;
const MIN_VALID_TS = new Date('2020-01-01').getTime();

const ArchiveDocSchema = z.object({
  eventId: z.string().uuid(),
  orgId: z.string().uuid(),
  createdAt: z.number().int()
    .min(MIN_VALID_TS, 'createdAt predates 2020')
    .refine((v) => v <= Date.now(), 'createdAt is in the future'),
  payload: z.record(z.unknown()),
}).strict();

function normalizeBsonDoc(raw) {
  return {
    ...raw,
    // Convert BSON Timestamp or Date to plain Unix ms integer
    createdAt: raw.createdAt instanceof BSON.Timestamp
      ? raw.createdAt.toNumber() * 1000
      : raw.createdAt instanceof Date
        ? raw.createdAt.getTime()
        : Number(raw.createdAt),
  };
}

async function applyTTL(s3Key) {
  const buf = await s3.getObject(s3Key);
  const rawDoc = BSON.deserialize(buf);
  let doc;
  try {
    doc = ArchiveDocSchema.parse(normalizeBsonDoc(rawDoc));
  } catch {
    // Quarantine invalid docs — never silently delete
    await s3.copyObject(s3Key, s3Key.replace('archive/', 'quarantine/'));
    return;
  }
  const ageMs = Date.now() - doc.createdAt;
  if (ageMs > TTL_MS) await s3.deleteObject(s3Key);
}

DESER17-004: Unsigned base64 replay token enables arbitrary event replay

The MCP skill registry exposes a webhook event replay API that allows organization admins to re-trigger delivery of a past event. To authorize a replay, the registry issues a replay token: a base64-encoded JSON object containing the eventId to replay, the orgId that owns the event, and an expiresAt Unix timestamp after which the token is no longer valid. The token is returned to the requesting admin and must be submitted with the POST /api/webhooks/replay endpoint. The critical flaw is that the token is not signed — there is no HMAC, no digital signature, and no server-side token store. The server validates the token solely by decoding the base64 JSON and checking whether Date.now() < token.expiresAt.

An attacker who can obtain any valid replay token (through network interception, an XSS vulnerability, or by being a low-privilege org member who requests a token for a benign event) can decode it, modify the eventId to any event identifier they wish to replay, set expiresAt to a timestamp far in the future (e.g. year 2099), re-encode as base64, and submit the crafted token. The server decodes it, sees expiresAt is in the future, and executes the replay. This allows replaying any past webhook event regardless of its original age or the requesting user's authorization to access that specific event. In audit-critical deployments, replaying certain events can re-trigger downstream integrations, duplicate financial records, or re-execute privilege escalation workflows at the receiving system.

// VULNERABLE — deser17-004
// routes/webhooks.js
const { requireAuth } = require('../middleware/auth');

router.post('/api/webhooks/replay', requireAuth, async (req, res) => {
  const { replayToken } = req.body;

  // Token is just base64 JSON — no signature, no server-side store
  // Attacker decodes, sets any eventId + far-future expiresAt, re-encodes
  const token = JSON.parse(Buffer.from(replayToken, 'base64').toString('utf8'));

  if (Date.now() > token.expiresAt) {
    return res.status(401).json({ error: 'Replay token expired' });
  }

  // No check that token.eventId belongs to req.user.orgId
  // Any eventId in the registry can be replayed
  const event = await db.webhookEvents.findById(token.eventId);
  await deliverWebhook(event);
  res.json({ replayed: token.eventId });
});

Fix DESER17-004: Replace the self-describing base64 JSON token with an opaque random token stored server-side in the database. When an admin requests a replay token, generate a cryptographically random 32-byte token, store it in a webhook_replay_tokens table with the associated eventId, orgId, requestedBy, expiresAt (short TTL, e.g. 15 minutes), and usedAt (null until redeemed). On redemption, look up the token by its opaque value, verify it belongs to the requesting orgId, check it has not been used, and mark it used before triggering delivery. If a signed token is preferred over a DB-stored one, use HMAC-SHA256 over a canonical payload and validate the signature server-side.

// FIXED — deser17-004
// routes/webhooks.js
const crypto = require('crypto');
const { requireAuth, requireRole } = require('../middleware/auth');

const REPLAY_TOKEN_TTL_MS = 15 * 60 * 1000; // 15 minutes

// Issue a replay token (opaque, DB-stored, single-use)
router.post('/api/webhooks/:eventId/replay-token', requireAuth, requireRole('admin'), async (req, res) => {
  const event = await db.webhookEvents.findOne({
    where: { id: req.params.eventId, orgId: req.user.orgId },
  });
  if (!event) return res.status(404).json({ error: 'Event not found' });

  const token = crypto.randomBytes(32).toString('hex');
  await db.webhookReplayTokens.create({
    token,
    eventId: event.id,
    orgId: req.user.orgId,
    requestedBy: req.user.id,
    expiresAt: new Date(Date.now() + REPLAY_TOKEN_TTL_MS),
    usedAt: null,
  });
  res.json({ replayToken: token });
});

// Redeem a replay token
router.post('/api/webhooks/replay', requireAuth, async (req, res) => {
  const record = await db.webhookReplayTokens.findOne({
    where: { token: req.body.replayToken, orgId: req.user.orgId, usedAt: null },
  });
  if (!record || record.expiresAt < new Date()) {
    return res.status(401).json({ error: 'Invalid or expired replay token' });
  }
  await db.webhookReplayTokens.update({ usedAt: new Date() }, { where: { token: record.token } });
  const event = await db.webhookEvents.findById(record.eventId);
  await deliverWebhook(event);
  res.json({ replayed: record.eventId });
});

Compound attack chain

An attacker with Redis write access can combine all four findings into a comprehensive attack that achieves privilege escalation, persistent service disruption, evidence destruction, and undetectable event replay. The chain opens with DESER17-001: a MessagePack payload with __proto__.isAdmin:true is injected into the BullMQ queue, poisoning all worker instances and enabling the attacker's subsequent queue jobs to execute with admin-level privileges. With admin context established in the worker, the attacker injects DESER17-002 payloads targeting the webhook endpoints of victim organizations — retryCount:-9999, nextRetryAt:0 jobs hammering each target's webhook URL until rate limits are exhausted, suppressing legitimate audit notifications. Simultaneously, the prototype-polluted worker now archives failed events via the BSON path; the attacker crafts DESER17-003 payloads with BSON Timestamps that trigger the anomaly-deletion branch, ensuring all forensic evidence of the attack's injected events is immediately removed from S3. Finally, using the admin context gained from DESER17-001, the attacker calls the replay token issuance endpoint to generate unsigned DESER17-004 tokens, modifies them to reference sensitive historical audit events, and replays those events to re-trigger downstream integrations — creating phantom audit findings or re-executing privilege escalation records in integrated SIEM systems. The result is privilege escalation, targeted denial of service, evidence destruction, and replay-based integrity violation achieved entirely from Redis-level write access.

Detection with SkillAudit tree-sitter queries

; Detect Object.assign or spread of decoded MessagePack/BSON/JSON into context
; without an intervening schema parse call
(call_expression
  function: (member_expression
    object: (identifier) @obj (#eq? @obj "Object")
    property: (property_identifier) @prop (#eq? @prop "assign"))
  arguments: (arguments
    (identifier)
    (call_expression
      function: (member_expression
        property: (property_identifier) @deser
          (#match? @deser "^(decode|deserialize|parse)$")))))

; Detect Buffer.from + base64 + JSON.parse pattern used for token decoding
; without a downstream HMAC verification call
(call_expression
  function: (member_expression
    object: (call_expression
      function: (member_expression
        object: (identifier) @cls (#eq? @cls "JSON")
        property: (property_identifier) @method (#eq? @method "parse")))
    property: (property_identifier))
  (#not-match? @method "verify"))

Summary

ID Severity Component Root cause Fix
DESER17-001 Critical BullMQ webhook queue worker Object.assign(ctx, decoded) of MessagePack queue data enables __proto__ prototype pollution escalating worker privilege Zod schema post-unpack; null-prototype target; never assign decoded queue data directly to context
DESER17-002 High Redis stream retry pipeline JSON.parse + spread of retry job data without validation; retryCount:-9999 and nextRetryAt:0 cause infinite immediate retries Zod RetryJobSchema rejects out-of-range values; cap retryCount to 0–10; nextRetryAt minimum current time + 1s
DESER17-003 High S3 webhook archive TTL worker BSON Timestamp at createdAt produces large integer; negative age triggers anomaly-deletion branch, silently deleting valid payloads Store as plain JSON; normalize BSON types to primitives at ingest; Zod schema enforces plausible timestamp range; quarantine instead of delete on anomaly
DESER17-004 High Webhook replay API Base64 JSON replay token has no HMAC; attacker modifies eventId and expiresAt to replay arbitrary past events Opaque DB-stored single-use token; HMAC-SHA256 or random 32-byte token; short TTL; orgId ownership check on redemption

Run a free SkillAudit scan on any public MCP skill repository at skillaudit.dev. Reports include insecure deserialization checks alongside SSRF, injection, privilege escalation, and 40+ other categories.