Repository navigation
feat(custom_audience): sandbox template parsing in isolated-vm - #5185
shekhar-rudder merged 3 commits into
Conversation
|
Warning Rate limit exceeded
You’ve run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (3)
Note
|
| Layer / File(s) | Summary |
|---|---|
Cache infrastructure with configurable metric names src/util/ivmCache/index.js |
DisposableCache now accepts options.name to set cacheName (defaulting to 'ivm'), and emitStats() uses that name in the cache metric tag instead of hardcoded values, enabling per-runner metric isolation. |
IvmScriptRunner cached isolate execution src/v0/destinations/custom_audience/template/ivmScriptRunner.ts |
IvmScriptRunner class manages cached isolated-vm isolate contexts keyed by cacheKey. Lazily loads bundle source, creates isolates with configurable memory/timeout limits, compiles and executes expressions inside cached contexts, evicts entries on errors, and implements per-key promise coalescing to prevent concurrent duplicate isolate creation. |
IvmScriptRunner promise coalescing and concurrency tests src/v0/destinations/custom_audience/template/ivmScriptRunner.test.ts |
Jest suite validates promise coalescing for concurrent same-key calls (single isolate created), per-key isolate isolation for different cache keys, and transient failure recovery with cleanup enabling retries. Mocks isolated-vm, fs.readFileSync, and logger/stats with race-window widening delays. |
Sandbox entry point with error wrapping and parser type export src/v0/destinations/custom_audience/template/sandboxedParse.entry.ts, src/v0/destinations/custom_audience/template/templateParser.ts, src/v0/destinations/custom_audience/template/templateParser.test.ts |
Bundled esbuild IIFE entry defines globalThis.parseTemplateInSandbox wrapper with try/catch error conversion. ParseTemplateResult type is exported from templateParser for public API use. Import in test file corrected to reference templateParser instead of templateValidator. |
sandboxedParseTemplate wrapper and runner initialization src/v0/destinations/custom_audience/template/templateParserSandbox.ts |
Module-level IvmScriptRunner instance executes parseTemplateInSandbox expressions scoped to workspace. Exported sandboxedParseTemplate(template, workspaceId) wraps execution in try/catch; logs errors with workspace context and returns unavailability result on failure. |
Sandboxed parser integration and bundle freshness tests src/v0/destinations/custom_audience/template/templateParserSandbox.test.ts |
Jest suite includes assertBundleFreshness() helper validating bundle exists and is not older than source files, with targeted build instruction errors. Parameterized tests over valid and invalid template cases verify result shapes and error regex matching. |
EventTestController sandbox integration with workspace validation src/controllers/eventTest.ts, src/controllers/__tests__/eventTest.test.ts |
parseCustomAudienceTemplate becomes async with Zod schema validation requiring non-empty requestBody and workspaceId. Returns HTTP 400 on validation failure or 200 with sandboxedParseTemplate result on success. Tests cover valid/invalid templates and workspace-scoped validation errors. |
Workflow CI build step update .github/workflows/dt-test-and-report-code-coverage.yml |
Adds "Build" step executing npm run build:ci before test/lint steps, ensuring the custom-audience-sandbox bundle is built in the coverage job CI workflow. |
Sequence Diagrams
IvmScriptRunner Cached Isolate Execution Flow
sequenceDiagram
participant Client as Application
participant Runner as IvmScriptRunner
participant Cache as DisposableCache
participant Isolate as isolated-vm Isolate
Client->>Runner: execute(cacheKey, expression)
Runner->>Cache: has(cacheKey)?
alt entry cached
Cache-->>Runner: cached {isolate, context}
else entry missing
Runner->>Runner: pendingCreations[cacheKey]?
alt creation in flight
Runner->>Runner: await pending promise
else first requester
Runner->>Isolate: create Isolate + context
Isolate-->>Runner: ready
Runner->>Cache: set(cacheKey, entry)
end
end
Runner->>Isolate: script.run(expression, {timeout, copy})
Isolate-->>Runner: result T
alt execution error
Runner->>Cache: delete(cacheKey)
Runner->>Runner: throw
else success
Runner-->>Client: result T
end
Controller Request Validation and Sandbox Execution
sequenceDiagram
participant Client as HTTP Client
participant Controller as EventTestController
participant Validator as Zod Schema
participant Sandbox as sandboxedParseTemplate
Client->>Controller: POST /test-router/custom_audience/parse-template
Controller->>Validator: safeParse({requestBody, workspaceId})
alt validation fails
Validator-->>Controller: error
Controller->>Controller: formatZodError(error)
Controller-->>Client: 400 {error: message}
else validation succeeds
Validator-->>Controller: {requestBody, workspaceId}
Controller->>Sandbox: await execute(requestBody, workspaceId)
Sandbox-->>Controller: ParseTemplateResult
Controller-->>Client: 200 {valid, recordFields or errors}
end
Estimated code review effort
🎯 4 (Complex) | ⏱️ ~60 minutes
This PR introduces substantial new infrastructure spanning isolated-vm isolate management with promise coalescing, bundled sandbox execution, comprehensive concurrent/failure testing, and multi-layer integration. The logic is dense in the IvmScriptRunner (cache entry lifecycle, error eviction, pending coalescing), requiring careful review of concurrency patterns. The breadth spans cache metrics, isolate management, bundled entry points, controller changes, and CI, with meaningful interdependencies between layers. Test coverage is thorough but involves mocking complexity that warrants verification against actual isolated-vm behavior.
🚥 Pre-merge checks | ✅ 3 | ❌ 2
❌ Failed checks (2 warnings)
| Check name | Status | Explanation | Resolution |
|---|---|---|---|
| Description check | The PR description is thorough and covers key sections, but the formal description template sections are not explicitly addressed in the required format. | Structure the description using the template sections: 'What are the changes', 'Related Linear task', 'Objectives', and complete all checklists. Currently missing explicit Linear task reference and formal section organization. | |
| Docstring Coverage | Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. | Write docstrings for the functions missing them to satisfy the coverage threshold. |
✅ Passed checks (3 passed)
| Check name | Status | Explanation |
|---|---|---|
| Title check | ✅ Passed | The title accurately and concisely summarizes the main objective of the PR: sandboxing template parsing in isolated-vm for the custom_audience destination. |
| 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. |
✏️ Tip: You can configure your own custom pre-merge checks in the settings.
✨ Finishing Touches
🧪 Generate unit tests (beta)
- Create PR with unit tests
- Commit unit tests in branch
feat/int-6296-isolate-vm-integration-for-template-parsing
Tip
💬 Introducing Slack Agent: The best way for teams to turn conversations into code.
Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.
- Generate code and open pull requests
- Plan features and break down work
- Investigate incidents and troubleshoot customer tickets together
- Automate recurring tasks and respond to alerts with triggers
- Summarize progress and report instantly
Built for teams:
- Shared memory across your entire org—no repeating context
- Per-thread sandboxes to safely plan and execute work
- Governance built-in—scoped access, auditability, and budget controls
One agent for your entire SDLC. Right inside Slack.
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 and usage tips.
436faf9 to
ee7c61b
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (3)
src/v0/destinations/custom_audience/template/templateParser.ts (1)
33-41: 💤 Low valueConsider verifying
INTERNAL_ROOTagainst the engine at startup.
'___d'is an undocumented internal alias injected by@rudderstack/json-template-engine. The existing unit tests catch a change implicitly (field extraction would return[]on valid templates), but a silent drift between the constant and the engine version could be subtle to debug in production.A lightweight guard would surface the mismatch early:
💡 Suggested assertion in templateParser.ts (dev/test environment)
+// Sanity-check the engine's internal root alias at module load time. +// If this throws, the engine's internal representation has changed and +// INTERNAL_ROOT must be updated to match. +const _check = JsonTemplateEngine.parse('$.x', { defaultPathType: PathType.JSON }); +const _root = (_check as any).statements?.[0]?.root; +if (_root !== INTERNAL_ROOT) { + throw new Error( + `json-template-engine internal root alias changed: expected "${INTERNAL_ROOT}", got "${String(_root)}". Update INTERNAL_ROOT.`, + ); +}🤖 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/v0/destinations/custom_audience/template/templateParser.ts` around lines 33 - 41, Add a startup guard in templateParser.ts that verifies the INTERNAL_ROOT constant matches the engine's internal alias by parsing a trivial JSONPath and inspecting the parser output; e.g., call the engine's parser (the same parser used by template parsing) on "$" or "$.foo" and assert the returned AST/root identifier equals INTERNAL_ROOT, run this check only in dev/test environments, and throw or log a clear error if it mismatches so drift is detected early.src/controllers/__tests__/eventTest.test.ts (2)
41-56: ⚡ Quick winAssert exact template passthrough to the sandbox mock.
Using
expect.any(String)weakens regression detection. Assert the exactrequestBodysent in the request.Suggested patch
- const response = await request(server) + const requestBody = `{ + "data": $.records.({ + "email": .email, + "phone": .phone_sha256 + }) + }`; + + const response = await request(server) .post(ENDPOINT) .send({ - requestBody: `{ - "data": $.records.({ - "email": .email, - "phone": .phone_sha256 - }) - }`, + requestBody, workspaceId: 'test-workspace', }); @@ - expect(mockParseTemplate).toHaveBeenCalledWith(expect.any(String), 'test-workspace'); + expect(mockParseTemplate).toHaveBeenCalledWith(requestBody, 'test-workspace');🤖 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/controllers/__tests__/eventTest.test.ts` around lines 41 - 56, The test currently uses a loose matcher expect.any(String) for the template passed to mockParseTemplate; change the assertion to verify the exact requestBody string is forwarded so regressions are caught: construct the exact string used in the POST (the requestBody payload sent to request(server).post(ENDPOINT).send(...)) and replace expect(mockParseTemplate).toHaveBeenCalledWith(expect.any(String), 'test-workspace') with an assertion that mockParseTemplate was called with that exact requestBody string and 'test-workspace' (use the same variable or inline literal matching the request payload) and keep the other expectations unchanged.
102-107: ⚡ Quick winVerify validation failures do not call the sandbox parser.
The 400 assertions are good; adding a no-call assertion ensures malformed input is always rejected before sandbox execution.
Suggested patch
it.each(badRequestCases)('should return 400: $name', async ({ body, expectedError }) => { const response = await request(server).post(ENDPOINT).send(body); expect(response.status).toBe(400); expect(response.body.error).toBe(expectedError); + expect(mockParseTemplate).not.toHaveBeenCalled(); });🤖 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/controllers/__tests__/eventTest.test.ts` around lines 102 - 107, Add an assertion that the sandbox parsing function is not invoked for badRequestCases: mock or spy the sandbox parser used by the controller (e.g., sandbox.parse or the sandboxParser export), run the existing it.each test that posts to ENDPOINT using server and badRequestCases, then expect the mock/spy toHaveBeenCalledTimes(0) (or not.toHaveBeenCalled()) after asserting status 400 and response.body.error; place the spy setup/teardown near the test and reference badRequestCases, ENDPOINT, and server so the test ensures validation fails before any sandbox parsing.
🤖 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/controllers/eventTest.ts`:
- Line 45: Wrap the call to sandboxedParseTemplate in a try/catch inside the
event test handler so sandbox/runtime failures don't bubble as unstructured
errors; call sandboxedParseTemplate(parsed.data.requestBody,
parsed.data.workspaceId) inside try, and in catch log the error
(ctx.logger.error or console.error), set a deterministic response (e.g.
ctx.status = 400 or 500) and return a structured body like { error: 'Template
parse failed', message: error.message } so the endpoint always returns a
well-formed error.
In `@src/v0/destinations/custom_audience/template/ivmScriptRunner.ts`:
- Around line 96-104: getOrCreate currently allows two concurrent callers to
race: both call createEntry() and cache.set(), causing the LRU dispose to
destroy the first entry while request A still uses it; implement promise
coalescing by storing the in-flight Promise from createEntry() in the cache (or
a separate inflight Map) keyed by cacheKey so concurrent getOrCreate callers
await the same promise instead of calling createEntry() twice; once the promise
resolves replace the Promise entry with the actual entry in cache (and ensure
dispose/destroy runs only on the real entry), and update any error handling that
currently calls this.cache.delete(cacheKey) so it only deletes the
inflight/pending entry when that promise rejects.
In `@src/v0/destinations/custom_audience/template/templateParserSandbox.ts`:
- Around line 13-14: Replace the fragile process.cwd() based bundle path in
templateParserSandbox.ts with a __dirname-relative resolution: update the
BUNDLE_PATH definition (symbol BUNDLE_PATH) so it uses __dirname (e.g.,
path.resolve or path.join from __dirname) to locate
dist/sandboxedParse.bundle.js relative to the templateParserSandbox.ts file,
ensuring the sandbox loader consistently finds the bundle even if the process
CWD changes.
---
Nitpick comments:
In `@src/controllers/__tests__/eventTest.test.ts`:
- Around line 41-56: The test currently uses a loose matcher expect.any(String)
for the template passed to mockParseTemplate; change the assertion to verify the
exact requestBody string is forwarded so regressions are caught: construct the
exact string used in the POST (the requestBody payload sent to
request(server).post(ENDPOINT).send(...)) and replace
expect(mockParseTemplate).toHaveBeenCalledWith(expect.any(String),
'test-workspace') with an assertion that mockParseTemplate was called with that
exact requestBody string and 'test-workspace' (use the same variable or inline
literal matching the request payload) and keep the other expectations unchanged.
- Around line 102-107: Add an assertion that the sandbox parsing function is not
invoked for badRequestCases: mock or spy the sandbox parser used by the
controller (e.g., sandbox.parse or the sandboxParser export), run the existing
it.each test that posts to ENDPOINT using server and badRequestCases, then
expect the mock/spy toHaveBeenCalledTimes(0) (or not.toHaveBeenCalled()) after
asserting status 400 and response.body.error; place the spy setup/teardown near
the test and reference badRequestCases, ENDPOINT, and server so the test ensures
validation fails before any sandbox parsing.
In `@src/v0/destinations/custom_audience/template/templateParser.ts`:
- Around line 33-41: Add a startup guard in templateParser.ts that verifies the
INTERNAL_ROOT constant matches the engine's internal alias by parsing a trivial
JSONPath and inspecting the parser output; e.g., call the engine's parser (the
same parser used by template parsing) on "$" or "$.foo" and assert the returned
AST/root identifier equals INTERNAL_ROOT, run this check only in dev/test
environments, and throw or log a clear error if it mismatches so drift is
detected early.
🪄 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: 4f809900-c1d1-45a4-b14c-f7f1c3979cc5
⛔ Files ignored due to path filters (7)
.claude/skills/code-structure/SKILL.mdis excluded by!**/*.md.claude/skills/typescript-guidelines/SKILL.mdis excluded by!**/*.md.claude/skills/writing-tests/SKILL.mdis excluded by!**/*.mdCLAUDE.mdis excluded by!**/*.mdpackage-lock.jsonis excluded by!**/package-lock.json,!**/*.jsonpackage.jsonis excluded by!**/*.jsontest/__tests__/ivmCache/index.test.jsis excluded by!**/test/**
📒 Files selected for processing (10)
src/controllers/__tests__/eventTest.test.tssrc/controllers/eventTest.tssrc/routes/testEvents.tssrc/util/ivmCache/index.jssrc/v0/destinations/custom_audience/template/ivmScriptRunner.tssrc/v0/destinations/custom_audience/template/sandboxedParse.entry.tssrc/v0/destinations/custom_audience/template/templateParser.test.tssrc/v0/destinations/custom_audience/template/templateParser.tssrc/v0/destinations/custom_audience/template/templateParserSandbox.test.tssrc/v0/destinations/custom_audience/template/templateParserSandbox.ts
5f61819 to
7b63ee3
Compare
9861abe to
35bf517
Compare
Run parseTemplate inside per-workspace isolated-vm isolates so user-supplied templates cannot affect the host process. Each isolate is LRU-cached (via DisposableCache) and loaded with an esbuild IIFE bundle of the parser.
9ecb2fb to
f18347f
Compare
.npmrc has ignore-scripts=true, so npm ci skips lifecycle hooks. The previous workflow explicitly called `npm run prepare` to rebuild isolated-vm, but that was dropped when switching to `npm run build:ci`. Co-Authored-By: Claude Opus 4.6 <[email protected]>
Codecov Report❌ Patch coverage is
Additional details and impacted files@@ Coverage Diff @@
## develop #5185 +/- ##
===========================================
- Coverage 92.32% 92.30% -0.03%
===========================================
Files 673 675 +2
Lines 36957 37020 +63
Branches 8672 8672
===========================================
+ Hits 34122 34172 +50
- Misses 2597 2610 +13
Partials 238 238 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
fa750f9 to
f125152
Compare
|
…vm (#5193) ## Summary Moves user-supplied `requestBody` template **evaluation** into isolated-vm, completing the sandbox work started in #5185 (which sandboxed only the *parse* step). After this change, untrusted templates supplied via destination config never run in the Node process — both validation and execution happen inside a memory- and time-limited isolate.



Summary
parseTemplateinside per-workspace isolated-vm isolates so user-supplied templates cannot affect the host processIvmScriptRunner— a cached isolate runner backed byDisposableCache(LRU with stats/logging/auto-disposal)sandboxedParse.bundle.js) loaded into each isolate contextparse-templateendpoint async and requireworkspaceIdfor per-workspace isolate isolationcacheNametoDisposableCacheso different caches emit distinct metric tagsIvmScriptRunner.getOrCreatevia promise coalescing — concurrent calls for the same workspace now share a single in-flight isolate creation instead of each creating their ownnpm run prepare(isolated-vm native rebuild) beforebuild:ci—.npmrchasignore-scripts=trueso lifecycle hooks don't auto-runTest plan
npm test -- --testPathPattern="custom_audience" --no-coverage— unit tests for templateParser + sandboxnpm test -- --testPathPattern="ivmScriptRunner" --no-coverage— promise coalescing race condition testsnpm test -- --testPathPattern="ivmCache" --no-coverage— cacheName and metric tag testsnpm test -- --testPathPattern="eventTest" --no-coverage— controller endpoint testsnpm run build:custom-audience-sandboxbuilds the bundle successfully--no-node-snapshotin the start script doesn't break normal startupuser_transformation*test suites no longer crash on missing isolated-vm binary)🤖 Generated with Claude Code