This is an automated email from the ASF dual-hosted git repository. Xuanwo pushed a commit to branch xuanwo/fix-nodejs-numeric-input-validation in repository https://gitbox.apache.org/repos/asf/opendal.git
commit e1056a7bd1a22985af7ef2bef57ce9ff743c2717 Author: Xuanwo <[email protected]> AuthorDate: Mon Nov 23 16:52:04 2026 +0100 fix(bindings/nodejs): validate numeric layer and option inputs N-API truncates fractional numbers and wraps out-of-range ones when it converts a JavaScript number to a fixed-width integer, and the binding cast the result again without checking it. Invalid input therefore changed the request instead of failing: - `timeout` and `ioTimeout` turned negative, `NaN`, and sub-millisecond values into a zero duration, so every operation timed out immediately, while `Infinity` became a deadline 584 million years away. - `maxTimes` wrapped `-1` to 4294967295 retries, truncated `1.5` to `1`, and wrapped `2 ** 32` to no retries at all. - `factor` accepted `NaN`, values below 1, and values wider than an `f32`, which make the backoff shrink or overflow. - `minDelay` and `maxDelay` clamped negative values to zero. - `ThrottleLayer` wrapped a negative bandwidth to 4294967295 B/s, which effectively disables throttling, and truncated a fractional one. - `concurrent`, `chunk`, `prefetch`, and `limit` wrapped `-1` to 4294967295 and truncated fractions. - `expires` of the presign calls wrapped a negative value into a request that stays valid for more than a century. Convert these inputs as `f64` and validate them into the type the core API expects, so the setter or constructor reports `InvalidArg` instead of silently changing the operation. Values that core treats as "use the default", such as a zero `concurrent`, `prefetch`, `chunk`, `limit`, or `maxTimes`, stay accepted. A zero timeout is rejected because it would time out every operation. The TypeScript signatures are unchanged because `f64` and the integer types both surface as `number`; only the generated doc comments gain the accepted ranges. The new tests cover negative, `NaN`, `Infinity`, fractional, and out-of-range values for every changed site, plus the valid boundaries. --- bindings/nodejs/generated.d.ts | 48 ++++++--- bindings/nodejs/src/layer.rs | 140 +++++++++++++------------- bindings/nodejs/src/lib.rs | 61 +++++++----- bindings/nodejs/src/options.rs | 87 ++++++++++++---- bindings/nodejs/src/validate.rs | 90 +++++++++++++++++ bindings/nodejs/tests/layer.test.mjs | 176 ++++++++++++++++++++++++++------- bindings/nodejs/tests/options.test.mjs | 145 ++++++++++++++++++++++++++- 7 files changed, 584 insertions(+), 163 deletions(-) diff --git a/bindings/nodejs/generated.d.ts b/bindings/nodejs/generated.d.ts index 2e9fa9690f..06269f5b97 100644 --- a/bindings/nodejs/generated.d.ts +++ b/bindings/nodejs/generated.d.ts @@ -260,7 +260,7 @@ export declare class ConcurrentLimitLayer { * * # Errors * - * Returns an error if `permits` is not greater than 0. + * Returns an error if `permits` is not an integer between 1 and 4294967295. */ constructor(permits: number) /** @@ -274,7 +274,7 @@ export declare class ConcurrentLimitLayer { * * # Errors * - * Returns an error if `v` is not greater than 0. + * Returns an error if `v` is not an integer between 1 and 4294967295. */ set httpPermits(v: number) /** @@ -816,7 +816,8 @@ export declare class Operator { /** * Get a presigned request for read. * - * Unit of `expires` is seconds. + * Unit of `expires` is seconds. The value must be an integer between 1 and + * 4294967295. * * ### Example * @@ -832,7 +833,8 @@ export declare class Operator { /** * Get a presigned request for `write`. * - * Unit of `expires` is seconds. + * Unit of `expires` is seconds. The value must be an integer between 1 and + * 4294967295. * * ### Example * @@ -848,7 +850,8 @@ export declare class Operator { /** * Get a presigned request for stat. * - * Unit of `expires` is seconds. + * Unit of `expires` is seconds. The value must be an integer between 1 and + * 4294967295. * * ### Example * @@ -864,7 +867,8 @@ export declare class Operator { /** * Get a presigned request for delete. * - * Unit of `expires` is seconds. + * Unit of `expires` is seconds. The value must be an integer between 1 and + * 4294967295. * * ### Example * @@ -941,14 +945,15 @@ export declare class RetryLayer { * Set max_times of current backoff. * * Backoff will return `None` if max times are reached. + * + * The value must be an integer between 0 and 4294967295. `0` disables + * retries. */ set maxTimes(v: number) /** * Set factor of current backoff. * - * # Panics - * - * This function will panic if the input factor is smaller than `1.0`. + * The value must be a finite number between `1.0` and `340282350000000000000000000000000000000`. */ set factor(v: number) /** @@ -959,6 +964,7 @@ export declare class RetryLayer { * # Notes * * - The unit of max_delay is millisecond. + * - The value must be a finite, non-negative number. */ set maxDelay(v: number) /** @@ -967,6 +973,7 @@ export declare class RetryLayer { * # Notes * * - The unit of min_delay is millisecond. + * - The value must be a finite, non-negative number. */ set minDelay(v: number) build(): ExternalObject<Layer> @@ -1010,8 +1017,9 @@ export declare class ThrottleLayer { * * # Notes * - * `bandwidth` and `burst` must be greater than 0. Values that N-API converts - * to 0, such as `NaN`, `Infinity`, and `2 ** 32`, are rejected as well. + * `bandwidth` and `burst` must be integers between 1 and 4294967295. + * Fractional values, and values that N-API would truncate or wrap, are + * rejected instead of silently changing the rate limit. */ constructor(bandwidth: number, burst: number) build(): ExternalObject<Layer> @@ -1057,6 +1065,8 @@ export declare class TimeoutLayer { * * - The unit is millisecond. * - Default is 60000ms (60 seconds). + * - The value must be finite and greater than 0. A zero timeout is + * rejected because it would time out every operation immediately. */ set timeout(v: number) /** @@ -1066,6 +1076,8 @@ export declare class TimeoutLayer { * * - The unit is millisecond. * - Default is 10000ms (10 seconds). + * - The value must be finite and greater than 0. A zero timeout is + * rejected because it would time out every operation immediately. */ set ioTimeout(v: number) build(): ExternalObject<Layer> @@ -1127,6 +1139,8 @@ export interface ListOptions { * that could return per-request. * * Users could use this to control the memory usage of list operation. + * + * The value must be an integer between 0 and 4294967295. */ limit?: number /** * The start_after passed to underlying service to specify the specified key @@ -1185,11 +1199,15 @@ export interface ReaderOptions { * * By setting `concurrent`, opendal will fetch chunks concurrently with * the give chunk size. + * + * The value must be an integer between 0 and 4294967295. */ concurrent?: number /** * Sets the chunk size for this operation. * * OpenDAL will use services' preferred chunk size by default. Users can set chunk based on their own needs. + * + * The value must be an integer between 0 and 4294967295. */ chunk?: number /** Controls the number of prefetched bytes ranges that can be buffered in memory @@ -1205,6 +1223,8 @@ export interface ReaderOptions { * * This option helps prevent memory exhaustion when reading large files with high * concurrency settings. + * + * The value must be an integer between 0 and 4294967295. */ prefetch?: number /** * Controls the optimization strategy for range reads in [`Reader::fetch`]. @@ -1255,11 +1275,15 @@ export interface ReadOptions { * * By setting `concurrent`, opendal will fetch chunks concurrently with * the give chunk size. + * + * The value must be an integer between 0 and 4294967295. */ concurrent?: number /** * Sets the chunk size for this operation. * * OpenDAL will use services' preferred chunk size by default. Users can set chunk based on their own needs. + * + * The value must be an integer between 0 and 4294967295. */ chunk?: number /** * Controls the optimization strategy for range reads in [`Reader::fetch`]. @@ -1432,6 +1456,8 @@ export interface WriteOptions { * - Write operations return immediately without waiting if tasks space are available * - Close operation ensures all writes complete in order * - Memory usage increases with concurrency level + * + * The value must be an integer between 0 and 4294967295. */ concurrent?: number } diff --git a/bindings/nodejs/src/layer.rs b/bindings/nodejs/src/layer.rs index caf411253f..4d3fcff128 100644 --- a/bindings/nodejs/src/layer.rs +++ b/bindings/nodejs/src/layer.rs @@ -22,6 +22,10 @@ use napi::bindgen_prelude::External; use napi::bindgen_prelude::Result; use napi::bindgen_prelude::Status; +use crate::validate::parse_count; +use crate::validate::parse_millis; +use crate::validate::parse_timeout_millis; + pub trait NodeLayer: Send + Sync { fn layer(&self, op: opendal::Operator) -> opendal::Operator; } @@ -98,10 +102,10 @@ impl CapabilityOverrideLayer { #[napi] pub struct RetryLayer { jitter: bool, - max_times: Option<u32>, - factor: Option<f64>, - max_delay: Option<f64>, - min_delay: Option<f64>, + max_times: Option<usize>, + factor: Option<f32>, + max_delay: Option<Duration>, + min_delay: Option<Duration>, } #[napi] @@ -123,19 +127,32 @@ impl RetryLayer { /// Set max_times of current backoff. /// /// Backoff will return `None` if max times are reached. + /// + /// The value must be an integer between 0 and 4294967295. `0` disables + /// retries. #[napi(setter)] - pub fn max_times(&mut self, v: u32) { - self.max_times = Some(v); + pub fn max_times(&mut self, v: f64) -> Result<()> { + self.max_times = Some(parse_count(v, "maxTimes", 0)?); + Ok(()) } /// Set factor of current backoff. /// - /// # Panics - /// - /// This function will panic if the input factor is smaller than `1.0`. + /// The value must be a finite number between `1.0` and `340282350000000000000000000000000000000`. #[napi(setter)] - pub fn factor(&mut self, v: f64) { - self.factor = Some(v); + pub fn factor(&mut self, v: f64) -> Result<()> { + if !(1.0..=f64::from(f32::MAX)).contains(&v) { + return Err(Error::new( + Status::InvalidArg, + format!( + "factor must be a finite number between 1.0 and {}", + f32::MAX + ), + )); + } + + self.factor = Some(v as f32); + Ok(()) } /// Set max_delay of current backoff. @@ -145,9 +162,11 @@ impl RetryLayer { /// # Notes /// /// - The unit of max_delay is millisecond. + /// - The value must be a finite, non-negative number. #[napi(setter)] - pub fn max_delay(&mut self, v: f64) { - self.max_delay = Some(v); + pub fn max_delay(&mut self, v: f64) -> Result<()> { + self.max_delay = Some(parse_millis(v, "maxDelay")?); + Ok(()) } /// Set min_delay of current backoff. @@ -155,9 +174,11 @@ impl RetryLayer { /// # Notes /// /// - The unit of min_delay is millisecond. + /// - The value must be a finite, non-negative number. #[napi(setter)] - pub fn min_delay(&mut self, v: f64) { - self.min_delay = Some(v); + pub fn min_delay(&mut self, v: f64) -> Result<()> { + self.min_delay = Some(parse_millis(v, "minDelay")?); + Ok(()) } #[napi] @@ -167,16 +188,16 @@ impl RetryLayer { l = l.with_jitter(); } if let Some(max_times) = self.max_times { - l = l.with_max_times(max_times as usize); + l = l.with_max_times(max_times); } if let Some(factor) = self.factor { - l = l.with_factor(factor as f32); + l = l.with_factor(factor); } if let Some(max_delay) = self.max_delay { - l = l.with_max_delay(Duration::from_millis(max_delay as u64)); + l = l.with_max_delay(max_delay); } if let Some(min_delay) = self.min_delay { - l = l.with_min_delay(Duration::from_millis(min_delay as u64)); + l = l.with_min_delay(min_delay); } External::new(Layer { inner: Box::new(l) }) @@ -189,27 +210,6 @@ impl NodeLayer for opendal::layers::ConcurrentLimitLayer { } } -/// Validate a permit count received from JavaScript. -/// -/// Zero permits block every operation forever, and negative values wrap to -/// `usize::MAX` and silently disable the limit, so only positive counts that -/// fit in `usize` are accepted. -fn parse_permits(value: i64, field: &str) -> Result<usize> { - if value <= 0 { - return Err(Error::new( - Status::InvalidArg, - format!("{field} must be greater than 0"), - )); - } - - usize::try_from(value).map_err(|_| { - Error::new( - Status::InvalidArg, - format!("{field} must not be greater than {}", usize::MAX), - ) - }) -} - /// Concurrent limit layer /// /// Add concurrent request limit. @@ -256,11 +256,11 @@ impl ConcurrentLimitLayer { /// /// # Errors /// - /// Returns an error if `permits` is not greater than 0. + /// Returns an error if `permits` is not an integer between 1 and 4294967295. #[napi(constructor)] - pub fn new(permits: i64) -> Result<Self> { + pub fn new(permits: f64) -> Result<Self> { Ok(Self { - permits: parse_permits(permits, "permits")?, + permits: parse_count(permits, "permits", 1)?, http_permits: None, }) } @@ -275,10 +275,10 @@ impl ConcurrentLimitLayer { /// /// # Errors /// - /// Returns an error if `v` is not greater than 0. + /// Returns an error if `v` is not an integer between 1 and 4294967295. #[napi(setter)] - pub fn http_permits(&mut self, v: i64) -> Result<()> { - self.http_permits = Some(parse_permits(v, "httpPermits")?); + pub fn http_permits(&mut self, v: f64) -> Result<()> { + self.http_permits = Some(parse_count(v, "httpPermits", 1)?); Ok(()) } @@ -335,8 +335,8 @@ impl NodeLayer for opendal::layers::TimeoutLayer { #[derive(Default)] #[napi] pub struct TimeoutLayer { - timeout: Option<f64>, - io_timeout: Option<f64>, + timeout: Option<Duration>, + io_timeout: Option<Duration>, } #[napi] @@ -352,9 +352,12 @@ impl TimeoutLayer { /// /// - The unit is millisecond. /// - Default is 60000ms (60 seconds). + /// - The value must be finite and greater than 0. A zero timeout is + /// rejected because it would time out every operation immediately. #[napi(setter)] - pub fn timeout(&mut self, v: f64) { - self.timeout = Some(v); + pub fn timeout(&mut self, v: f64) -> Result<()> { + self.timeout = Some(parse_timeout_millis(v, "timeout")?); + Ok(()) } /// Set timeout for IO operations (read, write, etc.) @@ -363,9 +366,12 @@ impl TimeoutLayer { /// /// - The unit is millisecond. /// - Default is 10000ms (10 seconds). + /// - The value must be finite and greater than 0. A zero timeout is + /// rejected because it would time out every operation immediately. #[napi(setter)] - pub fn io_timeout(&mut self, v: f64) { - self.io_timeout = Some(v); + pub fn io_timeout(&mut self, v: f64) -> Result<()> { + self.io_timeout = Some(parse_timeout_millis(v, "ioTimeout")?); + Ok(()) } #[napi] @@ -373,10 +379,10 @@ impl TimeoutLayer { let mut l = opendal::layers::TimeoutLayer::default(); if let Some(timeout) = self.timeout { - l = l.with_timeout(Duration::from_millis(timeout as u64)); + l = l.with_timeout(timeout); } if let Some(io_timeout) = self.io_timeout { - l = l.with_io_timeout(Duration::from_millis(io_timeout as u64)); + l = l.with_io_timeout(io_timeout); } External::new(Layer { inner: Box::new(l) }) @@ -491,24 +497,16 @@ impl ThrottleLayer { /// /// # Notes /// - /// `bandwidth` and `burst` must be greater than 0. Values that N-API converts - /// to 0, such as `NaN`, `Infinity`, and `2 ** 32`, are rejected as well. + /// `bandwidth` and `burst` must be integers between 1 and 4294967295. + /// Fractional values, and values that N-API would truncate or wrap, are + /// rejected instead of silently changing the rate limit. #[napi(constructor)] - pub fn new(bandwidth: u32, burst: u32) -> Result<Self> { - if bandwidth == 0 { - return Err(Error::new( - Status::InvalidArg, - "bandwidth must be greater than 0", - )); - } - if burst == 0 { - return Err(Error::new( - Status::InvalidArg, - "burst must be greater than 0", - )); - } - - Ok(Self { bandwidth, burst }) + pub fn new(bandwidth: f64, burst: f64) -> Result<Self> { + // `parse_count` bounds both values to `u32::MAX`, so the casts are exact. + Ok(Self { + bandwidth: parse_count(bandwidth, "bandwidth", 1)? as u32, + burst: parse_count(burst, "burst", 1)? as u32, + }) } #[napi] diff --git a/bindings/nodejs/src/lib.rs b/bindings/nodejs/src/lib.rs index 84cec53cf0..2ac1189847 100644 --- a/bindings/nodejs/src/lib.rs +++ b/bindings/nodejs/src/lib.rs @@ -21,7 +21,6 @@ extern crate napi_derive; use std::collections::HashMap; use std::fmt::Display; use std::io::Read; -use std::time::Duration; use futures::AsyncReadExt; use futures::TryStreamExt; @@ -32,10 +31,13 @@ use opendal::options::{ use tokio::sync::Mutex; use crate::layer::Layer; +use crate::validate::parse_count; +use crate::validate::parse_expires_secs; mod capability; mod layer; mod options; +mod validate; #[napi] pub struct Operator { @@ -628,7 +630,10 @@ impl Operator { path: String, options: Option<options::ListOptions>, ) -> Result<Vec<Entry>> { - let options = options.map_or(ListOptions::default(), ListOptions::from); + let options = options + .map(ListOptions::try_from) + .transpose()? + .unwrap_or_default(); let l = self .async_op .list_options(&path, options) @@ -676,7 +681,10 @@ impl Operator { path: String, options: Option<options::ListOptions>, ) -> Result<Vec<Entry>> { - let options = options.map_or(ListOptions::default(), ListOptions::from); + let options = options + .map(ListOptions::try_from) + .transpose()? + .unwrap_or_default(); let l = self .blocking_op .list_options(&path, options) @@ -719,7 +727,10 @@ impl Operator { path: String, options: Option<options::ListOptions>, ) -> Result<Lister> { - let options = options.map_or(ListOptions::default(), ListOptions::from); + let options = options + .map(ListOptions::try_from) + .transpose()? + .unwrap_or_default(); let l = self .async_op .lister_options(&path, options) @@ -765,7 +776,10 @@ impl Operator { path: String, options: Option<options::ListOptions>, ) -> Result<BlockingLister> { - let options = options.map_or(ListOptions::default(), ListOptions::from); + let options = options + .map(ListOptions::try_from) + .transpose()? + .unwrap_or_default(); let l = self .blocking_op .lister_options(&path, options) @@ -776,7 +790,8 @@ impl Operator { /// Get a presigned request for read. /// - /// Unit of `expires` is seconds. + /// Unit of `expires` is seconds. The value must be an integer between 1 and + /// 4294967295. /// /// ### Example /// @@ -788,10 +803,10 @@ impl Operator { /// console.log("headers: ", req.headers); /// ``` #[napi] - pub async fn presign_read(&self, path: String, expires: u32) -> Result<PresignedRequest> { + pub async fn presign_read(&self, path: String, expires: f64) -> Result<PresignedRequest> { let res = self .async_op - .presign_read(&path, Duration::from_secs(expires as u64)) + .presign_read(&path, parse_expires_secs(expires)?) .await .map_err(format_napi_error)?; Ok(PresignedRequest::new(res)) @@ -799,7 +814,8 @@ impl Operator { /// Get a presigned request for `write`. /// - /// Unit of `expires` is seconds. + /// Unit of `expires` is seconds. The value must be an integer between 1 and + /// 4294967295. /// /// ### Example /// @@ -811,10 +827,10 @@ impl Operator { /// console.log("headers: ", req.headers); /// ``` #[napi] - pub async fn presign_write(&self, path: String, expires: u32) -> Result<PresignedRequest> { + pub async fn presign_write(&self, path: String, expires: f64) -> Result<PresignedRequest> { let res = self .async_op - .presign_write(&path, Duration::from_secs(expires as u64)) + .presign_write(&path, parse_expires_secs(expires)?) .await .map_err(format_napi_error)?; Ok(PresignedRequest::new(res)) @@ -822,7 +838,8 @@ impl Operator { /// Get a presigned request for stat. /// - /// Unit of `expires` is seconds. + /// Unit of `expires` is seconds. The value must be an integer between 1 and + /// 4294967295. /// /// ### Example /// @@ -834,10 +851,10 @@ impl Operator { /// console.log("headers: ", req.headers); /// ``` #[napi] - pub async fn presign_stat(&self, path: String, expires: u32) -> Result<PresignedRequest> { + pub async fn presign_stat(&self, path: String, expires: f64) -> Result<PresignedRequest> { let res = self .async_op - .presign_stat(&path, Duration::from_secs(expires as u64)) + .presign_stat(&path, parse_expires_secs(expires)?) .await .map_err(format_napi_error)?; Ok(PresignedRequest::new(res)) @@ -845,7 +862,8 @@ impl Operator { /// Get a presigned request for delete. /// - /// Unit of `expires` is seconds. + /// Unit of `expires` is seconds. The value must be an integer between 1 and + /// 4294967295. /// /// ### Example /// @@ -857,10 +875,10 @@ impl Operator { /// console.log("headers: ", req.headers); /// ``` #[napi] - pub async fn presign_delete(&self, path: String, expires: u32) -> Result<PresignedRequest> { + pub async fn presign_delete(&self, path: String, expires: f64) -> Result<PresignedRequest> { let res = self .async_op - .presign_delete(&path, Duration::from_secs(expires as u64)) + .presign_delete(&path, parse_expires_secs(expires)?) .await .map_err(format_napi_error)?; Ok(PresignedRequest::new(res)) @@ -1053,18 +1071,13 @@ impl Reader { #[napi(ts_return_type = "Promise<Buffer | null>")] pub async fn read_chunk(&self, max_bytes: f64) -> Result<Option<ReadChunk>> { // N-API's uint32 conversion truncates and wraps JavaScript numbers. - if !(1.0..=f64::from(u32::MAX)).contains(&max_bytes) || max_bytes.fract() != 0.0 { - return Err(Error::new( - Status::InvalidArg, - "maxBytes must be an integer between 1 and 4294967295", - )); - } + let max_bytes = parse_count(max_bytes, "maxBytes", 1)?; let chunk = self .inner .lock() .await - .read_buffer(max_bytes as usize) + .read_buffer(max_bytes) .await .map_err(format_napi_error)?; Ok((!chunk.is_empty()).then_some(ReadChunk(chunk))) diff --git a/bindings/nodejs/src/options.rs b/bindings/nodejs/src/options.rs index 8094dfcc16..d2317e5995 100644 --- a/bindings/nodejs/src/options.rs +++ b/bindings/nodejs/src/options.rs @@ -21,6 +21,8 @@ use opendal::BytesRange; use opendal::raw::Timestamp; use std::collections::HashMap; +use crate::validate::parse_count; + /// Convert a JavaScript `BigInt` into a `u64` offset or size. /// /// `BigInt::get_u64` only reports the lowest 64-bit word and returns the sign @@ -173,15 +175,19 @@ pub struct ReadOptions { * * By setting `concurrent`, opendal will fetch chunks concurrently with * the give chunk size. + * + * The value must be an integer between 0 and 4294967295. */ - pub concurrent: Option<u32>, + pub concurrent: Option<f64>, /** * Sets the chunk size for this operation. * * OpenDAL will use services' preferred chunk size by default. Users can set chunk based on their own needs. + * + * The value must be an integer between 0 and 4294967295. */ - pub chunk: Option<u32>, + pub chunk: Option<f64>, /** * Controls the optimization strategy for range reads in [`Reader::fetch`]. @@ -296,11 +302,20 @@ impl TryFrom<ReadOptions> for opendal::options::ReadOptions { .as_ref() .map(|gap| bigint_to_usize(gap, "gap")) .transpose()?; + let concurrent = value + .concurrent + .map(|v| parse_count(v, "concurrent", 0)) + .transpose()? + .unwrap_or_default(); + let chunk = value + .chunk + .map(|v| parse_count(v, "chunk", 0)) + .transpose()?; Ok(Self { version: value.version, - concurrent: value.concurrent.unwrap_or_default() as usize, - chunk: value.chunk.map(|chunk| chunk as usize), + concurrent, + chunk, gap, range, if_match: value.if_match, @@ -335,15 +350,19 @@ pub struct ReaderOptions { * * By setting `concurrent`, opendal will fetch chunks concurrently with * the give chunk size. + * + * The value must be an integer between 0 and 4294967295. */ - pub concurrent: Option<u32>, + pub concurrent: Option<f64>, /** * Sets the chunk size for this operation. * * OpenDAL will use services' preferred chunk size by default. Users can set chunk based on their own needs. + * + * The value must be an integer between 0 and 4294967295. */ - pub chunk: Option<u32>, + pub chunk: Option<f64>, /** Controls the number of prefetched bytes ranges that can be buffered in memory * during concurrent reading. @@ -358,8 +377,10 @@ pub struct ReaderOptions { * * This option helps prevent memory exhaustion when reading large files with high * concurrency settings. + * + * The value must be an integer between 0 and 4294967295. */ - pub prefetch: Option<u32>, + pub prefetch: Option<f64>, /** * Controls the optimization strategy for range reads in [`Reader::fetch`]. @@ -421,13 +442,27 @@ impl TryFrom<ReaderOptions> for opendal::options::ReaderOptions { .as_ref() .map(|gap| bigint_to_usize(gap, "gap")) .transpose()?; + let concurrent = value + .concurrent + .map(|v| parse_count(v, "concurrent", 0)) + .transpose()? + .unwrap_or_default(); + let chunk = value + .chunk + .map(|v| parse_count(v, "chunk", 0)) + .transpose()?; + let prefetch = value + .prefetch + .map(|v| parse_count(v, "prefetch", 0)) + .transpose()? + .unwrap_or_default(); Ok(Self { version: value.version, - concurrent: value.concurrent.unwrap_or_default() as usize, - chunk: value.chunk.map(|chunk| chunk as usize), + concurrent, + chunk, gap, - prefetch: value.prefetch.unwrap_or_default() as usize, + prefetch, if_match: value.if_match, if_none_match: value.if_none_match, if_modified_since, @@ -446,8 +481,10 @@ pub struct ListOptions { * that could return per-request. * * Users could use this to control the memory usage of list operation. + * + * The value must be an integer between 0 and 4294967295. */ - pub limit: Option<u32>, + pub limit: Option<f64>, /** * The start_after passed to underlying service to specify the specified key @@ -488,16 +525,23 @@ pub struct ListOptions { pub deleted: Option<bool>, } -impl From<ListOptions> for opendal::options::ListOptions { - fn from(value: ListOptions) -> Self { - Self { - limit: value.limit.map(|v| v as usize), +impl TryFrom<ListOptions> for opendal::options::ListOptions { + type Error = napi::Error; + + fn try_from(value: ListOptions) -> napi::Result<Self> { + let limit = value + .limit + .map(|v| parse_count(v, "limit", 0)) + .transpose()?; + + Ok(Self { + limit, start_after: value.start_after, recursive: value.recursive.unwrap_or_default(), versions: value.versions.unwrap_or_default(), deleted: value.deleted.unwrap_or_default(), ..Default::default() - } + }) } } @@ -574,7 +618,9 @@ pub struct WriteOptions { /// - Write operations return immediately without waiting if tasks space are available /// - Close operation ensures all writes complete in order /// - Memory usage increases with concurrency level - pub concurrent: Option<u32>, + /// + /// The value must be an integer between 0 and 4294967295. + pub concurrent: Option<f64>, } impl TryFrom<WriteOptions> for opendal::options::WriteOptions { @@ -586,6 +632,11 @@ impl TryFrom<WriteOptions> for opendal::options::WriteOptions { .as_ref() .map(|chunk| bigint_to_usize(chunk, "chunk")) .transpose()?; + let concurrent = value + .concurrent + .map(|v| parse_count(v, "concurrent", 0)) + .transpose()? + .unwrap_or_default(); Ok(Self { append: value.append.unwrap_or_default(), @@ -598,7 +649,7 @@ impl TryFrom<WriteOptions> for opendal::options::WriteOptions { if_match: value.if_match, if_none_match: value.if_none_match, if_not_exists: value.if_not_exists.unwrap_or_default(), - concurrent: value.concurrent.unwrap_or_default() as usize, + concurrent, ..Default::default() }) } diff --git a/bindings/nodejs/src/validate.rs b/bindings/nodejs/src/validate.rs new file mode 100644 index 0000000000..2db3cd0a10 --- /dev/null +++ b/bindings/nodejs/src/validate.rs @@ -0,0 +1,90 @@ +// 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. + +use std::time::Duration; + +use napi::bindgen_prelude::Error; +use napi::bindgen_prelude::Result; +use napi::bindgen_prelude::Status; + +/// Parse a JavaScript count such as a concurrency limit or a retry count. +/// +/// N-API hands numbers over as `f64` and truncates or wraps them when it +/// converts to a fixed-width integer, so a fractional `1.5` used to become `1` +/// and a negative `-1` used to become the largest possible count. Accept only +/// integers within `min..=u32::MAX` instead of silently changing the request. +pub(crate) fn parse_count(value: f64, field: &str, min: u32) -> Result<usize> { + // The range comparison also rejects `NaN` and both infinities. + if !(f64::from(min)..=f64::from(u32::MAX)).contains(&value) || value.fract() != 0.0 { + return Err(Error::new( + Status::InvalidArg, + format!("{field} must be an integer between {min} and {}", u32::MAX), + )); + } + + Ok(value as usize) +} + +/// Parse the `expires` argument of a presign call, which is given in seconds. +/// +/// The value must be a whole number of seconds between 1 and 4294967295. +/// N-API used to wrap a negative value into a request that stays valid for +/// more than a century, so an invalid expiry is reported instead. +pub(crate) fn parse_expires_secs(value: f64) -> Result<Duration> { + let seconds = parse_count(value, "expires", 1)?; + Ok(Duration::from_secs(seconds as u64)) +} + +/// Parse a JavaScript duration given in milliseconds. +/// +/// Casting milliseconds to `u64` turns negative values and `NaN` into zero, +/// which arms an immediate deadline for every operation, and saturates +/// `Infinity` and huge values to a duration of about 584 million years. +/// Converting the value instead rejects everything a `Duration` cannot +/// represent, and keeps sub-millisecond precision. +pub(crate) fn parse_millis(value: f64, field: &str) -> Result<Duration> { + Duration::try_from_secs_f64(value / 1000.0).map_err(|_| { + Error::new( + Status::InvalidArg, + format!("{field} must be a finite, non-negative number of milliseconds"), + ) + }) +} + +/// Parse a JavaScript timeout given in milliseconds that must be greater than +/// zero. +/// +/// A non-positive, non-finite, or unrepresentable timeout fails the same way, +/// and a zero timeout would fire before the operation gets a chance to run, so +/// every call on the layer would fail. Reporting this when the layer is +/// configured keeps the mistake at the call site. +pub(crate) fn parse_timeout_millis(value: f64, field: &str) -> Result<Duration> { + let invalid = || { + Error::new( + Status::InvalidArg, + format!("{field} must be a positive, finite number of milliseconds"), + ) + }; + + let timeout = Duration::try_from_secs_f64(value / 1000.0).map_err(|_| invalid())?; + // Values below one nanosecond are positive but still round down to zero. + if timeout.is_zero() { + return Err(invalid()); + } + + Ok(timeout) +} diff --git a/bindings/nodejs/tests/layer.test.mjs b/bindings/nodejs/tests/layer.test.mjs index 175fabf789..bda66bd204 100644 --- a/bindings/nodejs/tests/layer.test.mjs +++ b/bindings/nodejs/tests/layer.test.mjs @@ -17,9 +17,9 @@ * under the License. */ -import { assert, test } from 'vitest' +import { assert, describe, test } from 'vitest' -import { ConcurrentLimitLayer, ThrottleLayer } from '../index.mjs' +import { ConcurrentLimitLayer, RetryLayer, ThrottleLayer, TimeoutLayer } from '../index.mjs' function assertInvalidArgument(createLayer, field) { let error @@ -33,54 +33,154 @@ function assertInvalidArgument(createLayer, field) { assert.match(error.message, new RegExp(field)) } -// N-API converts these values to 0 when it reads the u32 constructor arguments. -const zeroValues = [0, 2 ** 32, NaN, Infinity] +// N-API used to hand these values to the Rust layer unchanged: `-1` wrapped to +// the largest count, `1.5` was truncated to `1`, and `2 ** 32` wrapped to `0`. +const invalidCounts = [-1, 1.5, NaN, Infinity, 2 ** 32] -for (const bandwidth of zeroValues) { - test(`ThrottleLayer rejects bandwidth ${bandwidth}`, () => { - assertInvalidArgument(() => new ThrottleLayer(bandwidth, 1024), 'bandwidth') - }) -} +// Values that used to become a zero duration, which arms an immediate deadline, +// or a duration the core layer cannot represent. +const invalidMillis = [-1, -0.5, NaN, Infinity, -Infinity, 1e30] -for (const burst of zeroValues) { - test(`ThrottleLayer rejects burst ${burst}`, () => { - assertInvalidArgument(() => new ThrottleLayer(1024, burst), 'burst') +describe('ThrottleLayer', () => { + // A fractional rate was truncated to whole bytes and a negative rate wrapped + // to the largest one, which silently changed or disabled the rate limit. + for (const value of [0, ...invalidCounts]) { + test(`rejects bandwidth ${value}`, () => { + assertInvalidArgument(() => new ThrottleLayer(value, 1024), 'bandwidth') + }) + + test(`rejects burst ${value}`, () => { + assertInvalidArgument(() => new ThrottleLayer(1024, value), 'burst') + }) + } + + test('accepts a positive bandwidth and burst', () => { + const layer = new ThrottleLayer(1024, 2048) + assert.ok(layer.build()) }) -} -test('ThrottleLayer accepts positive bandwidth and burst', () => { - const layer = new ThrottleLayer(1024, 2048) - assert.ok(layer.build()) + test('accepts the largest bandwidth and burst', () => { + const layer = new ThrottleLayer(4294967295, 4294967295) + assert.ok(layer.build()) + }) }) -// A zero-permit semaphore never hands out a permit, so every operation hangs -// forever, and a negative permit count wraps to usize::MAX and disables the -// limit instead of failing. -const invalidPermits = [0, -1] +describe('ConcurrentLimitLayer', () => { + // A zero-permit semaphore never hands out a permit, so every operation hangs + // forever, and a negative permit count wraps to the largest count and + // disables the limit instead of failing. + for (const permits of [0, ...invalidCounts]) { + test(`rejects ${permits} permits`, () => { + assertInvalidArgument(() => new ConcurrentLimitLayer(permits), 'permits') + }) -for (const permits of invalidPermits) { - test(`ConcurrentLimitLayer rejects ${permits} permits`, () => { - assertInvalidArgument(() => new ConcurrentLimitLayer(permits), 'permits') - }) + test(`rejects ${permits} httpPermits`, () => { + const layer = new ConcurrentLimitLayer(1024) + assertInvalidArgument(() => { + layer.httpPermits = permits + }, 'httpPermits') + }) + } - test(`ConcurrentLimitLayer rejects ${permits} httpPermits`, () => { + test('accepts positive permits', () => { const layer = new ConcurrentLimitLayer(1024) - assertInvalidArgument(() => { - layer.httpPermits = permits - }, 'httpPermits') + layer.httpPermits = 512 + assert.ok(layer.build()) }) -} -test('ConcurrentLimitLayer accepts positive permits', () => { - const layer = new ConcurrentLimitLayer(1024) - layer.httpPermits = 512 - assert.ok(layer.build()) + test('stays usable after a rejected httpPermits', () => { + const layer = new ConcurrentLimitLayer(1024) + assert.throws(() => { + layer.httpPermits = 0 + }) + assert.ok(layer.build()) + }) }) -test('ConcurrentLimitLayer stays usable after a rejected httpPermits', () => { - const layer = new ConcurrentLimitLayer(1024) - assert.throws(() => { - layer.httpPermits = 0 +describe('RetryLayer', () => { + // A negative retry count wrapped to the largest count, so retrying never + // stopped, and a fractional one was truncated to fewer retries. + for (const maxTimes of invalidCounts) { + test(`rejects maxTimes ${maxTimes}`, () => { + const layer = new RetryLayer() + assertInvalidArgument(() => { + layer.maxTimes = maxTimes + }, 'maxTimes') + }) + } + + test('accepts a zero maxTimes', () => { + // Zero retries is a valid way to disable retrying. + const layer = new RetryLayer() + layer.maxTimes = 0 + assert.ok(layer.build()) }) - assert.ok(layer.build()) + + test('accepts a positive maxTimes', () => { + const layer = new RetryLayer() + layer.maxTimes = 3 + assert.ok(layer.build()) + }) + + // A factor below one makes the backoff shrink, and a non-finite one or a + // value beyond `f32` produces a delay that the core layer cannot represent. + for (const factor of [-1, 0, 0.5, NaN, Infinity, -Infinity, 1e39]) { + test(`rejects factor ${factor}`, () => { + const layer = new RetryLayer() + assertInvalidArgument(() => { + layer.factor = factor + }, 'factor') + }) + } + + test('accepts valid factors', () => { + for (const factor of [1, 1.5, 2, 3.4028234663852886e38]) { + const layer = new RetryLayer() + layer.factor = factor + assert.ok(layer.build()) + } + }) + + for (const field of ['minDelay', 'maxDelay']) { + for (const value of invalidMillis) { + test(`rejects ${field} ${value}`, () => { + const layer = new RetryLayer() + assertInvalidArgument(() => { + layer[field] = value + }, field) + }) + } + + test(`accepts non-negative ${field}`, () => { + // A zero delay is valid, it retries without waiting. + for (const value of [0, 1, 0.5, 60000]) { + const layer = new RetryLayer() + layer[field] = value + assert.ok(layer.build()) + } + }) + } +}) + +describe('TimeoutLayer', () => { + // A negative or `NaN` timeout became zero milliseconds, which timed out every + // operation immediately, and `Infinity` became a deadline a lifetime away. + for (const field of ['timeout', 'ioTimeout']) { + for (const value of [0, 1e-7, ...invalidMillis]) { + test(`rejects ${field} ${value}`, () => { + const layer = new TimeoutLayer() + assertInvalidArgument(() => { + layer[field] = value + }, field) + }) + } + + test(`accepts a positive ${field}`, () => { + for (const value of [1, 0.5, 10000]) { + const layer = new TimeoutLayer() + layer[field] = value + assert.ok(layer.build()) + } + }) + } }) diff --git a/bindings/nodejs/tests/options.test.mjs b/bindings/nodejs/tests/options.test.mjs index fa15c0ba27..36e9a4b998 100644 --- a/bindings/nodejs/tests/options.test.mjs +++ b/bindings/nodejs/tests/options.test.mjs @@ -135,7 +135,6 @@ describe('bigint options', () => { // An unparsable timestamp used to be dropped, so the conditional read, stat, // or reader silently ran unconditionally instead of reporting the mistake. const invalidTimestamps = ['not-a-date', new Date(0).toUTCString()] - // Return the error a promise rejects with, or undefined when it resolves. async function settle(promise) { try { @@ -191,3 +190,147 @@ describe('conditional timestamps', () => { expect(String(statError?.message ?? '')).not.toMatch('must be an ISO 8601') }) }) + +// N-API truncates fractional numbers and wraps negative ones when it converts +// them to the integer behind these options, so a negative `concurrent` silently +// became the largest possible count and `1.5` became `1`. +const invalidCounts = [-1, 1.5, NaN, Infinity, 2 ** 32] + +describe('numeric options', () => { + const op = new Operator('memory') + + beforeEach(async () => { + await op.write(path, content) + }) + + describe('read', () => { + for (const field of ['concurrent', 'chunk']) { + for (const value of invalidCounts) { + it(`read rejects ${field} ${value}`, async () => { + await expect(op.read(path, { [field]: value })).rejects.toThrowError(`${field} must be an integer`) + }) + + it(`readSync rejects ${field} ${value}`, () => { + expect(() => op.readSync(path, { [field]: value })).toThrowError(`${field} must be an integer`) + }) + } + } + + it('accepts a zero concurrent and chunk', async () => { + // Zero keeps the sequential default. + expect((await op.read(path, { concurrent: 0, chunk: 0 })).equals(content)).toBe(true) + expect(op.readSync(path, { concurrent: 0, chunk: 0 }).equals(content)).toBe(true) + }) + + it('accepts a positive concurrent and the largest chunk', async () => { + expect((await op.read(path, { concurrent: 8, chunk: 4294967295 })).equals(content)).toBe(true) + expect(op.readSync(path, { concurrent: 8, chunk: 4294967295 }).equals(content)).toBe(true) + }) + }) + + describe('reader', () => { + for (const field of ['concurrent', 'chunk', 'prefetch']) { + for (const value of invalidCounts) { + it(`reader rejects ${field} ${value}`, async () => { + await expect(op.reader(path, { [field]: value })).rejects.toThrowError(`${field} must be an integer`) + }) + + it(`readerSync rejects ${field} ${value}`, () => { + expect(() => op.readerSync(path, { [field]: value })).toThrowError(`${field} must be an integer`) + }) + } + } + + it('accepts a zero concurrent and prefetch', async () => { + // Zero keeps the sequential default and disables prefetching. + const reader = await op.reader(path, { concurrent: 0, prefetch: 0 }) + expect((await reader.readChunk(1024)).toString()).toBe(content.toString()) + }) + + it('accepts a positive concurrent, chunk and prefetch', async () => { + const reader = await op.reader(path, { concurrent: 2, chunk: 4, prefetch: 1 }) + const output = [] + let chunk + while ((chunk = await reader.readChunk(1024)) !== null) { + output.push(chunk) + } + expect(Buffer.concat(output).equals(content)).toBe(true) + }) + }) + + describe('list', () => { + for (const value of invalidCounts) { + it(`list rejects limit ${value}`, async () => { + await expect(op.list('/', { limit: value })).rejects.toThrowError('limit must be an integer') + }) + + it(`listSync rejects limit ${value}`, () => { + expect(() => op.listSync('/', { limit: value })).toThrowError('limit must be an integer') + }) + + it(`lister rejects limit ${value}`, async () => { + await expect(op.lister('/', { limit: value })).rejects.toThrowError('limit must be an integer') + }) + + it(`listerSync rejects limit ${value}`, () => { + expect(() => op.listerSync('/', { limit: value })).toThrowError('limit must be an integer') + }) + } + + it('accepts a zero and a positive limit', async () => { + const zero = await op.list('/', { limit: 0 }) + expect(zero.some((entry) => entry.path() === path)).toBe(true) + + const positive = await op.list('/', { limit: 1024 }) + expect(positive.some((entry) => entry.path() === path)).toBe(true) + }) + }) + + describe('write', () => { + for (const value of invalidCounts) { + it(`write rejects concurrent ${value}`, async () => { + await expect(op.write(path, 'hello', { concurrent: value })).rejects.toThrowError( + 'concurrent must be an integer', + ) + }) + + it(`writeSync rejects concurrent ${value}`, () => { + expect(() => op.writeSync(path, 'hello', { concurrent: value })).toThrowError('concurrent must be an integer') + }) + + it(`writer rejects concurrent ${value}`, async () => { + await expect(op.writer(path, { concurrent: value })).rejects.toThrowError('concurrent must be an integer') + }) + + it(`writerSync rejects concurrent ${value}`, () => { + expect(() => op.writerSync(path, { concurrent: value })).toThrowError('concurrent must be an integer') + }) + } + + it('accepts a zero concurrent', async () => { + await op.write(path, 'sequential', { concurrent: 0 }) + expect((await op.read(path)).toString()).toBe('sequential') + }) + }) +}) + +// `expires` was converted straight from a `u32`, so a negative value became a +// request that stays valid for more than a century. +describe('presign expires', () => { + const op = new Operator('memory') + + for (const method of ['presignRead', 'presignWrite', 'presignStat', 'presignDelete']) { + for (const value of invalidCounts) { + it(`${method} rejects expires ${value}`, async () => { + await expect(op[method](path, value)).rejects.toThrowError('expires must be an integer') + }) + } + + it(`${method} accepts a positive expires`, async () => { + // The memory service does not support presign, so the value must reach + // the service instead of being rejected as malformed. + const error = await settle(op[method](path, 3600)) + expect(String(error?.message ?? '')).not.toMatch('expires must be an integer') + }) + } +})
