Repository navigation
fix(security): sandbox tenant-config custom-mapping evaluation in isolated-vm [INT-6725] - #5348
Conversation
|
Warning Review limit reached
Next review available in: 45 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the 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 configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (4)
📒 Files selected for processing (16)
Note
|
| 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
- rudderlabs/rudder-transformer#5185: Updates related isolated-vm cache infrastructure used by sandbox execution.
- rudderlabs/rudder-transformer#5193: Uses the shared isolate-runner API for custom-audience template sandboxing.
Suggested reviewers: itssudip, krishna2020
🚥 Pre-merge checks | ✅ 4 | ❌ 1
❌ Failed checks (1 warning)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Docstring Coverage | 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.
Comment @coderabbitai help to get the list of available commands.
e87f423 to
f80254b
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
src/util/ivm/scriptRunner.ts (1)
75-86: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick winValidate the sandbox limits before creating the runner.
IvmScriptRunnerOptionsis shared by callers that parse these values from env vars, so malformed input can still flow through asNaN,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 winGuard against
NaNfrom 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",parseIntreturnsNaN, which is then passed directly toIvmScriptRunnerandisolated-vm. ANaNexecTimeoutMscould 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-vmv5.0.3 handlesNaNformemoryLimitandtimeoutoptions — 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
⛔ Files ignored due to path filters (4)
package.jsonis excluded by!**/*.jsontest/integrations/destinations/ga4_v2/processor/customMappings.tsis excluded by!**/test/**test/integrations/destinations/http/common.tsis excluded by!**/test/**test/integrations/destinations/http/processor/configuration.tsis excluded by!**/test/**
📒 Files selected for processing (15)
src/cdk/v2/destinations/http/procWorkflow.yamlsrc/cdk/v2/destinations/http/utils.tssrc/util/customMappings/mappingsSandbox.tssrc/util/customMappings/sandboxClient.test.tssrc/util/customMappings/sandboxClient.tssrc/util/ivm/scriptRunner.tssrc/v0/destinations/custom_audience/template/ivmScriptRunner.test.tssrc/v0/destinations/custom_audience/template/ivmScriptRunner.tssrc/v0/destinations/custom_audience/template/templateEngineSandbox.tssrc/v0/destinations/custom_audience/template/templateSandboxClient.tssrc/v0/destinations/ga4_v2/customMappingsHandler.jssrc/v0/destinations/ga4_v2/transform.test.tssrc/v0/destinations/ga4_v2/transform.tssrc/v0/util/index.jssrc/v0/util/index.test.js
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/util/customMappings/sandboxClient.ts (1)
25-30: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider guarding against NaN from misconfigured env vars.
Number.parseInt(process.env.CUSTOM_MAPPINGS_IVM_MEMORY_MB || '16', 10)will produceNaNif 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 passNaNtoIvmScriptRunnerwhich may not handle it gracefully. ANumber.isNaNcheck 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
📒 Files selected for processing (7)
src/cdk/v2/destinations/http/utils.test.tssrc/cdk/v2/destinations/http/utils.tssrc/util/customMappings/mappingsSandbox.tssrc/util/customMappings/sandboxClient.test.tssrc/util/customMappings/sandboxClient.tssrc/v0/destinations/ga4_v2/customMappingsHandler.jssrc/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 Report❌ Patch coverage is
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. 🚀 New features to boost your workflow:
|
5d58988 to
5cdbade
Compare
…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]>
bfcc8d7 to
2510bb7
Compare
|



Summary
Fixes INT-6725 (parent INT-6708): tenant-supplied destination "custom mappings" were evaluated in-process by
JsonTemplateEnginevia theFunctionconstructor with no sandbox, allowing SSTI → RCE (Function(...),require('child_process').execSync(...)) and full environment disclosure (process.env||$.userIddumps every env var — verified). Affected tenant-config paths: HTTPheaders/queryParams/propertiesMappingand GA4 v2eventProperties.This routes all such evaluation through an
isolated-vmsandbox whereprocess/require/host globals are unreachable, so the attack payloads resolve to a harmless fallback (or fail closed) and leak nothing.Approach
applyCustomMappings/applyJSONStringTemplate(src/v0/util/index.js) are now async and delegate to a sandboxed client. Every current and future caller inherits the sandbox.custom_audiencepattern — an esbuild IIFE bundle of the engine (dist/mappingsSandbox.bundle.js) loaded into a dedicated, per-workspaceIdisolate pool (custom_mappings_ivm), separate from custom_audience and sized lower (16 MB,maxSize20, 500 ms exec). Isolates are created lazily and self-evict via LRU + TTL.IvmScriptRunnerwas promoted tosrc/util/ivm/scriptRunner.ts.workspaceIdthrows — never a shared/default isolate (no cross-tenant state).CUSTOM_MAPPINGS_SANDBOX_ENABLED(default on;=falsereverts to byte-equivalent in-process eval, read per-call) — instant rollback without redeploy.globalThis.process = {}soprocess.env.Xresolves toundefined→ graceful fallback (deterministic; the real guarantee is V8 isolation + structured-clone-only marshaling — an adversarial review confirmed no host-data escape).Security verification
process.env||$.userId,process.env.SECRET||$.userId,Function('return process.env')(),({}).constructor.constructor('return process.env')(),Function('return this')()) leak no planted host secret;requireis unreachable.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 existingivm_cache_*metrics taggedcache:custom_mappings_ivm.Testing
build:ciPASS · sandbox/runner/GA4/custom_audience TS suites 108/108 · chokepoint +index.test.js196/196 · HTTP component 17/17 (incl. INT-6725 regression) · GA4 v2 component 11/11.Notes / follow-ups
rudder-integrations-configfrom/pathregex stays as defense-in-depth but is no longer the security boundary — no regex change needed.applyJSONStringTemplatecurrently has no production caller (reachable only via tests) — flag for follow-up: wire the intended caller or remove.docs/features.mdper org convention; startup bundle-existence check.🤖 Generated with Claude Code