This is an automated email from the ASF dual-hosted git repository.
Xuanwo pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/opendal.git
The following commit(s) were added to refs/heads/main by this push:
new 04e3a75db7 fix(bindings/nodejs): reject BigInt options that do not fit
into u64 (#8835)
04e3a75db7 is described below
commit 04e3a75db7ce41d4141f1c97257fd492f6522998
Author: Xuanwo <[email protected]>
AuthorDate: Mon Nov 23 15:12:35 2026 +0800
fix(bindings/nodejs): reject BigInt options that do not fit into u64 (#8835)
* fix(bindings/nodejs): reject BigInt options that do not fit into u64
`BigInt::get_u64` returns only the lowest 64-bit word plus a separate sign
bit and losslessness flag. Taking just the value turned `offset: -3n` into a
huge positive offset and `offset: 1n << 64n` into `0n`, so reads and writes
silently addressed the wrong bytes, sizes, chunks or gaps.
Validate `offset`, `size`, `gap` and `chunk` instead, and propagate the
error
from the option conversion to the caller.
* test(bindings/nodejs): correct the BigInt comment in the option tests
`BigInt::get_u64` returns the low word with a separate sign bit, so `-1n`
was
accepted as `1`, not as `u64::MAX`.
---
bindings/nodejs/src/lib.rs | 20 ++---
bindings/nodejs/src/options.rs | 111 ++++++++++++++++++++++-----
bindings/nodejs/tests/options.test.mjs | 133 +++++++++++++++++++++++++++++++++
3 files changed, 234 insertions(+), 30 deletions(-)
diff --git a/bindings/nodejs/src/lib.rs b/bindings/nodejs/src/lib.rs
index 030c818e58..351351d608 100644
--- a/bindings/nodejs/src/lib.rs
+++ b/bindings/nodejs/src/lib.rs
@@ -246,7 +246,7 @@ impl Operator {
path: String,
options: Option<options::ReadOptions>,
) -> Result<Buffer> {
- let options = options.map_or_else(ReadOptions::default,
ReadOptions::from);
+ let options = ReadOptions::try_from(options.unwrap_or_default())?;
let res = self
.async_op
.read_options(&path, options)
@@ -265,7 +265,7 @@ impl Operator {
path: String,
options: Option<options::ReaderOptions>,
) -> Result<Reader> {
- let options = options.map_or_else(ReaderOptions::default,
ReaderOptions::from);
+ let options = ReaderOptions::try_from(options.unwrap_or_default())?;
let r = self
.async_op
.reader_options(&path, options)
@@ -288,7 +288,7 @@ impl Operator {
/// ```
#[napi]
pub fn read_sync(&self, path: String, options:
Option<options::ReadOptions>) -> Result<Buffer> {
- let options = options.map_or_else(ReadOptions::default,
ReadOptions::from);
+ let options = ReadOptions::try_from(options.unwrap_or_default())?;
let res = self
.blocking_op
.read_options(&path, options)
@@ -306,7 +306,7 @@ impl Operator {
path: String,
options: Option<options::ReaderOptions>,
) -> Result<BlockingReader> {
- let options = options.map_or_else(ReaderOptions::default,
ReaderOptions::from);
+ let options = ReaderOptions::try_from(options.unwrap_or_default())?;
let r = self
.blocking_op
.reader_options(&path, options)
@@ -338,7 +338,7 @@ impl Operator {
Either::A(buf) => buf.as_ref().to_owned(),
Either::B(s) => s.into_bytes(),
};
- let options = options.map_or_else(WriteOptions::default,
WriteOptions::from);
+ let options = WriteOptions::try_from(options.unwrap_or_default())?;
let metadata = self
.async_op
.write_options(&path, c, options)
@@ -357,10 +357,10 @@ impl Operator {
path: String,
options: Option<options::WriteOptions>,
) -> Result<Writer> {
- let options = options.unwrap_or_default();
+ let options = WriteOptions::try_from(options.unwrap_or_default())?;
let writer = self
.async_op
- .writer_options(&path, options.into())
+ .writer_options(&path, options)
.await
.map_err(format_napi_error)?;
Ok(Writer {
@@ -377,10 +377,10 @@ impl Operator {
path: String,
options: Option<options::WriteOptions>,
) -> Result<BlockingWriter> {
- let options = options.unwrap_or_default();
+ let options = WriteOptions::try_from(options.unwrap_or_default())?;
let writer = self
.blocking_op
- .writer_options(&path, options.into())
+ .writer_options(&path, options)
.map_err(format_napi_error)?;
Ok(BlockingWriter(writer))
}
@@ -407,7 +407,7 @@ impl Operator {
Either::A(buf) => buf.as_ref().to_owned(),
Either::B(s) => s.into_bytes(),
};
- let options = options.map_or_else(WriteOptions::default,
WriteOptions::from);
+ let options = WriteOptions::try_from(options.unwrap_or_default())?;
let metadata = self
.blocking_op
.write_options(&path, c, options)
diff --git a/bindings/nodejs/src/options.rs b/bindings/nodejs/src/options.rs
index ad3da92cc6..6e2fedbe0a 100644
--- a/bindings/nodejs/src/options.rs
+++ b/bindings/nodejs/src/options.rs
@@ -15,11 +15,49 @@
// specific language governing permissions and limitations
// under the License.
+use napi::Status;
use napi::bindgen_prelude::BigInt;
use opendal::BytesRange;
use opendal::raw::Timestamp;
use std::collections::HashMap;
+/// Convert a JavaScript `BigInt` into a `u64` offset or size.
+///
+/// `BigInt::get_u64` only reports the lowest 64-bit word and returns the sign
+/// separately, so `-1n` and `1n << 64n` would both be accepted as valid values
+/// unless the caller rejects them here.
+fn bigint_to_u64(value: &BigInt, field: &str) -> napi::Result<u64> {
+ let (sign_bit, word, lossless) = value.get_u64();
+
+ if sign_bit {
+ return Err(napi::Error::new(
+ Status::InvalidArg,
+ format!("{field} must not be negative"),
+ ));
+ }
+
+ if !lossless {
+ return Err(napi::Error::new(
+ Status::InvalidArg,
+ format!("{field} must not be greater than {}", u64::MAX),
+ ));
+ }
+
+ Ok(word)
+}
+
+/// Convert a JavaScript `BigInt` into a `usize` count such as a gap or chunk
size.
+fn bigint_to_usize(value: &BigInt, field: &str) -> napi::Result<usize> {
+ let value = bigint_to_u64(value, field)?;
+
+ usize::try_from(value).map_err(|_| {
+ napi::Error::new(
+ Status::InvalidArg,
+ format!("{field} must not be greater than {}", usize::MAX),
+ )
+ })
+}
+
#[napi(object)]
#[derive(Debug)]
pub struct StatOptions {
@@ -205,16 +243,28 @@ pub struct ReadOptions {
}
impl ReadOptions {
- pub fn make_range(&self) -> BytesRange {
- let offset = self.offset.clone().map(|offset| offset.get_u64().1);
- let size = self.size.clone().map(|size| size.get_u64().1);
- BytesRange::new(offset.unwrap_or_default(), size)
+ fn make_range(&self) -> napi::Result<BytesRange> {
+ let offset = self
+ .offset
+ .as_ref()
+ .map(|offset| bigint_to_u64(offset, "offset"))
+ .transpose()?
+ .unwrap_or_default();
+ let size = self
+ .size
+ .as_ref()
+ .map(|size| bigint_to_u64(size, "size"))
+ .transpose()?;
+
+ Ok(BytesRange::new(offset, size))
}
}
-impl From<ReadOptions> for opendal::options::ReadOptions {
- fn from(value: ReadOptions) -> Self {
- let range = value.make_range();
+impl TryFrom<ReadOptions> for opendal::options::ReadOptions {
+ type Error = napi::Error;
+
+ fn try_from(value: ReadOptions) -> napi::Result<Self> {
+ let range = value.make_range()?;
let if_modified_since = value
.if_modified_since
.and_then(|v| v.parse::<Timestamp>().ok());
@@ -222,11 +272,17 @@ impl From<ReadOptions> for opendal::options::ReadOptions {
.if_unmodified_since
.and_then(|v| v.parse::<Timestamp>().ok());
- Self {
+ let gap = value
+ .gap
+ .as_ref()
+ .map(|gap| bigint_to_usize(gap, "gap"))
+ .transpose()?;
+
+ Ok(Self {
version: value.version,
concurrent: value.concurrent.unwrap_or_default() as usize,
chunk: value.chunk.map(|chunk| chunk as usize),
- gap: value.gap.map(|gap| gap.get_u64().1 as usize),
+ gap,
range,
if_match: value.if_match,
if_none_match: value.if_none_match,
@@ -237,7 +293,7 @@ impl From<ReadOptions> for opendal::options::ReadOptions {
override_cache_control: value.cache_control,
override_content_disposition: value.content_disposition,
..Default::default()
- }
+ })
}
}
@@ -329,20 +385,27 @@ pub struct ReaderOptions {
pub if_unmodified_since: Option<String>,
}
-impl From<ReaderOptions> for opendal::options::ReaderOptions {
- fn from(value: ReaderOptions) -> Self {
+impl TryFrom<ReaderOptions> for opendal::options::ReaderOptions {
+ type Error = napi::Error;
+
+ fn try_from(value: ReaderOptions) -> napi::Result<Self> {
let if_modified_since = value
.if_modified_since
.and_then(|v| v.parse::<Timestamp>().ok());
let if_unmodified_since = value
.if_unmodified_since
.and_then(|v| v.parse::<Timestamp>().ok());
+ let gap = value
+ .gap
+ .as_ref()
+ .map(|gap| bigint_to_usize(gap, "gap"))
+ .transpose()?;
- Self {
+ Ok(Self {
version: value.version,
concurrent: value.concurrent.unwrap_or_default() as usize,
chunk: value.chunk.map(|chunk| chunk as usize),
- gap: value.gap.map(|gap| gap.get_u64().1 as usize),
+ gap,
prefetch: value.prefetch.unwrap_or_default() as usize,
if_match: value.if_match,
if_none_match: value.if_none_match,
@@ -350,7 +413,7 @@ impl From<ReaderOptions> for
opendal::options::ReaderOptions {
if_unmodified_since,
content_length_hint: None,
..Default::default()
- }
+ })
}
}
@@ -493,11 +556,19 @@ pub struct WriteOptions {
pub concurrent: Option<u32>,
}
-impl From<WriteOptions> for opendal::options::WriteOptions {
- fn from(value: WriteOptions) -> Self {
- Self {
+impl TryFrom<WriteOptions> for opendal::options::WriteOptions {
+ type Error = napi::Error;
+
+ fn try_from(value: WriteOptions) -> napi::Result<Self> {
+ let chunk = value
+ .chunk
+ .as_ref()
+ .map(|chunk| bigint_to_usize(chunk, "chunk"))
+ .transpose()?;
+
+ Ok(Self {
append: value.append.unwrap_or_default(),
- chunk: value.chunk.map(|v| v.get_u64().1 as usize),
+ chunk,
content_type: value.content_type,
content_disposition: value.content_disposition,
cache_control: value.cache_control,
@@ -508,7 +579,7 @@ impl From<WriteOptions> for opendal::options::WriteOptions {
if_not_exists: value.if_not_exists.unwrap_or_default(),
concurrent: value.concurrent.unwrap_or_default() as usize,
..Default::default()
- }
+ })
}
}
diff --git a/bindings/nodejs/tests/options.test.mjs
b/bindings/nodejs/tests/options.test.mjs
new file mode 100644
index 0000000000..ddc8dce6e9
--- /dev/null
+++ b/bindings/nodejs/tests/options.test.mjs
@@ -0,0 +1,133 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+import { beforeEach, describe, expect, it } from 'vitest'
+
+import { Operator } from '../index.mjs'
+
+const path = 'options-bigint'
+const content = Buffer.from('0123456789abcdef')
+
+// BigInt values that cannot be represented as an unsigned 64-bit integer.
+// Accepting them silently dropped the sign and the high bits, so -1n became 1
+// and 1n << 64n became 0, and reads and writes addressed the wrong bytes
+// instead of failing.
+const invalidValues = [
+ ['negative', -1n],
+ ['wider than u64', 1n << 64n],
+]
+
+describe('bigint options', () => {
+ const op = new Operator('memory')
+
+ beforeEach(async () => {
+ await op.write(path, content)
+ })
+
+ describe('read', () => {
+ for (const field of ['offset', 'size', 'gap']) {
+ for (const [label, value] of invalidValues) {
+ it(`read rejects ${field} that is ${label}`, async () => {
+ await expect(op.read(path, { [field]: value
})).rejects.toThrowError(`${field} must`)
+ })
+
+ it(`readSync rejects ${field} that is ${label}`, () => {
+ expect(() => op.readSync(path, { [field]: value
})).toThrowError(`${field} must`)
+ })
+ }
+ }
+
+ for (const [label, value] of invalidValues) {
+ it(`reader rejects gap that is ${label}`, async () => {
+ await expect(op.reader(path, { gap: value
})).rejects.toThrowError('gap must')
+ })
+
+ it(`readerSync rejects gap that is ${label}`, () => {
+ expect(() => op.readerSync(path, { gap: value })).toThrowError('gap
must')
+ })
+ }
+
+ it('accepts a zero offset', async () => {
+ expect((await op.read(path, { offset: 0n })).equals(content)).toBe(true)
+ expect(op.readSync(path, { offset: 0n }).equals(content)).toBe(true)
+ })
+
+ it('accepts an offset and size', async () => {
+ expect((await op.read(path, { offset: 3n, size: 4n
})).toString()).toBe('3456')
+ expect(op.readSync(path, { offset: 3n, size: 4n
}).toString()).toBe('3456')
+ })
+
+ it('accepts the largest offset', async () => {
+ // An offset past the end of the object reads no bytes, it must not wrap.
+ const answer = await op.read(path, { offset: 0xffffffffffffffffn })
+ expect(answer.length).toBe(0)
+ expect(op.readSync(path, { offset: 0xffffffffffffffffn }).length).toBe(0)
+ })
+
+ it('accepts a zero gap', async () => {
+ const reader = await op.reader(path, { gap: 0n })
+ expect((await
reader.readChunk(1024)).toString()).toBe(content.toString())
+ })
+
+ it('accepts a positive gap', () => {
+ const reader = op.readerSync(path, { gap: 1024n })
+ const buf = Buffer.alloc(content.length)
+ expect(reader.read(buf)).toBe(BigInt(content.length))
+ expect(buf.equals(content)).toBe(true)
+ })
+ })
+
+ describe('write', () => {
+ for (const [label, value] of invalidValues) {
+ it(`write rejects chunk that is ${label}`, async () => {
+ await expect(op.write(path, 'hello', { chunk: value
})).rejects.toThrowError('chunk must')
+ })
+
+ it(`writeSync rejects chunk that is ${label}`, () => {
+ expect(() => op.writeSync(path, 'hello', { chunk: value
})).toThrowError('chunk must')
+ })
+
+ it(`writer rejects chunk that is ${label}`, async () => {
+ await expect(op.writer(path, { chunk: value
})).rejects.toThrowError('chunk must')
+ })
+
+ it(`writerSync rejects chunk that is ${label}`, () => {
+ expect(() => op.writerSync(path, { chunk: value
})).toThrowError('chunk must')
+ })
+ }
+
+ it('accepts a chunk size', async () => {
+ await op.write(path, 'chunked', { chunk: 4n })
+ expect((await op.read(path)).toString()).toBe('chunked')
+ })
+
+ it('accepts a chunk size when streaming', async () => {
+ const writer = await op.writer(path, { chunk: 4n })
+ await writer.write('chunked')
+ await writer.close()
+ expect((await op.read(path)).toString()).toBe('chunked')
+ })
+
+ it('accepts a chunk size when streaming synchronously', () => {
+ const writer = op.writerSync(path, { chunk: 4n })
+ writer.write('chunked')
+ writer.close()
+ expect(op.readSync(path).toString()).toBe('chunked')
+ })
+ })
+})