Skip to content

fix(security): sandbox tenant-config custom-mapping evaluation in isolated-vm [INT-6725] - #5348

Merged
shekhar-rudder merged 2 commits into
developfrom
feature/int-6725-unsandboxed-jsontemplate-evaluation-of-destination-custom
Jul 13, 2026
Merged

shekhar-rudder merged 2 commits into
developfrom
feature/int-6725-unsandboxed-jsontemplate-evaluation-of-destination-custom

Conversation

@shekhar-rudder

Copy link
Copy Markdown
Member

Summary

Fixes INT-6725 (parent INT-6708): tenant-supplied destination "custom mappings" were evaluated in-process by JsonTemplateEngine via the Function constructor with no sandbox, allowing SSTI → RCE (Function(...), require('child_process').execSync(...)) and full environment disclosure (process.env||$.userId dumps every env var — verified). Affected tenant-config paths: HTTP headers/queryParams/propertiesMapping and GA4 v2 eventProperties.

This routes all such evaluation through an isolated-vm sandbox where process/require/host globals are unreachable, so the attack payloads resolve to a harmless fallback (or fail closed) and leak nothing.

Approach

  • Centralized chokepoint: applyCustomMappings / applyJSONStringTemplate (src/v0/util/index.js) are now async and delegate to a sandboxed client. Every current and future caller inherits the sandbox.
  • isolated-vm containment: reuses the custom_audience pattern — an esbuild IIFE bundle of the engine (dist/mappingsSandbox.bundle.js) loaded into a dedicated, per-workspaceId isolate pool (custom_mappings_ivm), separate from custom_audience and sized lower (16 MB, maxSize 20, 500 ms exec). Isolates are created lazily and self-evict via LRU + TTL. IvmScriptRunner was promoted to src/util/ivm/scriptRunner.ts.
  • Fail closed: a falsy workspaceId throws — never a shared/default isolate (no cross-tenant state).
  • Feature flag: CUSTOM_MAPPINGS_SANDBOX_ENABLED (default on; =false reverts to byte-equivalent in-process eval, read per-call) — instant rollback without redeploy.
  • process stub: the bundle sets globalThis.process = {} so process.env.X resolves to undefined → graceful fallback (deterministic; the real guarantee is V8 isolation + structured-clone-only marshaling — an adversarial review confirmed no host-data escape).

Security verification

  • Unit + component tests assert the INT-6725 payloads (process.env||$.userId, process.env.SECRET||$.userId, Function('return process.env')(), ({}).constructor.constructor('return process.env')(), Function('return this')()) leak no planted host secret; require is unreachable.
  • Focused adversarial security review: verdict SECURE (no escape via Function/constructor-chain/eval/this; structured-clone boundary rejects returning host-ish objects).

Env vars (documented in docs/features.md)

CUSTOM_MAPPINGS_SANDBOX_ENABLED, CUSTOM_MAPPINGS_IVM_MEMORY_MB (16), CUSTOM_MAPPINGS_IVM_CACHE_MAX_SIZE (20), CUSTOM_MAPPINGS_IVM_CACHE_TTL_MS (300000), CUSTOM_MAPPINGS_IVM_INIT_TIMEOUT_MS (5000), CUSTOM_MAPPINGS_IVM_EXEC_TIMEOUT_MS (500). Observability via existing ivm_cache_* metrics tagged cache:custom_mappings_ivm.

Testing

build:ci PASS · sandbox/runner/GA4/custom_audience TS suites 108/108 · chokepoint + index.test.js 196/196 · HTTP component 17/17 (incl. INT-6725 regression) · GA4 v2 component 11/11.

Notes / follow-ups

  • The rudder-integrations-config from/path regex stays as defense-in-depth but is no longer the security boundary — no regex change needed.
  • applyJSONStringTemplate currently has no production caller (reachable only via tests) — flag for follow-up: wire the intended caller or remove.
  • Deferred minors: relocate docs/features.md per org convention; startup bundle-existence check.

🤖 Generated with Claude Code

@shekhar-rudder
shekhar-rudder requested review from a team as code owners July 8, 2026 09:16
@coderabbitai

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@shekhar-rudder, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 45 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 068a0744-8777-4da2-9c14-ebb42db25794

📥 Commits

Reviewing files that changed from the base of the PR and between dbf8127 and 2510bb7.

⛔ Files ignored due to path filters (4)
  • package.json is excluded by !**/*.json
  • test/integrations/destinations/ga4_v2/processor/customMappings.ts is excluded by !**/test/**
  • test/integrations/destinations/http/common.ts is excluded by !**/test/**
  • test/integrations/destinations/http/processor/configuration.ts is excluded by !**/test/**
📒 Files selected for processing (16)
  • src/cdk/v2/destinations/http/procWorkflow.yaml
  • src/cdk/v2/destinations/http/utils.test.ts
  • src/cdk/v2/destinations/http/utils.ts
  • src/util/customMappings/mappingsSandbox.ts
  • src/util/customMappings/sandboxClient.test.ts
  • src/util/customMappings/sandboxClient.ts
  • src/util/ivm/scriptRunner.ts
  • src/v0/destinations/custom_audience/template/ivmScriptRunner.test.ts
  • src/v0/destinations/custom_audience/template/ivmScriptRunner.ts
  • src/v0/destinations/custom_audience/template/templateEngineSandbox.ts
  • src/v0/destinations/custom_audience/template/templateSandboxClient.ts
  • src/v0/destinations/ga4_v2/customMappingsHandler.js
  • src/v0/destinations/ga4_v2/transform.test.ts
  • src/v0/destinations/ga4_v2/transform.ts
  • src/v0/util/index.js
  • src/v0/util/index.test.js

Note

.coderabbit.yaml has unrecognized properties

CodeRabbit is using all valid settings from your configuration. Unrecognized properties (listed below) have been ignored and may indicate typos or deprecated fields that can be removed.

⚠️ Parsing warnings (1)
Validation error: Unrecognized key: "auto_resolve_threads"
⚙️ Configuration instructions
  • Please see the configuration documentation for more information.
  • You can also validate your configuration using the online YAML validator.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Walkthrough

This PR adds shared isolated-vm execution for custom mappings, introduces workspace-scoped sandbox evaluation, and updates HTTP and GA4 destination flows to await asynchronous mapping results. Custom-audience template sandboxing now reuses the shared runner.

Changes

Sandboxed custom mappings and workspace scoping

Layer / File(s) Summary
Shared IVM script runner and cache
src/util/ivm/scriptRunner.ts, src/v0/destinations/custom_audience/template/...
Adds cached isolate execution, bundle resolution, timeouts, heap metrics, and shared custom-audience runner wiring.
Sandbox mapping evaluation
src/util/customMappings/...
Evaluates mappings in an isolate, validates workspaceId, converts failures to typed errors, and tests environment isolation and escape vectors.
Async mapping chokepoint
src/v0/util/index.js, src/v0/util/index.test.js
Makes applyCustomMappings asynchronous, passes workspaceId, and selects sandboxed or legacy evaluation by configuration.
CDK v2 HTTP integration
src/cdk/v2/destinations/http/...
Makes mapping derivation asynchronous and awaits workspace-scoped header, parameter, and payload results.
GA4 v2 integration
src/v0/destinations/ga4_v2/...
Makes custom mapping processing asynchronous, forwards workspaceId, evaluates mappings concurrently, and updates tests for promise-based behavior.

Estimated code review effort: 4 (Complex) | ~60 minutes

Possibly related PRs

Suggested reviewers: itssudip, krishna2020

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 40.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the security-focused sandboxing change for tenant custom-mapping evaluation and includes the task ID.
Description check ✅ Passed The description covers summary, task, approach, security verification, environment variables, testing, and follow-up notes.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/int-6725-unsandboxed-jsontemplate-evaluation-of-destination-custom

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@shekhar-rudder
shekhar-rudder force-pushed the feature/int-6725-unsandboxed-jsontemplate-evaluation-of-destination-custom branch 6 times, most recently from e87f423 to f80254b Compare July 8, 2026 10:18

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
src/util/ivm/scriptRunner.ts (1)

75-86: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Validate the sandbox limits before creating the runner. IvmScriptRunnerOptions is shared by callers that parse these values from env vars, so malformed input can still flow through as NaN, 0, or negatives and break isolate creation or timeout behavior at runtime. A small guard in the constructor would fail fast with a clearer error.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/util/ivm/scriptRunner.ts` around lines 75 - 86, Validate the sandbox
limits in IvmScriptRunner before constructing the runner state: the constructor
currently accepts values from IvmScriptRunnerOptions without checking for NaN,
zero, or negatives, which can break isolate creation and timeout behavior later.
Add a fail-fast validation step in the IvmScriptRunner constructor (before
assigning bundlePath, memoryLimitMb, initTimeoutMs, execTimeoutMs, or creating
the DisposableCache) to verify the numeric limits are finite and positive, and
throw a clear error when invalid input is provided.
src/util/customMappings/sandboxClient.ts (1)

14-25: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Guard against NaN from non-numeric env vars.

Number.parseInt(process.env.X || '16', 10) only falls back when the env var is empty/undefined. If set to a non-numeric string like "abc", parseInt returns NaN, which is then passed directly to IvmScriptRunner and isolated-vm. A NaN execTimeoutMs could silently disable the execution timeout, allowing a malicious mapping to run indefinitely.

♻️ Proposed refactor: add a small env-int helper
+function envInt(key: string, defaultValue: number): number {
+  const parsed = Number.parseInt(process.env[key] || '', 10);
+  return Number.isNaN(parsed) ? defaultValue : parsed;
+}
+
 export const mappingsSandboxRunner = new IvmScriptRunner({
   bundlePath: BUNDLE_PATH,
-  memoryLimitMb: Number.parseInt(process.env.CUSTOM_MAPPINGS_IVM_MEMORY_MB || '16', 10),
-  initTimeoutMs: Number.parseInt(process.env.CUSTOM_MAPPINGS_IVM_INIT_TIMEOUT_MS || '5000', 10),
-  execTimeoutMs: Number.parseInt(process.env.CUSTOM_MAPPINGS_IVM_EXEC_TIMEOUT_MS || '500', 10),
+  memoryLimitMb: envInt('CUSTOM_MAPPINGS_IVM_MEMORY_MB', 16),
+  initTimeoutMs: envInt('CUSTOM_MAPPINGS_IVM_INIT_TIMEOUT_MS', 5000),
+  execTimeoutMs: envInt('CUSTOM_MAPPINGS_IVM_EXEC_TIMEOUT_MS', 500),
   cacheName: 'custom_mappings_ivm',
-  maxSize: Number.parseInt(process.env.CUSTOM_MAPPINGS_IVM_CACHE_MAX_SIZE || '20', 10),
-  ttlMs: Number.parseInt(process.env.CUSTOM_MAPPINGS_IVM_CACHE_TTL_MS || '300000', 10),
+  maxSize: envInt('CUSTOM_MAPPINGS_IVM_CACHE_MAX_SIZE', 20),
+  ttlMs: envInt('CUSTOM_MAPPINGS_IVM_CACHE_TTL_MS', 300000),
 });

Please verify how isolated-vm v5.0.3 handles NaN for memoryLimit and timeout options — whether it throws, uses a default, or silently allows unbounded execution.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/util/customMappings/sandboxClient.ts` around lines 14 - 25,
`mappingsSandboxRunner` in `sandboxClient.ts` should not pass raw
`Number.parseInt(...)` results directly into `IvmScriptRunner`, because
non-numeric env values can become `NaN` and break or weaken limits. Add a small
reusable env-int helper near `mappingsSandboxRunner` that parses each
`CUSTOM_MAPPINGS_IVM_*` variable, validates it is a finite number, and falls
back to the existing defaults when parsing fails. Apply it to `memoryLimitMb`,
`initTimeoutMs`, `execTimeoutMs`, `maxSize`, and `ttlMs`, and ensure the values
handed to `IvmScriptRunner` are always valid numbers.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/util/customMappings/sandboxClient.test.ts`:
- Around line 96-101: The Vector 2 test in sandboxedApplyCustomMappings is
awaiting a potentially rejecting expression directly, so the assertion against
SECRET may never run if the constructor escape fails first. Update the test
around sandboxedApplyCustomMappings to handle this vector the same way as Vector
1, using the existing try/catch pattern or a rejects-style assertion, then keep
the secret check on the resolved output path.

---

Nitpick comments:
In `@src/util/customMappings/sandboxClient.ts`:
- Around line 14-25: `mappingsSandboxRunner` in `sandboxClient.ts` should not
pass raw `Number.parseInt(...)` results directly into `IvmScriptRunner`, because
non-numeric env values can become `NaN` and break or weaken limits. Add a small
reusable env-int helper near `mappingsSandboxRunner` that parses each
`CUSTOM_MAPPINGS_IVM_*` variable, validates it is a finite number, and falls
back to the existing defaults when parsing fails. Apply it to `memoryLimitMb`,
`initTimeoutMs`, `execTimeoutMs`, `maxSize`, and `ttlMs`, and ensure the values
handed to `IvmScriptRunner` are always valid numbers.

In `@src/util/ivm/scriptRunner.ts`:
- Around line 75-86: Validate the sandbox limits in IvmScriptRunner before
constructing the runner state: the constructor currently accepts values from
IvmScriptRunnerOptions without checking for NaN, zero, or negatives, which can
break isolate creation and timeout behavior later. Add a fail-fast validation
step in the IvmScriptRunner constructor (before assigning bundlePath,
memoryLimitMb, initTimeoutMs, execTimeoutMs, or creating the DisposableCache) to
verify the numeric limits are finite and positive, and throw a clear error when
invalid input is provided.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 62bf4943-7ce3-4ad4-8853-e4e06e180574

📥 Commits

Reviewing files that changed from the base of the PR and between 3611c0b and f80254b.

⛔ Files ignored due to path filters (4)
  • package.json is excluded by !**/*.json
  • test/integrations/destinations/ga4_v2/processor/customMappings.ts is excluded by !**/test/**
  • test/integrations/destinations/http/common.ts is excluded by !**/test/**
  • test/integrations/destinations/http/processor/configuration.ts is excluded by !**/test/**
📒 Files selected for processing (15)
  • src/cdk/v2/destinations/http/procWorkflow.yaml
  • src/cdk/v2/destinations/http/utils.ts
  • src/util/customMappings/mappingsSandbox.ts
  • src/util/customMappings/sandboxClient.test.ts
  • src/util/customMappings/sandboxClient.ts
  • src/util/ivm/scriptRunner.ts
  • src/v0/destinations/custom_audience/template/ivmScriptRunner.test.ts
  • src/v0/destinations/custom_audience/template/ivmScriptRunner.ts
  • src/v0/destinations/custom_audience/template/templateEngineSandbox.ts
  • src/v0/destinations/custom_audience/template/templateSandboxClient.ts
  • src/v0/destinations/ga4_v2/customMappingsHandler.js
  • src/v0/destinations/ga4_v2/transform.test.ts
  • src/v0/destinations/ga4_v2/transform.ts
  • src/v0/util/index.js
  • src/v0/util/index.test.js

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
src/util/customMappings/sandboxClient.ts (1)

25-30: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider guarding against NaN from misconfigured env vars.

Number.parseInt(process.env.CUSTOM_MAPPINGS_IVM_MEMORY_MB || '16', 10) will produce NaN if the env var is set to a non-numeric string (e.g., "abc"), since non-empty strings are truthy and bypass the || fallback. This would pass NaN to IvmScriptRunner which may not handle it gracefully. A Number.isNaN check or a small helper would make this more robust against operator misconfiguration.

♻️ Optional: add a safe-int helper
+const safeInt = (val: string | undefined, fallback: number): number => {
+  const n = Number.parseInt(val || '', 10);
+  return Number.isNaN(n) ? fallback : n;
+};
+
 let runner: IvmScriptRunner | undefined;
 const getRunner = (): IvmScriptRunner => {
   if (!runner) {
     runner = new IvmScriptRunner({
       bundlePath: BUNDLE_PATH,
-      memoryLimitMb: Number.parseInt(process.env.CUSTOM_MAPPINGS_IVM_MEMORY_MB || '16', 10),
-      initTimeoutMs: Number.parseInt(process.env.CUSTOM_MAPPINGS_IVM_INIT_TIMEOUT_MS || '5000', 10),
-      execTimeoutMs: Number.parseInt(process.env.CUSTOM_MAPPINGS_IVM_EXEC_TIMEOUT_MS || '500', 10),
+      memoryLimitMb: safeInt(process.env.CUSTOM_MAPPINGS_IVM_MEMORY_MB, 16),
+      initTimeoutMs: safeInt(process.env.CUSTOM_MAPPINGS_IVM_INIT_TIMEOUT_MS, 5000),
+      execTimeoutMs: safeInt(process.env.CUSTOM_MAPPINGS_IVM_EXEC_TIMEOUT_MS, 500),
       cacheName: 'custom_mappings_ivm',
-      maxSize: Number.parseInt(process.env.CUSTOM_MAPPINGS_IVM_CACHE_MAX_SIZE || '20', 10),
-      ttlMs: Number.parseInt(process.env.CUSTOM_MAPPINGS_IVM_CACHE_TTL_MS || '300000', 10),
+      maxSize: safeInt(process.env.CUSTOM_MAPPINGS_IVM_CACHE_MAX_SIZE, 20),
+      ttlMs: safeInt(process.env.CUSTOM_MAPPINGS_IVM_CACHE_TTL_MS, 300000),
     });
   }
   return runner;
 };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/util/customMappings/sandboxClient.ts` around lines 25 - 30, The numeric
env parsing in sandboxClient’s IvmScriptRunner config can pass NaN when a custom
mapping env var is set to a non-numeric value, because the current fallback only
handles empty values. Add a small safe-int helper or equivalent Number.isNaN
guard around the parsed values used for memoryLimitMb, initTimeoutMs,
execTimeoutMs, maxSize, and ttlMs, so each setting falls back to its default
when parsing fails.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/util/customMappings/sandboxClient.ts`:
- Around line 25-30: The numeric env parsing in sandboxClient’s IvmScriptRunner
config can pass NaN when a custom mapping env var is set to a non-numeric value,
because the current fallback only handles empty values. Add a small safe-int
helper or equivalent Number.isNaN guard around the parsed values used for
memoryLimitMb, initTimeoutMs, execTimeoutMs, maxSize, and ttlMs, so each setting
falls back to its default when parsing fails.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5f97c000-5c28-437a-aa1d-d4962774f6b2

📥 Commits

Reviewing files that changed from the base of the PR and between f80254b and 7f113e3.

📒 Files selected for processing (7)
  • src/cdk/v2/destinations/http/utils.test.ts
  • src/cdk/v2/destinations/http/utils.ts
  • src/util/customMappings/mappingsSandbox.ts
  • src/util/customMappings/sandboxClient.test.ts
  • src/util/customMappings/sandboxClient.ts
  • src/v0/destinations/ga4_v2/customMappingsHandler.js
  • src/v0/destinations/ga4_v2/transform.ts
🚧 Files skipped from review as they are similar to previous changes (5)
  • src/v0/destinations/ga4_v2/transform.ts
  • src/util/customMappings/mappingsSandbox.ts
  • src/v0/destinations/ga4_v2/customMappingsHandler.js
  • src/cdk/v2/destinations/http/utils.ts
  • src/util/customMappings/sandboxClient.test.ts

@codecov

codecov Bot commented Jul 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 96.21212% with 5 lines in your changes missing coverage. Please review.
✅ Project coverage is 92.76%. Comparing base (b17bd30) to head (2510bb7).

Files with missing lines Patch % Lines
src/util/ivm/scriptRunner.ts 95.52% 3 Missing ⚠️
...rc/v0/destinations/ga4_v2/customMappingsHandler.js 90.47% 2 Missing ⚠️
Additional details and impacted files
@@             Coverage Diff             @@
##           develop    #5348      +/-   ##
===========================================
+ Coverage    92.74%   92.76%   +0.01%     
===========================================
  Files          704      706       +2     
  Lines        38287    38323      +36     
  Branches      8986     8996      +10     
===========================================
+ Hits         35511    35551      +40     
- Misses        2548     2562      +14     
+ Partials       228      210      -18     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@shekhar-rudder
shekhar-rudder force-pushed the feature/int-6725-unsandboxed-jsontemplate-evaluation-of-destination-custom branch from 5d58988 to 5cdbade Compare July 8, 2026 12:18
saikumarrs
saikumarrs previously approved these changes Jul 13, 2026
Comment thread package.json Resolved
saikumarrs
saikumarrs previously approved these changes Jul 13, 2026
shekhar-rudder and others added 2 commits July 13, 2026 12:23
…lated-vm [INT-6725]

Tenant-supplied destination custom mappings (HTTP headers/queryParams/
propertiesMapping, GA4 v2 eventProperties) were evaluated in-process by
JsonTemplateEngine via the Function constructor with no sandbox, allowing
SSTI -> RCE and full environment disclosure (e.g. process.env||$.userId).

Route all such evaluation through an isolated-vm sandbox where process/require/
host globals are unreachable, so attack payloads cannot read the host env or
execute host code. Verified end-to-end over HTTP: with the sandbox on,
process.env-based expressions throw ("process is not defined") and the event
fails with a ConfigurationError; with it off (legacy path) the same payloads
leak a planted secret and the host PATH.

- Promote IvmScriptRunner to a shared util (src/util/ivm/scriptRunner.ts) with
  cacheName/maxSize/ttlMs options and a shared resolveBundlePath helper;
  custom_audience keeps its defaults.
- esbuild IIFE bundle of the engine (mappingsSandbox.ts -> dist/mappingsSandbox.bundle.js),
  built by the shared `npm run build:sandboxes` (both sandboxes) wired into
  build:ci/test/test:ts. The isolate has no process/require, so tenant
  expressions touching them throw and leak nothing (guaranteed by V8 isolation
  + structured-clone-only marshaling; verified by an adversarial review).
- Dedicated per-workspaceId isolate pool (custom_mappings_ivm), separate from
  custom_audience, sized lower (16MB, cache maxSize 20, 500ms exec); the runner
  is created lazily so importing the module has no side effects. Isolates are
  created lazily per workspace and purged by LRU + TTL; observability via the
  existing ivm_cache_* metrics tagged cache:custom_mappings_ivm.
- Centralize at the async chokepoint applyCustomMappings, behind
  CUSTOM_MAPPINGS_SANDBOX_ENABLED (default on; =false reverts to the
  byte-equivalent in-process eval, read per-call for instant rollback).
- Fail closed: a falsy workspaceId throws (never a shared/default isolate).
- Thread async + workspaceId through HTTP (procWorkflow + utils) and GA4 v2
  (handleCustomMappings + process). Transient PlatformError (sandbox
  unavailable / fail-closed) propagates as retryable; only genuine mapping
  errors become ConfigurationError. Infra errors surface a generic message
  (no infra-detail leak); the same hardening applied to custom_audience.
- Remove applyJSONStringTemplate (dead code, no production caller) and its helpers.
- Tests: unit (sandbox client incl. process/Function/constructor-chain escape
  vectors + fail-closed) and processor component security-regression fixtures
  for HTTP and GA4 v2 asserting no env leak.

Notes: the rudder-integrations-config from/path regex remains defense-in-depth
only (no change needed).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The two sandbox bundles were built by two chained esbuild commands that
duplicated an identical flag set, so every new sandbox meant copying the
whole flag string again. Pass both entry points to one esbuild call using
--outdir with --entry-names=[name].bundle, which emits the same
dist/*.bundle.js filenames while stating the shared flags once.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@shekhar-rudder
shekhar-rudder force-pushed the feature/int-6725-unsandboxed-jsontemplate-evaluation-of-destination-custom branch from bfcc8d7 to 2510bb7 Compare July 13, 2026 06:54
@sonarqubecloud

Copy link
Copy Markdown

@shekhar-rudder
shekhar-rudder merged commit 6def3f0 into develop Jul 13, 2026
34 checks passed
@shekhar-rudder
shekhar-rudder deleted the feature/int-6725-unsandboxed-jsontemplate-evaluation-of-destination-custom branch July 13, 2026 07:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants