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 802e986cf8 fix(bindings/nodejs): avoid accessing JS Buffer memory on 
worker threads (#8937)
802e986cf8 is described below

commit 802e986cf82dc4366e339df9e94b0d9b6288367f
Author: Xuanwo <[email protected]>
AuthorDate: Tue Nov 24 04:12:10 2026 +0800

    fix(bindings/nodejs): avoid accessing JS Buffer memory on worker threads 
(#8937)
---
 bindings/nodejs/src/lib.rs                   | 159 +++++++++++++++++++++++++--
 bindings/nodejs/tests/suites/async.suite.mjs | 152 +++++++++++++++++++++++++
 2 files changed, 302 insertions(+), 9 deletions(-)

diff --git a/bindings/nodejs/src/lib.rs b/bindings/nodejs/src/lib.rs
index 2ac1189847..a5613c8e42 100644
--- a/bindings/nodejs/src/lib.rs
+++ b/bindings/nodejs/src/lib.rs
@@ -22,7 +22,6 @@ use std::collections::HashMap;
 use std::fmt::Display;
 use std::io::Read;
 
-use futures::AsyncReadExt;
 use futures::TryStreamExt;
 use napi::bindgen_prelude::*;
 use opendal::options::{
@@ -339,11 +338,11 @@ impl Operator {
     pub async fn write(
         &self,
         path: String,
-        content: Either<Buffer, String>,
+        #[napi(ts_arg_type = "Buffer | string")] content: Either<OwnedBuffer, 
String>,
         options: Option<options::WriteOptions>,
     ) -> Result<Metadata> {
         let c = match content {
-            Either::A(buf) => buf.as_ref().to_owned(),
+            Either::A(buf) => buf.0,
             Either::B(s) => s.into_bytes(),
         };
         let options = WriteOptions::try_from(options.unwrap_or_default())?;
@@ -1058,10 +1057,19 @@ impl Reader {
     /// Read bytes from this reader into the given buffer.
     ///
     /// Wait for the promise to settle before accessing the buffer again.
-    #[napi]
-    pub async fn read(&self, mut buf: Buffer) -> Result<usize> {
-        let mut inner = self.inner.lock().await;
-        inner.read(buf.as_mut()).await.map_err(format_napi_error)
+    #[napi(ts_return_type = "Promise<bigint>")]
+    pub async fn read(
+        &self,
+        #[napi(ts_arg_type = "Buffer")] buf: ReadTarget,
+    ) -> Result<ReadIntoBuffer> {
+        let chunk = self
+            .inner
+            .lock()
+            .await
+            .read_buffer(buf.requested_len)
+            .await
+            .map_err(format_napi_error)?;
+        Ok(ReadIntoBuffer { target: buf, chunk })
     }
 
     /// Read up to `maxBytes` bytes from the same cursor as `read`.
@@ -1084,6 +1092,136 @@ impl Reader {
     }
 }
 
+/// Copies a JS `Buffer` into an owned `Vec<u8>` on the JS thread so async
+/// writes never read from an `ArrayBuffer` that JS may detach or mutate.
+pub struct OwnedBuffer(Vec<u8>);
+
+impl TypeName for OwnedBuffer {
+    fn type_name() -> &'static str {
+        "Buffer"
+    }
+
+    fn value_type() -> ValueType {
+        ValueType::Object
+    }
+}
+
+impl ValidateNapiValue for OwnedBuffer {
+    unsafe fn validate(
+        env: napi::sys::napi_env,
+        napi_val: napi::sys::napi_value,
+    ) -> Result<napi::sys::napi_value> {
+        unsafe { BufferSlice::validate(env, napi_val) }
+    }
+}
+
+impl FromNapiValue for OwnedBuffer {
+    unsafe fn from_napi_value(
+        env: napi::sys::napi_env,
+        napi_val: napi::sys::napi_value,
+    ) -> Result<Self> {
+        let slice = unsafe { BufferSlice::from_napi_value(env, napi_val)? };
+        Ok(Self(slice.as_ref().to_vec()))
+    }
+}
+
+/// Rooted JS `Buffer` destination whose requested length is captured on the JS
+/// thread so background async reads never touch V8's backing store.
+pub struct ReadTarget {
+    buf: Buffer,
+    requested_len: usize,
+}
+
+impl TypeName for ReadTarget {
+    fn type_name() -> &'static str {
+        "Buffer"
+    }
+
+    fn value_type() -> ValueType {
+        ValueType::Object
+    }
+}
+
+impl ValidateNapiValue for ReadTarget {
+    unsafe fn validate(
+        env: napi::sys::napi_env,
+        napi_val: napi::sys::napi_value,
+    ) -> Result<napi::sys::napi_value> {
+        unsafe { Buffer::validate(env, napi_val) }
+    }
+}
+
+impl FromNapiValue for ReadTarget {
+    unsafe fn from_napi_value(
+        env: napi::sys::napi_env,
+        napi_val: napi::sys::napi_value,
+    ) -> Result<Self> {
+        unsafe { Buffer::validate(env, napi_val)? };
+        let mut data = std::ptr::null_mut();
+        let mut requested_len = 0usize;
+        napi::check_status!(
+            unsafe {
+                napi::sys::napi_get_buffer_info(env, napi_val, &mut data, &mut 
requested_len)
+            },
+            "Failed to get Buffer pointer and length"
+        )?;
+        let buf = unsafe { Buffer::from_napi_value(env, napi_val)? };
+        Ok(Self { buf, requested_len })
+    }
+}
+
+/// Copies an async read result into the caller's JS `Buffer` on the JS thread
+/// at Promise resolution after re-checking the live backing store.
+pub struct ReadIntoBuffer {
+    target: ReadTarget,
+    chunk: opendal::Buffer,
+}
+
+impl ToNapiValue for ReadIntoBuffer {
+    unsafe fn to_napi_value(env: napi::sys::napi_env, val: Self) -> 
Result<napi::sys::napi_value> {
+        let js_buf = unsafe { Buffer::to_napi_value(env, val.target.buf)? };
+        let mut data = std::ptr::null_mut();
+        let mut current_len = 0usize;
+        napi::check_status!(
+            unsafe { napi::sys::napi_get_buffer_info(env, js_buf, &mut data, 
&mut current_len) },
+            "Failed to get Buffer pointer and length"
+        )?;
+
+        let copied = val.chunk.len();
+        if current_len < val.target.requested_len || current_len < copied {
+            return Err(Error::new(
+                Status::GenericFailure,
+                "Destination buffer was detached or shrunk while read was in 
progress",
+            ));
+        }
+
+        if copied > 0 {
+            if data.is_null() {
+                return Err(Error::new(
+                    Status::GenericFailure,
+                    "Destination buffer backing store is unavailable",
+                ));
+            }
+            let mut offset = 0;
+            for part in val.chunk {
+                // SAFETY: `napi_get_buffer_info` just returned a live pointer
+                // of at least `copied` bytes on the JS thread, and `part` is 
an
+                // owned OpenDAL chunk disjoint from V8's ArrayBuffer memory.
+                unsafe {
+                    std::ptr::copy_nonoverlapping(
+                        part.as_ptr(),
+                        data.cast::<u8>().add(offset),
+                        part.len(),
+                    );
+                }
+                offset += part.len();
+            }
+        }
+
+        unsafe { usize::to_napi_value(env, copied) }
+    }
+}
+
 // Choose the buffer's backing allocation on the JS thread at Promise 
resolution.
 pub struct ReadChunk(opendal::Buffer);
 
@@ -1202,9 +1340,12 @@ impl Writer {
     /// await writer.close();
     /// ```
     #[napi]
-    pub async fn write(&self, content: Either<Buffer, String>) -> Result<()> {
+    pub async fn write(
+        &self,
+        #[napi(ts_arg_type = "Buffer | string")] content: Either<OwnedBuffer, 
String>,
+    ) -> Result<()> {
         let c = match content {
-            Either::A(buf) => buf.as_ref().to_owned(),
+            Either::A(buf) => buf.0,
             Either::B(s) => s.into_bytes(),
         };
         let mut inner = self.inner.lock().await;
diff --git a/bindings/nodejs/tests/suites/async.suite.mjs 
b/bindings/nodejs/tests/suites/async.suite.mjs
index 1cbb2c4ebc..90c898cf25 100644
--- a/bindings/nodejs/tests/suites/async.suite.mjs
+++ b/bindings/nodejs/tests/suites/async.suite.mjs
@@ -28,6 +28,14 @@ import { onTestFinished, test } from 'vitest'
 import { Operator } from '../../index.mjs'
 import { generateBytes, generateFixedBytes } from '../utils.mjs'
 
+function detachArrayBuffer(ab) {
+  if (typeof ab.transfer === 'function') {
+    ab.transfer(0)
+  } else {
+    structuredClone(ab, { transfer: [ab] })
+  }
+}
+
 export function run(op) {
   describe('async tests', () => {
     test('async stat not exist files', async () => {
@@ -130,6 +138,150 @@ export function run(op) {
       expect(await reader.readChunk(1)).toBeNull()
     })
 
+    test('reader.read rejects when destination buffer is detached while in 
flight', async () => {
+      const payload = Buffer.alloc(1024 * 1024, 0x41)
+      const server = createServer()
+      server.listen(0, '127.0.0.1')
+      onTestFinished(() => {
+        server.closeAllConnections()
+        server.close()
+      })
+      await once(server, 'listening')
+
+      const httpOp = new Operator('http', { endpoint: 
`http://127.0.0.1:${server.address().port}` })
+      const reader = await httpOp.reader('object')
+
+      const requested = once(server, 'request')
+      const ab = new ArrayBuffer(payload.length)
+      const buf = Buffer.from(ab)
+      const pending = reader.read(buf)
+
+      const [, response] = await requested
+      detachArrayBuffer(ab)
+      expect(buf.byteLength).toBe(0)
+
+      response.writeHead(200, { 'Content-Length': payload.length })
+      response.end(payload)
+
+      await expect(pending).rejects.toThrow('Destination buffer was detached 
or shrunk')
+
+      // Detaching a non-empty buffer at EOF also rejects instead of silently 
returning 0.
+      const memory = new Operator('memory')
+      await memory.write('empty', Buffer.alloc(0))
+      const eofReader = await memory.reader('empty')
+      const eofAb = new ArrayBuffer(16)
+      const eofBuf = Buffer.from(eofAb)
+      const eofPending = eofReader.read(eofBuf)
+      detachArrayBuffer(eofAb)
+      await expect(eofPending).rejects.toThrow('Destination buffer was 
detached or shrunk')
+    })
+
+    test('reader.read handles resizable buffers, subarrays, and zero-length 
buffers', async () => {
+      const memory = new Operator('memory')
+      await memory.write('object', Buffer.from('0123456789abcdef'))
+      const reader = await memory.reader('object')
+
+      // Zero-length and already-detached buffers return 0n without advancing 
the cursor.
+      expect(await reader.read(Buffer.alloc(0))).toBe(0n)
+      const preDetachedAb = new ArrayBuffer(8)
+      const preDetachedBuf = Buffer.from(preDetachedAb)
+      detachArrayBuffer(preDetachedAb)
+      expect(await reader.read(preDetachedBuf)).toBe(0n)
+
+      // Subarray with non-zero byteOffset only modifies its own slice.
+      const backing = Buffer.alloc(16, 0xaa)
+      const slice = backing.subarray(4, 10)
+      expect(await reader.read(slice)).toBe(6n)
+      expect(slice.toString()).toBe('012345')
+      expect(backing.subarray(0, 4)).toEqual(Buffer.alloc(4, 0xaa))
+      expect(backing.subarray(10, 16)).toEqual(Buffer.alloc(6, 0xaa))
+
+      // Growing a resizable ArrayBuffer while a read is in flight succeeds.
+      const growAb = new ArrayBuffer(4, { maxByteLength: 32 })
+      const growBuf = Buffer.from(growAb)
+      const growPending = reader.read(growBuf)
+      growAb.resize(16)
+      expect(await growPending).toBe(4n)
+      expect(growBuf.subarray(0, 4).toString()).toBe('6789')
+
+      // Shrinking a resizable ArrayBuffer while a read is in flight rejects 
cleanly.
+      const server = createServer()
+      server.listen(0, '127.0.0.1')
+      onTestFinished(() => {
+        server.closeAllConnections()
+        server.close()
+      })
+      await once(server, 'listening')
+
+      const httpOp = new Operator('http', { endpoint: 
`http://127.0.0.1:${server.address().port}` })
+      const httpReader = await httpOp.reader('shrink')
+      const requested = once(server, 'request')
+      const shrinkAb = new ArrayBuffer(16, { maxByteLength: 32 })
+      const shrinkBuf = Buffer.from(shrinkAb)
+      const shrinkPending = httpReader.read(shrinkBuf)
+      const [, response] = await requested
+      shrinkAb.resize(4)
+      response.writeHead(200, { 'Content-Length': 16 })
+      response.end(Buffer.from('0123456789abcdef'))
+      await expect(shrinkPending).rejects.toThrow('Destination buffer was 
detached or shrunk')
+
+      // Remaining bytes and EOF on the memory reader.
+      const tail = Buffer.alloc(10)
+      expect(await reader.read(tail)).toBe(6n)
+      expect(tail.subarray(0, 6).toString()).toBe('abcdef')
+      expect(await reader.read(tail)).toBe(0n)
+
+      // An async read error cleanly releases the rooted destination buffer.
+      const missingReader = await memory.reader('missing')
+      await 
expect(missingReader.read(Buffer.alloc(8))).rejects.toThrow('NotFound')
+    })
+
+    test('op.write snapshots buffer bytes before returning', async () => {
+      const memory = new Operator('memory')
+
+      // Detaching the backing ArrayBuffer immediately after op.write must not 
UAF or corrupt data.
+      const payload = Buffer.alloc(1024 * 1024, 0x42)
+      const ab = new ArrayBuffer(payload.length)
+      const buf = Buffer.from(ab)
+      payload.copy(buf)
+      const writePending = memory.write('detached', buf)
+      detachArrayBuffer(ab)
+      await writePending
+      expect(Buffer.compare(await memory.read('detached'), payload)).toBe(0)
+
+      // Mutating a subarray immediately after op.write must not affect the 
written snapshot.
+      const full = Buffer.from('xxxxhello worldyyyy')
+      const sub = full.subarray(4, 15)
+      const mutatePending = memory.write('mutated', sub)
+      full.fill(0)
+      await mutatePending
+      expect((await memory.read('mutated')).toString()).toBe('hello world')
+    })
+
+    test('writer.write snapshots buffer bytes before returning', async () => {
+      const memory = new Operator('memory')
+      const writer = await memory.writer('streamed')
+
+      const chunkA = Buffer.alloc(512 * 1024, 0x43)
+      const abA = new ArrayBuffer(chunkA.length)
+      const bufA = Buffer.from(abA)
+      chunkA.copy(bufA)
+      const pA = writer.write(bufA)
+      detachArrayBuffer(abA)
+      await pA
+
+      const backingB = Buffer.from('__second-chunk__')
+      const subB = backingB.subarray(2, 14)
+      const pB = writer.write(subB)
+      backingB.fill(0)
+      await pB
+
+      await writer.close()
+
+      const written = await memory.read('streamed')
+      expect(Buffer.compare(written, Buffer.concat([chunkA, 
Buffer.from('second-chunk')]))).toBe(0)
+    })
+
     test('overlapping writer writes are serialized without losing data', async 
() => {
       const memory = new Operator('memory')
       const filename = `writer_concurrency_${randomUUID()}`

Reply via email to