
Cloud Vulnerability DB
A community-led vulnerabilities database
&mut in napi (napi-rs): borrowed External<T> arguments skip the native-borrow guard| Field | Value |
|---|---|
| Package | napi (Rust, pkg:github/napi-rs/napi-rs) |
| Repository | https://github.com/napi-rs/napi-rs |
| Component | <External<T> as FromNapiMutRef>::from_napi_mut_ref in crates/napi/src/bindgen_runtime/js_values/external.rs, as called by the generated #[napi] argument conversion in crates/backend/src/codegen/fn.rs |
| Vulnerability class | Memory safety: JavaScript can create aliasing Rust references (&mut + &mut, or &mut + &) to one External<T> payload, leading to use-after-free in safe downstream code |
| CWE | CWE-668 |
| Severity (reporter assessment) | High |
| Verified against | d6d795a391f60d22d4af4c3eeb2543b62c28bded (napi 3.16.1). Earlier releases were not checked; the version that introduced the behaviour is not established. |
| API surface | Public documented API: External<T> is listed as a supported Rust/JavaScript type (README.md:225) |
| Affected in default configuration | Yes. No opt-in is needed: the generated glue uses FromNapiMutRef for every &mut argument (fn.rs:680-713), and the External<T> conversion never registers a native borrow. |
impl FromNapiMutRef for External<T> turns a napi_external payload into an unrestricted &'static mut External<T> after checking only that the pointer is a live payload of the right External<T> type. The generated #[napi] glue runs this conversion separately for each borrowed External argument and, unlike #[napi] class references, does not register the payload with the native-borrow guard (NativeBorrowScope). A JavaScript caller can therefore pass the same External object in two argument slots and obtain aliasing references that safe Rust is entitled to assume cannot exist.
In a consuming addon, any JavaScript code that can get an External<T> from the addon (for example from a factory function) and call an exported function taking two borrowed External<T> parameters of the same T, at least one of them &mut, can trigger this with f(h, h). Merge, copy, compare and swap operations over opaque native handles naturally take this shape, and JavaScript has no way to express Rust's requirement that the two references be distinct.
The runtime already guards the equivalent pattern for class references; only the External<T> path is unguarded:
#[napi] class references (&mut Cls, &mut Cls) -> guarded: the generated conversion calls register_native_borrow_with_value (crates/backend/src/codegen/fn.rs:447-466), and aliasing is rejected at runtime&mut External<T> arguments -> unguarded: from_napi_mut_ref returns &'static mut External<T> with no borrow registration (crates/napi/src/bindgen_runtime/js_values/external.rs:181-201); the file contains no native-borrow registration call for any External reference conversion&mut arguments to async #[napi] functions -> rejected by the generated glue (exact line not recorded in this review)Safe Rust in a downstream addon becomes undefined behaviour when JavaScript passes aliased External arguments. Depending on what the safe code does, the result is a use-after-free read or write, a process crash, or native memory disclosure or corruption in the process hosting the addon. During verification, a safe function that held &b[0] while clearing/reallocating a segfaulted in 3 of 3 runs when given the same External twice.
Without this bug, the aliasing call would be rejected (as it already is for #[napi] class references), and the example operation would only read a live second handle. With it, JavaScript can hold two live references to one payload, at least one of them exclusive, and use that to make the addon free memory that a still-live reference points to.
Not CVSS-scored: exploitability depends on the consuming addon's API. It needs an exported synchronous function that takes two or more borrowed External<T> parameters of the same T, at least one &mut, and whose implementation relies on the references not aliasing. Not affected: addons that export no such function; #[napi] class references (already guarded); async #[napi] functions (the generated glue rejects &mut arguments there).
d6d795a391f60d22d4af4c3eeb2543b62c28bded; earlier versions not checked).#[napi] function with two or more borrowed External<T> parameters of the same T, at least one &mut (&mut + &mut, or &mut + &). The generated glue handles these by default: it calls FromNapiMutRef for each &mut argument (fn.rs:680-713) and only rejects mutable references for async functions.External<T> from the addon (for example a factory returning External::new(...)) to pass in both positions.External<T> is listed as a supported type in README.md:225, and the repository's example (examples/napi/src/external.rs:4-19) shows factory, shared-borrow and mutable-borrow APIs without any warning that JavaScript callers must preserve Rust aliasing. The behaviour is not documented as the caller's responsibility.External<T> from an addon factory (the documented example pattern) and passes the same napi_external value in two borrowed-argument slots: addon.readAfterReplace(h, h) (examples/napi/src/external.rs:4-5).#[napi] glue calls <External<T> as FromNapiMutRef>::from_napi_mut_ref separately for each argument, and napi_get_value_external returns the identical payload pointer both times (crates/backend/src/codegen/fn.rs:680-713).External<T> type (External::from_raw_impl, external.rs:65-81) and returns it as an unrestricted &'static mut: Some(external) => Ok(external) (crates/napi/src/bindgen_runtime/js_values/external.rs:181-201). No borrow is registered with NativeBorrowScope.#[napi]-exported synchronous function with two or more borrowed External<T> parameters (same T, at least one &mut) is called directly from JavaScript. External<T> and its reference conversions are public binding types, and the repository's own example exports both creation and borrowed mutation (examples/napi/src/external.rs:4-19).crates/napi/src/bindgen_runtime/js_values/external.rs, lines 181-201 at d6d795a391f60d22d4af4c3eeb2543b62c28bded (pinned link).
Excerpt as captured during source review: the error arm is elided (Err(...)), and the complete range is at the pinned link. The trailing comments are added.
impl<T: 'static> FromNapiMutRef for External<T> {
unsafe fn from_napi_mut_ref(env: sys::napi_env, napi_val: sys::napi_value) -> crate::Result<&'static mut Self> {
let mut unknown_tagged_object = ptr::null_mut();
check_status!(unsafe { sys::napi_get_value_external(env, napi_val, &mut unknown_tagged_object) }, "Failed to get external value")?;
match Self::from_raw_impl(unknown_tagged_object) { // type/provenance check only (external.rs:65-81)
Some(external) => Ok(external), // SINK: unrestricted &'static mut, no native-borrow registration
None => Err(...),
}
}
}For comparison, the generated conversions for #[napi] class references register the borrow with register_native_borrow_with_value before returning (fn.rs:447-466). That is the safe sibling path.
Verified on Node v24 against d6d795a391f60d22d4af4c3eeb2543b62c28bded (napi 3.16.1). A minimal cdylib addon was built with path dependencies on crates/napi and crates/macro at that commit and loaded in Node. Operating system, Rust toolchain and allocator details were not recorded.
Observed:
fn mut_mut_alias(a: &mut External<u32>, b: &mut External<u32>) returns whether the two references are pointer-equal. Two distinct externals give false. The same External passed twice gives true, so two live aliasing &mut references exist.&mut pattern with a #[napi] class (&mut Cls, &mut Cls) is rejected with The same native value cannot be borrowed mutably while another borrow is active.fn shared_mut_uaf(a: &mut External<Vec<String>>, b: &External<Vec<String>>) holds &b[0] while clearing/reallocating a. With distinct externals it works. With the same External passed twice the process segfaults (exit code 139, 3 of 3 runs).
The full source of that verification addon was not recorded. The minimal example below uses the same pattern (two &mut External parameters, with a reference held through one while the other is replaced), but it is not the code that was executed above.use napi::bindgen_prelude::*;
use napi_derive::napi;
#[napi]
pub fn make_box(v: u8) -> External<Box<u8>> { External::new(Box::new(v)) }
#[napi]
pub fn read_after_replace(a: &mut External<Box<u8>>, b: &mut External<Box<u8>>) -> u8 {
let saved: &u8 = &***b;
**a = Box::new(0x42); // drops the allocation behind `saved` if a and b alias
*saved // safe Rust, but a use-after-free when JS passes the same External twice
}// Node
const h = addon.makeBox(0x41);
console.log(addon.readAfterReplace(h, h));To see the use-after-free in this example directly, run it under ASan or Miri, or arrange allocator reuse. How this particular example behaves under those tools has not been verified.
InvalidArg, because an exclusive borrow of the same External payload is already active, as already happens for class references.&mut references and, in the shared + mutable case, a segfault (exit code 139, 3 of 3 runs).Track External<T> reference borrows in the active NativeBorrowScope the same way #[napi] class references are tracked: before returning &External<T> or &mut External<T>, register the payload pointer and the source napi value, and reject any borrow that conflicts with one already active.
This is a sketch and has not been compiled. The registration call should mirror the one that the generated class-reference conversions already make; its exact signature is not reproduced here.
impl<T: 'static> FromNapiMutRef for External<T> {
unsafe fn from_napi_mut_ref(env: sys::napi_env, napi_val: sys::napi_value) -> crate::Result<&'static mut Self> {
let mut unknown_tagged_object = ptr::null_mut();
check_status!(unsafe { sys::napi_get_value_external(env, napi_val, &mut unknown_tagged_object) }, "Failed to get external value")?;
match Self::from_raw_impl(unknown_tagged_object) {
Some(external) => {
// NEW: register an exclusive borrow of this payload (pointer + napi_val) in the
// active NativeBorrowScope, as class references do via register_native_borrow_with_value.
// Return InvalidArg if any borrow of the same payload is already active.
Ok(external)
}
None => Err(...),
}
}
}If it fits the project's structure better, the same check can be emitted by the generated argument glue in crates/backend/src/codegen/fn.rs, next to the existing register_native_borrow_with_value calls for class references (fn.rs:447-466).
Notes:
&External<T>) as well, registering it as a shared borrow, so that &mut + & of one payload is rejected. That combination produced the use-after-free in verification. Two shared borrows of one payload do not conflict and can stay allowed.External reference conversions should use the same guard.#[napi] class reference conversions (guarded, with rejection confirmed in verification) and &mut arguments to async functions (rejected by the generated glue). The type/provenance check in External::from_raw_impl (external.rs:65-81) is still needed and does not change.
Suggested regression test alongside the existing External examples (examples/napi/src/external.rs; the matching test file was not identified in this review): export fn(a: &mut External<u32>, b: &mut External<u32>) and fn(a: &mut External<u32>, b: &External<u32>). Calling either from JavaScript with the same External in both positions should throw an InvalidArg error, like the existing class-reference rejection, while calls with two distinct External values keep succeeding.main (bfc2dff1). Fix merged in commit fb1c6d4627ce61ba0ed2803ab8fa79b27382b0f1 ("Merge commit from fork", 2026-11-22) and shipped in napi 3.16.3 (2026-11-23), together with napi-derive 3.7.2 and napi-derive-backend 8.0.0 for the generated-constructor barrier.napi >= 3.0.0-alpha.1, <= 3.16.2 (FromNapiRef / FromNapiMutRef for External<T> were introduced in commit 0550c56f / PR #2013).#[napi] surface (&External<T> / &mut External<T> / ExternalRef<T> / Option/Vec/Either-container parameters, re-entrant callbacks), but these paths still hand out untracked references:JsExternal::get_value::<T>() (js_values/external.rs:51-53) — public, non-unsafe, returns &mut T with no guard. JsExternal is a valid generated #[napi] parameter type, so two JsExternal parameters with get_value::<T>() on both bypass tracking.External::inner_from_raw_mut / External::inner_from_raw (external.rs:118-128) — pub unsafe, return untracked references; correctness is the caller's responsibility (no in-repo callers).&mut pattern): Env::get_value_external<T> (compat mode, env.rs:1064-1090) and Env::get_instance_data<T> (napi6, env.rs:1469-1505).FromNapiRef for External<T> previously delegated to FromNapiMutRef, creating a transient &'static mut External<T> even on shared (&External<T>, &External<T>) reads (External::inner_from_raw had the same issue). Both now validate the raw pointer without creating &mut before registering a shared borrow.ExternalRef<T> (FromNapiValue, ExternalRef::new, JsExternal::create_ref) previously bypassed NATIVE_BORROWS; it now acquires an owned exclusive NativeBorrowGuard before napi_create_reference and releases it before napi_delete_reference in Drop.Env::create_function_from_closure, Property::with_setter_closure / with_getter_closure, PromiseRaw then/catch/finally, ThreadsafeFunction::call_js_cb, class accessor trampolines, sync/async generator callbacks, default struct constructors) now install NativeBorrowBarrier so they cannot bypass External<T> borrow tracking or attach nested local handles to an outer collecting NativeBorrowScope.NativeBorrowStorage::ensure_rooted now rolls back partially created roots on failure instead of marking the scope rooted with missing entries.napi (to the patched release) and napi-derive (>= 3.12.1, or latest) so generated #[napi] entrypoints emit NativeBorrowScope. Addons that upgrade only napi while remaining on napi-derive < 3.12.1 (or using deprecated compat-mode #[js_function], which is slated for removal in v4) do not install a NativeBorrowScope and remain unguarded.Source: NVD
Free Vulnerability Assessment
Evaluate your cloud security practices across 9 security domains to benchmark your risk level and identify gaps in your defenses.
Get a personalized demo
"Best User Experience I have ever seen, provides full visibility to cloud workloads."
"Wiz provides a single pane of glass to see what is going on in our cloud environments."
"We know that if Wiz identifies something as critical, it actually is."