Skip to content

Conversation

@frontegg-david
Copy link
Contributor

@frontegg-david frontegg-david commented Jan 5, 2026

Summary by CodeRabbit

  • New Features

    • Selectable AST validation presets for configurable enclave validation behavior.
  • Security Improvements

    • Stronger sandbox isolation for user-provided globals with recursive protection.
    • New runtime protections addressing function-gadget and other sandbox escape patterns.
  • Documentation

    • Security audit updated to v2.0.0 with detailed security model, attack research, and recommendations.
  • Tests

    • Test suite expanded to ~1,184 tests (100% pass); blocked attack vectors increased to ~150+.

✏️ Tip: You can customize this high-level summary in your review settings.

… for custom globals and adding AST validation presets
@coderabbitai
Copy link

coderabbitai bot commented Jan 5, 2026

📝 Walkthrough

Walkthrough

The PR adds configurable AST validation presets, recursively secures user-provided globals with SecureProxy (including bound functions and nested objects), and introduces extensive runtime and function-gadget sandbox-escape test suites; README and SECURITY-AUDIT metrics/docs updated to reflect v2.0.0 and expanded test coverage.

Changes

Cohort / File(s) Summary
Docs & Security Audit
libs/enclave-vm/README.md, libs/enclave-vm/SECURITY-AUDIT.md
Updated security metrics (tests: 516+ → 1184+, attack vectors: 81+ → 150+). Added v2.0.0 research sections (Runtime Attack Vector Research, Function Gadget Attack Research), security model details, Security Mode Differences, and Version History notes.
AST Preset API & Types
libs/enclave-vm/src/types.ts, libs/enclave-vm/src/index.ts, libs/enclave-vm/src/enclave.ts
New exported AstPreset type and preset?: AstPreset option on CreateEnclaveOptions. Replaced hardcoded AST validator with createValidator(presetName, customAllowedGlobals) factory supporting presets: agentscript, strict, secure, standard, permissive. Agentscript merges custom allowed globals; other presets use their own validators.
SecureProxy Integration (globals)
libs/enclave-vm/src/adapters/vm-adapter.ts
When injecting user globals, object values are wrapped via createSecureProxy(...) with config from execution context; primitives are assigned directly.
SecureProxy Recursive Binding
libs/enclave-vm/src/double-vm/parent-vm-bootstrap.ts
SecureProxy get trap now binds function values to original target and returns recursively proxied bound functions (createSecureProxy(boundMethod, depth+1)); nested object property accesses are recursively proxied to preserve the security boundary.
Runtime Attack Vector Tests
libs/enclave-vm/src/__tests__/runtime-attack-vectors.spec.ts
New comprehensive suite covering computed property attacks, iterator/generator chains, error-object exploits, type coercion, known CVE patterns, tool-result interactions, syntax obfuscation, and custom globals security; documents coverage.
Function Gadget Attack Tests
libs/enclave-vm/src/__tests__/function-gadget-attacks.spec.ts
New large suite exercising 10 categories of gadget attacks (constructor chains, callback injection, coercion gadgets, Function.prototype exploitation, tagged templates, JSON reviver/replacer, implicit coercion, getter/setter attacks, prototype pollution, combined chains).
Custom Globals Security Tests (duplicated)
libs/enclave-vm/src/__tests__/enclave.security.spec.ts
Added "Sandbox Escape Prevention (Custom Globals)" tests validating __proto__ blocking, prototype-chain escape prevention, and constructor access blocking with Double VM enabled/disabled. Note: the suite appears duplicated in the diff (two identical insertions).

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Poem

🐰 I hop through presets, five ways to play,

Proxies curl tight where dark tricks stray.
Tests multiplied, a vigilant crew,
One-thousand-one-hundred-eighty-four guards anew. 🥕🔒

Pre-merge checks

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the two main changes: recursive SecureProxy wrapping for custom globals and AST validation presets, both of which are core to the changeset.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

📜 Recent review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 63d8417 and 62cbe12.

📒 Files selected for processing (2)
  • libs/enclave-vm/README.md
  • libs/enclave-vm/SECURITY-AUDIT.md
🧰 Additional context used
📓 Path-based instructions (1)
libs/**

⚙️ CodeRabbit configuration file

libs/**: Contains publishable SDK libraries. Review for API correctness, breaking changes, and consistency with docs. When public APIs change, ensure there is a matching docs/draft/docs/** update (not direct edits under docs/docs/**).

Files:

  • libs/enclave-vm/README.md
  • libs/enclave-vm/SECURITY-AUDIT.md
🔇 Additional comments (7)
libs/enclave-vm/README.md (2)

15-16: Security metrics accurately reflect expanded test coverage.

The updated metrics (1184+ tests, 150+ blocked attack vectors) are consistent with the PR's introduction of extensive runtime and function-gadget sandbox-escape test suites mentioned in the ai_summary.


124-159: AST Presets documentation is clear and well-structured.

The section effectively explains the distinction between preset (AST-level validation before execution) and securityLevel (runtime constraints), with the Key Differences table being particularly helpful for users to understand when and why to use each option. The TypeScript example demonstrates correct usage.

One clarification needed: Line 158 references the allowedGlobals option for AST validation, but this option is not documented in the CreateEnclaveOptions interface (lines 81–102). Please clarify whether allowedGlobals is:

  • A separate configuration option that should be added to the interface documentation
  • An automatic feature when using the agentscript preset (no additional config needed)
  • Implicitly handled when custom globals are provided with the agentscript preset

This will help users understand the exact API contract for whitelisting globals in AST validation.

libs/enclave-vm/SECURITY-AUDIT.md (5)

571-591: v2.0.0 changelog accurately reflects test expansion and new research areas.

The entry documents 1184 total tests (up from 690), new test categories covering runtime and function gadget attacks, and the critical finding about custom globals. The structure and metrics align with the PR's focus on enhancing security through SecureProxy wrapping.


595-699: Runtime Attack Vector Research section is comprehensive and well-structured.

The section properly documents:

  • The three-layer security model (wrapped objects, sandbox-created objects, AST validation)
  • The critical custom globals vulnerability and its fix via recursive SecureProxy wrapping
  • The known limitation with constructor functions as globals (clearly marked as "NOT safe")
  • 24 attack categories with individual vector counts and status indicators

The mitigation guidance (only pass primitives or plain objects, avoid constructor functions) is explicit and actionable.


701-763: Function Gadget Attack Research section provides thorough coverage of sophisticated attack vectors.

The table comprehensively maps 50 test cases across 10 attack categories (primitive constructor chains, callbacks, coercion, Function.prototype exploitation, etc.), with security level and result indicators for each. The key insight about sandbox-created objects leading to the sandbox's Function constructor (not the host's) is clearly articulated and explains why gadget chains remain contained.


764-783: Security Mode Differences table clearly delineates AgentScript (default) vs PERMISSIVE behavior.

The comparison properly highlights:

  • Function expressions, getters/setters, and arguments.callee availability in PERMISSIVE mode
  • Constructor access differences for wrapped globals
  • Consistent host isolation guarantees in both modes

This provides users with clear guidance on the security/flexibility tradeoff when choosing presets.


1-10: The AstPreset type is properly exported from the public API in libs/enclave-vm/src/index.ts (line 29), and all five preset names documented in SECURITY-AUDIT.md (agentscript, strict, secure, standard, permissive) are correctly defined in src/types.ts (line 41) and implemented in src/enclave.ts with corresponding factory functions and switch-case handling (lines 623–651).


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

@frontegg-david
Copy link
Contributor Author

frontegg-david commented Jan 5, 2026

Snyk checks have passed. No issues have been found so far.

Status Scanner Critical High Medium Low Total (0)
Open Source Security 0 0 0 0 0 issues
Code Security 0 0 0 0 0 issues

💻 Catch issues earlier using the plugins for VS Code, JetBrains IDEs, Visual Studio, and Eclipse.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
libs/enclave-vm/SECURITY-AUDIT.md (1)

452-453: Inconsistent test count in conclusion section.

The conclusion states "100% test pass rate (690/690 passing)" but the header at line 5-6 indicates "1184 security tests" with "1184/1184 passing". Update the conclusion to reflect the correct test count.

🔎 Proposed fix
-- ✅ **100% test pass rate** (690/690 passing)
+- ✅ **100% test pass rate** (1184/1184 passing)
🧹 Nitpick comments (1)
libs/enclave-vm/src/__tests__/runtime-attack-vectors.spec.ts (1)

567-623: Important known limitation documentation test.

This test at line 567 correctly documents a critical security consideration: passing constructor functions (like Map) as globals exposes the host's Function constructor. The test doesn't fail - it documents the behavior with a console.warn.

Consider using a more structured approach to document this limitation rather than console.warn in test output, which may be noisy or missed.

🔎 Alternative approach
         if (!isBlockedOrNoAccess) {
           // This confirms the limitation: host access IS possible
           // When Map is passed as global, Function constructor is host's
-          console.warn('⚠️  KNOWN LIMITATION: Passing Map as global allows host access:', result.value);
+          // Note: This is expected behavior - documented limitation
+          // See SECURITY-AUDIT.md section "Constructor Functions as Globals"
         }

The limitation is already well-documented in the SECURITY-AUDIT.md file, so the runtime warning may be redundant.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a9bbd2d and 63d8417.

📒 Files selected for processing (10)
  • libs/enclave-vm/README.md
  • libs/enclave-vm/SECURITY-AUDIT.md
  • libs/enclave-vm/src/__tests__/enclave.security.spec.ts
  • libs/enclave-vm/src/__tests__/function-gadget-attacks.spec.ts
  • libs/enclave-vm/src/__tests__/runtime-attack-vectors.spec.ts
  • libs/enclave-vm/src/adapters/vm-adapter.ts
  • libs/enclave-vm/src/double-vm/parent-vm-bootstrap.ts
  • libs/enclave-vm/src/enclave.ts
  • libs/enclave-vm/src/index.ts
  • libs/enclave-vm/src/types.ts
🧰 Additional context used
📓 Path-based instructions (1)
libs/**

⚙️ CodeRabbit configuration file

libs/**: Contains publishable SDK libraries. Review for API correctness, breaking changes, and consistency with docs. When public APIs change, ensure there is a matching docs/draft/docs/** update (not direct edits under docs/docs/**).

Files:

  • libs/enclave-vm/src/index.ts
  • libs/enclave-vm/src/types.ts
  • libs/enclave-vm/src/__tests__/function-gadget-attacks.spec.ts
  • libs/enclave-vm/src/__tests__/runtime-attack-vectors.spec.ts
  • libs/enclave-vm/src/double-vm/parent-vm-bootstrap.ts
  • libs/enclave-vm/README.md
  • libs/enclave-vm/src/__tests__/enclave.security.spec.ts
  • libs/enclave-vm/src/enclave.ts
  • libs/enclave-vm/src/adapters/vm-adapter.ts
  • libs/enclave-vm/SECURITY-AUDIT.md
🧬 Code graph analysis (3)
libs/enclave-vm/src/types.ts (1)
libs/enclave-vm/src/index.ts (1)
  • AstPreset (29-29)
libs/enclave-vm/src/enclave.ts (2)
libs/enclave-vm/src/types.ts (1)
  • AstPreset (41-41)
libs/ast-guard/src/presets/agentscript.preset.ts (1)
  • createAgentScriptPreset (178-424)
libs/enclave-vm/src/adapters/vm-adapter.ts (2)
libs/enclave-vm/src/index.ts (1)
  • createSecureProxy (92-92)
libs/enclave-vm/src/secure-proxy.ts (1)
  • createSecureProxy (399-627)
🪛 markdownlint-cli2 (0.18.1)
libs/enclave-vm/SECURITY-AUDIT.md

719-719: Table column count
Expected: 4; Actual: 1; Too few cells, row will be missing data

(MD056, table-column-count)


726-726: Table column count
Expected: 4; Actual: 1; Too few cells, row will be missing data

(MD056, table-column-count)


732-732: Table column count
Expected: 4; Actual: 1; Too few cells, row will be missing data

(MD056, table-column-count)


737-737: Table column count
Expected: 4; Actual: 1; Too few cells, row will be missing data

(MD056, table-column-count)


741-741: Table column count
Expected: 4; Actual: 1; Too few cells, row will be missing data

(MD056, table-column-count)


744-744: Table column count
Expected: 4; Actual: 1; Too few cells, row will be missing data

(MD056, table-column-count)


747-747: Table column count
Expected: 4; Actual: 1; Too few cells, row will be missing data

(MD056, table-column-count)


751-751: Table column count
Expected: 4; Actual: 1; Too few cells, row will be missing data

(MD056, table-column-count)


755-755: Table column count
Expected: 4; Actual: 1; Too few cells, row will be missing data

(MD056, table-column-count)


759-759: Table column count
Expected: 4; Actual: 1; Too few cells, row will be missing data

(MD056, table-column-count)

🔇 Additional comments (16)
libs/enclave-vm/src/double-vm/parent-vm-bootstrap.ts (1)

240-251: LGTM! Enhanced recursive proxying strengthens security.

The recursive wrapping of both bound methods and nested objects prevents deep property chain attacks. The depth limit (max 10) provides adequate protection against stack overflow while allowing reasonable nesting.

Key benefits:

  • Blocks attacks via bound function constructor access
  • Prevents prototype pollution through nested objects
  • Maintains internal slot access for built-in objects like Promise
libs/enclave-vm/src/index.ts (1)

29-29: New public API export looks good.

The AstPreset type addition is properly documented in types.ts with clear examples and preset descriptions.

Based on coding guidelines, when public APIs change in libs/, there should be a matching docs/draft/docs/ update. If documentation hasn't been prepared yet, please ensure it's added before release.

libs/enclave-vm/README.md (1)

15-16: Documentation updates reflect expanded test coverage.

The metrics correctly reflect the PR's enhanced security testing, with test count more than doubling (516+ → 1184+) and attack vector coverage increasing significantly (81+ → 150+).

libs/enclave-vm/src/adapters/vm-adapter.ts (1)

388-400: Enhanced custom globals security looks good.

Wrapping user-provided globals with createSecureProxy effectively prevents prototype chain attacks through custom objects. The conditional logic correctly bypasses primitives which don't need protection.

Minor observation: The as any cast on line 394 is necessary but consider using a more specific type if possible for better type safety.

libs/enclave-vm/src/types.ts (2)

26-41: Well-designed AstPreset type with excellent documentation.

The type follows TypeScript best practices and provides clear guidance through comprehensive JSDoc. The preset names are intuitive and align well with the existing SecurityLevel pattern.


714-738: Excellent API design and documentation for the preset option.

The new preset field is:

  • Non-breaking (optional)
  • Well-documented with clear examples
  • Aligned with existing patterns
  • Provides good developer guidance

The note about custom globals compatibility is particularly helpful.

libs/enclave-vm/src/__tests__/enclave.security.spec.ts (1)

1303-1426: Well-structured security test suite for custom globals.

The new test suite thoroughly covers critical security scenarios for custom globals with both Double VM enabled and disabled modes. The tests properly:

  • Verify __proto__ access blocking via string concatenation
  • Test prototype chain attack prevention
  • Validate constructor access blocking on nested objects
  • Consistently use securityLevel: 'STRICT' for appropriate test conditions
  • Properly dispose enclave instances after each test
libs/enclave-vm/src/enclave.ts (2)

14-21: LGTM - New preset imports are well-organized.

The imports for the preset factories are cleanly grouped and align with the new multi-preset architecture.


224-228: LGTM - Clean preset selection implementation.

The preset selection with fallback to 'agentscript' is straightforward and maintains backward compatibility.

libs/enclave-vm/src/__tests__/function-gadget-attacks.spec.ts (3)

1-29: Excellent documentation header explaining the security model.

The file header clearly explains the three-layer security approach (AST Layer, Runtime Layer, Sandbox Context) and the attack categories being tested. This is valuable documentation for future maintainers.


30-283: Comprehensive primitive constructor chain tests.

The tests thoroughly cover constructor chain attacks via String, Number, Boolean, Array, Object, and RegExp primitives. The tests correctly verify that even when the Function constructor is accessible through sandbox-created objects, it runs in sandbox context without host access.

Good practice: Tests use appropriate presets (PERMISSIVE for RegExp tests where needed).


1286-1339: Coverage summary provides good test documentation.

The coverage summary test that documents all attack categories and verifies vector counts (10 categories, 30+ vectors) is a useful pattern for maintaining test completeness.

libs/enclave-vm/src/__tests__/runtime-attack-vectors.spec.ts (4)

1-51: Excellent security model documentation.

The header comment provides crucial context about the three-layer security model (wrapped objects, sandbox-created objects, AST validation) and clearly explains what each layer protects. This is essential documentation for understanding the test expectations.


751-803: Critical host isolation verification for Error.prepareStackTrace.

Good security practice: the test at line 771 verifies that the host's Error.prepareStackTrace is NOT modified by sandbox code, preventing a potential sandbox escape vector. The test correctly stores and compares the original value.


1477-1529: Critical process.env isolation tests.

These tests are essential for verifying that custom globals with process.env-like structures cannot be exploited to access real host environment variables. The tests correctly verify:

  1. __proto__ chain attack is blocked
  2. Only provided env vars are visible, not real ones like PATH or HOME

1537-1601: Coverage summary provides test completeness verification.

The coverage summary documents 8 categories and 35+ vectors, providing a useful reference for test scope and maintaining coverage over time.

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