Skip to content

fix: bound jsonb string length to remaining input - #7867

Merged
wenshao merged 3 commits into
alibaba:mainfrom
Support-itecz:jsonb-string-length
Oct 17, 2026
Merged

wenshao merged 3 commits into
alibaba:mainfrom
Support-itecz:jsonb-string-length

Conversation

@Support-itecz

@Support-itecz Support-itecz commented Sep 14, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does / why we need it?

A JSONB string frame carries its byte length on the wire. JSONReaderJSONB's string readers take that length from readLength() (capped only at 256MB) and then copy that many bytes out of the backing array to build the String, without checking it against the frame end. BC_BINARY and BC_BIGINT already reject a length greater than end - offset; the string readers did not.

With the slice API (JSONB.parseObject(byte[], off, len, type) / JSONReader.ofJSONB(byte[], off, len)) end is the frame boundary rather than bytes.length, so a declared string length larger than the frame but still inside the backing buffer reads past end and hands the caller adjacent bytes as a String or map key. In a shared or pooled buffer that leaks data from a neighboring frame. This is separate from #7737, which bounds array item counts; here the concern is the string byte length and the bytes it returns.

Summary of your change

Two guards next to the existing checkBigintLen:

  • checkStrLen(strlen, offset, end) bounds the length against the bytes left in the frame and nothing else, for the sites that resolve a negative length as a symbol ordinal (getString, readAny's BC_STR_ASCII branch, readString, readString(Charset), and readFieldName, which resolves it after its guards).
  • checkStrLenCopy(strlen, offset, end) additionally rejects a negative length, for the sites that copy straight out of the array with no symbol reference ahead of them (readAny's five non-ASCII string cases, readGB18030, readUTF16BE, readUTF16LE, readStringUTF8). Those used to reach the copy and raise NegativeArraySizeException, StringIndexOutOfBoundsException or NullPointerException instead of JSONException, and readStringUTF8 returned "" and then applied offset += strlen, rewinding the cursor behind where it started.

Both are 16 and 20 bytes of bytecode, under MaxInlineSize, with the message built in a separate cold strLenOutOfRange.

Applied at 22 sites, including readFieldName's fixed-length ASCII arm (strlen = strtype - BC_STR_ASCII_FIX_MIN) and its one- and two-character fast paths. That arm matters most for keys: JSONBWriter emits the fixed-length form for every key up to STR_ASCII_FIX_LEN, and it was previously bounded only against bytes.length. Its array bound stays in place as well as the new frame bound, because JSONReader.ofJSONB(byte[], int, int) does not validate off + length <= bytes.length, so end can itself exceed the array.

JSONBStringLengthTest asserts the frame-bound message rather than just the exception type, since a duplicate check further downstream also throws JSONException. Measured by deleting one guard at a time and re-running the class, all 22 sites are individually pinned; the > to >= and guard-body-removed mutants are killed by the exact-fit and round-trip cases.

Known limitation

The bound is enforced at the consumers of the wire length, not where the length is decoded, so the sibling consumers outside the string readers still read past end. These are pre-existing and untouched here, but the coverage of this PR should not be read as complete:

  • the readInt32Value()-driven numeric coercion arms, which return a number parsed from bytes lying entirely outside the frame with nothing thrown
  • readUUID() and readBoolValue0(), which interpolate the over-read bytes into the exception message
  • the hash readers (readFieldNameHashCode, readValueHashCode, readTypeHashCode0, getNameHashCodeLCase), where the strlen <= 8 fast path packs raw bytes into the returned long
  • skipName(), which advances offset by an unbounded readLength()

Making it fail-closed at the producer is a larger change across those methods and I'd rather keep this PR to the string readers. Happy to follow up with it as a separate PR if that split works for you.

Please indicate you've done the following:

  • Made sure tests are passing and test coverage is added if needed.
  • Made sure commit message follow the rule of Conventional Commits specification.
  • Considered the docs impact and opened a new docs issue or PR with docs changes if needed.

@CLAassistant

CLAassistant commented Sep 14, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

wenshao
wenshao previously requested changes Oct 7, 2026

@wenshao wenshao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not explored to full depth (tool budget reached): "agent 6c": did not run the project's own suite ( mvn test ) or the new JSONBStringLengthTest under JUnit — all runtime evidence above comes from standalone differential …; "agent 6c": the JDK 8 arm of the valid-input regression probe was overwritten by a tag collision in my run script; only the JDK 17 base-vs-head diff was retained (the malfo…; "agent 6c": the SymbolTable round-trip leg of the valid-input probe aborted with a ClassCastException: HashMap cannot be cast to [C that is **identical on base and head…; "agent 6c": did not open the for (int i = 0; i < strlen; ++i) hash loops at :2236 , :2293 , :2360 to confirm they share the unchecked shape of :1538 / :1805 / :1963 ….

— qwen3.8-max via Qwen Code /review (v0.25.0)

@Support-itecz

Copy link
Copy Markdown
Contributor Author

Pushed c71a11f. Replied in each thread; the short version:

  • R1-1 the fixed-length ASCII field-name arm is now bounded against the frame end, with the array bound kept alongside it, and the 1- and 2-character fast paths are bounded too.
  • R1-2 split into checkStrLen (upper bound, for the sites that resolve a symbol ordinal) and checkStrLenCopy (also rejects negatives, for the sites that copy directly). The negative stays out of the shared helper so symbol-encoded JSONB keeps parsing.
  • R1-3 noted in the description as a known limitation rather than grown into this PR, with the producer-side readStrLen() fix offered as a follow-up.
  • R1-4/R1-5 every case asserts the frame-bound message, and all 22 guard sites are individually pinned now, measured by deleting one guard line at a time.
  • R1-6 message build moved to a cold strLenOutOfRange; checkStrLen is 48 to 16 bytes.

mvn validate is clean, core is 8010/8010 and fastjson1-compatible 1355/1355.

AI tooling helps me find and prepare these changes; this account reviews and is responsible for what it submits.

中文

已推送 c71a11f,各条评论均已在对应 thread 中回复,概要如下:

  • R1-1 定长 ASCII 字段名分支现已按 frame 末尾做边界检查,同时保留原有的数组边界;1 字节和 2 字节的快速路径也已加上边界。
  • R1-2 拆分为 checkStrLen(仅上界,用于会先解析 symbol 序号的调用点)和 checkStrLenCopy(额外拒绝负值,用于直接拷贝的调用点)。负值判断没有放进公共方法,以免影响 symbol 编码的 JSONB 解析。
  • R1-3 按您给的第二个选项,在描述中记录为已知限制,没有扩大本 PR 的范围;生产端 readStrLen() 方案可作为后续 PR 提交。
  • R1-4/R1-5 所有用例改为断言具体的越界信息,22 个调用点现在都能被单独钉住,通过逐行删除 guard 后重跑验证。
  • R1-6 异常信息构造移入冷路径 strLenOutOfRange,checkStrLen 由 48 字节降到 16 字节。

mvn validate 无告警,core 8010/8010 通过,fastjson1-compatible 1355/1355 通过。

这些改动的发现和准备过程借助了 AI 工具,提交内容由本账号审核并负责。

@wenshao wenshao left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Not explored to full depth (tool budget reached): "agent 6c": none — all checks I attempted were completed within the ceiling (~24 of ~43 calls).; "agent 3a": none — all checks completed within budget (19 of ~43 calls).; "agent 6a": readTypeHashCode / readTypeHashCode0 (1635–1735), readFieldNameHashCodeUnquote (5560+), 数字字符串分支 readInt64Value / readInt64 / readBigDecimal / readBigIntege…; "agent 1a": the new test class was never compiled or run (mvnw build deliberately skipped) — test pass/fail status is unverified; assertions were checked against the source…; "agent 1a": the public entry point that reaches readTypeHashCode0() 's unguarded readLength() (line 1793) was not traced end-to-end; the site itself was read and is name….

— glm-5.3-flash via Qwen Code /review (v0.25.1)

* Bound a string byte length against the bytes left in the frame. A negative length is a symbol
* reference only at the sites that resolve one before calling - {@link #getString()},
* {@link #readAny()}'s BC_STR_ASCII branch, {@link #readString()}, {@link #readString(Charset)}
* and {@link #readFieldName()}, which resolves it after its guards - so those pass it through.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[Critical] R2-1: [fails-closed] The checkStrLen pass-through contract is not delivered inside readFieldName() — a hostile negative wire length still escapes JSONB.parseObject as a raw RuntimeException instead of JSONException, the exact outcome the description says this class of guard eliminates. At the BC_STR_ASCII arm, the shared name-cache gate bytes[offset + strlen - 1] > 0 evaluates the array read before nameValue0 != -1, so a negative length from readLength() (0xF0 = -16) indexes bytes[-15] and throws ArrayIndexOutOfBoundsException — on every JVM, no JDK-11/endianness precondition, reachable straight through parseObject(byte[], off, len, JSONObject.class). The UTF8/UTF16LE/UTF16BE arms' JDK11 fast paths consume the length before the tail (new byte[strlen] throws NegativeArraySizeException on JDK 11+ LE/BE; the UTF8 path rewinds the cursor via offset += strlen). And the tails the contract leans on are not safe on the default path either: symbolTable is null on the ofJSONB(byte[], int, int) readers that parseObject itself builds, so every negative reaching a "resolution" tail NPEs (:2867, :2996, :966, :160, plus :1960 which the javadoc does not list). The new test's exclusion comments (:155, :179) describe that NPE path as a symbol resolution. The over-length half of the contract is genuinely closed at these arms — the residual is precisely the negative half.

Witness (probe on this PR's build; base = parent blob, arms discriminated):

parseObject [BC_OBJECT][UTF16LE][-16] frameLen=5 -> THROWN java.lang.NegativeArraySizeException: -16
readFieldName [BC_STR_ASCII][0xF0] -> THROWN java.lang.ArrayIndexOutOfBoundsException: Index -15 (via parseObject: Index -14)
parseObject(frame(BC_STR_UTF16, -16), String.class) -> THROWN NullPointerException "this.symbolTable" is null @ :2996
control: same negative frame + real SymbolTable -> parses "name22", no exception (NPE is the null default-path table)
positive control: over-length 40 -> JSONException string length out of range: 40, available: 2
base arm: identical crashes at the merge base (pre-existing; this files the contract gap, not a regression)
one-term strlen >= 0 gate probe: AIOOBE gone, but the arm then NPEs at the tail on the default path

Suggested fix — fail the negative closed while keeping the ordinal path where a table exists:

// ASCII arm's shared cache gate (:2741-2742)
if (strlen >= 0 && bytes[offset + strlen - 1] > 0 && nameValue0 != -1) {
// UTF16LE (:2835) / UTF16BE (:2848) / UTF8 (:2802) fast paths
if (strlen >= 0 && STRING_CREATOR_JDK11 != null && !JDKUtils.BIG_ENDIAN) {
// then fail the negative closed at these arms (throw strLenOutOfRange(strlen, end - offset))
// or null-guard the tail resolution — the gates alone still NPE via parseObject

The fix must not remove the ordinal semantics: a negative ASCII/UTF8 name length is a legitimate symbol reference by wire design (BC_INT32_NUM_MIN = -16; the tail resolves strlen < 0 at :2862–2868 and readFieldNameHashCode at :1493), so reject only where resolution is unavailable — and the strict-> over-length bound plus the fixed arm's array bound (:2654–2656, kept because ofJSONB does not validate off + length <= bytes.length) must stay. Please add fieldNameNegativeLengthRejected / fieldNameNegativeAsciiLength to JSONBStringLengthTest — drive readFieldName() with BC_INT32_NUM_MIN lengths for the four string types and assert the frame-bound JSONException; they red today with NASE/AIOOBE/NPE and go red again if any added gate is removed.

— glm-5.3-flash via Qwen Code /review (v0.25.1)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Confirmed all three shapes on c71a11f and fixed them in 2b470c3, keeping the ordinal path wherever a table exists:

  • ASCII arm: reordered the cache gate to nameValue0 != -1 && bytes[offset + strlen - 1] > 0. nameValue0 is only set by the fixed-length arm, so a BC_STR_ASCII length never reaches the array read now, and the check is no more expensive than before.
  • UTF8 / UTF16LE / UTF16BE fast paths: gated on strlen >= 0, so a negative falls through to the symbol tail instead of hitting new byte[strlen] or rewinding the cursor.
  • Null table: the tails now go through a small symbolName(strlen) helper that throws strLenOutOfRange when symbolTable is null, used at getString, readAny's ASCII branch, readString(Charset) and readFieldName. readValueHashCode (:1960) gets the same treatment via symbolHashCode. readFieldNameHashCode and readTypeHashCode0 are unchanged.

The over-length bound and the fixed arm's array bound stay as they were. The checkStrLen javadoc now says the pass-through sites reject the negative when there is no table.

Tests: fieldNameNegativeLengthRejected drives readFieldName() with BC_INT32_NUM_MIN for all six string types, fieldNameNegativeAsciiLength goes through parseObject(..., JSONObject.class), and symbolLengthWithoutTableRejected covers the parseObject(String.class) / readAny / readValueHashCode NPE tails. Each asserts string length out of range: -16, available: 2. fieldNameSymbolLengthResolves is the positive control: the same negative ASCII name with a real SymbolTable still resolves to id.

on c71a11f source         -> 3 red (AIOOBE x2, NPE)
revert gate reorder       -> fieldNameNegativeAsciiLength + fieldNameNegativeLengthRejected red (AIOOBE)
revert UTF8 gate          -> fieldNameNegativeLengthRejected red (available: 18, cursor rewound)
revert UTF16LE gate       -> fieldNameNegativeLengthRejected red (NegativeArraySizeException)

The UTF16BE gate only runs on a big-endian JVM, so it can't be made to fail here. mvn validate is clean and core is 8014/8014 on JDK 21.

中文

在 c71a11f 上复现了这三种情况,已在 2b470c3 中修复,存在 symbol table 时序号解析路径保持不变:

  • ASCII 分支:缓存判断调整为 nameValue0 != -1 && bytes[offset + strlen - 1] > 0。nameValue0 只在定长分支中赋值,所以 BC_STR_ASCII 的负长度不会再走到数组访问,判断开销也没有增加。
  • UTF8 / UTF16LE / UTF16BE 快速路径:加上 strlen >= 0 条件,负值直接落到 symbol 解析尾部,不再触发 new byte[strlen] 或回退游标。
  • symbolTable 为 null:尾部改为调用 symbolName(strlen),symbolTable 为 null 时抛出 strLenOutOfRange,用于 getString、readAny 的 ASCII 分支、readString(Charset) 和 readFieldName。readValueHashCode(:1960)通过 symbolHashCode 做同样处理。readFieldNameHashCode 和 readTypeHashCode0 未改动。

超长上界检查和定长分支的数组边界保持不变。checkStrLen 的 javadoc 已注明:没有 symbol table 时,这些调用点会拒绝负值。

测试:fieldNameNegativeLengthRejected 用 BC_INT32_NUM_MIN 对六种字符串类型直接调用 readFieldName();fieldNameNegativeAsciiLength 走 parseObject(..., JSONObject.class);symbolLengthWithoutTableRejected 覆盖 parseObject(String.class) / readAny / readValueHashCode 的 NPE 路径,均断言 string length out of range: -16, available: 2。fieldNameSymbolLengthResolves 为正向对照:同样的负长度 ASCII 名称在有 SymbolTable 时仍解析为 id。

逐项删除验证结果见上方代码块。UTF16BE 的条件只在大端 JVM 上执行,本机无法让其失败。mvn validate 无告警,core 在 JDK 21 上 8014/8014 通过。

@wenshao
wenshao dismissed stale reviews from themself October 17, 2026 11:59

R2-1 addressed in head 2b470c3 (cache gate reordered to nameValue0 != -1 first, fast paths gated on strlen >= 0, null-table tails fail closed); CI green on head (run 38712287711). Dismissing stale round-2 review.

@wenshao
wenshao merged commit 56c7ac7 into alibaba:main Oct 17, 2026
30 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants