← Blog

Insecure Deserialization in MCP Skill Registry Message Queues — Redis Pub/Sub and BullMQ

Message queues and cache invalidation channels feel like internal infrastructure — only trusted services write to them, so the data flowing through them must be safe. That assumption collapses the moment an attacker gains indirect write access to Redis: via SSRF to a Redis HTTP admin endpoint, via a SQL injection point that enables a crafted NOTIFY, or via a compromised worker process that injects jobs. When a skill registry deserializes queue messages without schema validation, the blast radius spans from cache inconsistency to SQL injection to remote code execution. This post walks through the four SA-SKL-DESER4 patterns SkillAudit finds in MCP skill registry message queue infrastructure.

By SkillAudit  |  12 Nov 2026  |  15 min read

In this post

  1. Why message queues are a deserialization blind spot
  2. DESER4-001 — Redis SUBSCRIBE without Zod schema validation
  3. DESER4-002 — BullMQ job data scriptPath to execFile()
  4. DESER4-003 — PostgreSQL NOTIFY/LISTEN JSON without schema
  5. DESER4-004 — WebSocket JSON.parse + Object.assign prototype pollution
  6. How SkillAudit detects these patterns
  7. Summary and checklist
SA-SKL-DESER4 findings at a glance
CRITICALDESER4-001 — Redis SUBSCRIBE callback passes JSON.parse() output directly to downstream SQL queries without schema validation; attacker with Redis write access injects crafted message; SQL injection pivot or crash-and-leak
CRITICALDESER4-002 — BullMQ job data scriptPath field passed to execFile() without validation; attacker with Redis write injects arbitrary path; arbitrary file execution on worker host
HIGHDESER4-003 — PostgreSQL NOTIFY/LISTEN cache invalidation parses payload with JSON.parse() without schema; attacker crafts NOTIFY via SQL injection point; unvalidated data reaches cache handler
HIGHDESER4-004 — WebSocket JSON.parse() combined with Object.assign(req.session, parsedMessage); attacker sends {"__proto__":{"isAdmin":true}}; prototype pollution sets isAdmin on Object.prototype for all users

Why message queues are a deserialization blind spot

Web request handlers are battle-tested against hostile input — every Express tutorial warns about SQL injection, XSS, and input validation. But the message queue subscriber sitting next to the web server typically has no such training data in its ancestry. It was written by a backend engineer for speed, not adversarial robustness, and the implicit threat model was: "Only our own services write to this queue." That implicit trust makes queue consumers a consistent high-severity target when the trust assumption breaks.

The trust assumption breaks in MCP skill registries in three recurring ways:

None of these entry points are exotic. All three appear in published CVEs against self-hosted CI runners and package registries. The deserialization vulnerability is what converts an opportunistic Redis write into a business-critical compromise.

DESER4-001 — Redis SUBSCRIBE callback without Zod schema validation

MCP skill registries commonly use Redis pub/sub for real-time events: a new skill version is published, a background audit completes, an org-level cache entry is invalidated. The subscriber code is typically brief — it was written to route a message type to a handler, not to defend against adversarial inputs. The pattern looks harmless because the message shape never changes in development or staging. But the shape is not enforced at the protocol level — it is merely a convention.

When the subscriber passes fields from the deserialized message directly into a downstream database query without parameterising them, an attacker who controls the message content controls a fragment of SQL. The entry point is the Redis channel, not the HTTP API — no JWT is checked, no rate limit applies, no WAF sees the payload.

Vulnerable
// DESER4-001 — VULNERABLE
// Redis SUBSCRIBE callback deserializes with JSON.parse() and passes fields to a query
// without schema validation or parameterisation.

import { createClient } from 'redis';
import { pool } from './db.js';

const subscriber = createClient();
await subscriber.connect();

await subscriber.subscribe('skill-cache-invalidation', async (raw) => {
  // No schema validation — any shape accepted
  const msg = JSON.parse(raw);

  // msg.skillId comes from the Redis message — attacker-controlled
  // The query uses template literal interpolation — SQL injection
  await pool.query(
    `DELETE FROM skill_cache WHERE skill_id = '${msg.skillId}'`
  );

  console.log(`Cache cleared for skill: ${msg.skillId}`);
});

// Attacker publishes via SSRF to Redis admin:
// PUBLISH skill-cache-invalidation '{"skillId":"1'  OR '1'='1"}'
// → DELETE FROM skill_cache WHERE skill_id = '1' OR '1'='1'
// → entire skill_cache table deleted
Fixed
// DESER4-001 — FIXED
// Three-layer defence: Zod schema validation, parameterised query, UUID allowlist.

import { createClient } from 'redis';
import { z } from 'zod';
import { pool } from './db.js';

const CacheInvalidationMessage = z.object({
  type: z.literal('invalidate'),
  skillId: z.string().uuid(),          // Fix 1: UUID constraint — rejects SQL fragments
  requestedAt: z.string().datetime(),
});

const subscriber = createClient();
await subscriber.connect();

await subscriber.subscribe('skill-cache-invalidation', async (raw) => {
  let msg;
  try {
    msg = CacheInvalidationMessage.parse(JSON.parse(raw));
  } catch (err) {
    // Fix 2: log and discard; never forward to DB
    console.error('Invalid cache invalidation message — discarded', { raw, err });
    return;
  }

  // Fix 3: parameterised query — even if Zod is bypassed, no injection possible
  await pool.query(
    'DELETE FROM skill_cache WHERE skill_id = $1',
    [msg.skillId]
  );
});

The privilege escalation path: From an SSRF vulnerability (SA-SKL-SSRF21) to Redis write access, the attacker publishes a crafted cache invalidation message. The unvalidated msg.skillId is interpolated directly into a SQL DELETE statement. With '; DROP TABLE skills; -- as the value, the entire skills table is deleted. With ' UNION SELECT password_hash, null FROM users WHERE '1'='1 in a SELECT context, credential hashes are exfiltrated. The SSRF enables the write; the missing schema validation converts the write into full database compromise.

SkillAudit's static analysis detects Redis subscriber callbacks that call JSON.parse() without immediately running the result through a schema validator before accessing any fields. The check inspects the parse-to-use distance: if any property access on the parsed object occurs before a Zod (or Joi, or Yup) schema .parse() or .safeParse() call, the finding is raised at CRITICAL.

DESER4-002 — BullMQ job data scriptPath to execFile()

BullMQ workers that execute skill test scripts have a natural requirement to know which script to run. A common implementation stores the script path in the job data — added by the API handler when it enqueues the job, consumed by the worker when it processes the job. The assumption: the API handler always puts a safe, controlled path into the job. The break point: the job data is stored in and read from Redis. If an attacker can write to Redis (the same SSRF vector as DESER4-001), they can inject a job with an arbitrary scriptPath.

Vulnerable
// DESER4-002 — VULNERABLE
// BullMQ worker reads scriptPath from job.data and passes it to execFile().
// Attacker with Redis write injects a job with scriptPath = '/etc/passwd'
// or scriptPath = '/tmp/attacker-payload.sh'.

import { Worker } from 'bullmq';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';

const execFileAsync = promisify(execFile);

const worker = new Worker('skill-tests', async (job) => {
  // VULNERABLE: scriptPath from job.data, no validation, no path boundary check
  const { scriptPath, skillId } = job.data;

  const { stdout, stderr } = await execFileAsync(
    'node',
    [scriptPath],             // ← attacker controls this
    { timeout: 30_000 }
  );

  await saveTestResult(skillId, { stdout, stderr });
}, { connection: redisConnection });

// Attacker injects via SSRF to Redis admin:
// RPUSH bull:skill-tests:wait '{"name":"run-tests","data":{"skillId":"...","scriptPath":"/tmp/attacker.js"},"opts":{}}'
// Worker processes the injected job and executes /tmp/attacker.js
Fixed
// DESER4-002 — FIXED
// scriptPath is never trusted from job data.
// The worker derives the script path from the database using the skillId.
// No attacker-controlled string reaches the filesystem or execFile arguments.

import { Worker } from 'bullmq';
import { execFile } from 'node:child_process';
import { promisify } from 'node:util';
import { z } from 'zod';
import path from 'node:path';
import { pool } from './db.js';

const execFileAsync = promisify(execFile);

const JobSchema = z.object({
  skillId: z.string().uuid(),           // Fix 1: schema validation on job data
  // scriptPath intentionally NOT in schema — derived server-side only
});

const SCRIPTS_BASE = path.resolve('/app/skill-tests');

const worker = new Worker('skill-tests', async (job) => {
  const { skillId } = JobSchema.parse(job.data);

  // Fix 2: derive path from DB, never from job data
  const { rows } = await pool.query(
    'SELECT test_script_name FROM skills WHERE id = $1',
    [skillId]
  );
  if (!rows.length) throw new Error(`Skill not found: ${skillId}`);

  const scriptName = rows[0].test_script_name;

  // Fix 3: path.resolve + boundary check — prevents directory traversal
  const scriptPath = path.resolve(SCRIPTS_BASE, scriptName);
  if (!scriptPath.startsWith(SCRIPTS_BASE + path.sep)) {
    throw new Error(`Path traversal attempt for skill: ${skillId}`);
  }

  const { stdout, stderr } = await execFileAsync(
    'node',
    [scriptPath],
    { timeout: 30_000 }
  );

  await saveTestResult(skillId, { stdout, stderr });
}, { connection: redisConnection });

Why BullMQ is not the problem: BullMQ stores job payloads faithfully in Redis and delivers them to workers with equal fidelity. It has no concept of "trusted" vs "untrusted" job producers — that distinction must be enforced by the application. The fix is architectural: treat job data the same way you treat HTTP request bodies — validate the shape, strip any fields that shouldn't be there, and derive sensitive values (file paths, SQL identifiers, shell arguments) from server-side state rather than from the job payload itself. See also SA-SKL-SSRF21 for how sandbox escape enables this attack.

DESER4-003 — PostgreSQL NOTIFY/LISTEN JSON without schema

Some MCP skill registries use PostgreSQL's native pub/sub mechanism — NOTIFY and LISTEN — to push cache invalidation events directly from the database tier to the application tier without an external message broker. The NOTIFY payload is a string, commonly JSON-encoded. The application listener calls JSON.parse() on the payload and uses the resulting fields to decide which cache entries to clear.

The issue is that NOTIFY can be executed as a SQL statement — including inside an injection payload. Any SQL injection in the application (search endpoint, filter parameter, unsanitised sort field) that reaches the database as an arbitrary SQL fragment can be used to issue a SELECT pg_notify('cache-invalidation', '{"table":"...","id":"..."}'). The attacker controls the payload content, and the listening application processes it without schema validation.

Vulnerable
// DESER4-003 — VULNERABLE
// PostgreSQL NOTIFY/LISTEN: application listener processes payload without schema.
// Attacker injects NOTIFY via SQL injection in the search endpoint.

// Application side — listener
import pg from 'pg';
const client = new pg.Client();
await client.connect();
await client.query("LISTEN cache-invalidation");

client.on('notification', async (msg) => {
  if (msg.channel === 'cache-invalidation') {
    // No schema validation — msg.payload comes from the database event
    const payload = JSON.parse(msg.payload);

    // payload.table and payload.id are attacker-controlled
    await pool.query(
      `DELETE FROM ${payload.table}_cache WHERE id = '${payload.id}'`
    );
  }
});

// Attacker exploits SQL injection in GET /api/skills/search?q=...
// Payload: '; SELECT pg_notify('cache-invalidation',
//   '{"table":"skills","id":"1'' UNION SELECT password_hash FROM users--"}'); --
// → table interpolated into query, id interpolated without parameterisation
// → SQL injection via the cache invalidation path
Fixed
// DESER4-003 — FIXED
// Zod schema with strict enum table allowlist and UUID constraint on id.
// Even if attacker reaches NOTIFY, the payload shape is enforced before use.

import pg from 'pg';
import { z } from 'zod';

const CacheInvalidationPayload = z.object({
  table: z.enum(['skills', 'skill_versions', 'audit_results', 'org_members']),
  id: z.string().uuid(),
});

const TABLE_TO_CACHE: Record = {
  skills: 'skill_cache',
  skill_versions: 'version_cache',
  audit_results: 'audit_cache',
  org_members: 'member_cache',
};

const client = new pg.Client();
await client.connect();
await client.query("LISTEN cache-invalidation");

client.on('notification', async (msg) => {
  if (msg.channel !== 'cache-invalidation') return;

  let payload;
  try {
    payload = CacheInvalidationPayload.parse(JSON.parse(msg.payload));
  } catch {
    // Fix 1: discard any non-conforming message; log for ops visibility
    console.error('Invalid NOTIFY payload — discarded', msg.payload);
    return;
  }

  // Fix 2: derive cache table from server-side map, not from payload
  const cacheTable = TABLE_TO_CACHE[payload.table];

  // Fix 3: parameterised query — no interpolation of payload fields
  await pool.query(
    `DELETE FROM ${cacheTable} WHERE id = $1`,
    [payload.id]
  );
});

Parameterise the cache table name too: Even with a Zod enum allowlist, the cache table name in the DELETE statement is derived from an enum value. Use a server-side mapping (a plain JS object or a TypeScript Record) to convert the validated enum value to a hardcoded table name, rather than using the enum value directly in the query string. This two-layer approach means that even if a future developer removes the Zod enum, the mapping still prevents unrecognised table names from reaching the query.

DESER4-004 — WebSocket JSON.parse + Object.assign prototype pollution

Prototype pollution is a JavaScript-specific vulnerability where an attacker can modify Object.prototype — the base object from which every JS object inherits properties — by supplying a specially crafted key in a plain object. The key __proto__ is handled specially by JavaScript engines: when you do Object.assign(target, { "__proto__": { "isAdmin": true } }), some runtime versions mutate Object.prototype rather than adding a property named __proto__ to target. After mutation, ({}).isAdmin returns true for every object in the process — including req.user, req.session, and any authorization context object created after the mutation.

In MCP skill registry WebSocket handlers, the pollution vector is JSON.parse() combined with Object.assign(). The WebSocket message arrives as a JSON string. The handler parses it and merges it into the session or user context object. If the JSON contains a __proto__ key, the merge mutates the prototype.

Vulnerable
// DESER4-004 — VULNERABLE
// WebSocket message parsed with JSON.parse() and merged into session via Object.assign().
// Attacker sends {"__proto__":{"isAdmin":true}} to escalate to admin for all subsequent users.

import { WebSocketServer } from 'ws';

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', (ws, req) => {
  ws.on('message', (data) => {
    let msg;
    try {
      msg = JSON.parse(data.toString());
    } catch {
      ws.close(1003, 'Invalid JSON');
      return;
    }

    // VULNERABLE: Object.assign with untrusted parsed object
    // If msg === {"__proto__":{"isAdmin":true}}, this mutates Object.prototype
    Object.assign(req.session, msg);

    if (req.session.isAdmin) {
      broadcastToAdmins(msg);
    }
  });
});

// Attacker sends via WebSocket:
// {"__proto__":{"isAdmin":true},"type":"subscribe","channel":"admin-audit-feed"}
// After this message, every req.user.isAdmin and req.session.isAdmin in the entire
// process returns true — not just for this WebSocket connection, but for every
// subsequently-created object in the Node.js heap.
Fixed
// DESER4-004 — FIXED
// Three-layer defence: Zod discriminated union, structured clone to strip __proto__,
// explicit property allowlist — never Object.assign untrusted data.

import { WebSocketServer } from 'ws';
import { z } from 'zod';

const WsMessageSchema = z.discriminatedUnion('type', [
  z.object({
    type: z.literal('subscribe'),
    channel: z.enum(['audit-feed', 'skill-events', 'org-notifications']),
  }),
  z.object({
    type: z.literal('unsubscribe'),
    channel: z.enum(['audit-feed', 'skill-events', 'org-notifications']),
  }),
  z.object({
    type: z.literal('ping'),
  }),
]);

const wss = new WebSocketServer({ port: 8080 });

wss.on('connection', (ws, req) => {
  ws.on('message', (data) => {
    let msg;
    try {
      // Fix 1: Zod discriminated union — rejects any message not matching known types;
      // the schema's key set never includes __proto__, constructor, or prototype
      msg = WsMessageSchema.parse(JSON.parse(data.toString()));
    } catch {
      ws.close(1003, 'Unrecognised message type');
      return;
    }

    // Fix 2: Never Object.assign — handle message fields explicitly
    if (msg.type === 'subscribe') {
      subscribeToChannel(ws, req.session.userId, msg.channel);
    } else if (msg.type === 'unsubscribe') {
      unsubscribeFromChannel(ws, req.session.userId, msg.channel);
    }
    // No session mutation from WebSocket message content
  });
});

Process-wide impact: Prototype pollution via WebSocket is not a per-connection exploit — it mutates Object.prototype for the entire Node.js process. A single attacker WebSocket connection can escalate privileges for every user served by the same process worker. In a multi-process setup (PM2 cluster, Node.js Worker Threads), the mutation is confined to the target worker, but that worker may be handling thousands of concurrent requests. The fix must be preventive: once pollution has occurred, there is no clean rollback short of restarting the process.

Note that JSON.parse() alone does not cause prototype pollution in modern V8 — the JSON parser correctly treats "__proto__" as a regular string key. The danger is in what you do with the parsed object: Object.assign(), lodash's merge(), and manual recursive merge functions are all historical pollution vectors. See SA-SKL-DESER5 for the lodash.merge variant.

How SkillAudit detects these patterns

SkillAudit's static analysis scanner uses tree-sitter to parse the AST of uploaded skill and registry source code. For DESER4 patterns, the scanner runs four targeted queries:

  1. Redis SUBSCRIBE without schema: Finds subscriber.subscribe( or client.subscribe( call expressions; inspects the callback body for a JSON.parse( call; checks whether the parsed value is passed through a schema validator (.parse(, .safeParse(, .validate() before any property access or database query. If the parse-to-access path exists without an intervening schema check, DESER4-001 is raised at CRITICAL.
  2. BullMQ execFile from job.data: Finds new Worker( expressions; traces all references to job.data within the callback; flags any path that reaches execFile(, exec(, spawn(, or spawnSync( with a job.data-derived value. Flags path traversal guards as partial mitigations (MEDIUM) vs no path guard at all (CRITICAL).
  3. NOTIFY/LISTEN without schema: Finds client.query("LISTEN patterns; inspects the 'notification' event callback for JSON.parse( usage; checks whether the result passes a schema validator before use in another query. Additionally checks the other side: looks for pg_notify in SQL template literals combined with interpolated user input (SQL injection enabling a NOTIFY) in the same codebase.
  4. Object.assign with parsed WebSocket: Finds WebSocket 'message' event callbacks; traces JSON.parse( results to Object.assign( calls where the parsed object is the source argument. Also checks for lodash.merge(, _.merge(, and deepmerge( with untrusted sources. See SA-SKL-INJECTION12 for how command injection patterns in the same analysis pipeline are detected.

For DESER4-002 specifically, SkillAudit also performs a grep-based detection pass for the string pattern job.data. followed by a path-like property name (scriptPath, filePath, execPath, binaryPath) within 10 lines of a execFile or spawn call. This catches the pattern even when tree-sitter parsing fails due to syntax errors in the uploaded source.

All four detections are cross-referenced with the SSRF findings from SA-SKL-SSRF21. When an SSRF vulnerability is present in the same codebase alongside a DESER4 pattern, SkillAudit raises a compound finding that describes the full attack chain: SSRF to Redis write to deserialization exploit. Compound chains are scored at a minimum of CRITICAL regardless of the individual finding severities.

Summary and checklist

PatternRoot causeFixSeverity
DESER4-001Redis SUBSCRIBE callback uses JSON.parse() without schema; fields passed to unparameterised SQLZod schema immediately after JSON.parse(); parameterised queriesCRITICAL
DESER4-002BullMQ job.data.scriptPath passed to execFile() without path validationDerive path from DB using job.data.skillId; path.resolve + boundary checkCRITICAL
DESER4-003PostgreSQL NOTIFY/LISTEN payload parsed without schema; table name interpolated into SQLZod enum allowlist for table; server-side mapping to cache table name; parameterised idHIGH
DESER4-004WebSocket JSON.parse() result passed to Object.assign(session, msg)Zod discriminated union; never Object.assign untrusted data; handle message fields explicitlyHIGH

Quick deserialization hardening checklist for MCP skill registry message queues:

For more deserialization patterns in MCP skill registries see SA-SKL-DESER3 (node-serialize, js-yaml, Python pickle, MessagePack). For the SSRF entry points that enable Redis write access, see SA-SKL-SSRF21 (sandbox execution environment SSRF). For command injection patterns in the same static analysis pipeline, see SA-SKL-INJECTION12 (command injection in linting pipeline).