← Blog

Claude skill cron job security — SA-SKL-CRON

Scheduled tasks in MCP skills introduce a class of vulnerabilities distinct from synchronous request handlers: cron expression injection, cross-tenant worker confusion, duplicate execution from concurrent pods, and over-privileged service accounts that survive a path traversal. SA-SKL-CRON covers all four.

By SkillAudit  |  6 Nov 2026

Why scheduled tasks require special attention in MCP skills

Most MCP skill security reviews focus on the request/response boundary: tool call inputs, HTTP headers, JWT validation, and output sanitization. Cron jobs operate outside that boundary entirely. They run on a timer, often in a separate worker process with shared infrastructure, and their inputs may come from a database row written by a completely different tenant minutes or hours earlier. This combination of deferred execution, shared worker pools, and indirect input sourcing creates four distinct attack surfaces that standard input-validation guidance does not address.

The node-cron library, the most common scheduler used in Node.js MCP skills, accepts any string as a cron expression and silently schedules it. There is no built-in validation, no rate cap, and no tenant-scoping at the library level. A skill that exposes schedule customization to end users must enforce all of these properties itself — and most skills do not.

SA-SKL-CRON in scope: CRON-001 (cron expression injection), CRON-002 (cross-tenant job execution), CRON-003 (missing idempotency guard), CRON-004 (over-privileged service account). Each pattern includes SkillAudit detection rules and correct fixes.

CRON-001 — Cron expression injection via user-supplied schedule string

When a skill lets users configure their own audit schedule, the natural implementation passes the user-supplied string directly to node-cron.schedule(). An attacker can supply * * * * * (every minute) instead of the intended daily schedule, causing the job to run 1,440 times per day instead of once. Beyond frequency abuse, node-cron extensions on some builds accept non-standard sixth fields (seconds) or special syntax that may interact unexpectedly with the host environment. The fix is to validate the schedule against an explicit allowlist of safe values, or to validate the string against a strict regex that only accepts five standard fields with numeric, range, and step values.

// VULNERABLE — user-supplied schedule string passed directly to node-cron
import cron from 'node-cron';

export async function setAuditSchedule(orgId: string, userSchedule: string) {
  // No validation: attacker supplies "* * * * *" for every-minute execution
  cron.schedule(userSchedule, () => runAudit(orgId));
  await db.orgs.update({ where: { id: orgId }, data: { schedule: userSchedule } });
}
// FIXED — validate against an allowlist of safe schedules
import cron from 'node-cron';

const ALLOWED_SCHEDULES: Record<string, string> = {
  daily:   '0 2 * * *',   // 02:00 UTC daily
  weekly:  '0 2 * * 1',   // 02:00 UTC every Monday
  monthly: '0 2 1 * *',   // 02:00 UTC first of month
};

export async function setAuditSchedule(orgId: string, scheduleKey: string) {
  const expression = ALLOWED_SCHEDULES[scheduleKey];
  if (!expression) {
    throw new Error(`Invalid schedule key: ${scheduleKey}. Allowed: ${Object.keys(ALLOWED_SCHEDULES).join(', ')}`);
  }
  cron.schedule(expression, () => runAudit(orgId));
  await db.orgs.update({ where: { id: orgId }, data: { schedule: scheduleKey } });
}
HIGH
SA-SKL-CRON-001 — User-supplied cron expression string passed to node-cron.schedule() without validation enables schedule frequency abuse; fix by validating against an explicit key-to-expression allowlist. Detection: SkillAudit flags any call where the first argument to cron.schedule() or schedule() is derived from a function parameter, request body field, or database value without an intervening allowlist or regex check.

CRON-002 — Cross-tenant cron job execution in shared worker pool

Multi-tenant MCP skills commonly run a single cron worker process that polls a scheduled_jobs table for jobs due to execute. When the worker query fetches rows without filtering on organization_id, or when a later step trusts a caller-supplied org context instead of re-reading it from the job record, job execution can proceed under the wrong tenant's context. If job ID sequences between tenants overlap (sequential integer IDs are common), tenant A's job ID 42 may be picked up and executed using tenant B's service credentials. The fix is to always re-read organization_id from the job record itself immediately before execution and validate it against the executing context — never trust the caller's claim.

// VULNERABLE — worker fetches all due jobs without tenant filtering
async function runDueJobs() {
  // Missing WHERE organization_id condition — fetches across all tenants
  const jobs = await db.query(
    `SELECT * FROM scheduled_jobs WHERE next_run_at <= NOW() AND status = 'pending'`
  );

  for (const job of jobs) {
    // Trusts job.context which may have been tampered or mismatched
    await executeJob(job.id, job.context.organizationId);
  }
}
// FIXED — always re-validate organization_id from the authoritative job record
async function runDueJobs(workerOrgId: string) {
  const jobs = await db.query(
    `SELECT * FROM scheduled_jobs
     WHERE next_run_at <= NOW()
       AND status = 'pending'
       AND organization_id = $1`,
    [workerOrgId]
  );

  for (const job of jobs) {
    // Re-read org from DB record; never use caller-supplied value alone
    if (job.organization_id !== workerOrgId) {
      logger.error(`Job ${job.id} org mismatch: expected ${workerOrgId}, got ${job.organization_id}`);
      continue;
    }
    await executeJob(job.id, job.organization_id);
  }
}
CRITICAL
SA-SKL-CRON-002 — Shared cron worker fetches scheduled jobs without filtering by organization_id, enabling cross-tenant job execution when job ID namespaces overlap; fix by filtering on organization_id in the fetch query and re-validating the field from the job record before execution. Detection: SkillAudit flags worker queries against scheduled_jobs or similar tables that lack a WHERE organization_id condition, or execution paths that trust a caller-supplied tenant ID without re-reading from the job record.

CRON-003 — Missing job idempotency guard causes duplicate execution

Horizontally scaled MCP skill deployments run multiple worker pod replicas. Without a distributed lock or database-level advisory lock, all running pods may poll the jobs table simultaneously, find the same due job, and begin executing it in parallel. For a job that sends a report email and updates a metrics counter, this results in duplicate emails to the customer and double-counted metric values — both hard to reverse. The fix is to use SELECT … FOR UPDATE SKIP LOCKED so only one worker can claim a row, or to acquire a Redis distributed lock (SET key NX EX ttl) before beginning execution and release it on completion.

// VULNERABLE — no lock; multiple worker pods execute the same job simultaneously
async function claimAndRunJob(jobId: string) {
  const job = await db.query(
    `SELECT * FROM scheduled_jobs WHERE id = $1 AND status = 'pending'`,
    [jobId]
  );
  if (!job) return;

  // Race condition: another pod already past this point with the same job
  await db.query(`UPDATE scheduled_jobs SET status = 'running' WHERE id = $1`, [jobId]);
  await sendReportEmail(job.orgId);
  await incrementMetric(job.orgId, 'audits_run');
}
// FIXED — use SELECT FOR UPDATE SKIP LOCKED to atomically claim exactly one job
async function claimAndRunJob(): Promise<void> {
  await db.transaction(async (tx) => {
    const [job] = await tx.query(
      `SELECT * FROM scheduled_jobs
       WHERE status = 'pending' AND next_run_at <= NOW()
       ORDER BY next_run_at ASC
       LIMIT 1
       FOR UPDATE SKIP LOCKED`
    );
    if (!job) return;

    await tx.query(
      `UPDATE scheduled_jobs SET status = 'running', claimed_at = NOW() WHERE id = $1`,
      [job.id]
    );

    // Only one pod reaches here per job
    try {
      await sendReportEmail(job.orgId);
      await incrementMetric(job.orgId, 'audits_run');
      await tx.query(
        `UPDATE scheduled_jobs SET status = 'done', completed_at = NOW() WHERE id = $1`,
        [job.id]
      );
    } catch (err) {
      await tx.query(
        `UPDATE scheduled_jobs SET status = 'failed', error = $2 WHERE id = $1`,
        [job.id, String(err)]
      );
      throw err;
    }
  });
}
HIGH
SA-SKL-CRON-003 — Scheduled jobs fetched without an advisory or distributed lock allow multiple worker pods to execute the same job simultaneously, causing duplicate side effects such as duplicate emails and double-counted metrics; fix with SELECT … FOR UPDATE SKIP LOCKED in a transaction or a Redis SET NX EX lock. Detection: SkillAudit flags job execution paths that read a job row and perform side effects (email, DB writes, external API calls) without an intervening FOR UPDATE or distributed lock acquisition.

CRON-004 — Scheduled job runs with over-privileged service account

It is common for MCP skill deployments to share a single database connection pool between the HTTP request handlers and the cron worker. That pool typically uses the application DB role, which carries full INSERT, UPDATE, and DELETE privileges across all tables including users, billing, and audit_logs. If the cron job contains a path traversal bug or a logic error, it can inadvertently write to sensitive tables it has no business touching. The fix is to create a dedicated, restricted DB role for cron execution that is granted only the minimum privileges the jobs actually need, and to open a separate connection pool using that restricted role for all scheduled task paths.

// VULNERABLE — cron worker reuses the same DB pool as the HTTP server
import { pool } from '../db'; // Full INSERT/UPDATE/DELETE on all tables

async function runAuditJob(orgId: string, skillPath: string) {
  // If skillPath contains path traversal, the over-privileged role can
  // write to users, billing, or other sensitive tables via follow-on queries
  const result = await pool.query(
    `INSERT INTO audit_results (org_id, skill_path, ran_at) VALUES ($1, $2, NOW())`,
    [orgId, skillPath]
  );
  return result.rows[0];
}
// FIXED — dedicated restricted DB role for cron execution paths
import { Pool } from 'pg';

// Connect with a cron-specific role that has minimal privileges:
//   GRANT SELECT ON audit_runs, skills TO cron_worker;
//   GRANT INSERT ON audit_results TO cron_worker;
const cronPool = new Pool({
  connectionString: process.env.DATABASE_URL_CRON, // separate DSN for restricted role
});

async function runAuditJob(orgId: string, skillId: string) {
  // skillId validated as UUID before this point (allowlist check upstream)
  const result = await cronPool.query(
    `INSERT INTO audit_results (org_id, skill_id, ran_at) VALUES ($1, $2, NOW())`,
    [orgId, skillId]
  );
  return result.rows[0];
}

// SQL to create the restricted role (run once in migration):
// CREATE ROLE cron_worker LOGIN PASSWORD '...';
// GRANT CONNECT ON DATABASE skillaudit TO cron_worker;
// GRANT USAGE ON SCHEMA public TO cron_worker;
// GRANT SELECT ON audit_runs, skills TO cron_worker;
// GRANT INSERT ON audit_results TO cron_worker;
// GRANT USAGE, SELECT ON SEQUENCE audit_results_id_seq TO cron_worker;
MEDIUM
SA-SKL-CRON-004 — Scheduled job reuses the HTTP server's over-privileged DB connection pool, granting the cron worker unnecessary write access to sensitive tables; fix by creating a dedicated least-privilege DB role for cron jobs and connecting with a separate pool using that role. Detection: SkillAudit flags cron job execution paths that import or reference the same DB pool instance used by HTTP request handlers without a privilege-scoping wrapper.