Skip to content

fix(api-gateway): Guard member-expression SQL eval against JS injection - #12207

Merged
paveltiunov merged 12 commits into
masterfrom
pavel-claude/focused-babbage-4bxhk2
Oct 11, 2026
Merged

paveltiunov merged 12 commits into
masterfrom
pavel-claude/focused-babbage-4bxhk2

Conversation

@paveltiunov

@paveltiunov paveltiunov commented Oct 11, 2026 •

Copy link
Copy Markdown
Member

Check List

  • Tests have been run in packages where changes have been made if available
  • Linter has been run for changed code
  • Tests for the changes have been added if not covered yet
  • Docs have been added / updated if required

Description of Changes Made

Member expressions arriving over the SQL API carry a SQL fragment (expr.sql) that the gateway compiles into Function.constructor(...cubeParams, \return `${sql}``) and evaluates (evalMemberExpressioningateway.ts). Nothing validated that compiled expression, so a fragment (or a crafted cubeParams` entry) could execute arbitrary JavaScript in the API process.

This adds a single guard at the eval sink:

  • New src/member-expression-security.ts exporting assertSafeCompiledMemberExpression(expression). For the compiled [...cubeParams, body] array it:
    • requires each cubeParams entry to be a plain identifier (they are spliced as raw Function parameter source, so a non-identifier entry like [a = <expr>] = [] would execute);
    • requires body to be the canonical return `<sql>` wrapper, then validates <sql>: no template-literal breakout (unescaped backtick / trailing odd backslash), and every ${…} interpolation a dotted path rooted at one of cubeParams, segments being identifiers and never constructor/__proto__/prototype. The ${…} scan is a linear indexOf walk (no polynomial-regex ReDoS).
  • gateway.ts calls the guard in evalMemberExpression for both sinks — the SqlFunction array and each PatchMeasure addFilters entry — before Function.constructor.

Guarding at the eval sink (rather than at parse time) covers string-form members, object-form members (the parsedMemberExpression query-schema alternative, which skips parseMemberExpression), and the extra parse+eval pass after RLS / queryRewrite. It runs in the gateway before either planner, so it protects both Tesseract and the legacy planner. It does not depend on CubeSQL's escape_interpolation_quotes, and accepts everything CubeSQL legitimately emits (${Cube.member}, $N$ param placeholders, escaped SQL).

Tests

  • test/member-expression-security.test.ts — unit cases for the guard: exploit shapes (arbitrary JS, non-identifier cubeParams, backtick breakout, ${process…}, prototype pivots, unterminated ${) and the shapes the planner really emits.
  • test/index.test.ts — gateway-level cases through apiGateway.sql({ memberExpressions: true }) that hit both sink call sites (SqlFunction and PatchMeasure.addFilters) and the object-form path, asserting rejection, alongside the existing accept case.

🤖 Generated with Claude Code

https://claude.ai/code/session_017j4dBMJMVpABP9CvD6jzrE

Member expressions from the SQL API carry a SQL fragment that the gateway
splices into a JS template literal and evaluates via Function.constructor
(parseMemberExpression/evalMemberExpression). The only interpolations the
planner ever emits there are references to the declared cube params
(e.g. ${Orders.amount}); the existing backtick/backslash escaping does not
neutralize ${...}.

Add assertSafeMemberExpressionSql(), which rejects any ${...} whose root is
not one of the declared cubeParams, whose segments are not plain identifiers,
or that touches a prototype key (constructor/__proto__/prototype). This blocks
arbitrary JavaScript (${7*191}, ${process.env...}, ${x()}, Function-constructor
pivots) from reaching the eval while preserving every legitimate member
reference. The guard runs in the gateway, upstream of both the legacy and
Tesseract planners, so it closes the sink for both.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017j4dBMJMVpABP9CvD6jzrE
@paveltiunov
paveltiunov requested a review from a team as a code owner October 11, 2026 06:34
@github-actions github-actions Bot added the javascript Pull requests that update Javascript code label Oct 11, 2026
@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 3m 23s —— View job


Changes requested: 1 high, 1 medium, 3 low. The ${…} guard has a bypass through cubeParams.

Review details
  • Gather context (diff, changed files, call sites)
  • Analyze guard for bypasses
  • Review tests
  • Resolve/check prior review threads
  • Post review

Findings

Severity Where Issue
High packages/cubejs-api-gateway/src/member-expression-security.ts:37 The guard never validates cubeParams, but the gateway passes them to Function.constructor as raw parameter source. cubeParams: ["[a = process.mainModule.require('child_process').execSync('id')] = []"] with sql: "1" passes, and the default runs when the function is called. CubeSymbols.funcArguments resolves that signature to an empty argument list. Fix: require every param to match IDENTIFIER_RE.
Medium member-expression-security.ts:36 The guard doesn't check unescaped backticks or a trailing backslash. ` + process.version + ` has no ${ and closes the template literal. It is blocked today only by CubeSQL's escape_interpolation_quotes, which the PR says this guard shouldn't rely on. Either reject unescaped backticks too, or better, build the function from parsed chunks instead of evaluating a template literal.
Low member-expression-security.ts:3-20 The 17-line header comment is over the 3-line limit and repeats the test cases.
Low member-expression-security.ts:38-43 sql.matchAll(INTERPOLATION_RE) would replace the RegExp clone, the exec loop and the eslint-disable.
Low test/member-expression-security.test.ts Missing tests: no cubeParams-injection or backtick cases, and no gateway-level test showing parseMemberExpression rejects a payload on the sqlApiLoad path. It is wired at gateway.ts:1631 and :1643, but only the helper is tested.

Notes

  • Reachability: member expressions are accepted only on the SQL API paths (sql-server.ts:210, :240 set memberExpressions: true). Both bypasses need control over the expression JSON that CubeSQL sends to the gateway. That is the same threat model the PR defends against, so the guard is incomplete within its own premise.
  • Not verified at runtime: Node execution was blocked in this CI sandbox. I traced both bypasses from gateway.ts:1625-1712 and CubeSymbols.ts:1291/:1312 (FunctionRegex) rather than running them.
  • Planner scope: the PR description is right that the sink sits in the gateway, upstream of both the Tesseract and legacy planners, so both findings apply to both.
  • Legitimate shapes still pass: ${Cube.member}, nested paths, multiple params, and $0$ placeholders are all accepted.

Review threads

The listing returned 0 of my own threads (no prior threads), so nothing was resolved or re-affirmed.

The guard checked only the ${...} interpolations in `sql`, but `cubeParams`
entries are spliced into `Function(...)` as raw parameter source
(evalMemberExpression), so a non-identifier entry can carry an executing
default-value / destructuring parameter (e.g. `[a = <expr>] = []` or
`x = <expr>`) even when `sql` has no interpolation. Reject any cubeParams
entry that is not a plain identifier, and add regression tests.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017j4dBMJMVpABP9CvD6jzrE
@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Reviewing PR #12207

  • Gather context (diff, changed files)
  • Analyze guard against eval sink
  • Run tests
  • Resolve/dedupe review threads
  • Post review

View job run

…on SQL

Address review: the sink `return \`${sql}\`` places sql in template-literal
position, so an unescaped backtick (or a trailing odd backslash escaping the
closing backtick) breaks out into arbitrary JS without any `${...}`. Add
hasTemplateBreakout() so the guard no longer relies on CubeSQL's escaping.
Also simplify the interpolation scan to String.matchAll and tighten the
file comments. Adds regression tests for the breakout shapes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017j4dBMJMVpABP9CvD6jzrE
@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Reviewing PR #12207

  • Gather diff and changed files
  • Analyze guard and gateway call sites
  • Reconcile prior review threads
  • Post findings

View job run

CodeQL flagged /\$\{([^}]*)\}/g as a polynomial-time regex on user input
(it backtracks per start position under the global scan). Replace it with a
linear manual indexOf scan for `${...}` interpolations; an unterminated `${`
is now rejected explicitly. Verified linear: 1M-char hostile input ~12ms.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017j4dBMJMVpABP9CvD6jzrE
@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 2m 26s —— View job


Review of #12207: guard looks sound, no blocking issues (0 high, 0 medium, 2 low)

Details
  • Read changed files and gateway call sites
  • Analyze guard for bypasses / regressions
  • Review tests
  • Resolve / dedupe prior review threads
  • Post review

Security

I checked assertSafeMemberExpressionSql (packages/cubejs-api-gateway/src/member-expression-security.ts:35) against the three ways input could execute code once it is spliced into Function.constructor(...cubeParams, "return \${sql}`")`:

  • cubeParams entries. These become raw Function parameter source. They are now limited to IDENTIFIER_RE, which is the same ASCII rule CubeValidator.identifierRegex applies to cube names, so no legitimate cube name is lost.
  • Template breakout. A bare backtick or a trailing odd run of backslashes is rejected. Template escapes like ` / \u{7B} produce literal characters and can't open a ${. A malformed escape is a SyntaxError, not code execution.
  • Interpolations. The scan uses indexOf and runs in linear time. searchFrom = close + 1 can't skip over a ${, because an accepted body only contains identifier characters and dots and never a {. Spaced, nested or escaped (\${…}) forms are rejected, so the guard fails closed.

Compatibility

The guard accepts everything CubeSQL emits:

  • ${Cube.member} and ${Cube.td.granularity} (rust/cubesql/cubesql/src/compile/engine/df/wrapper.rs:2900, :3653, :3830).
  • cube_params from prepare_used_cubes.
  • String literals, which become $N$ params (wrapper.rs:3273).

escape_interpolation_quotes only runs in ungrouped / push-to-cube context (wrapper.rs:3888). A grouped expression whose SQL contains an identifier with a backtick in it, such as a quoted alias, will now be rejected rather than evaluated. That is the right trade-off.

The guard only runs on the SQL API path: memberExpressions: true is set only in sql-server.ts:210,240. REST /load accepts pre-parsed array expressions (query.js:74), but it never calls evalMemberExpression on them, so it isn't an alternative sink. The guard runs before the query reaches either planner, so it covers Tesseract and the legacy planner alike.

Inline (low)

  1. member-expression-security.ts:27: the JSDoc is 6 lines and mostly lists checks the function body already makes. I suggested cutting it to the sentence about the sink.
  2. test/member-expression-security.test.ts:5: the tests call the guard on its own. Removing the call at gateway.ts:1631 or gateway.ts:1643 wouldn't fail any test, so this needs a test through the gateway for each branch.

Not verified: I didn't run the tests myself. The sandbox wouldn't run jest without approval, so the "30 cases, all green" result in the PR thread is unconfirmed by me.

Review threads: the listing returned 0 of my own threads (none from earlier rounds), so I resolved 0 and re-affirmed 0. The existing threads from paveltiunov and the CodeQL bot were left alone. The CodeQL polynomial-regex alert looks fixed by 90b2deb (the regex was replaced with an indexOf scan).

Address review: the guard was only unit-tested via assertSafeMemberExpressionSql,
so removing the call in parseMemberExpression wouldn't fail any test. Add
gateway-level cases through apiGateway.sql (memberExpressions: true) covering both
wiring sites — SqlFunction (arbitrary ${...}, non-identifier cubeParams, backtick
breakout) and PatchMeasure addFilters — asserting rejection; the existing
"expressions are allowed" case covers the accept path. Also trim the guard's JSDoc.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017j4dBMJMVpABP9CvD6jzrE
@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 2m 36s —— View job


Looks good to merge. 0 high, 0 medium, 2 low. I found no way around the guard on the SQL API path.

Review details
  • Read diff and changed files
  • Analyze guard for bypasses
  • Review tests
  • Resolve/dedupe prior threads
  • Post review

Findings

Severity Location Issue
Low packages/cubejs-api-gateway/src/gateway.ts:1631 The guard runs when the JSON string is parsed, not where the code is evaluated. Members that arrive already parsed (parsedMemberExpression, allowed by query.js:181) reach Function.constructor in evalMemberExpression without being checked. This is only reachable on REST when queryRewrite or a policy adds an expression string.
Low packages/cubejs-api-gateway/test/index.test.ts:943 4-line comment that mostly explains why the tests were added; one line is enough.

Bypass analysis (no issues found)

Code runs through Function(...cubeParams, \return `${sql}``)`. I checked every way input could escape into JavaScript there:

  • cubeParams as parameter source: each entry must be an identifier and can't be constructor, __proto__ or prototype. That blocks default-value and destructuring payloads.
  • Closing the template literal: an unescaped backtick is rejected, and so is an odd run of backslashes at the end. That matches how JS parses a template literal. A ``` escape produces a backtick character, not a delimiter, so it can't close the literal.
  • ${…} bodies: the scan takes the body up to the first }, which is also where JS ends an identifier path. Each body must be a dotted path starting with a cube param, with no calls, no operators and no prototype keys. ${ with no closing brace is rejected. The scan treats escaped \${ as an interpolation too, which is safe because it rejects rather than allows.
  • Legitimate shapes: the planner sends literals as $N$ params, so a real ${ in a string literal never reaches the guard. In grouped mode escape_interpolation_quotes passes sql through unchanged (rust/cubesql/cubesql/src/compile/engine/df/wrapper.rs:3887). A raw backtick there already broke the template before this PR, so rejecting it now doesn't break anything that used to work.
  • Planners: the guard runs in the gateway before either planner gets the function, so it covers both Tesseract and the legacy planner.
  • ReDoS: the indexOf scan and the backslash walk are both linear.

Tests

The unit cases cover the known exploit shapes plus the shapes the planner really emits. The gateway-level tests in index.test.ts hit both call sites (SqlFunction and PatchMeasure.addFilters). I did not run the tests here: dependencies aren't installed in this checkout (no jest in node_modules).

Review threads

The listing returned 0 of my own threads (no prior threads), so I resolved 0 and re-affirmed 0. The paveltiunov and CodeQL threads aren't mine, so I left them alone.

Address review (defence in depth): the parse-time guard only runs on string
members, but Function.constructor in evalMemberExpression also runs on members
that arrive already parsed as objects (querySchema accepts parsedMemberExpression),
which skip parseMemberExpression entirely. Add assertSafeCompiledMemberExpression,
run at the eval sink on the compiled `[...cubeParams, body]` array (and each
PatchMeasure addFilters entry): it validates params as identifiers and re-checks
the `return \`<sql>\`` body via the same sql guard. Adds unit tests for the
object-form bypass shapes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017j4dBMJMVpABP9CvD6jzrE
Address review nit: collapse the 4-line explanatory comment to one line.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017j4dBMJMVpABP9CvD6jzrE
@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 2m 16s —— View job


No security holes left in the guard. 0 high, 0 medium, 2 low (one test-accuracy issue, one simplification).

Review details
  • Read changed files
  • Analyze security / correctness
  • Run tests: skipped. node_modules isn't installed in this checkout, so I didn't run jest on the new specs.
  • Resolve stale threads
  • Post review

Security

I traced each input that reaches Function.constructor at src/gateway.ts:1698 / :1710. None of them can execute arbitrary JS any more:

  • cubeParams: each entry must match IDENTIFIER_RE. A non-string JSON value that coerces to a string coerces the same way in Function, so it gets no extra reach.
  • Template breakout: hasTemplateBreakout counts backslash parity correctly. Inside the scanned region, \${ is treated as an interpolation, so it fails closed.
  • Interpolations: the body runs up to the first } and may contain only dotted identifiers. That rules out calls, so the only reachable behaviour is property reads and string coercion. Prototype keys are blocked.
  • COMPILED_BODY_RE (src/member-expression-security.ts:81): it's greedy, but any trailing JS after a closing backtick leaves an unescaped backtick in the capture, and the breakout check rejects that. JS $ without the m flag doesn't match before a trailing newline. The regex is anchored, so it runs in linear time.
  • Object-form path (parsedMemberExpression): it's only evaluated when hasExpressionsInQuery is true. That requires memberExpressions, and the sink guard now covers it. On REST with no string expressions, object forms are never evaluated in the gateway.
  • Planner coverage: the guard runs before both the legacy planner and Tesseract.
  • No regression for real CubeSQL output: CubeSQL only emits ${<member.field_name>}, $N$ placeholders, and backslash/backtick-escaped SQL (escape_interpolation_quotes in rust/cubesql/.../wrapper.rs:3887, applied whenever push_to_cube_context is set). All of these pass the guard.

Inline (low)

  • test/index.test.ts:943: the comment "Fails if the guard call in parseMemberExpression is removed" has been false since 01af92f, because the sink guard rejects the same inputs. The object-form vector that only the sink guard covers has no gateway-level test.
  • src/gateway.ts:1631 / :1643: the parse-time calls repeat the sink guard and throw the same error messages. Keeping the sink as the only guard would remove the need to keep two in sync.

Comments

All comments are within 3 lines and explain why, not what.

Review threads

The listing returned 0 of my own unresolved threads (none from earlier rounds), so I resolved 0 and re-affirmed 0.

Address review: correct the now-inaccurate comment (since the eval-sink guard,
the four cases no longer pin the parse-time call) and add the one vector only
the sink guard closes — an object-form member (parsedMemberExpression) placed
next to a string expression so hasExpressionsInQuery routes it to
evalMemberExpression, asserting it is rejected.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017j4dBMJMVpABP9CvD6jzrE
@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Reviewing PR #12207

  • Read changed files
  • Analyze guard / sink wiring
  • Review tests
  • Resolve stale threads
  • Post review

View job run

Address review: with assertSafeCompiledMemberExpression running in
evalMemberExpression, the parse-time assertSafeMemberExpressionSql calls are a
strict subset (every parsed expression reaches the sink) and only add a second
choke point to keep in sync. Drop the parse-time calls and keep the sink as the
single guard; parseMemberExpression returns to its original shape. The
gateway-level and unit tests are unchanged and still pass via the sink guard.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017j4dBMJMVpABP9CvD6jzrE
@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 2m 34s —— View job


LGTM: the sink guard closes the reported injection vectors and I found no bypass. Findings: 0 high, 0 medium, 3 low (all comment or PR metadata).

Review details
  • Read changed files
  • Analyze guard and wiring
  • Review tests
  • Resolve/dedupe prior threads
  • Post review

Security

The guard now lives at the only eval sinks: Function.constructor in evalMemberExpression, at gateway.ts:1694 and gateway.ts:1707. That covers three ways in:

  • the string form, which goes through parseMemberExpression;
  • the object form allowed by parsedMemberExpression (query.js:74);
  • the extra parse+eval pass after RLS and queryRewrite (gateway.ts:1497).

There are no other Function.constructor calls on request data in packages/*/src. The guard protects the gateway's eval sink, which both the Tesseract and the legacy planner rely on, so neither one changes this result.

Bypasses I tried, none of which get through:

  • Parameter-source injection: cubeParams must match IDENTIFIER_RE, and Joi already limits the items to strings.
  • Template breakout: the backslash-parity scan in member-expression-security.ts:11 handles this. ` or ${ escapes don't open an interpolation or close the template.
  • Interpolation bodies: the first } ends the scan, the root must be one of the cube params, segments must be identifiers, and prototype keys are blocked.
  • Compiled body: COMPILED_BODY_RE is anchored with a single greedy quantifier, so it doesn't backtrack polynomially. A smuggled ` + x + ` is still caught, because the captured inner SQL goes through hasTemplateBreakout again.
  • Invalid escapes such as \x: these give a SyntaxError, not code execution.

Compatibility with what CubeSQL emits

  • Every ${…} CubeSQL produces has the form ${<member.field_name>} (wrapper.rs:2900, wrapper.rs:3653, wrapper.rs:3830). That includes Cube.dim.granularity, which passes the segment check.
  • Push-to-cube SQL always goes through escape_interpolation_quotes(..., true) (wrapper.rs:1766, wrapper.rs:2286). Backslash runs therefore come out even and backticks come out escaped, so the breakout check doesn't reject valid input.
  • cube_params comes from prepare_used_cubes, which returns cube names. Those are validated identifiers.

Low

  • gateway.ts:1631: the comment duplicates gateway.ts:1692 and explains where the validation moved; suggest deleting it (inline).
  • member-expression-security.ts:83: the JSDoc is 5 lines, over the 3-line limit; suggest condensing it (inline).
  • PR metadata:
    • The title subject should start with a capital letter per CLAUDE.md: fix(api-gateway): Guard member-expression SQL eval against JS injection. The squash commit takes the PR title.
    • The description is out of date. It says 22 cases, and it says assertSafeMemberExpressionSql is called in parseMemberExpression. The wiring is now assertSafeCompiledMemberExpression in evalMemberExpression, and the tests also cover object-form and gateway-level cases.

Tests

The unit cases cover the exploit shapes and the valid planner shapes. The gateway-level cases in test/index.test.ts exercise both guard call sites and the object-form path. I could not run jest here because the CI sandbox denied the command, so I have not seen the tests pass.

Review threads

The listing returned 0 of my threads, so I resolved 0 and re-affirmed 0.

Address review nits: drop the parse-site comment that duplicated the sink
comment, and condense the assertSafeCompiledMemberExpression JSDoc.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017j4dBMJMVpABP9CvD6jzrE
@paveltiunov paveltiunov changed the title fix(api-gateway): guard member-expression SQL eval against JS injection fix(api-gateway): Guard member-expression SQL eval against JS injection Oct 11, 2026
@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 2m 24s —— View job


Review of PR #12207: no blocking issues (0 high, 0 medium, 2 low)

Details
  • Read diff and changed files
  • Analyze security / correctness
  • Review tests and comments
  • Resolve stale threads / dedupe
  • Post review

Security

The sink guard at packages/cubejs-api-gateway/src/gateway.ts:1691 / :1704 closes all three ways out of Function(...cubeParams, "return "). Inputs I checked against member-expression-security.ts:

  • cubeParams as parameter source ([a = …] = [], x = …): rejected by IDENTIFIER_RE. Params that pass, such as process or arguments, only shadow globals with values the compiler supplies, so they aren't exploitable.
  • Template breakout: hasTemplateBreakout counts how many backslashes come before each backtick and also catches a trailing odd run. The \`` that CubeSQL emits (rust/cubesql/cubesql/src/compile/engine/df/wrapper.rs:3889`) still passes.
  • Interpolation body: unicode escapes (${Orders.constructor}), comments, whitespace inside a path, nested {, and escaped \${…} all fail closed. An allowed reference can only read a property, never call one. Stringifying the result at worst calls Function.prototype.toString.
  • Object-form members (parsedMemberExpression in query.js:74, which REST accepts as well): the only Function.constructor sinks for request data are in evalMemberExpression. Any other eval sites under packages/*/src take their input from the data model.
  • ReDoS: the indexOf scan is linear. COMPILED_BODY_RE is anchored at both ends and doesn't backtrack quadratically.

Both planners call the function the gateway builds, so the fix covers Tesseract and the legacy planner alike.

Findings

  1. Low (inline): the comment at gateway.ts:1689-1690 is out of date. It mentions "parseMemberExpression's validation", which was removed in 1ed7d5f, so the sink call looks redundant when it is now the only guard.
  2. Low: the PR description no longer matches the code. It says gateway.ts calls the guard "for both the SqlFunction path and each PatchMeasure addFilters entry" in parseMemberExpression, and gives "22 cases". The guard now lives only in evalMemberExpression (as assertSafeCompiledMemberExpression), and the unit and gateway tests together have far more cases. The squash commit body will be taken from this text.

Tests

The unit cases in test/member-expression-security.test.ts cover the exploit shapes: injection through params, backtick breakout, trailing backslash, object-form bypass, and an unterminated ${. The gateway cases in test/index.test.ts:943-1061 exercise both sink call sites and the object-form path. I didn't run the tests because this checkout has no node_modules.

Review threads

The listing returned 0 of my own threads (the PR had no review threads), so I resolved 0 and re-affirmed 0.

The object-form gateway test used `definition: ''`, which Joi rejects
(Joi.string() disallows empty strings), so the query failed schema validation
before reaching the eval sink — the assertion saw "Invalid query format"
instead of "Unsafe member expression". Use a non-empty definition so the
member reaches evalMemberExpression and is rejected there. Also refresh the
now-stale sink comment.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017j4dBMJMVpABP9CvD6jzrE
@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 2m 11s —— View job


LGTM: no security or correctness issues, 1 low (test duplication).

Review details
  • Gather diff and read changed files
  • Analyze guard for bypasses
  • Review tests / comments
  • Resolve stale threads
  • Post review

Security: no bypass found

I checked every way into Function.constructor.apply(null, …) at packages/cubejs-api-gateway/src/gateway.ts:1690 and :1703:

  • Params: they are tested by IDENTIFIER_RE. Joi forces string items. Reserved words (this, return) make Function throw a SyntaxError without running anything. A param named process just shadows the global, so it's harmless.
  • Body: COMPILED_BODY_RE has no m flag, so $ anchors at the true end of the string. A greedy return \a` + x + `b`puts the inner backticks intomatch[1], and hasTemplateBreakout` rejects them.
  • Interpolations: the body up to the first } must be a dotted identifier path. It cannot hold braces, quotes or backticks, so the guard's } is the same one the JS parser closes on. Invalid template escapes (\u, octal) are SyntaxErrors, not code execution.
  • Bodies that skip the gateway guard: object-form members are only evaluated when hasExpressionsInQuery is true. Otherwise they reach the schema compiler as plain arrays, and nothing there calls Function on them. The only other new Function call sites are in CubeSymbols/CubeEvaluator, and they compile model source, not request data.
  • ReDoS: the indexOf scan is linear, so the earlier CodeQL alert no longer applies to the head commit.

False-positive risk is low. CubeSQL's escape_interpolation_quotes (rust/cubesql/cubesql/src/compile/engine/df/wrapper.rs:3887) doubles \ and escapes backticks only in ungrouped/push-to-cube mode. In grouped mode a raw backtick in expression SQL is now rejected where it used to be evaluated, which is the right trade. Literals arrive as $N$ params, so this should not come up in practice.

The guard runs in the gateway before SQL planning, so it covers Tesseract and the legacy planner equally.

Findings

  • Low: packages/cubejs-api-gateway/test/index.test.ts:1019. The object-form test copies the full QueryRequest literal instead of reusing rejectedMemberExpression; widening that helper's members type would fix it (inline comment).

Comments

All new comments are 3 lines or fewer, and each one guards against a regression (the regex-ReDoS note, the backtick/backslash rationale, the object-form test setup). Nothing to flag.

Tests

I couldn't run them: running jest needs permission this job doesn't have. The cases cover every exploit shape above plus the shapes CubeSQL actually emits, and they exercise both evaluation call sites through apiGateway.sql.

Review threads

The listing returned 0 of my own threads, so I resolved 0 and re-affirmed 0 (no prior threads).

@codecov

codecov Bot commented Oct 11, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.82609% with 1 line in your changes missing coverage. Please review.
✅ Project coverage is 64.69%. Comparing base (42bfe75) to head (ecc90e5).
⚠️ Report is 171 commits behind head on master.

Files with missing lines Patch % Lines
...bejs-api-gateway/src/member-expression-security.ts 97.67% 0 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #12207      +/-   ##
==========================================
+ Coverage   61.23%   64.69%   +3.45%     
==========================================
  Files         247      252       +5     
  Lines       19824    20562     +738     
  Branches     4043     4292     +249     
==========================================
+ Hits        12140    13303    +1163     
+ Misses       7112     6632     -480     
- Partials      572      627      +55     
Flag Coverage Δ
cube-backend 64.69% <97.82%> (+3.45%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ 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.

Address review: widen the rejectedMemberExpression helper's members type to
(string | Record<string, unknown>)[] so the object-form test reuses it instead
of duplicating the full QueryRequest literal.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017j4dBMJMVpABP9CvD6jzrE
@claude

claude Bot commented Oct 11, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @paveltiunov's task in 2m 30s —— View job


LGTM: no issues found (0 high, 0 medium, 0 low)

Review details
  • Read changed files
  • Analyze guard for bypasses
  • Review tests
  • Resolve stale threads
  • Post review

Security: checked for bypasses, found none

There are two eval sinks, both in evalMemberExpression: packages/cubejs-api-gateway/src/gateway.ts:1690 and :1703. Both are guarded. No other Function.constructor / new Function call in api-gateway, server-core or schema-compiler takes request-supplied arrays.

I tried these inputs against packages/cubejs-api-gateway/src/member-expression-security.ts and none got through:

  • Escaped interpolation: \${…} and \\${…} are both rejected. The scan treats every ${ as live, so it fails closed.
  • Breaking out of ${…}: $${…}, whitespace, comments, nested braces or backticks inside ${…} are all rejected. The body must be identifiers joined by dots, so JS and the scanner always agree on where the interpolation ends.
  • Breaking out via the body regex: return `a` + x + `b` gets past COMPILED_BODY_RE, but hasTemplateBreakout then rejects the inner backtick.
  • Malformed cubeParams: non-string entries are coerced the same way by IDENTIFIER_RE.test and by Function. Reserved words such as return only cause a SyntaxError. A param named after a global (process, globalThis) shadows that global, so ${process.version} can't reach it even when listed in cubeParams.
  • Object-form member with no string sibling: hasExpressionsInQuery stays false, so the array is never evaluated. It isn't run as code anywhere further down.

The guard runs in the gateway before planning starts, so it covers both Tesseract and the legacy planner.

Compatibility: what CubeSQL emits still passes

escape_interpolation_quotes (rust/cubesql/cubesql/src/compile/engine/df/wrapper.rs:3887) escapes \ and ` only on the ungrouped path. The output it produces there, with even backslash runs and \`, passes the guard. The grouped path doesn't escape at all, so a raw backtick there used to be an injection and is now rejected, which is the intended behaviour. Neither path ever produces a ${ that isn't a member reference.

Tests

The unit cases cover each check in both directions (accepted and rejected). The gateway-level cases go through both sink call sites and the object-form path. I couldn't run Jest locally because npx jest needed an approval this run doesn't have, so I relied on CI for the results.

Comments

Every comment is 3 lines or fewer, and each one guards against a reintroduced bug (the regex ReDoS note, the even/odd backslash rule, the single-guard note at the sink). Nothing to flag.

Review threads

The listing returned 0 of my threads, so there were no prior threads and nothing to resolve or re-affirm. There are 0 unresolved threads from others.

@paveltiunov
paveltiunov merged commit 3c09976 into master Oct 11, 2026
58 checks passed
@paveltiunov
paveltiunov deleted the pavel-claude/focused-babbage-4bxhk2 branch October 11, 2026 18:14
ovr pushed a commit that referenced this pull request Nov 9, 2026
…on (#12207)

**Check List**
- [x] Tests have been run in packages where changes have been made if
available
- [x] Linter has been run for changed code
- [x] Tests for the changes have been added if not covered yet
- [ ] Docs have been added / updated if required

**Description of Changes Made**

Member expressions arriving over the SQL API carry a SQL fragment
(`expr.sql`) that the gateway compiles into
`Function.constructor(...cubeParams, \`return \`${sql}\`\`)` and
evaluates (`evalMemberExpression` in `gateway.ts`). Nothing validated
that compiled expression, so a fragment (or a crafted `cubeParams`
entry) could execute arbitrary JavaScript in the API process.

This adds a single guard at the eval sink:

- New `src/member-expression-security.ts` exporting
`assertSafeCompiledMemberExpression(expression)`. For the compiled
`[...cubeParams, body]` array it:
- requires each `cubeParams` entry to be a plain identifier (they are
spliced as raw `Function` parameter source, so a non-identifier entry
like `[a = <expr>] = []` would execute);
- requires `body` to be the canonical `` return `<sql>` `` wrapper, then
validates `<sql>`: no template-literal breakout (unescaped backtick /
trailing odd backslash), and every `${…}` interpolation a dotted path
rooted at one of `cubeParams`, segments being identifiers and never
`constructor`/`__proto__`/`prototype`. The `${…}` scan is a linear
`indexOf` walk (no polynomial-regex ReDoS).
- `gateway.ts` calls the guard in `evalMemberExpression` for both sinks
— the `SqlFunction` array and each `PatchMeasure` `addFilters` entry —
before `Function.constructor`.

Guarding at the eval sink (rather than at parse time) covers string-form
members, object-form members (the `parsedMemberExpression` query-schema
alternative, which skips `parseMemberExpression`), and the extra
parse+eval pass after RLS / `queryRewrite`. It runs in the gateway
before either planner, so it protects both Tesseract and the legacy
planner. It does not depend on CubeSQL's `escape_interpolation_quotes`,
and accepts everything CubeSQL legitimately emits (`${Cube.member}`,
`$N$` param placeholders, escaped SQL).

**Tests**

- `test/member-expression-security.test.ts` — unit cases for the guard:
exploit shapes (arbitrary JS, non-identifier `cubeParams`, backtick
breakout, `${process…}`, prototype pivots, unterminated `${`) and the
shapes the planner really emits.
- `test/index.test.ts` — gateway-level cases through `apiGateway.sql({
memberExpressions: true })` that hit both sink call sites (`SqlFunction`
and `PatchMeasure.addFilters`) and the object-form path, asserting
rejection, alongside the existing accept case.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_017j4dBMJMVpABP9CvD6jzrE

---------

Co-authored-by: Claude <noreply@anthropic.com>
(cherry picked from commit d24d1d6)
kewin-robetti pushed a commit to viasoftkorp/cube that referenced this pull request Nov 13, 2026
…on (cube-js#12207)

**Check List**
- [x] Tests have been run in packages where changes have been made if
available
- [x] Linter has been run for changed code
- [x] Tests for the changes have been added if not covered yet
- [ ] Docs have been added / updated if required

**Description of Changes Made**

Member expressions arriving over the SQL API carry a SQL fragment
(`expr.sql`) that the gateway compiles into
`Function.constructor(...cubeParams, \`return \`${sql}\`\`)` and
evaluates (`evalMemberExpression` in `gateway.ts`). Nothing validated
that compiled expression, so a fragment (or a crafted `cubeParams`
entry) could execute arbitrary JavaScript in the API process.

This adds a single guard at the eval sink:

- New `src/member-expression-security.ts` exporting
`assertSafeCompiledMemberExpression(expression)`. For the compiled
`[...cubeParams, body]` array it:
- requires each `cubeParams` entry to be a plain identifier (they are
spliced as raw `Function` parameter source, so a non-identifier entry
like `[a = <expr>] = []` would execute);
- requires `body` to be the canonical `` return `<sql>` `` wrapper, then
validates `<sql>`: no template-literal breakout (unescaped backtick /
trailing odd backslash), and every `${…}` interpolation a dotted path
rooted at one of `cubeParams`, segments being identifiers and never
`constructor`/`__proto__`/`prototype`. The `${…}` scan is a linear
`indexOf` walk (no polynomial-regex ReDoS).
- `gateway.ts` calls the guard in `evalMemberExpression` for both sinks
— the `SqlFunction` array and each `PatchMeasure` `addFilters` entry —
before `Function.constructor`.

Guarding at the eval sink (rather than at parse time) covers string-form
members, object-form members (the `parsedMemberExpression` query-schema
alternative, which skips `parseMemberExpression`), and the extra
parse+eval pass after RLS / `queryRewrite`. It runs in the gateway
before either planner, so it protects both Tesseract and the legacy
planner. It does not depend on CubeSQL's `escape_interpolation_quotes`,
and accepts everything CubeSQL legitimately emits (`${Cube.member}`,
`$N$` param placeholders, escaped SQL).

**Tests**

- `test/member-expression-security.test.ts` — unit cases for the guard:
exploit shapes (arbitrary JS, non-identifier `cubeParams`, backtick
breakout, `${process…}`, prototype pivots, unterminated `${`) and the
shapes the planner really emits.
- `test/index.test.ts` — gateway-level cases through `apiGateway.sql({
memberExpressions: true })` that hit both sink call sites (`SqlFunction`
and `PatchMeasure.addFilters`) and the object-form path, asserting
rejection, alongside the existing accept case.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_017j4dBMJMVpABP9CvD6jzrE

---------

Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

javascript Pull requests that update Javascript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants

⌂ Proxy