Repository navigation
fix: bound jsonb string length to remaining input - #7867
Conversation
wenshao
left a comment
There was a problem hiding this comment.
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)
|
Pushed c71a11f. Replied in each thread; the short version:
AI tooling helps me find and prepare these changes; this account reviews and is responsible for what it submits. 中文已推送 c71a11f,各条评论均已在对应 thread 中回复,概要如下:
这些改动的发现和准备过程借助了 AI 工具,提交内容由本账号审核并负责。 |
wenshao
left a comment
There was a problem hiding this comment.
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. |
There was a problem hiding this comment.
[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 parseObjectThe 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)
There was a problem hiding this comment.
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.nameValue0is only set by the fixed-length arm, so aBC_STR_ASCIIlength 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 hittingnew byte[strlen]or rewinding the cursor. - Null table: the tails now go through a small
symbolName(strlen)helper that throwsstrLenOutOfRangewhensymbolTableis null, used atgetString,readAny's ASCII branch,readString(Charset)andreadFieldName.readValueHashCode(:1960) gets the same treatment viasymbolHashCode.readFieldNameHashCodeandreadTypeHashCode0are 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 通过。
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.
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 fromreadLength()(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_BINARYandBC_BIGINTalready reject a length greater thanend - offset; the string readers did not.With the slice API (
JSONB.parseObject(byte[], off, len, type)/JSONReader.ofJSONB(byte[], off, len))endis the frame boundary rather thanbytes.length, so a declared string length larger than the frame but still inside the backing buffer reads pastendand 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'sBC_STR_ASCIIbranch,readString,readString(Charset), andreadFieldName, 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 raiseNegativeArraySizeException,StringIndexOutOfBoundsExceptionorNullPointerExceptioninstead ofJSONException, andreadStringUTF8returned""and then appliedoffset += 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 coldstrLenOutOfRange.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:JSONBWriteremits the fixed-length form for every key up toSTR_ASCII_FIX_LEN, and it was previously bounded only againstbytes.length. Its array bound stays in place as well as the new frame bound, becauseJSONReader.ofJSONB(byte[], int, int)does not validateoff + length <= bytes.length, soendcan itself exceed the array.JSONBStringLengthTestasserts the frame-bound message rather than just the exception type, since a duplicate check further downstream also throwsJSONException. 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:readInt32Value()-driven numeric coercion arms, which return a number parsed from bytes lying entirely outside the frame with nothing thrownreadUUID()andreadBoolValue0(), which interpolate the over-read bytes into the exception messagereadFieldNameHashCode,readValueHashCode,readTypeHashCode0,getNameHashCodeLCase), where thestrlen <= 8fast path packs raw bytes into the returnedlongskipName(), which advancesoffsetby an unboundedreadLength()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: