cloudflare / cloudflare/workerd
🐛 Bug Report Runtime APIs node:buffer: Buffer.alloc and Buffer.allocUnsafe throw ERR_OUT_OF_RANGE for size === kMaxLength (off-by-one)
- Dominant language
- C++
- Stars
- 8.7k
- Forks
- 739
- Avg merge
- 2d 20h
- Merged PRs (30d)
- 174
Description
Description
Buffer.alloc(size) and Buffer.allocUnsafe(size) incorrectly throw ERR_OUT_OF_RANGE when size === buffer.kMaxLength (2147483647), because the check uses >= instead of >. The internal createBuffer function correctly uses >, so there is an inconsistency within the same file.
Reproduction
js
import { kMaxLength } from 'node:buffer';
console.log(kMaxLength); // 2147483647
// These should succeed (kMaxLength is the maximum *valid* size):
Buffer.alloc(kMaxLength); // throws ERR_OUT_OF_RANGE in workerd
Buffer.allocUnsafe(kMaxLength); // throws ERR_OUT_OF_RANGE in workerd
// This correctly throws (size exceeds maximum):
Buffer.alloc(kMaxLength + 1); // throws — correct
Expected behavior (Node.js v22)
Buffer.alloc(kMaxLength) and Buffer.allocUnsafe(kMaxLength) succeed (memory permitting). Only size > kMaxLength should throw ERR_OUT_OF_RANGE.
Actual behavior (workerd)
Both throw:
RangeError [ERR_OUT_OF_RANGE]: The value of "size" is out of range.
It must be >= 0 and <= 2147483647. Received 2147483647
Note that the error message itself says "0 to 2147483647" is valid, confirming that 2147483647 should not throw.
Root cause
In src/node/internal/internal_buffer.ts, the alloc() function uses >=:
ts
// BUG — uses >= so kMaxLength throws
if (size >= kMaxLength) {
throw new ERR_OUT_OF_RANGE('size', `0 to ${kMaxLength}`, size);
}
But createBuffer() in the same file correctly uses >:
ts
// CORRECT
if (length > kMaxLength) {
throw new ERR_OUT_OF_RANGE(...);
}
Fix: Change size >= kMaxLength to size > kMaxLength in alloc().
Impact
Any code calling Buffer.alloc(buffer.kMaxLength) incorrectly receives ERR_OUT_OF_RANGE when the size is valid.
Contributor guide
Research direction
Start in src/node/internal/internal_buffer.ts and compare the alloc() and createBuffer() boundary checks described in the report. Verify that the maximum valid size is accepted and one value above it still raises ERR_OUT_OF_RANGE, with memory constraints considered when running the reproduction.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- node.js, typescript
- Domain
- api
- Issue type
- Bug
- Difficulty
- 1/5
- Estimated time
- Under an hour
- Activity status
- Quiet
- Clarity
- Clearly specified
- Newbie friendliness
- 88/100