Skip to content

fix: Validate query timezone against IANA zones - #11575

Merged
ovr merged 21 commits into
masterfrom
hanoi
Aug 19, 2026
Merged

ovr merged 21 commits into
masterfrom
hanoi

Conversation

@ovr

@ovr ovr commented Aug 17, 2026

Copy link
Copy Markdown
Member

The query timezone was only validated as a free-form string, so invalid or malformed values were accepted and handled inconsistently between the native (Tesseract) and legacy planners. Validate it against known IANA zone names so bad values are rejected early with a clear error.

The query `timezone` was only validated as a free-form string, so invalid or
malformed values were accepted and handled inconsistently between the native
(Tesseract) and legacy planners. Validate it against known IANA zone names so
bad values are rejected early with a clear error.
@ovr
ovr requested review from a team as code owners August 17, 2026 12:02
@github-actions github-actions Bot added the javascript Pull requests that update Javascript code label Aug 17, 2026
@claude

claude Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 4m 49s —— View job


Review complete — approach is sound, and it closes a real SQL injection vector. 1 medium, 4 low (4 inline comments)

Full review — findings, verification notes, and task list

Summary

The fix is well-placed. BaseQuery's constructor guard sits upstream of both buildSqlAndParamsRust and the legacy path, so it covers every query source — including ones that never pass through the API gateway's Joi schema (SQL API session timezone, scheduled refresh, pre-agg jobs). The gateway schema then gives callers an early, cheap rejection. Belt-and-braces in the right order.

Worth stating explicitly in the PR description: this is not only a consistency/UX fix. this.timezone is interpolated raw into SQL string literals across most dialects — PostgresQuery.ts:28 (AT TIME ZONE '${this.timezone}'), ClickHouseQuery.ts:50, SnowflakeQuery.ts:38, BigqueryQuery.ts:45, HiveQuery.ts:30, TrinoQuery.ts:7, VerticaQuery.ts:16, MysqlQuery.ts:49 — so a quote-bearing timezone could previously escape that literal. Framing it as a security fix affects how it gets backported and communicated.

Findings

# Sev Location Issue
1 Medium query.js:59-64, BaseQuery.js:301 moment.tz.zone() is case-insensitive (zones[name.toLowerCase().replace(/\//g,'_')]), so utc / america/new_york pass validation and then fail in Tesseract (query_tools.rs:61, chrono-tz 0.8 parse::<Tz>() is case-sensitive) while the legacy planner accepts them. The cross-planner divergence this PR targets survives for case variants. Suggested moment.tz.names()-Set membership, or canonicalize via moment.tz.zone(v).name.
2 Low query.js:61 helpers.error('any.invalid') renders as "timezone" contains an invalid value — doesn't name the value or say an IANA name is expected. Reads worse in the array cases ("timezones[0]" ...). Use helpers.message(...).
3 Low query.js:425 CUBEJS_DEFAULT_TIMEZONE is folded into query.timezone before querySchema.validate, so a misconfigured env var now surfaces on every query as Invalid query format: ... — pointing the operator at their payload when the fault is server config. Validate the env once at startup, or use a distinct message here. (Couldn't post inline: line not in the diff.)
4 Low base-query.test.ts:127-151 The list is called maliciousTimezones but no entry carries a quote — the actual injection vector is untested. Also: for loop instead of it.each (opaque failures), and no positive-case assertion, so an over-strict validator would still pass.
5 Low coverage preAggsJobsRequestSchema.timezones, queryPreAggregationsSchema.timezone(s) and the now-required queryPreAggregationPreviewSchema.timezone all changed with no tests. Separately, scheduledRefreshTimeZones (cubejs-server-core/src/core/optionsValidate.ts:99) and /v1/cubesql's req.body.timezone (gateway.ts:483) remain unvalidated at their entry points — the BaseQuery guard catches them eventually, just not "early with a clear error".

Residual gap noted inline: moment-timezone 0.5.4x ships a newer tzdb than chrono-tz 0.8.2, so recently-added zone names can pass the JS validator and still fail in the native planner. Follow-up material, not a blocker.

Verified, not a problem

  • Dependencies — moment-timezone is already a direct dependency of both packages (cubejs-api-gateway ^0.5.46, cubejs-schema-compiler ^0.5.48); no new dep. The moment → moment-timezone import swap in query.js is safe, since moment-timezone re-exports moment (moment.utc, moment.HTML5_FMT at lines 280-281 still resolve).
  • Prototype-pollution style bypass — moment.tz.zone('constructor') looks up a plain object literal, but getZone gates on instanceof Zone / typeof === 'string' before returning, so it yields null. No bypass.
  • Docs — docs-mintlify/reference/core-data-apis/rest-api/query-format.mdx:45-47 already documents timezone as a TZ Database Name, so validation matches the documented contract. A changelog note that previously-tolerated values (e.g. +05:00) now hard-fail would still help users hitting it.
  • Joi usage — .custom(fn, description) signature and schema immutability around timezoneSchema.required() are both correct.
  • Perf — moment.tz.zone() per query is a hashed lookup plus a one-time lazy unpack; negligible. (moment.tz.names(), if adopted, should be hoisted to module scope — it builds and sorts a ~600-entry array per call.)

Not verified

Couldn't run yarn test for either package — node_modules is not installed in this checkout and installing the monorepo's dependencies was out of scope for the review. The test changes were reviewed by reading only. CI results should be the source of truth here.

Task list

  • Read PR diff
  • Check moment-timezone dependency + imports in changed packages
  • Verify other timezone entry points (SQL API / Tesseract / pre-agg jobs / scheduled refresh)
  • Cross-check JS validation against Rust parse::<Tz>() semantics
  • Trace whether timezone reaches SQL text unescaped
  • Assess test coverage and error messages
  • Check docs for documented timezone contract
  • Post inline comments and review

No prior review threads existed on this PR, so nothing to resolve or dedupe against.

· branch [`hanoi`](https://github.com/cube-js/cube/tree/hanoi)

@codecov

codecov Bot commented Aug 17, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 59.28%. Comparing base (e77835a) to head (b4d5ef6).
⚠️ Report is 13 commits behind head on master.

❗ There is a different number of reports uploaded between BASE (e77835a) and HEAD (b4d5ef6). Click for more details.

HEAD has 1 upload less than BASE
Flag BASE (e77835a) HEAD (b4d5ef6)
cubesql 1 0
Additional details and impacted files
@@             Coverage Diff             @@
##           master   #11575       +/-   ##
===========================================
- Coverage   84.05%   59.28%   -24.78%     
===========================================
  Files         257      228       -29     
  Lines       81582    18200    -63382     
  Branches        0     3681     +3681     
===========================================
- Hits        68576    10790    -57786     
+ Misses      13006     6861     -6145     
- Partials        0      549      +549     
Flag Coverage Δ
cube-backend 59.28% <100.00%> (?)
cubesql ?

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.

Accept the query `timezone` case-insensitively and normalize it to the
canonical IANA zone name in the API gateway, so downstream consumers (the
generated SQL and the query response) always receive a well-formed value.

Add tests covering case-insensitive acceptance and canonical normalization.
@claude

claude Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 3m 7s —— View job


Re-review of 47516ce (normalization commit) — 2 medium, 4 low (3 new inline comments)

Full review — findings, verification notes, and task list

What changed since the last pass

The new commit takes the "normalize" option from the prior review: timezoneSchema now returns zone.name instead of just passing the value through, normalizeQuery canonicalizes at query.js:450, and the tests grew case-variant coverage on both sides. The direction is right — but the normalization only lands on one of the four routes, and BaseQuery still validates without canonicalizing, so the cross-planner divergence the PR targets is not actually closed yet.

Findings

# Sev Location Issue
1 Medium query.js:513-514, query.js:525, query.js:552, gateway.ts:988 Joi returns the coerced value in value, not by mutating the input. Three of the four call sites destructure only error, so timezoneSchema's return zone.name is dead code there — the pre-agg and jobs routes forward the raw string. Only normalizeQuery is normalized, and only because it redoes the work by hand at line 450.
2 Medium BaseQuery.js:301, base-query.test.ts:152-176 BaseQuery validates but doesn't canonicalize, and the new positive test now asserts 'utc' / 'america/new_york' construct fine. For any path that skips querySchema (SQL API req.body.timezone at gateway.ts:483, scheduled refresh, and the pre-agg routes from #1) those values reach Tesseract and fail at parse::<Tz>() (query_tools.rs:61, chrono-tz 0.8.2 is case-sensitive) while the legacy planner accepts them. The test enshrines the divergence rather than closing it.
3 Low query.js:59-67 Normalizing rewrites deprecated aliases to canonical names (Europe/Kiev→Europe/Kyiv, Asia/Calcutta→Asia/Kolkata, US/Eastern→America/New_York). Since timezone feeds pre-aggregation partition/version keys, affected tenants get a pre-agg rebuild on upgrade. Fine as a decision — needs to be a documented behavior change, not a surprise.
4 Low query.js:61 helpers.error('any.invalid') still renders as "timezone" contains an invalid value — names neither the offending value nor the expected format. Worse in the array cases ("timezones[0]" ...).
5 Low query.js:428 CUBEJS_DEFAULT_TIMEZONE is folded into query.timezone before querySchema.validate, so a misconfigured env var now surfaces on every query as Invalid query format: ..., pointing the operator at their payload when the fault is server config. Validate the env once at startup, or use a distinct message. (Line not in the diff, so not postable inline.)
6 Low base-query.test.ts Still no quote-carrying entry in the negative list, so the injection vector into AT TIME ZONE '${this.timezone}' has no regression test; still a for loop rather than it.each, so a failure doesn't say which input broke.

The cheapest fix for #1 + #2 together is to drop the normalization from Joi (validate only) and canonicalize once in the BaseQuery constructor — this.timezone = zone.name. That's the single choke point every path already passes through, and it makes query.js:450 unnecessary.

Verified, not a problem

  • Security fix still intact — this.timezone is interpolated raw into SQL string literals across most dialects (PostgresQuery.ts:28, ClickHouseQuery.ts:50, SnowflakeQuery.ts:38, BigqueryQuery.ts:45, HiveQuery.ts:30, TrinoQuery.ts:7, VerticaQuery.ts:16, MysqlQuery.ts:49). The BaseQuery guard closes that on every path regardless of the normalization gaps above. Worth stating in the PR description/changelog — it affects how this gets backported.
  • Dependencies / imports — moment-timezone is already a direct dep of both packages; BaseQuery.js:11 already imported it, and the moment → moment-timezone swap in query.js:2 is safe (moment-timezone re-exports moment, so moment.utc / moment.HTML5_FMT still resolve).
  • moment.tz.zone(...)?.name at line 450 — optional chaining is already used elsewhere in this file and the package's babel config handles it.
  • timezoneSchema.required() — Joi schemas are immutable, so deriving the required variant for queryPreAggregationPreviewSchema doesn't leak required into the shared schema.
  • Perf — one hashed zone lookup per query plus a one-time lazy unpack; negligible.
  • Docs — docs-mintlify/reference/core-data-apis/rest-api/query-format.mdx:45-47 documents timezone as a TZ Database Name, so validation matches the documented contract.

Not verified

  • Could not execute node or yarn test in this checkout (dependencies not installed / command not permitted), so the moment-timezone alias behavior in finding ResultSet pivot methods documentation  #3 comes from reading addLink/getZone rather than an empirical check — worth a 10-second node -e confirmation before writing it into release notes. The test changes were reviewed by reading only; CI is the source of truth for pass/fail.

Task list

  • Diff origin/master...HEAD and identify what the new commit changed
  • Trace whether Joi's normalized value actually reaches consumers on each route
  • Re-check BaseQuery guard against the Rust parse::<Tz>() semantics (chrono-tz 0.8.2)
  • Assess the pre-agg cache-key implications of canonicalization
  • Re-assess test coverage against the new behavior
  • Dedupe against prior threads; resolve stale ones
  • Post inline comments and summary

Resolved one of my own now-addressed threads (the query.js:67 "canonicalize instead of existence-check" comment — the fix direction was taken). Left the BaseQuery.js:303 and base-query.test.ts:176 threads unresolved: both concerns still apply, and the new inline comments extend them with what the latest commit changed. No human-authored threads touched.

· branch [`hanoi`](https://github.com/cube-js/cube/tree/hanoi)

@claude

claude Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Re-review of 6141a98 — most prior findings addressed; 2 medium, 3 low remain (2 new inline comments)

Full review — findings, verification notes, and task list

What changed since the last pass

This commit takes essentially every structural suggestion from the previous round:

  • All four Joi call sites now consume value instead of the raw input (query.js:456, :556, :584, gateway.ts:991/1000), so the timezoneSchema normalization actually reaches consumers. The hand-rolled moment.tz.zone(...)?.name at the old line 450 is gone.
  • /v1/cubesql gets a real guard via the new exported normalizeTimezone helper (gateway.ts:484) — throws UserError inside the existing try, so it surfaces as a 400.
  • scheduledRefreshTimeZones is validated (optionsValidate.ts:109) with a new unit test file.
  • base-query.test.ts converted to it.each, and there's now a positive assertion on the rendered SQL (AT TIME ZONE 'America/New_York').
  • BaseQuery's message aligned with the Rust side (Incorrect timezone ${tz}).

Coverage is now genuinely good — normalizeQueryPreAggregations, normalizeQueryPreAggregationPreview, normalizeTimezone and optionsValidate all have tests, including the empty-value passthrough cases.

Findings

# Sev Location Issue
1 Medium query.js:72 helpers.message() is called with a bare string; joi expects a messages object keyed by error code. The sibling validator added in this same PR uses the correct form (optionsValidate.ts:9), as does the existing CubeValidator.ts:392 — this is the only bare-string call in the repo. joi resolves messages['custom'] to undefined and falls back to its "error code is not defined" placeholder, so the intended message is likely never shown. No test asserts the message body on this route (only /Invalid query format/), so CI won't catch it. Also, both validators interpolate the user value into the template source — timezone: "{{#label}}" echoes the label and an unbalanced { can throw during error rendering (400 → 500); pass it as a local ({ tz: value }) instead.
2 Medium optionsValidate.ts:9, OptsHandler.ts:92/:417 optionsValidate(opts) runs on user-supplied options only, while the env default is merged after — so CUBEJS_SCHEDULED_REFRESH_TIMEZONES (env.ts:273, plain split(',')) bypasses the new schema entirely. The Joi.func() alternative is likewise unchecked (server.ts:797). And the custom validates without canonicalizing (and optionsValidate discards Joi's value), so ['utc'] passes and is forwarded verbatim → RefreshScheduler → BaseQuery → Tesseract parse::<Tz>() failure while the legacy planner accepts it. Scheduled refresh is now the one route where the divergence this PR targets still exists.
3 Low BaseQuery.js:301 (existing thread) BaseQuery still validates without canonicalizing, and base-query.test.ts:150-160 now asserts 'utc'/'america/new_york' construct fine on the strength of a comment saying normalization "happens at the API gateway input layer". True for the gateway routes after this commit — not for scheduled refresh (#2) or direct BaseQuery consumers. this.timezone = zone.name in the constructor makes the assertion true and collapses #2's second half at the same time.
4 Low changelog / docs (existing thread) Canonicalization rewrites deprecated aliases (Europe/Kiev→Europe/Kyiv, Asia/Calcutta→Asia/Kolkata, US/Eastern→America/New_York). Since timezone feeds pre-agg partition/version keys, affected tenants get a rebuild on upgrade. Fine as a decision — should be an explicit release-note line. Same for previously-tolerated values like +05:00 now hard-failing.
5 Low base-query.test.ts Negative list is 'Not/AZone', '+05:00', '+05', '05', 'foo/bar' — still no quote-bearing entry, so the actual injection vector into AT TIME ZONE '${this.timezone}' (PostgresQuery.ts:28) has no regression test. One entry like "UTC' AT TIME ZONE 'UTC" would pin it.

Verified, not a problem

  • value vs raw at the new call sites — preAggsJobsRequestSchema and the pre-agg schemas are plain Joi.object().keys(...) without stripUnknown/unknown(true), so unknown keys error rather than being silently dropped; switching to value.selector / value.timezones doesn't lose fields.
  • normalizeTimezone on /v1/cubesql — throws inside the existing try, so it routes through handleError and becomes a 400 rather than an unhandled rejection. Empty/undefined passthrough is correct and tested (the SQL API supplies its own default downstream).
  • normalizeQueryPreAggregationPreview — { ...query, timezone: value.timezone } is safe; timezone is required() on that schema so value.timezone is always populated.
  • New moment-timezone dep in cubejs-server-core — ^0.5.46 already exists as a resolved range in the workspace (cubejs-api-gateway uses the identical range), so no lockfile churn. Ranges differ across packages (0.5.46/0.5.47/0.5.48) but that predates this PR.
  • Security fix intact — this.timezone is still interpolated raw into SQL string literals (PostgresQuery.ts:28, ClickHouseQuery.ts:50, SnowflakeQuery.ts:38, BigqueryQuery.ts:45, HiveQuery.ts:30, TrinoQuery.ts:7, VerticaQuery.ts:16, MysqlQuery.ts:49); the BaseQuery guard closes that on every path. Still worth stating in the PR description — it affects backport handling.
  • tzdb skew — moment-timezone here is much newer than chrono-tz 0.8.2 (cubesqlplanner/Cargo.toml:20), so recently-added zone names pass JS validation and fail in the native planner. Follow-up, not a blocker.

Not verified

node_modules is not installed in this checkout and I couldn't install joi, so finding #1 rests on reading joi's error-template resolution plus the repo's own precedent (CubeValidator.ts:392, optionsValidate.ts:9) rather than an empirical run. A 10-second check — assert the thrown message in normalize-query.test.ts — settles it either way, and is worth having as a test regardless. Test suites were reviewed by reading only; CI is the source of truth for pass/fail.

Thread housekeeping

Resolved two of my own now-addressed threads: the query.js:540 "normalized value discarded at three call sites" thread (all four sites now use value) and the base-query.test.ts "for-loop / no positive assertion" thread (converted to it.each, SQL assertion added). Left unresolved: BaseQuery.js:303 (canonicalization, finding #3), the query.js alias/changelog thread (finding #4), and the base-query.test.ts positive-block thread (findings #3/#5) — all still apply. No human-authored threads touched.

Task list

  • Diff 47516ce..HEAD and identify what the new commit changed
  • Re-verify each prior finding against the current code
  • Trace the env-var / function paths for scheduledRefreshTimeZones
  • Check value vs raw semantics at the switched call sites (unknown-key stripping)
  • Check helpers.message usage against repo precedent
  • Verify the new moment-timezone dependency needs no lockfile change
  • Resolve stale threads, dedupe new comments
  • Post inline comments and summary

View job run · branch hanoi

Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
@claude

claude Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Re-review of 5f5d081 — the helpers.message fix is correct; 1 medium, 4 low remain (2 new inline comments)

Full review — findings, verification notes, and task list

What changed since the last pass

One-line commit, exactly the suggested form:

return helpers.message({ custom: '{{#label}} must be a valid IANA time zone, got "{{#tz}}"' }, { tz: value });

That resolves both halves of the previous medium — the messages object is now keyed by error code (so joi resolves messages.custom instead of falling through to its "error code is not defined" placeholder), and the user value moves out of the template source into a local, so a value containing joi template syntax can no longer be re-parsed as a template.

Findings

# Sev Location Issue
1 Medium optionsValidate.ts:9, OptsHandler.ts:92/:417 Existing thread, still open. optionsValidate(opts) sees user-supplied options only; scheduledRefreshTimeZones: getEnv('scheduledRefreshTimezones') is merged as a default after, so CUBEJS_SCHEDULED_REFRESH_TIMEZONES (env.ts:273, plain split(',')) bypasses the new schema — as does the Joi.func() alternative (server.ts:797). And the custom validates without canonicalizing while optionsValidate discards joi's value, so ['utc'] is forwarded verbatim → RefreshScheduler → BaseQuery → Tesseract parse::<Tz>() failure, legacy planner accepts. Scheduled refresh remains the one route where the divergence this PR targets survives.
2 Low optionsValidate.ts:9 (new) The { tz: value } treatment landed in query.js but not in the sibling validator, which still interpolates ${value} into the template source. Same message-fidelity / template-parse exposure the query.js fix just closed.
3 Low BaseQuery.js:301 (existing thread) Still validates without canonicalizing, and base-query.test.ts:150-161 asserts 'utc'/'america/new_york' construct fine on the strength of a comment saying normalization happens "at the API gateway input layer" — true for the gateway routes after 6141a98, not for scheduled refresh (#1) or direct BaseQuery consumers. this.timezone = zone.name makes the assertion true and collapses half of #1 at the same time. (The message-colon nit in that thread is fixed — it now reads Incorrect timezone ${tz}, matching the Rust side.)
4 Low query.js:455 (new) CUBEJS_DEFAULT_TIMEZONE is folded into query.timezone before querySchema.validate, so a misconfigured env var now surfaces on every request as Invalid query format: "timezone" must be a valid IANA time zone… — accurate about what is wrong, misleading about whose input caused it. normalizeTimezone at startup would fail fast instead.
5 Low changelog + base-query.test.ts (existing threads) (a) Canonicalization rewrites deprecated aliases (Europe/Kiev→Europe/Kyiv, Asia/Calcutta→Asia/Kolkata, US/Eastern→America/New_York); since timezone feeds pre-agg partition/version keys, affected tenants get a rebuild on upgrade — needs an explicit release-note line, along with previously-tolerated values like +05:00 now hard-failing. (b) The negative list still has no quote-bearing entry, so the injection vector into AT TIME ZONE '${this.timezone}' (PostgresQuery.ts:28) has no regression test; one case like "UTC' AT TIME ZONE 'UTC" would pin it.

Verified, not a problem

  • helpers.message(messages, local) — two-argument form is the documented joi 17 signature for custom methods, and {{#tz}} is the correct local-context reference (# prefix). Matches the repo's own precedent at CubeValidator.ts:392.
  • All four joi call sites consume value — query.js:474, :559, :585, gateway.ts:1000. None of these schemas use stripUnknown/unknown(true), so unknown keys error rather than being silently dropped; switching from raw to value loses nothing. normalizeQueryPreAggregationPreview's { ...query, timezone: value.timezone } is safe because that field is required().
  • Security fix intact — this.timezone still reaches SQL string literals raw across dialects (PostgresQuery.ts:28, ClickHouseQuery.ts:50, SnowflakeQuery.ts:38, BigqueryQuery.ts:45, HiveQuery.ts:30, TrinoQuery.ts:7, VerticaQuery.ts:16, MysqlQuery.ts:49); the BaseQuery guard closes that on every path. Still worth stating in the PR description — it affects how this gets backported.
  • Coverage — normalizeQuery, normalizeQueryPreAggregations, normalizeQueryPreAggregationPreview, normalizeTimezone and optionsValidate all have tests including empty-value passthrough, and base-query.test.ts:163 now asserts the rendered AT TIME ZONE 'America/New_York'. One gap: the joi-route tests assert only /Invalid query format/, never the rendered message body, so the fix in this commit has no direct regression test — the only assertion on the text (normalize-query.test.ts:105) covers the non-joi normalizeTimezone path.
  • tzdb skew — moment-timezone is much newer than chrono-tz 0.8.2 (cubesqlplanner/Cargo.toml:20), so recently-added zone names pass JS validation and fail in the native planner. Follow-up, not a blocker.

Not verified

node_modules is not installed here and running node wasn't permitted, so the joi template-resolution reasoning in #2 and the alias list in #5(a) come from reading joi's template compiler and moment-timezone's addLink/getZone rather than an empirical check. Both are worth a 10-second node -e confirmation before the alias behavior goes into release notes. Test suites were reviewed by reading only; CI is the source of truth for pass/fail.

Thread housekeeping

Nothing to resolve this round — all four unresolved claude threads still have live concerns (BaseQuery.js:303, the query.js alias/changelog thread, the base-query.test.ts positive-block thread, and optionsValidate.ts:9). Re-affirmed rather than re-posted; the unresolved state already communicates that. The bare-string helpers.message thread was addressed by this commit and is already resolved. No human-authored threads touched.

Task list

  • Diff 6141a98..HEAD and identify what changed
  • Verify the helpers.message({ custom }, { tz }) form against joi's API and repo precedent
  • Re-check each prior finding against current code
  • Confirm all joi call sites consume the normalized value
  • Check test coverage for the message body specifically
  • List review threads, dedupe, resolve stale ones (none stale)
  • Post inline comments and summary

View job run · branch hanoi

ovr and others added 2 commits August 17, 2026 16:41
@ovr
ovr requested a review from keydunov as a code owner August 17, 2026 15:32
@mintlify

mintlify Bot commented Aug 17, 2026 •

Copy link
Copy Markdown
Contributor

Preview deployment for your docs. Learn more about Mintlify Previews.

Project Status Preview Updated (UTC)
cubed3 🟢 Ready View Preview Aug 17, 2026, 3:33 PM

💡 Tip: Enable Workflows to automatically generate PRs for you.

@claude

claude Bot commented Aug 17, 2026

Copy link
Copy Markdown
Contributor

Claude Code is working…

I'll analyze this and get back to you.

View job run

The route validated only the timezone and read the remaining fields straight off
req.body. Describe the body with a Joi schema instead, covering query, timezone,
cache and throwContinueWait, and pass the validated value to execSql. Follows how
the other routes validate their input, and gives the next field added here a place
to be declared.

A missing query and unknown fields or cache modes are now rejected with
"Invalid query format" instead of reaching the native side.

Also reuse one cache-mode schema for querySchema.cacheMode/cache and this route.
@claude

claude Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 3m 22s —— View job


Re-review of 35f969f — whole-body schema is the right shape; 0 medium, 4 low (1 new inline comment)

Full review — findings, verification notes, and task list

What changed since c08ded8

/v1/cubesql goes from "validate the timezone, read the rest off req.body" to a declared body schema:

export const cubeSqlRequestSchema = Joi.object().keys({
  query: Joi.string().required(),
  timezone: timezoneSchema,
  cache: cacheModeSchema,
  throwContinueWait: Joi.boolean(),
});

Two side effects I'd call improvements. It fixes the label problem from my last pass for free: validating an object means joi derives the label from the key, so the message reads "timezone" must be a valid IANA time zone, got "foo/bar" and the errors: { label: false } hack (which left the message with an empty subject) is gone — I've resolved that thread. And timezoneSchema goes back to being module-private, which is fine since it was only exported one commit ago and never shipped.

The cacheModeSchema extraction removes a duplicated four-value literal that appeared three times (querySchema.cacheMode, querySchema.cache, and this route). Joi schemas are immutable, so sharing the instance across three keys is safe.

Traced the client side for the strictness change: cubeSql sends { query, throwContinueWait, cache?, timezone? } (cubejs-client-core/src/index.ts:783-798, after HttpTransport.request strips method/signal/fetchTimeout/baseRequestId), and cubeSqlStream sends { query, cache, timezone } with undefined values dropped by JSON.stringify. Every field is declared, so no client breaks. Same for the four existing route tests and smoke-cubesql.test.ts — all send only declared keys, so CI shouldn't surface this.

Findings

# Sev Location Issue
1 Low gateway.ts:484 (new inline) Three edges: (a) Joi.object() without .required() accepts undefined, so an absent req.body passes validation and body.query throws a TypeError → 500 instead of 400 — unreachable today (line 474 destructures req.body first, express.json() always sets an object) but one token to close; (b) unknown keys are now a hard 400 for the whole request, which is a version-skew break worth a release note — a newer client sending a field an older gateway doesn't declare fails the entire query, and cacheMode (accepted by querySchema, not here) goes from silently-ignored to 400; (c) null/'' timezones used to be forwarded as unset and now 400 — deliberate, but JSON clients that serialize absent optional fields as null will start failing.
2 Low test/index.test.ts:1322-1500 No route-level negative test. The new normalize-query.test.ts block exercises cubeSqlRequestSchema in isolation, so nothing pins the wiring (UserError → handleError → 400) or the response body. One supertest case with timezone: 'Not/AZone' expecting 400 + /valid IANA time zone/, and one with {} expecting "query" is required, would cover it.
3 Low optionsValidate.ts:108, server.ts:797 The Joi.func() alternative for scheduledRefreshTimeZones remains unvalidated — its awaited result goes straight into queryingOptions.timezones. With the env var canonicalizing at the source and the array form canonicalizing in validateOptions, the function form is the last route where the cross-planner divergence survives: a config returning ['utc'] fails Tesseract's case-sensitive parse::<Tz>() (query_tools.rs:61) while the legacy planner accepts it. A canonicalTimezone pass over the resolved list closes it.
4 Low BaseQuery.js:307 Still truthiness-gated (this.timezone && (typeof … !== 'string' || !canonicalTimezone(…))), so a falsy non-string — 0, false, NaN — skips validation and reaches the dialect's AT TIME ZONE '${this.timezone}' sink. No quote, so not injection, but a DB error rather than a UserError. The gateway half is closed by Joi.string(); this is the queryRewrite / refresh-scheduler path. Gating on !== undefined && !== null && !== '' closes it.
5 Low docs (a) environment-variables.mdx:1409-1419 — re-checked, still no <Warning> under CUBEJS_SCHEDULED_REFRESH_TIMEZONES while CUBEJS_DEFAULT_TIMEZONE has one, though it now also fails the boot on an invalid zone, rejects +05:00, and ignores empty entries from trailing commas. (b) rest-api/reference.mdx:409-413 lists query/timezone/cache but not throwContinueWait — now that the schema is a closed list, that's a documented-vs-accepted mismatch. Fix (a) →
6 Low base-query.test.ts:139-146, timezone.test.ts:28-40 Neither negative list has a quote-bearing entry, so the injection vector into AT TIME ZONE '${this.timezone}' (PostgresQuery.ts:28) — the thing this PR is really protecting — still has no regression test. One case like "UTC' AT TIME ZONE 'UTC" would pin it. (Author resolved this thread earlier; noted once more, your call.)

Nit: cacheModeSchema is Joi.any().valid(...) rather than Joi.string().valid(...), so a non-string gets must be one of [...] rather than must be a string — harmless, just slightly less precise than the sibling fields.

Verified, not a problem

  • timezoneSchema un-export — no consumer outside query.js imported it (grepped packages/*/src and packages/*/test); it was exported one commit ago and never released, so this isn't a breaking change to @cubejs-backend/api-gateway's surface.
  • cacheModeSchema reuse — joi schemas are immutable, and the extracted value list is character-identical to both inlined copies it replaces, so querySchema.cache/cacheMode behavior is unchanged.
  • throwContinueWait: Joi.boolean() — with joi's default convert: true, 'true'/'false' strings now become booleans before reaching execSql (sql-server.ts:79 declares throwContinueWait?: boolean), so 'false' no longer arrives as a truthy string. Strictly better.
  • query: Joi.string().required() — Joi.string() doesn't coerce numbers, and rejects '' by default, so both now 400 instead of reaching the native side. Matches the commit message.
  • Error routing — the throw is still inside the existing try, so it goes through handleError as a 400; handleError's query: { sql: query } still reads the pre-validation query from line 474, which is fine (it's for logging).
  • Security fix intact — this.timezone still reaches SQL string literals raw across dialects (PostgresQuery.ts:28, ClickHouseQuery.ts:50, SnowflakeQuery.ts:38, BigqueryQuery.ts:45, HiveQuery.ts:30, TrinoQuery.ts:7, VerticaQuery.ts:16, MysqlQuery.ts:49); the BaseQuery constructor guard closes it on every path. Still worth one line in the PR description — it affects how this gets backported.
  • tzdb skew — moment-timezone here is much newer than chrono-tz 0.8.2 (cubesqlplanner/Cargo.toml:20), so recently-added zone names pass JS validation and fail in the native planner. Follow-up, not a blocker.

Not verified

node_modules isn't installed in this checkout, so I couldn't run yarn tsc or the suites; the joi semantics above (object-without-required accepting undefined, Joi.string() not coercing, convert on booleans) come from reading joi 17 rather than an empirical run, and the client-side field lists come from reading HttpTransport.request/requestStream. CI is the source of truth for pass/fail.

Thread housekeeping

Resolved the one open thread (gateway.ts, the errors: { label: false } empty-subject message) — this commit deletes that call entirely and object validation gives the message a proper label. Its other two halves (no route-level 400 test, null/'' compat) are carried forward as findings #1/#2 in a new comment on the current line rather than left on an outdated diff. All 15 other prior claude threads were already resolved. Findings #3-#6 aren't on diff lines, so they're written out above. No human-authored threads touched.

Task list

  • Diff c08ded8..35f969f and identify what changed
  • Trace every /v1/cubesql client (cubeSql, cubeSqlStream, HttpTransport, smoke tests) against the closed key list
  • Check execSql's signature vs the coerced values now passed
  • Check whether un-exporting timezoneSchema breaks any consumer
  • Look for route-level negative coverage
  • Re-verify each remaining open finding against the current tree
  • List review threads, resolve stale ones, dedupe
  • Post inline comment and summary
· branch [`hanoi`](https://github.com/cube-js/cube/tree/hanoi)

canonicalTimezone relied on moment.tz.zone() happening to return null for an empty
string. Treat '' as unset next to undefined/null instead, so the null result is the
function's own contract rather than a moment implementation detail. Behaviour is
unchanged.
@claude

claude Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 1m 28s —— View job


Re-review of eef56da — behavior-preserving cleanup, correct as described. 0 medium, 4 low remain (no new inline comments; 1 prior thread still open)

Full review — findings, verification notes, and task list

What changed since 35f969f

Six lines, and the commit message is accurate: canonicalTimezone now treats '' as unset explicitly instead of relying on moment.tz.zone('') happening to miss, and the test case moves from the "invalid value" block to the "unset or empty" block accordingly. Behavior is unchanged either way — normalizeName coerces via (name || ''), so zones[''] was already a miss — but the contract is now the function's own rather than a moment implementation detail, and the doc comment says so.

Placement is right, and the comment earns its keep: the '' test sits before the typeof guard (safe, '' is a string) and explicitly warns off the !value shorthand, which would swallow 0/false/NaN that the next branch is supposed to throw on. That's exactly the bug shape I flagged twice earlier in this PR on the two callers, so pinning the reasoning in a comment where the next editor will see it is the useful place for it.

timezone.test.ts still covers all four buckets — canonical resolution, link names preserved, invalid strings → null, non-strings → TypeError (including 0 and false) — so the reclassified '' case doesn't leave a hole.

Findings

All carried over; nothing in eef56da introduces or resolves any of them.

# Sev Location Issue
1 Low gateway.ts:484 (open thread) Three edges on the new body schema, re-verified against the current code: (a) Joi.object() without .required() accepts undefined, so an absent req.body would pass and body.query would throw a TypeError → 500 instead of 400 — unreachable today (line 474 destructures req.body, express.json() always sets an object) but one token to close; (b) unknown keys are now a hard 400 for the whole request — right default, but a version-skew break worth a release note, and cacheMode (accepted by querySchema, not here) goes from silently-ignored to 400; (c) null/'' timezones used to be forwarded as unset and now 400 — deliberate, but JSON clients that serialize absent optional fields as null will start failing. Still no route-level negative test either: test/index.test.ts:1322-1500 is happy-path only, and the schema tests exercise cubeSqlRequestSchema in isolation, so nothing pins the UserError → handleError → 400 wiring.
2 Low BaseQuery.js:307 Still truthiness-gated (this.timezone && (typeof … !== 'string' || !canonicalTimezone(…))), so a falsy non-string — 0, false, NaN — skips validation and reaches the dialect's AT TIME ZONE '${this.timezone}' sink. No quote, so not injection, but a DB error rather than a UserError. Note the irony with this commit: canonicalTimezone itself now documents in a comment why !value is the wrong gate, and timezone.test.ts pins 0/false as throwing — but this caller's !value-shaped guard is the one place that keeps those values from ever reaching it. Gating on !== undefined && !== null && !== '' closes it.
3 Low optionsValidate.ts:108, server.ts:797 Re-verified: scheduledRefreshTimeZones is Joi.alternatives().try(Joi.array().items(timezoneSchema), Joi.func()) — the Joi.func() branch is unvalidated, and await this.scheduledRefreshTimeZones(context) goes straight into queryingOptions.timezones at server.ts:799. With the env var canonicalizing at the source and the array form canonicalizing in validateOptions, the function form is the last route where the cross-planner divergence survives: a config returning ['utc'] fails Tesseract's case-sensitive parse::<Tz>() (query_tools.rs:61) while the legacy planner accepts it. A canonicalTimezone pass over the resolved list closes it.
4 Low environment-variables.mdx:1409-1419 Confirmed still absent: the CUBEJS_SCHEDULED_REFRESH_TIMEZONES section is four lines plus a table, no <Warning>, while CUBEJS_DEFAULT_TIMEZONE has one. This var now also fails the boot on an invalid zone, also rejects +05:00, and (since 062b0e7) ignores empty entries from trailing/repeated commas — three documentable behaviors, zero doc lines. Fix this →
5 Low timezone.test.ts:28-38, base-query.test.ts:140-146 Re-read both negative lists — 'Not/AZone', 'Europ/Berlin', 'foo/bar', '+05:00', '+05', '05', the untrimmed variants — still no quote-bearing entry, so the injection vector into AT TIME ZONE '${this.timezone}' (PostgresQuery.ts:28) — the thing this PR is really protecting — has no regression test. One case like "UTC' AT TIME ZONE 'UTC" would pin it. (Author resolved this thread earlier; noted once more, your call.)

Verified, not a problem

  • '' reclassification is behavior-identical — the value was already returning null via moment.tz.zone(''); only the reason changed. Both callers treat null the same way (timezoneSchema → validation message, BaseQuery never reaches it because '' is falsy), so nothing downstream shifts.
  • Check ordering — '' is tested before typeof, which is fine since '' is a string; no non-string can take the early return.
  • Doc comment matches behavior — @throws {TypeError} when value is neither a string nor unset still holds, and the summary line was updated to mention "empty" in step with the code.
  • TypeError still unreachable from src — the two joi customs sit behind Joi.string() (joi 17's string type doesn't coerce numbers or booleans, and custom runs after base validation), both env.ts readers always hold strings, and BaseQuery pre-checks the type. No route that produced a 400 now produces a 500.
  • Security fix intact — this.timezone still reaches SQL string literals raw across dialects (PostgresQuery.ts:28, ClickHouseQuery.ts:50, SnowflakeQuery.ts:38, BigqueryQuery.ts:45, HiveQuery.ts:30, TrinoQuery.ts:7, VerticaQuery.ts:16, MysqlQuery.ts:49); the BaseQuery constructor guard closes it on every path. Still worth one line in the PR description — it affects how this gets backported.
  • tzdb skew — moment-timezone here is much newer than chrono-tz 0.8.2 (cubesqlplanner/Cargo.toml:20), so recently-added zone names pass JS validation and fail in the native planner. Follow-up, not a blocker.

Not verified

node_modules isn't installed in this checkout, so I couldn't run yarn tsc or the suites; the moment.tz.zone('') equivalence claim comes from reading normalizeName/getZone rather than an empirical run — the reclassified test case is exactly what confirms it, so CI is the source of truth for pass/fail.

Thread housekeeping

Listed all 17 threads: 16 already resolved, 1 open (gateway.ts:484, finding #1). It still applies verbatim to the current code — this commit didn't touch that file — so I left it unresolved rather than re-posting. No new inline comments this pass, since nothing in eef56da introduces a new issue. Findings #3 and #4 aren't on diff lines and #5's thread was resolved by the author, so those are written out above. No human-authored threads touched.

Task list

  • Diff 35f969f..eef56da and identify what changed
  • Confirm the '' reclassification is behavior-preserving and check ordering vs the typeof guard
  • Re-verify each remaining open finding against the current tree (BaseQuery.js, optionsValidate.ts, server.ts, the mdx section, both negative test lists)
  • List review threads, resolve stale ones (none stale), dedupe
  • Post summary
· branch [`hanoi`](https://github.com/cube-js/cube/tree/hanoi)

An empty string is not an unset value, and no caller passes one: Joi rejects it
before the timezone validators run, the env accessors filter empty entries out and
fall back to UTC, and the BaseQuery guard short-circuits on a falsy timezone. So
treat it as a bad argument and throw, rather than reporting it as an unknown zone.
@claude

claude Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 2m 29s —— View job


Re-review of 3393f95 — behavior-neutral today; the contract is now caller-coupled. 0 medium, 5 low (1 new inline comment)

Full review — findings, verification notes, and task list

What changed since eef56da

The '' case moves from "unset → null" to "bad argument → TypeError", one commit after it was made an explicit null case. The doc comment and the test split follow along, and the test.each for non-strings still covers 0/false, so nothing lost coverage.

I verified the commit message's claim caller by caller, and it holds as of this commit:

  • query.js:62 and optionsValidate.ts:5 are Joi.string().custom(...) — joi rejects '' with string.empty before the custom runs.
  • env.ts:275-278 — .asArray().map(trim).filter(Boolean), so no empty segment survives.
  • env.ts:355 — (… || '').trim() || 'UTC', so never ''.
  • BaseQuery.js:307 — truthiness-gated, so '' short-circuits and never reaches the helper.

So this is behavior-neutral right now. My reservations are about the shape of the contract rather than the current tree, and both are in the inline comment: the throw's unreachability depends on Joi.string()'s default empty-string rejection (which .allow(null, '') — a compat option I floated on the open gateway.ts thread — would remove, turning a 400 into a 500), and '' is the one bad value most likely to arrive from user input rather than a call-site bug, so grouping it with 123/{} gives the likeliest input the least useful failure mode. RangeError would also fit a well-typed-but-empty value better than TypeError.

Findings

# Sev Location Issue
1 Low timezone.ts:17-19 (new inline) '' reclassified as a TypeError. Unreachable today, but only because all four callers filter it first; .allow('') on either joi schema would make it a 500 where the old contract gave a 400. Also a poor fit for the "call-site bug" bucket, and the removed comment's durable point (!value is not a valid unset check, it swallows the non-strings that must throw) is worth keeping.
2 Low gateway.ts:484 (open thread) Unchanged by this commit. (a) Joi.object() without .required() accepts undefined, so an absent req.body would pass and body.query would throw a TypeError → 500 — unreachable today (line 474 destructures req.body, express.json() always sets an object) but one token to close; (b) unknown keys are now a hard 400 for the whole request — right default, but a version-skew break worth a release note, and cacheMode (accepted by querySchema, not here) goes from silently-ignored to 400; (c) null/'' timezones used to be forwarded as unset and now 400. Still no route-level negative test: test/index.test.ts:1322-1500 is happy-path only, and the schema tests exercise cubeSqlRequestSchema in isolation, so nothing pins the UserError → handleError → 400 wiring.
3 Low BaseQuery.js:307 Still truthiness-gated (this.timezone && (typeof … !== 'string' || !canonicalTimezone(…))), so a falsy non-string — 0, false, NaN — skips validation and reaches the dialect's AT TIME ZONE '${this.timezone}' sink. No quote, so not injection, but a DB error rather than a UserError. Gateway routes are covered by Joi.string(); this is the queryRewrite / refresh-scheduler path. Note this guard is also what keeps '' from reaching the helper's new throw, so the two are now coupled: gating on !== undefined && !== null && !== '' closes the falsy-non-string hole and keeps '' out.
4 Low optionsValidate.ts:108, server.ts:797 Re-verified: scheduledRefreshTimeZones is Joi.alternatives().try(Joi.array().items(timezoneSchema), Joi.func()) — the Joi.func() branch is unvalidated, and its awaited result goes straight into queryingOptions.timezones. With the env var canonicalizing at the source and the array form canonicalizing in validateOptions, the function form is the last route where the cross-planner divergence survives: a config returning ['utc'] fails Tesseract's case-sensitive parse::<Tz>() (query_tools.rs:61) while the legacy planner accepts it. A canonicalTimezone pass over the resolved list closes it.
5 Low environment-variables.mdx:1409-1419 Re-read it: the CUBEJS_SCHEDULED_REFRESH_TIMEZONES section is four lines plus a table, still no <Warning>, while CUBEJS_DEFAULT_TIMEZONE has one. This var now also fails the boot on an invalid zone, also rejects +05:00, and (since 062b0e7) ignores empty entries from trailing/repeated commas — three documentable behaviors, zero doc lines. Fix this →
6 Low timezone.test.ts:28-40, base-query.test.ts:140-146 Neither negative list has a quote-bearing entry, so the injection vector into AT TIME ZONE '${this.timezone}' (PostgresQuery.ts:28) — the thing this PR is really protecting — has no regression test. One case like "UTC' AT TIME ZONE 'UTC" would pin it. (Author resolved this thread earlier; noted once more, your call.)

Verified, not a problem

  • Every canonicalTimezone caller enumerated (query.js:63, optionsValidate.ts:6, env.ts:281, env.ts:357, BaseQuery.js:307) — none can pass '' today, so the new throw is unreachable from packages/*/src.
  • Check ordering — typeof before the '' test, and '' is a string either way, so the two branches can't shadow each other.
  • Doc comment matches behavior — the summary line and @throws were both updated in step with the code.
  • Test coverage of the reclassification — the '' case moved to its own toThrow(TypeError) test rather than being dropped, and the non-string block still pins 0/false, so the falsy cases stay covered.
  • Security fix intact — this.timezone still reaches SQL string literals raw across dialects (PostgresQuery.ts:28, ClickHouseQuery.ts:50, SnowflakeQuery.ts:38, BigqueryQuery.ts:45, HiveQuery.ts:30, TrinoQuery.ts:7, VerticaQuery.ts:16, MysqlQuery.ts:49); the BaseQuery constructor guard closes it on every path. Still worth one line in the PR description — it affects how this gets backported.
  • tzdb skew — moment-timezone here is much newer than chrono-tz 0.8.2 (cubesqlplanner/Cargo.toml:20), so recently-added zone names pass JS validation and fail in the native planner. Follow-up, not a blocker.

Not verified

node_modules isn't installed in this checkout (confirmed — no node_modules at the root or in cubejs-backend-shared), so I couldn't run yarn tsc or the suites. Joi.string()'s default string.empty rejection — which the reachability argument above rests on — comes from reading joi 17 rather than an empirical run. CI is the source of truth for pass/fail.

Thread housekeeping

Listed all 16 threads: 15 already resolved, 1 open (gateway.ts, finding #2). It still applies verbatim — this commit didn't touch that file — so I left it unresolved rather than re-posting. Posted one new inline comment (#1, a different file and line, no overlap with the open thread). Findings #4 and #5 aren't on diff lines and #6's thread was resolved by the author, so those are written out above. No human-authored threads touched.

Task list

  • Diff eef56da..3393f95 and identify what changed
  • Verify the "no caller passes ''" claim against all five call sites
  • Check the interaction with the .allow('') compat option suggested on the open thread
  • Re-verify each remaining open finding against the current tree
  • List review threads, resolve stale ones (none stale), dedupe
  • Post inline comment and summary
· branch [`hanoi`](https://github.com/cube-js/cube/tree/hanoi)

Drop the halves of the timezone comments that repeat what the assertion, the test
name or the guard below already says, keeping only the part that explains why.
@claude

claude Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 1m 37s —— View job


Re-review of 3b59610 — comment-only trim, no behavior change. 0 medium, 5 low carried over (no new inline comments; 2 prior threads still open)

Full review — findings, verification notes, and task list

What changed since 3393f95

Three files, comments only — git show --stat is 4 insertions / 8 deletions across env.test.ts, timezone.test.ts and BaseQuery.js, no executable lines touched. Each edit drops the half of a comment that restated the adjacent assertion or test name and keeps the half that explains why:

  • env.test.ts:188 — keeps the non-obvious fact (env-var's .default() doesn't fire for a present but blank value, and doesn't trim), drops "so they must keep booting", which the test name already says.
  • env.test.ts:239 — keeps "trailing/repeated separators are common in .env files and compose YAML", drops "so they must not be read as an empty zone" — the test name (ignores empty entries) plus the assertions cover that.
  • BaseQuery.js:301-305 — keeps the two loads that aren't inferable from the code (why it deliberately doesn't canonicalize, and why the type is checked here rather than delegated to canonicalTimezone's TypeError), drops "Message matches the native planner", which the string literal on the next line shows.

Good instinct across all three: the surviving text is the part a reader can't reconstruct from the code, and the deleted text is the part they can. BaseQuery.js is the one I'd have been most careful with, and the kept rationale is exactly right — that comment is the only thing standing between the deliberate no-canonicalization decision and a future "why isn't this normalized?" patch.

One trim I'd have kept as-is: timezone.test.ts:54 loses "A wrong type is a bug at the call site, not an unknown zone." That isn't a restatement — it's the reason the block asserts TypeError rather than null, and it's the distinction the whole strict-argument refactor rests on. The surviving sentence explains the as any casts, which is a different point. Minor, and the doc comment in timezone.ts carries the same information, so not worth a round-trip on its own.

Findings

All carried over verbatim; nothing in 3b59610 introduces or resolves any of them. Re-verified each against the current tree.

# Sev Location Issue
1 Low gateway.ts:484 (open thread) (a) Joi.object() without .required() accepts undefined, so an absent req.body would pass and body.query would throw a TypeError → 500 instead of 400 — unreachable today (line 474 destructures req.body, express.json() always sets an object) but one token to close; (b) unknown keys are now a hard 400 for the whole request — right default, but a version-skew break worth a release note, and cacheMode (accepted by querySchema, not here) goes from silently-ignored to 400; (c) null/'' timezones used to be forwarded as unset and now 400. Still no route-level negative test: test/index.test.ts:1322-1500 is happy-path only, and the schema tests exercise cubeSqlRequestSchema in isolation, so nothing pins the UserError → handleError → 400 wiring.
2 Low timezone.ts:19 (open thread) '' is classified as a TypeError ("call-site bug") rather than returning null. Unreachable today — re-confirmed all four callers filter it first (Joi.string()'s string.empty at query.js:62 and optionsValidate.ts:5, .filter(Boolean) at env.ts:275-278, `
3 Low BaseQuery.js:307 Still truthiness-gated (this.timezone && (typeof … !== 'string' || !canonicalTimezone(…))), so a falsy non-string — 0, false, NaN — skips validation and reaches the dialect's AT TIME ZONE '${this.timezone}' sink. No quote, so not injection, but a DB error rather than a UserError. Gateway routes are covered by Joi.string(); this is the queryRewrite / refresh-scheduler path. Gating on !== undefined && !== null && !== '' closes it, and would also keep '' away from #2's throw.
4 Low optionsValidate.ts:108-111, server.ts:797-799 Re-read both: scheduledRefreshTimeZones is Joi.alternatives().try(Joi.array().items(timezoneSchema), Joi.func()) — the Joi.func() branch is unvalidated, and await this.scheduledRefreshTimeZones(context) lands straight in queryingOptions.timezones at server.ts:799. With the env var canonicalizing at the source and the array form canonicalizing in validateOptions, the function form is the last route where the cross-planner divergence survives: a config returning ['utc'] fails Tesseract's case-sensitive parse::<Tz>() (query_tools.rs:61) while the legacy planner accepts it. A canonicalTimezone pass over the resolved list closes it.
5 Low environment-variables.mdx:1409-1419 Re-read the section: four lines plus a table, still no <Warning>, while CUBEJS_DEFAULT_TIMEZONE has one. This var now also fails the boot on an invalid zone, also rejects +05:00, and (since 062b0e7) ignores empty entries from trailing/repeated commas — three documentable behaviors, zero doc lines. Fix this →
6 Low timezone.test.ts:28-40, base-query.test.ts:140-146 Neither negative list has a quote-bearing entry, so the injection vector into AT TIME ZONE '${this.timezone}' (PostgresQuery.ts:28) — the thing this PR is really protecting — has no regression test. One case like "UTC' AT TIME ZONE 'UTC" would pin it. (Author resolved this thread earlier; noted once more, your call.)

Verified, not a problem

  • The commit is genuinely comment-only — the diff touches no expressions, no test cases, no assertions; BaseQuery.js's guard, canonicalTimezone's branches and both test bodies are byte-identical.
  • canonicalTimezone contract unchanged — re-read timezone.ts: undefined/null → null, non-string → TypeError, '' → TypeError, otherwise moment.tz.zone()?.name. The doc comment still matches.
  • Security fix intact — this.timezone still reaches SQL string literals raw across dialects (PostgresQuery.ts:28, ClickHouseQuery.ts:50, SnowflakeQuery.ts:38, BigqueryQuery.ts:45, HiveQuery.ts:30, TrinoQuery.ts:7, VerticaQuery.ts:16, MysqlQuery.ts:49); the BaseQuery constructor guard closes it on every path. Still worth one line in the PR description — it affects how this gets backported.
  • tzdb skew — moment-timezone here is much newer than chrono-tz 0.8.2 (cubesqlplanner/Cargo.toml:20), so recently-added zone names pass JS validation and fail in the native planner. Follow-up, not a blocker.

Not verified

node_modules isn't installed in this checkout, so I couldn't run yarn tsc or the suites. Nothing in this commit could affect either, since no code changed — but CI remains the source of truth for pass/fail.

Thread housekeeping

Listed all threads: 2 open (both claude), the rest already resolved. Both open ones — gateway.ts:484 (finding #1) and timezone.ts:19 (finding #2) — still apply verbatim, since this commit touches neither file, so I left them unresolved rather than re-posting. No new inline comments this pass: 3b59610 introduces no issue, and the one nit above (timezone.test.ts's dropped rationale) isn't worth a thread. Findings #4 and #5 aren't on diff lines and #6's thread was resolved by the author, so those are written out above. No human-authored threads touched.

Task list

  • Diff 3393f95..3b59610 and confirm it is comment-only
  • Check each trimmed comment for lost rationale
  • Re-verify each open finding against the current tree (timezone.ts, BaseQuery.js, optionsValidate.ts, server.ts, the mdx section)
  • List review threads, resolve stale ones (none stale), dedupe
  • Post summary
· branch [`hanoi`](https://github.com/cube-js/cube/tree/hanoi)

The section listed the accepted values but none of the validation behaviour, while
CUBEJS_DEFAULT_TIMEZONE already carried the same warning. State that an invalid zone
fails at startup, that UTC offsets are rejected, and that empty entries left by a
trailing or repeated comma are ignored.
@claude

claude Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 1m 27s —— View job


Re-review of d60aa38 — docs-only, and it closes a prior finding. 0 medium, 4 low remain (no new inline comments; 2 prior threads still open)

Full review — findings, verification notes, and task list

What changed since 3b59610

One file, eight added lines: a <Warning> under CUBEJS_SCHEDULED_REFRESH_TIMEZONES in environment-variables.mdx, mirroring the one CUBEJS_DEFAULT_TIMEZONE already carries at :1109. This is the doc finding I'd carried for six passes; it's closed.

I checked each of the three claims against the implementation, and all three hold:

  • "An invalid value fails at server startup" — env.ts:280-287 throws InvalidConfiguration, and the read is eager: OptsHandler constructor (:47) → initializeCoreOptions → getEnv('scheduledRefreshTimezones') at :403. So it's genuinely boot-time, not first-refresh-time.
  • "fixed UTC offsets such as +05:00 are rejected" — canonicalTimezone only resolves tz-database names; timezone.test.ts pins '+05:00'/'+05'/'05' as null.
  • "Empty entries are ignored, so a trailing or repeated comma … is not an error" — env.ts:275-278 (.asArray().map(trim).filter(Boolean)), with env.test.ts covering 'UTC,', 'UTC,,America/Los_Angeles', ' UTC , ', ','.

Placement and wording are right: it sits after the values table and before the "can also be set using scheduled_refresh_time_zones" pointer, and the phrasing deliberately parallels the CUBEJS_DEFAULT_TIMEZONE warning so the two read as one rule rather than two. The third sentence is the one a reader couldn't have guessed, and it's the one that's specific to this var.

One thing the warning doesn't say, and arguably shouldn't: the sibling scheduled_refresh_time_zones config option validates the array form the same way but not the function form (finding #2 below), so "fails at startup" is true of the env var and the array, not of a function that returns a bad zone. Fine to leave implicit in an env-var reference; worth knowing if #2 gets closed and the config-option page gets a matching note.

Findings

All carried over; a docs-only commit can't change any of them. Re-verified each against the current tree.

# Sev Location Issue
1 Low gateway.ts:484 (open thread) (a) Joi.object() without .required() accepts undefined, so an absent req.body would pass and body.query would throw a TypeError → 500 instead of 400 — unreachable today (line 474 destructures req.body, express.json() always sets an object) but one token to close; (b) unknown keys are now a hard 400 for the whole request — right default, but a version-skew break worth a release note, and cacheMode (accepted by querySchema, not here) goes from silently-ignored to 400; (c) null/'' timezones used to be forwarded as unset and now 400. Still no route-level negative test: test/index.test.ts:1322-1500 is happy-path only, and the schema tests exercise cubeSqlRequestSchema in isolation, so nothing pins the UserError → handleError → 400 wiring.
2 Low optionsValidate.ts:108, server.ts:797 The Joi.func() alternative for scheduledRefreshTimeZones remains unvalidated — await this.scheduledRefreshTimeZones(context) lands straight in queryingOptions.timezones (server.ts:797). With the env var canonicalizing at the source and the array form canonicalizing in validateOptions, the function form is the last route where the cross-planner divergence this PR targets survives: a config returning ['utc'] fails Tesseract's case-sensitive parse::<Tz>() (query_tools.rs:61) while the legacy planner accepts it. A canonicalTimezone pass over the resolved list closes it — and would make this commit's "fails at startup" framing true of every route into the option.
3 Low timezone.ts:19 (open thread) '' is classified as a TypeError ("call-site bug") rather than returning null. Unreachable today — all four callers filter it first (Joi.string()'s string.empty at query.js:62 and optionsValidate.ts:5, .filter(Boolean) at env.ts:275-278, || 'UTC' at env.ts:355, truthiness at BaseQuery.js:307) — but '' is the one bad value most likely to come from user input, and .allow(null, '') on timezoneSchema (the compat option floated on thread #1) would turn a clean 400 into a 500. RangeError would also fit a well-typed-but-empty value better.
4 Low BaseQuery.js:307 Still truthiness-gated (this.timezone && (typeof … !== 'string' || !canonicalTimezone(…))), so a falsy non-string — 0, false, NaN — skips validation and reaches the dialect's AT TIME ZONE '${this.timezone}' sink. No quote, so not injection, but a DB error rather than a UserError. Gateway routes are covered by Joi.string(); this is the queryRewrite / refresh-scheduler path. Gating on !== undefined && !== null && !== '' closes it, and would also keep '' away from #3's throw.
5 Low timezone.test.ts:28-38, base-query.test.ts:140-146 Neither negative list has a quote-bearing entry, so the injection vector into AT TIME ZONE '${this.timezone}' (PostgresQuery.ts:28) — the thing this PR is really protecting — has no regression test. One case like "UTC' AT TIME ZONE 'UTC" would pin it. (Author resolved this thread earlier; noted once more, your call.)

Verified, not a problem

  • Commit is docs-only — git show --stat is one file, 8 insertions, 0 deletions; no code or test lines touched.
  • Startup-failure claim — traced the eager read through the OptsHandler constructor (:47 → initializeCoreOptions → :403), so the throw lands at boot as documented. OptsHandler.test.ts already pins that behavior.
  • Warning renders — blank lines after <Warning> and before </Warning>, matching the CUBEJS_DEFAULT_TIMEZONE block and the repo's Mintlify convention, so the markdown inside will render.
  • Security fix intact — this.timezone still reaches SQL string literals raw across dialects (PostgresQuery.ts:28, ClickHouseQuery.ts:50, SnowflakeQuery.ts:38, BigqueryQuery.ts:45, HiveQuery.ts:30, TrinoQuery.ts:7, VerticaQuery.ts:16, MysqlQuery.ts:49); the BaseQuery constructor guard closes it on every path. Still worth one line in the PR description — it affects how this gets backported.
  • tzdb skew — moment-timezone here is much newer than chrono-tz 0.8.2 (cubesqlplanner/Cargo.toml:20), so recently-added zone names pass JS validation and fail in the native planner. Follow-up, not a blocker.

Not verified

node_modules isn't installed in this checkout, so I couldn't run the suites or the Mintlify dev server — the render check is by reading the file against the sibling block's structure, and the behavioral claims by reading env.ts/OptsHandler.ts rather than an empirical run. Nothing in this commit could affect CI, since no code changed.

Thread housekeeping

Two threads open, both mine: gateway.ts:484 (finding #1) and timezone.ts:19 (finding #3). This commit touches neither file, so both still apply verbatim — left unresolved rather than re-posted. Nothing became stale this pass; everything else was already resolved. No new inline comments, since d60aa38 introduces no issue. Findings #2, #4 and #5 aren't on diff lines, so they're written out above. No human-authored threads touched.

Task list

  • Diff 3b59610..d60aa38 and confirm it is docs-only
  • Verify each documented claim against env.ts and OptsHandler.ts
  • Confirm the eager read makes "fails at server startup" accurate
  • Check the <Warning> block against the sibling precedent and Mintlify conventions
  • Re-verify each remaining open finding against the current tree
  • List review threads, resolve stale ones (none stale), dedupe
  • Post summary
· branch [`hanoi`](https://github.com/cube-js/cube/tree/hanoi)

@claude

claude Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 1m 15s —— View job


Re-review of 7005ea1 — docs-only, one-line trim. 0 medium, 4 low carried over (no new inline comments; 2 prior threads still open)

Full review — findings, verification notes, and task list

What changed since d60aa38

One file, +1/−2: the <Warning> under CUBEJS_SCHEDULED_REFRESH_TIMEZONES loses its last sentence, keeping only the two rules a user can trip over:

An invalid value fails at server startup. Only TZ Database names are accepted — fixed
UTC offsets such as `+05:00` are rejected.

Both surviving claims still check out against the implementation — env.ts:275-292 throws InvalidConfiguration on an unresolvable zone and the read is eager via the OptsHandler constructor → initializeCoreOptions, so "at server startup" is literal; and canonicalTimezone only resolves tz-database names, with '+05:00'/'+05'/'05' pinned as rejected in timezone.test.ts.

The dropped sentence ("Empty entries are ignored, so a trailing or repeated comma, e.g. UTC,, is not an error") was also accurate — .asArray().map(trim).filter(Boolean) at env.ts:275-278, covered by the 'UTC,' / 'UTC,,America/Los_Angeles' / ',' cases in env.test.ts. So this is a shortening, not a correction. Reasonable call: leniency generally doesn't need documenting, and a warning box reads better when every line in it is something that can fail. The one argument for keeping it is that 062b0e7 deliberately made trailing commas non-fatal in this same PR, and the boot-failure warning immediately above it is exactly what would make a reader assume UTC, is now dangerous — so the sentence was pre-empting a wrong inference the neighbouring line invites. Not worth a round trip either way; noting it as the tradeoff being made.

Findings

All carried over; a docs-only trim can't change any of them. Re-verified each against the current tree.

# Sev Location Issue
1 Low gateway.ts:484 (open thread) (a) Joi.object() without .required() accepts undefined, so an absent req.body would pass and body.query would throw a TypeError → 500 instead of 400 — unreachable today (line 474 destructures req.body, express.json() always sets an object) but one token to close; (b) unknown keys are now a hard 400 for the whole request — right default, but a version-skew break worth a release note, and cacheMode (accepted by querySchema, not here) goes from silently-ignored to 400; (c) null/'' timezones used to be forwarded as unset and now 400. Still no route-level negative test: test/index.test.ts:1322-1500 is happy-path only, and the schema tests exercise cubeSqlRequestSchema in isolation, so nothing pins the UserError → handleError → 400 wiring.
2 Low timezone.ts:19 (open thread) '' is classified as a TypeError ("call-site bug") rather than returning null. Unreachable today — all callers filter it first (Joi.string()'s string.empty at query.js:62 and optionsValidate.ts:5, .filter(Boolean) at env.ts:275-278, || 'UTC' at env.ts:355, truthiness at BaseQuery.js:307) — but '' is the one bad value most likely to come from user input, and .allow(null, '') on timezoneSchema (the compat option floated on thread #1) would turn a clean 400 into a 500. RangeError would also fit a well-typed-but-empty value better.
3 Low BaseQuery.js:307 Still truthiness-gated (this.timezone && (typeof … !== 'string' || !canonicalTimezone(…))), so a falsy non-string — 0, false, NaN — skips validation and reaches the dialect's AT TIME ZONE '${this.timezone}' sink. No quote, so not injection, but a DB error rather than a UserError. Gateway routes are covered by Joi.string(); this is the queryRewrite / refresh-scheduler path. Gating on !== undefined && !== null && !== '' closes it, and would also keep '' away from #2's throw.
4 Low optionsValidate.ts:108, server.ts:797 The Joi.func() alternative for scheduledRefreshTimeZones remains unvalidated — its awaited result lands straight in queryingOptions.timezones. With the env var canonicalizing at the source and the array form canonicalizing in validateOptions, the function form is the last route where the cross-planner divergence this PR targets survives: a config returning ['utc'] fails Tesseract's case-sensitive parse::<Tz>() (query_tools.rs:61) while the legacy planner accepts it. A canonicalTimezone pass over the resolved list closes it — and would make the <Warning> this commit edits true of every route into the option, not just the env var.
5 Low timezone.test.ts:28-38, base-query.test.ts:140-146 Neither negative list has a quote-bearing entry, so the injection vector into AT TIME ZONE '${this.timezone}' (PostgresQuery.ts:28) — the thing this PR is really protecting — has no regression test. One case like "UTC' AT TIME ZONE 'UTC" would pin it. (Author resolved this thread earlier; noted once more, your call.)

Verified, not a problem

  • Commit is docs-only — git show --stat is one file, 1 insertion, 2 deletions; no code or test lines touched, so nothing in CI can shift.
  • Both surviving warning claims re-checked against env.ts / OptsHandler.ts / timezone.test.ts; both hold.
  • The removed claim was also true, so no accuracy issue either way — env.test.ts still pins the empty-segment cases, so the behavior stays tested even though it's no longer documented.
  • <Warning> still renders — blank lines after the open tag and before the close, matching the CUBEJS_DEFAULT_TIMEZONE block.
  • Security fix intact — this.timezone still reaches SQL string literals raw across dialects (PostgresQuery.ts:28, ClickHouseQuery.ts:50, SnowflakeQuery.ts:38, BigqueryQuery.ts:45, HiveQuery.ts:30, TrinoQuery.ts:7, VerticaQuery.ts:16, MysqlQuery.ts:49); the BaseQuery constructor guard closes it on every path. Still worth one line in the PR description — it affects how this gets backported.
  • tzdb skew — moment-timezone here is much newer than chrono-tz 0.8.2 (cubesqlplanner/Cargo.toml:20), so recently-added zone names pass JS validation and fail in the native planner. Follow-up, not a blocker.

Not verified

node_modules isn't installed in this checkout, so I couldn't run yarn tsc, the suites, or the Mintlify dev server — the render check is by reading the file against the sibling block, and the behavioral claims by reading env.ts/OptsHandler.ts. Nothing in this commit could affect CI, since no code changed.

Thread housekeeping

17 threads total: 15 resolved, 2 open (both mine) — gateway.ts:484 (finding #1) and timezone.ts:19 (finding #2). This commit touches neither file, so both still apply verbatim; left unresolved rather than re-posted. No new inline comments, since 7005ea1 introduces no issue and the one tradeoff noted above isn't worth a thread. Findings #3–#5 aren't on diff lines, so they're written out above. No human-authored threads touched.

Task list

  • Diff d60aa38..7005ea1 and confirm it is docs-only
  • Re-verify the two surviving warning claims against env.ts and OptsHandler.ts
  • Check whether the removed sentence was accurate / still covered by tests
  • Re-verify each open finding against the current tree
  • List review threads, resolve stale ones (none stale), dedupe
  • Post summary
· branch [`hanoi`](https://github.com/cube-js/cube/tree/hanoi)

The guard only checked that the timezone was a known zone and left the original
casing in place, so a lowercase name such as utc reached the dialects verbatim and
failed on the native planner, which parses the zone case-sensitively. Assign the
canonical name and pass it to the native query params, so both planners see the
same zone whichever entry point built the query.

A non-string timezone now surfaces as the TypeError canonicalTimezone raises. No
route can produce one: they all validate the timezone as a string beforehand.
@claude

claude Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 3m 22s —— View job


Re-review of 79b1c43 — canonicalizing in BaseQuery closes the last divergence route. 0 medium, 5 low (1 new inline comment)

Full review — findings, verification notes, and task list

What changed since 7005ea1

BaseQuery reverses the "validate but don't canonicalize" decision: the constructor now assigns this.timezone = canonicalTimezone(this.timezone), and both native param builders (buildSqlAndParamsRust, findPreAggregationForQueryRust) switched from this.options.timezone to this.timezone. The test block follows — 'utc' → 'UTC' with an assertion on the rendered AT TIME ZONE 'UTC', and the non-string cases now expect TypeError rather than UserError.

This is the change I'd argued for across the first three passes and then accepted the opposite of; it's better this way. It closes the one route where the divergence this PR targets still survived — the Joi.func() alternative for scheduledRefreshTimeZones, whose resolved list is still unvalidated (optionsValidate.ts:108 → server.ts:797). A config hook returning ['utc'] now canonicalizes at the choke point every path passes through, so that finding is gone, and the "canonicalize the resolved list in server.ts" follow-up is no longer needed.

I checked the commit message's claim that no route can produce a non-string, and it holds for HTTP: queryRewrite's output is re-validated (gateway.ts:1422 calls normalizeQuery on the rewritten query), so a hook returning timezone: 123 still fails as a 400 via Joi.string() rather than escaping as a TypeError. The remaining producer is a config hook feeding the refresh scheduler directly, which is what the test comment says.

Findings

# Sev Location Issue
1 Low BaseQuery.js:302 (new inline) if (this.timezone) leaves the new contract inconsistent for falsy non-strings: 123/{}/true throw TypeError as the tests pin, but 0, false and NaN skip the gate entirely and reach AT TIME ZONE '${this.timezone}' (PostgresQuery.ts:28) as AT TIME ZONE '0' — a DB error rather than a validation one. !== undefined && !== null && !== '' closes it; 0/false are worth adding to the it.each.
2 Low BaseQuery.js:274, PreAggregations.ts:380 Two readers still take the raw option. The compilerCache.getQueryCache key is still this.options.timezone, so 'utc' and 'UTC' now allocate two entries holding identical SQL (harmless, just a wasted slot — canonicalizing above the getQueryCache call fixes it). And the pre-agg descriptor's timezone: this.query.options?.timezone hands the raw spelling to the orchestrator's localTimestampToUtc/extractDate calls (PreAggregationPartitionRangeLoader.ts:161-200, :463-492) — moment is lenient so ranges resolve the same, but the descriptor and the SQL it describes now disagree on the spelling.
3 Low release notes Canonicalization moves pre-aggregation structure versions. getStructureVersion hashes preAggregation.loadSql (query-orchestrator/src/orchestrator/PreAggregations.ts:74-86), and loadSql embeds the rendered AT TIME ZONE '…', so any tenant currently sending utc — or a lowercase zone via scheduledRefreshTimeZones — gets a new structure version and a one-time rebuild on upgrade. Exactly what the comment this commit replaces was guarding; the tradeoff is right, but it needs an explicit release-note line rather than a surprise rebuild.
4 Low gateway.ts:484 (open thread) (a) Joi.object() without .required() accepts undefined, so an absent req.body would pass and body.query would throw → 500 rather than 400 — unreachable today (line 474 destructures req.body, express.json() always sets an object) but one token to close; (b) unknown keys are now a hard 400 for the whole request — right default, but a version-skew break worth a release note, and cacheMode (accepted by querySchema, not here) goes from silently-ignored to 400; (c) null/'' timezones used to be forwarded as unset and now 400. Still no route-level negative test: test/index.test.ts:1322-1500 is happy-path only, and the schema tests exercise cubeSqlRequestSchema in isolation, so nothing pins the UserError → handleError → 400 wiring.
5 Low timezone.ts:19 (open thread) '' is classified as a TypeError ("call-site bug") rather than returning null. Still unreachable — Joi.string()'s string.empty at query.js:62 and optionsValidate.ts:5, .filter(Boolean) at env.ts:275-278, || 'UTC' at env.ts:355, and BaseQuery's truthiness gate all filter it first — but '' is the one bad value most likely to come from user input, and .allow(null, '') on timezoneSchema (the compat option floated on thread #4) would turn a clean 400 into a 500. RangeError would also fit a well-typed-but-empty value better. Note this commit tightens the coupling: BaseQuery's truthiness gate is now the only thing keeping '' away from the throw, and finding #1 asks to replace that gate.
6 Low timezone.test.ts:28-38, base-query.test.ts:140-146 Neither negative list has a quote-bearing entry, so the injection vector into AT TIME ZONE '${this.timezone}' — the thing this PR is really protecting — has no regression test. One case like "UTC' AT TIME ZONE 'UTC" would pin it. (Author resolved this thread earlier; noted once more, your call.)

Verified, not a problem

  • queryRewrite can't produce a TypeError — gateway.ts:1422 re-runs normalizeQuery on the rewritten query, so a hook setting a non-string timezone is caught by Joi.string() as a 400. The TypeError path is reachable only from config hooks that build queries outside the gateway.
  • Both native param builders updated — buildSqlAndParamsRust:956 and findPreAggregationForQueryRust:1014 now pass this.timezone, so the native planner sees the canonical name; those were the two sites that mattered for the case-sensitivity mismatch at query_tools.rs:61.
  • Partition table names don't embed the timezone, so the rebuild in finding ResultSet pivot methods documentation  #3 comes from the loadSql hash only — no partition-naming churn on top of it.
  • '' still short-circuits the guard, so this commit doesn't make canonicalTimezone's empty-string throw reachable.
  • Security fix intact — this.timezone still reaches SQL string literals raw across dialects (PostgresQuery.ts:28, ClickHouseQuery.ts:50, SnowflakeQuery.ts:38, BigqueryQuery.ts:45, HiveQuery.ts:30, TrinoQuery.ts:7, VerticaQuery.ts:16, MysqlQuery.ts:49); the constructor guard closes it on every path. Still worth one line in the PR description — it affects how this gets backported.
  • tzdb skew — moment-timezone here is much newer than chrono-tz 0.8.2 (cubesqlplanner/Cargo.toml:20), so recently-added zone names pass JS validation and fail in the native planner. Follow-up, not a blocker.

Not verified

node_modules isn't installed in this checkout, so I couldn't run yarn tsc or the suites — findings #2 and #3 come from reading the orchestrator's getStructureVersion / PreAggregationPartitionRangeLoader call chain rather than an empirical build-and-compare. CI is the source of truth for pass/fail.

Thread housekeeping

Two threads open, both mine: gateway.ts:484 (finding #4) and timezone.ts:19 (finding #5). This commit touches neither file and both still apply verbatim, so I left them unresolved rather than re-posting. Nothing became stale — the BaseQuery canonicalization thread I'd carried for three passes was already resolved when I accepted the opposite decision, and this commit implements it. Posted one new inline comment (#1–#3, all on the changed lines). Finding #6's thread was resolved by the author, so it's written out above. No human-authored threads touched.

Task list

  • Diff 7005ea1..79b1c43 and identify what changed
  • Verify the "no route can produce a non-string" claim, including queryRewrite
  • Find every remaining reader of the raw this.options.timezone
  • Trace whether canonicalization moves pre-agg structure versions / partition names
  • Re-verify each remaining open finding against the current tree
  • List review threads, resolve stale ones (none stale), dedupe
  • Post inline comment and summary
· branch [`hanoi`](https://github.com/cube-js/cube/tree/hanoi)

The wrong-type inputs are unreachable over HTTP — every route validates the
timezone as a string before the query is built.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@claude

claude Bot commented Aug 19, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @ovr's task in 2m 15s —— View job


Re-review of b4d5ef6 — test-only deletion; the explicit-error change you asked for still isn't in the tree. 0 medium, 4 low (1 new inline comment)

Full review — findings, verification notes, and task list

What changed since 79b1c43

One commit, test-only: the it.each([123, {}, true])('rejects non-string timezone') block is deleted from base-query.test.ts (−11 lines, no source touched).

Reasonable on coverage grounds — timezone.test.ts:53-64 already pins 123/0/{}/[]/true/false as TypeError at the unit level, so the deleted block was mostly duplicating that one layer up. The only thing genuinely lost is the assertion that BaseQuery lets the TypeError propagate rather than wrapping it in a UserError, which is cheap.

The commit message's claim also holds: no HTTP route can deliver a non-string, since timezoneSchema is Joi.string() (query.js:62) on /v1/load and the pre-agg routes, and cubeSqlRequestSchema covers /v1/cubesql. The remaining producers are config hooks and direct BaseQuery consumers.

The thing worth a second look

Two review rounds ago, on both BaseQuery.js:311 and timezone.ts:19, you said you wanted an explicit error, not a silent ignore. That change was never applied — the push was rejected with a 403, and this commit goes the other direction, removing the tests rather than tightening the gate. So the current tree still has:

if (this.timezone) {          // BaseQuery.js:304
timezone behavior at HEAD
undefined, null skipped — intended (trino-presto-date-time-dimension.test.ts:102 passes null)
'' silently skipped → AT TIME ZONE ''
0, false, NaN silently skipped → AT TIME ZONE '0'
123, {}, true TypeError — correct, but no longer tested here

canonicalTimezone's empty-string throw (3393f95) and its non-string throw are therefore both unreachable through this path for precisely the inputs a truthiness check swallows. Flipping the gate to !== undefined && !== null is the one-line change that makes the helper's documented contract take effect; the inline comment carries the guard plus the two it.each blocks that would pin it.

Findings

# Sev Location Issue
1 Low BaseQuery.js:304, base-query.test.ts (new inline) Truthiness gate lets ''/0/false/NaN skip validation entirely and reach the dialect's AT TIME ZONE '${this.timezone}' sink (PostgresQuery.ts:28). No quote, so not injection, but a DB error rather than a UserError/TypeError — and this commit removes the last schema-compiler coverage of the throw branch, so nothing pins any of it.
2 Low BaseQuery.js:274, PreAggregations.ts:380 Two readers still take the raw option. The compilerCache.getQueryCache key is this.options.timezone, so 'utc' and 'UTC' now allocate two entries holding identical SQL (harmless, one wasted slot — canonicalizing above the getQueryCache call collapses them). And the pre-agg descriptor's timezone: this.query.options?.timezone hands the raw spelling to the orchestrator's localTimestampToUtc/extractDate calls while the SQL it describes carries the canonical one; moment is lenient so ranges resolve the same, but the two disagree.
3 Low release notes Canonicalization moves pre-aggregation structure versions. getStructureVersion hashes preAggregation.loadSql (query-orchestrator/src/orchestrator/PreAggregations.ts:74-86) and loadSql embeds the rendered AT TIME ZONE '…', so any tenant currently sending utc — or a lowercase zone via scheduledRefreshTimeZones — gets a one-time rebuild on upgrade. Right tradeoff, but it should be an explicit release-note line rather than a surprise. Same note should mention +05:00 now hard-failing, and that unknown keys on /v1/cubesql are now a 400.
4 Low optionsValidate.ts:108, server.ts:797-799 Re-verified: scheduledRefreshTimeZones is Joi.alternatives().try(Joi.array().items(timezoneSchema), Joi.func()), and await this.scheduledRefreshTimeZones(context) lands straight in queryingOptions.timezones. The Joi.func() branch is unvalidated — but now that BaseQuery canonicalizes (79b1c43), a hook returning ['utc'] is fixed up at the choke point rather than failing in Tesseract, so this is down to "no early, clear error" rather than a divergence.
5 Low timezone.test.ts:28-38, base-query.test.ts:140-146 Neither negative list has a quote-bearing entry, so the injection vector into AT TIME ZONE '${this.timezone}' — the thing this PR is really protecting — has no regression test. One case like "UTC' AT TIME ZONE 'UTC" would pin it. (Thread resolved earlier; noted once more, your call.)

Verified, not a problem

  • Commit is test-only — git show --stat is one file, 0 insertions / 11 deletions; no source or behavior change.
  • The deleted coverage is duplicated at the unit level in timezone.test.ts, which still exercises every wrong-type case including 0/false.
  • null must stay "unset" — trino-presto-date-time-dimension.test.ts:102 constructs a query with timezone: null, so the suggested gate deliberately keeps undefined/null accepted.
  • No route can deliver a non-string — Joi.string() gates query.js:62 (used by querySchema, the pre-agg schemas and preAggsJobsRequestSchema) and cubeSqlRequestSchema covers /v1/cubesql; queryRewrite's output is re-validated at gateway.ts:1422.
  • Security fix intact — this.timezone still reaches SQL string literals raw across dialects (PostgresQuery.ts:28, ClickHouseQuery.ts:50, SnowflakeQuery.ts:38, BigqueryQuery.ts:45, HiveQuery.ts:30, TrinoQuery.ts:7, VerticaQuery.ts:16, MysqlQuery.ts:49); the constructor guard closes it for every string input. Still worth one line in the PR description — it affects how this gets backported.
  • tzdb skew — moment-timezone here is much newer than chrono-tz 0.8.2 (cubesqlplanner/Cargo.toml:20), so recently-added zone names pass JS validation and fail in the native planner. Follow-up, not a blocker.

Not verified

node_modules isn't installed in this checkout, so I couldn't run yarn tsc or the suites — nothing in this commit could affect compilation, and the deleted tests can't fail, but CI remains the source of truth. Findings #2 and #3 come from reading the orchestrator's getStructureVersion / PreAggregationPartitionRangeLoader call chain rather than a build-and-compare.

Thread housekeeping

All 18 threads on this PR are already resolved — nothing to resolve, nothing to dedupe against. Posted one new inline comment (finding #1). It restates the concern from the now-resolved BaseQuery.js:311 thread, but on a different file and line, and because the change you asked for on that thread was never pushed (403) — so it's the live version of the request rather than a duplicate. Findings #2–#5 aren't on diff lines, so they're written out above. No human-authored threads touched.

Task list

  • Diff 79b1c43..b4d5ef6 and identify what changed
  • Check whether the deleted cases are covered elsewhere (timezone.test.ts)
  • Verify the commit message's "unreachable over HTTP" claim across every route
  • Re-check the BaseQuery guard against the explicit-error request from the prior round
  • Confirm null is a supported "unset" spelling before suggesting a stricter gate
  • Re-verify each remaining open finding against the current tree
  • List review threads, resolve stale ones (none open), dedupe
  • Post inline comment and summary
· branch [`hanoi`](https://github.com/cube-js/cube/tree/hanoi)

const query = buildTimezoneQuery(timezone);
expect(query.timezone).toBe(expected);
expect(query.buildSqlAndParams()[0]).toContain(`AT TIME ZONE '${expected}'`);
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Removing these is defensible on coverage grounds — timezone.test.ts:53-64 already pins 123/0/{}/[]/true/false as TypeError at the unit level, so the only thing lost is the assertion that BaseQuery lets that throw propagate rather than wrapping it in a UserError. Cheap to lose.

What concerns me is what it leaves behind. Two comments ago you said you wanted an explicit error rather than a silent ignore at BaseQuery.js:304, and that change never landed — the guard is still if (this.timezone), so the truthy non-strings these tests covered throw while the falsy ones don't:

timezone current behavior
undefined, null skipped (intended — trino-presto-date-time-dimension.test.ts:102 relies on null)
'' silently skipped → AT TIME ZONE ''
0, false, NaN silently skipped → AT TIME ZONE '0'
123, {}, true TypeError (no longer tested here)

So canonicalTimezone's empty-string throw (3393f95) and its non-string throw are both unreachable through this path for exactly the inputs a truthiness check swallows, and after this commit nothing in the schema-compiler suite pins any of it. If the intent is that a bad argument fails loudly, the gate is the thing to change, not the tests:

Suggested change
});
});
// A falsy value such as '' or 0 is a bad argument rather than "no timezone", so it
// must reach canonicalTimezone and fail instead of flowing into convertTz().
it.each([
'',
0,
false,
])('rejects falsy non-unset timezone %j', async (timezone) => {
await compilers.compiler.compile();
expect(() => buildTimezoneQuery(timezone as any)).toThrow(TypeError);
});
it.each([
undefined,
null,
])('accepts an unset timezone %j', async (timezone) => {
await compilers.compiler.compile();
expect(() => buildTimezoneQuery(timezone as any)).not.toThrow();
});

paired with if (this.timezone !== undefined && this.timezone !== null) in the constructor. Nothing in packages/*/src passes an empty timezone today (RefreshScheduler.ts:271 and query.js:456 both || 'UTC', env.ts:355 falls back to 'UTC'), so I'd expect no fallout beyond the null case above, which stays accepted.

Fix this →

@ovr
ovr merged commit d1ba22a into master Aug 19, 2026
99 of 100 checks passed
@ovr
ovr deleted the hanoi branch August 19, 2026 12:27
@claude claude Bot mentioned this pull request Aug 25, 2026
kewin-robetti pushed a commit to viasoftkorp/cube that referenced this pull request Aug 28, 2026
Backport of d1ba22a to LTS v1.4.

`canonicalTimezone()` (new, in `@cubejs-backend/shared`) resolves a value to a
canonical tz-database zone name case-insensitively, or null. It is wired into
every entry point a timezone can arrive through:

| Sink | Guard |
| --- | --- |
| REST query | `timezoneSchema` on `querySchema` |
| `/v1/cubesql` body | new `cubeSqlRequestSchema` |
| Pre-agg jobs / preview | `preAggsJobsRequestSchema`, `queryPreAggregations*Schema` |
| `CUBEJS_SCHEDULED_REFRESH_TIMEZONES` | `getEnv` throws `InvalidConfiguration` |
| `CreateOptions.scheduledRefreshTimeZones` | `validateOptions` |
| Everything else (queryRewrite, refresh scheduler, SQL API) | `BaseQuery` constructor backstop |

The Joi schemas now return their validated `value`, so the canonical name is
what reaches the dialects' `convertTz()` — the native planner parses zones
case-sensitively, so `utc` had to become `UTC` before it got there.
`optionsValidate`'s default export becomes the named `validateOptions`, which
returns the sanitized options; `OptsHandler.assertOptions` becomes
`sanitizeOptions` and feeds them into `initializeCoreOptions`.

Differences from master, all because the target lacks features that landed later:

| Dropped | Reason |
| --- | --- |
| `CUBEJS_DEFAULT_TIMEZONE` validation + its docs and the `OptsHandler` startup probe | The env var itself does not exist on v1.4 |
| `preciseDecimalInCubestore` | Unrelated, adjacent to the same env.ts hunk |
| The v1.7.0 `CreateOptions.dbType` removal throw | v1.4 still supports `dbType`; its handling is kept as-is |
| `execSql`'s `timezone`/`throwContinueWait`/`requestId` args | v1.4's `execSql` takes 4 params |
| `responseFormat: 'columnar'` test case | v1.4 accepts `default` and `compact` only |

`cubeSqlRequestSchema` still accepts `timezone` and `throwContinueWait` so that
bodies which work today keep working; v1.4 ignores both, as it did before.

Verified: backend-shared timezone/env suites, api-gateway (new
normalize-query.test.ts, 33 tests), server-core optionsValidate + the 3 new
OptsHandler timezone tests, and the full schema-compiler unit suite. Remaining
failures in those packages reproduce identically on the parent commit
(numeric-to-string serialization in api-gateway, stale sibling `dist` in
server-core, `error-reporter` in schema-compiler).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
kewin-robetti pushed a commit to viasoftkorp/cube that referenced this pull request Aug 28, 2026

This branch was successfully deployed

2 active (1 outdated) deployments
Preview — b4d5ef6b Deployed Aug 19, 2026 by vercel[bot]
staging - docs-mintlify — 7005ea11 Deployed Aug 19, 2026 by mintlify[bot]
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.

2 participants

⌂ Proxy