diff --git a/docs/trusted-scripts.md b/docs/trusted-scripts.md new file mode 100644 index 000000000..dcb9f3aef --- /dev/null +++ b/docs/trusted-scripts.md @@ -0,0 +1,200 @@ +# Trusted script sources and execution-state queries + +PR #106 adds two env-based helpers: + +```c +napi_status unofficial_napi_create_trusted_script( + napi_env env, napi_value source, napi_value* result); +napi_status unofficial_napi_is_executing_js(napi_env env, bool* result); +``` + +They follow the [realm model](realms.md): one env serves an engine instance, +object creation uses the current N-API realm, and a native callback acts in the +realm where its function was created. Neither helper needs a new realm argument. +Both must be called on the engine's owning thread. + +## Support + +| Provider | create_trusted_script | is_executing_js | +|---|---|---| +| V8 | Native code-like object and code-generation hook | Native stack and microtask-checkpoint state | +| QuickJS | Unsupported; napi_generic_failure and NULL output | Native bytecode-frame and executing-job state | +| Host JS | Unsupported; napi_generic_failure and zero value id | Unsupported; napi_generic_failure and false output | + +Unsupported operations do not emulate direct eval or infer VM execution state +from adapter bookkeeping. Host-JS guest stubs still validate output pointers and +zero valid outputs. A value id occupies four bytes; a bool occupies one byte. + +## Trusted-script contract on V8 + +The source must be a primitive string. Objects, including boxed strings, are +rejected with `napi_string_expected` without coercion. Null arguments are +invalid. The result is an object allocated in the current realm, with a native +default `toString` from that realm. It is not itself a full WebIDL TrustedScript +implementation; the embedder supplies any WebIDL prototype and policy layer. + +Direct `eval(trusted)` uses the stored primitive source and preserves the +caller's lexical scope. It does not call author `toString` or `Symbol.toPrimitive`. +Indirect eval keeps ordinary global-eval semantics. The native brand cannot be +copied, inherited, obtained by name through `create_private_symbol`, or forwarded +by a Proxy. Prototype replacement and freezing do not remove the object's brand. + +A trusted source can be passed between realms of the same agent. Eval uses the +receiving caller's scope and code-generation policy, not the source object's +creation realm. A receiving realm with string code generation disabled rejects +it with `EvalError`; the object is not a policy bypass. + +**Function constructors have a narrower guarantee.** `Function(trusted)` works +through the default native stringifier, but V8 converts its arguments before +its code-generation hook. An author's replacement `toString` or +`Symbol.toPrimitive` can therefore change the function source. This API does +not provide hardened Trusted Types integration for Function, AsyncFunction, +GeneratorFunction, or AsyncGeneratorFunction. V8's +[dynamic-function implementation](https://github.com/v8/v8/blob/13.6.233/src/builtins/builtins-function.cc) +shows that argument coercion precedes compilation. The regression suite pins +ordinary Function coercion so it cannot be confused with the direct-eval guarantee. + +Creation follows the provider's sticky termination contract and returns +`napi_pending_exception` while execution is terminating. It remains usable in +cleanup hooks while the live env and its agent support JavaScript, consistent +with `release_env`. The read-only execution query also remains usable during +termination and cleanup and preserves a pending exception. + +## Agent state and hook ownership + +The private brand and reusable code-like ObjectTemplate belong to `napi_agent__`. +They are shared by the env's realms and reset before the isolate is disposed. +There is no process-global map or lock for trusted-script brands. A single +reusable template avoids V8 retaining a fresh template instantiation for every +created object. The template does not retain its first creation realm after +that realm and its values become unreachable; a regression checks collection. + +On the first trusted-script creation in an agent, the provider installs its +isolate-wide `ModifyCodeGenerationFromStrings` callback. V8 supplies no getter +for the previous callback, so an earlier embedder callback is replaced and +cannot be chained. An embedder callback installed later is preserved: further +trusted-script creation does not reinstall the provider hook. Such a callback +then determines how code-like objects are treated. + +For values not bearing the provider's brand, the provider hook preserves V8's +behavior: eval returns unbranded non-string objects unchanged, while ordinary +strings follow the receiving context's code-generation policy. This hook is +not a general CSP/Trusted Types policy API. In particular, when string code +generation is allowed V8 does not send ordinary strings through this hook, so +it cannot enforce a “trusted objects only” policy in that configuration. + +## Execution-state semantics + +`is_executing_js` describes the whole engine instance, across its realms and +security tokens. It returns true while a user-JavaScript frame exists or a +microtask checkpoint (V8) or job (QuickJS) is running. V8 provider-driven +checkpoints, including a realm's own queue, use an agent-wide scoped depth so +the answer stays true when a callback temporarily runs in a different N-API +realm. The query does not scan the realm registry or take bridge/provider locks. + +Entering a realm from C++ does not mean JavaScript is executing. A native +function called directly from C, or through a builtin with no user-JavaScript +frame below it, returns false outside a checkpoint. A native callback invoked +by a promise checkpoint returns true even when no user-JavaScript frame is +visible. This contract measures observable VM frames and checkpoints, not all +possible internal engine activity. + +The bridge calls use the existing owner-thread validation. They do not hold +`g_mu` while invoking the provider; restoring the old recursive lock or +changing it to a plain-mutex guard would violate the bridge's concurrency model. + +### QuickJS execution-state implementation + +The QuickJS fork exposes `JS_IsExecutingJS(JSRuntime*)`. It walks the live frame +chain and recognizes ordinary, generator, async, and async-generator bytecode +functions. Native C functions, C function-data callbacks, closures, and builtins +do not count by themselves. Suspended coroutines are absent from the active +chain. A runtime-wide job depth spans `JS_ExecutePendingJob`, including cleanup, +so native-only promise/microtask callbacks count, nested job calls retain the +outer job's state, and errors or termination unwind the state. Queuing a job +alone does not make the runtime active. + +This is a read-only engine query: it allocates nothing, invokes no JavaScript, +and does not inspect or clear pending exceptions. It covers every context in +the runtime and remains accurate when a native callback acts in its creation +realm while JavaScript runs in another realm. The provider returns `napi_ok` +with that result. Both the env and runtime must remain live, and calls stay on +the owning thread. + +QuickJS uses its runtime job queue; its realm `own_microtask_queue` option does +not introduce a separate V8-style checkpoint. The query does not change job +scheduling or implement that separate queue capability. + +## QuickJS trusted-script follow-up + +Native QuickJS trusted-script support would be useful for embedders using this +API across providers, but it needs additional engine changes. At the pinned +QuickJS revision, +`JS_EvalObject` returns non-string arguments unchanged before entering the +parser. The Function constructor separately stringifies its arguments. +Replacing the global eval function or coercing the object in the provider +cannot preserve native direct-eval scope and the unforgeable-source guarantee. + +A separate engine/provider follow-up should cover: + +1. A native branded object with a traced primitive-string payload, correct + finalization, and no inherited or Proxy-forwarded brand lookup. +2. Unwrapping only that brand inside the direct/indirect eval engine path, + preserving its caller frame, lexical scope, strictness, and eval mode. +3. Receiving-realm dynamic-code-generation policy. QuickJS currently ignores + `create_realm`'s code-generation flags, so equivalent policy enforcement + needs engine support too; it must not silently claim V8's restriction. +4. A deliberate Function-constructor contract, including its ordinary argument + coercion, with no stronger guarantee than is implemented. +5. Forgery, prototype mutation, proxies, cross-realm scope/policy, termination, + GC, teardown, Unicode, and native/WASIX regression coverage. + +`is_executing_js` is a separate capability and is implemented in this PR. +Trusted scripts remain explicitly unsupported on QuickJS. This PR updates the +pinned fork to include the native execution-state query; it does not emulate +trusted scripts in the provider. + +## Validation of the realm adaptation + +The primary runner is `tests/runners/test_79_unofficial_trusted_script.cc`: +23 V8 cases and seven QuickJS cases (six execution-state cases and one +unsupported trusted-script case). Original direct-eval and brand +checks are retained. The new realm coverage includes callback-creation realm, +receiving-realm lexical scope and policy, realm collection, security-token +boundaries, entered-but-idle realms, termination, cleanup hooks, and Function's +coercion limitation. The deprecated context-token hook callback is still +checked through `create_realm`; other tests use the explicit realm APIs. + +`tests/programs/test_trusted_script.c` drives both helpers and the realm +imports natively and through WASIX, including pointer bounds, code generation, +and cross-realm direct eval. `tests/programs/test_execution_state.c` separately +checks the query without +requiring trusted-script support, including native callbacks, promise jobs, +cross-realm execution and pending exceptions. The QuickJS fork also runs its +focused `api-test --is-executing-js` regression through `make test` in CI, including +C-function variants, builtins, coroutine suspension, nested job errors, runtime isolation +and interruption. A wasm-bindgen test instantiates a WAT guest to +check real host-JS import dispatch, unsupported statuses, output zeroing, +and the different u32/bool pointer bounds. + +Recorded macOS arm64 results and remaining limitations are reported in the +PR description. The V8 package is named 11.9.9; its headers report V8 +13.6.233.17. No EdgeJS or WebkitWasm application build is claimed by these +provider/guest tests, and no execution-query performance improvement is claimed: +the V8 query still captures a stack trace on each call. + +The QuickJS execution-query follow-up uses fork revision `883881a` from +[QuickJS PR #11](https://github.com/wasmerio/quickjs/pull/11). Local macOS arm64 +validation passed the complete Release suites (313 QuickJS and 379 V8 tests), +the engine's focused regression in Release and Debug with ASan + UBSan, and its +bundled conformance run (0/120 errors, 10 excluded). The standalone execution-state +program passes against native QuickJS, native V8, and as WASIX through the V8 +CLI. All seven QuickJS feature cases pass with the combined sanitizers. + +The broader QuickJS Debug + ASan + UBSan suite has 309 passes and four failures. +All four reproduce on the unchanged `317ed89` PR head with QuickJS `870aa7b`: +`ErrorMetadataSnapshotConsumesPreservedStateAtomically` and the two +`ModuleStateIsOneAtomicSnapshot` cases trigger UBSan on intentionally invalid +enum value 99; `RecursionThroughRealms` exceeds the Debug sanitizer stack limit. +These results do not claim a clean full Debug sanitizer suite. Sanitizer runs +use `ASAN_OPTIONS=detect_leaks=0` and `UBSAN_OPTIONS=halt_on_error=1`. diff --git a/include/unofficial_napi.h b/include/unofficial_napi.h index 13304b20e..fe50990eb 100644 --- a/include/unofficial_napi.h +++ b/include/unofficial_napi.h @@ -646,6 +646,45 @@ NAPI_EXTENSION_WASMER_EXTERN napi_status unofficial_napi_terminate_execution(nap // V8 drops the remaining microtasks when a running microtask is terminated. NAPI_EXTENSION_WASMER_EXTERN napi_status unofficial_napi_cancel_terminate_execution(napi_env env); +// Provider intrinsic trusted source. V8 evaluates it through its native code +// generation hook: direct eval retains lexical scope and never calls author +// toString/@@toPrimitive. Its private brand survives prototype changes, cannot +// be copied, inherited or recreated (unofficial_napi_create_private_symbol +// cannot name it), and does not bypass a context's codegen restriction. +// Creation acts in the current N-API realm: both the object and its native +// default toString belong to that realm. No explicit realm argument is needed. +// Eval uses its caller's lexical scope and the receiving realm's codegen +// restriction, even when the trusted source was made in another realm. +// Function(trusted) uses ordinary string coercion; only eval's source lookup +// bypasses author toString/@@toPrimitive. The default native toString enables +// Function(trusted) but is not a hardened Function-constructor integration. +// Source must be a primitive string. While terminating, V8 refuses creation +// with napi_pending_exception. Creation and the query below remain usable +// during cleanup hooks while the env and its agent are still live. +// QuickJS and host-JS are unsupported: they return napi_generic_failure and +// zero the output. QuickJS support needs a native direct-eval engine hook. +// The hook is isolate-wide: the first call on an isolate installs this +// provider's ModifyCodeGenerationFromStrings callback, replacing any callback +// the embedder installed. V8 cannot report the previous callback, so it is not +// chained. A callback the embedder installs afterwards is kept, and trusted +// scripts then follow that callback instead. For other values the hook keeps +// V8's behavior: eval returns non-string objects unchanged, and strings follow +// each context's code generation setting. +NAPI_EXTENSION_WASMER_EXTERN napi_status unofficial_napi_create_trusted_script( + napi_env env, napi_value source, napi_value* result); +// Owning VM thread only. Reports true only while the VM has a JavaScript frame +// on its stack (in any context, including other security origins) or is +// running a microtask checkpoint (V8) or job (QuickJS). A native function called +// from C through napi_call_function, directly or through a builtin, with no JavaScript frame +// below it reports false. Does not execute JS, take provider locks, or replace +// an existing pending exception, so it may be called from any provider +// callback, including during termination. It covers the agent's realms; +// entering a realm alone does not count as executing JavaScript. Unsupported +// engines return napi_generic_failure with *result set to false. V8 and +// QuickJS support this query; host JS does not expose native execution state. +NAPI_EXTENSION_WASMER_EXTERN napi_status unofficial_napi_is_executing_js( + napi_env env, bool* result); + typedef void (*unofficial_napi_interrupt_callback)(napi_env env, void* data); // Unofficial helper. Requests execution of a callback on the target env's diff --git a/quickjs/deps/quickjs b/quickjs/deps/quickjs index 870aa7b60..883881a05 160000 --- a/quickjs/deps/quickjs +++ b/quickjs/deps/quickjs @@ -1 +1 @@ -Subproject commit 870aa7b604792cf38c597e9f8d57c19b3c05afea +Subproject commit 883881a05961afa8b807ffdcdf20b76cdd496230 diff --git a/quickjs/src/unofficial_napi.cc b/quickjs/src/unofficial_napi.cc index c72c99d2d..7fcb064da 100644 --- a/quickjs/src/unofficial_napi.cc +++ b/quickjs/src/unofficial_napi.cc @@ -513,6 +513,21 @@ extern "C" return napi_ok; } + napi_status NAPI_CDECL unofficial_napi_create_trusted_script( + napi_env env, napi_value, napi_value* result) + { + if (!napi_util__::check_env(env) || result == nullptr) return napi_invalid_arg; + *result = nullptr; + return napi_generic_failure; + } + + napi_status NAPI_CDECL unofficial_napi_is_executing_js(napi_env env, bool* result) + { + if (!napi_util__::check_env(env) || result == nullptr) return napi_invalid_arg; + *result = JS_IsExecutingJS(napi_util__::runtime(env)); + return napi_ok; + } + napi_status NAPI_CDECL unofficial_napi_enqueue_microtask(napi_env env, napi_value callback) { if (!napi_util__::check_env(env) || !napi_util__::is_callable(env, callback)) diff --git a/src/guest/napi.rs b/src/guest/napi.rs index d17adced5..a564874cc 100644 --- a/src/guest/napi.rs +++ b/src/guest/napi.rs @@ -717,6 +717,42 @@ fn guest_unofficial_napi_message_drop(_env: FunctionEnvMut, payload: u3 unsafe { snapi_bridge_unofficial_message_drop(payload) }; } +fn guest_unofficial_napi_create_trusted_script( + mut env: FunctionEnvMut, + napi_env: u32, + source: u32, + result_ptr: u32, +) -> i32 { + if result_ptr == 0 || !write_guest_u32(&mut env, result_ptr, 0) { + return 1; + } + let mut result = 0; + let handle = snapi_env(&env, napi_env); + let status = + unsafe { snapi_bridge_unofficial_create_trusted_script(handle, source, &mut result) }; + if status == 0 && !write_guest_u32(&mut env, result_ptr, result) { + return 1; + } + status +} + +fn guest_unofficial_napi_is_executing_js( + mut env: FunctionEnvMut, + napi_env: u32, + result_ptr: u32, +) -> i32 { + if result_ptr == 0 || !write_guest_u8(&mut env, result_ptr, 0) { + return 1; + } + let mut result = 0; + let handle = snapi_env(&env, napi_env); + let status = unsafe { snapi_bridge_unofficial_is_executing_js(handle, &mut result) }; + if status == 0 && !write_guest_u8(&mut env, result_ptr, (result != 0) as u8) { + return 1; + } + status +} + fn guest_unofficial_napi_enqueue_microtask( env: FunctionEnvMut, napi_env: u32, @@ -5112,6 +5148,8 @@ pub fn register_napi_imports( "unofficial_napi_message_create" => Function::new_typed_with_env(store, fe, guest_unofficial_napi_message_create), "unofficial_napi_message_take" => Function::new_typed_with_env(store, fe, guest_unofficial_napi_message_take), "unofficial_napi_message_drop" => Function::new_typed_with_env(store, fe, guest_unofficial_napi_message_drop), + "unofficial_napi_create_trusted_script" => Function::new_typed_with_env(store, fe, guest_unofficial_napi_create_trusted_script), + "unofficial_napi_is_executing_js" => Function::new_typed_with_env(store, fe, guest_unofficial_napi_is_executing_js), "unofficial_napi_enqueue_microtask" => Function::new_typed_with_env(store, fe, guest_unofficial_napi_enqueue_microtask), "unofficial_napi_set_promise_reject_callback" => Function::new_typed_with_env(store, fe, guest_unofficial_napi_set_promise_reject_callback), "unofficial_napi_get_own_non_index_properties" => Function::new_typed_with_env(store, fe, guest_unofficial_napi_get_own_non_index_properties), diff --git a/src/guest/napi_js.rs b/src/guest/napi_js.rs index 8619a5ea9..37b3030ce 100644 --- a/src/guest/napi_js.rs +++ b/src/guest/napi_js.rs @@ -1155,6 +1155,29 @@ fn guest_unofficial_napi_message_drop(_env: FunctionEnvMut, payload: u3 unsafe { snapi_bridge_unofficial_message_drop(payload) }; } +fn guest_unofficial_napi_create_trusted_script( + mut env: FunctionEnvMut, + _napi_env: u32, + _source: u32, + result_ptr: u32, +) -> i32 { + if result_ptr == 0 || !write_guest_u32(&mut env, result_ptr, 0) { + return 1; + } + 9 // No native direct-eval brand on ordinary host JS objects. +} + +fn guest_unofficial_napi_is_executing_js( + mut env: FunctionEnvMut, + _napi_env: u32, + result_ptr: u32, +) -> i32 { + if result_ptr == 0 || !write_guest_u8(&mut env, result_ptr, 0) { + return 1; + } + 9 // Never infer VM stack emptiness from JS adapter bookkeeping. +} + fn guest_unofficial_napi_enqueue_microtask( env: FunctionEnvMut, napi_env: u32, @@ -5885,6 +5908,8 @@ pub fn register_napi_imports( "unofficial_napi_message_create" => Function::new_typed_with_env(store, fe, guest_unofficial_napi_message_create), "unofficial_napi_message_take" => message_take_import(store, fe), "unofficial_napi_message_drop" => Function::new_typed_with_env(store, fe, guest_unofficial_napi_message_drop), + "unofficial_napi_create_trusted_script" => Function::new_typed_with_env(store, fe, guest_unofficial_napi_create_trusted_script), + "unofficial_napi_is_executing_js" => Function::new_typed_with_env(store, fe, guest_unofficial_napi_is_executing_js), "unofficial_napi_enqueue_microtask" => Function::new_typed_with_env(store, fe, guest_unofficial_napi_enqueue_microtask), "unofficial_napi_set_promise_reject_callback" => Function::new_typed_with_env(store, fe, guest_unofficial_napi_set_promise_reject_callback), "unofficial_napi_get_own_non_index_properties" => Function::new_typed_with_env(store, fe, guest_unofficial_napi_get_own_non_index_properties), diff --git a/src/napi_bridge_init.cc b/src/napi_bridge_init.cc index 9387b598a..bc13336dc 100644 --- a/src/napi_bridge_init.cc +++ b/src/napi_bridge_init.cc @@ -3626,6 +3626,29 @@ extern "C" int snapi_bridge_unofficial_request_interrupt(SnapiEnvState* env_stat return s; } +extern "C" int snapi_bridge_unofficial_create_trusted_script( + SnapiEnvState* state, uint32_t source_id, uint32_t* result_out) { + auto* bridge = RequireEnvState(state); + if (bridge == nullptr || result_out == nullptr) return napi_invalid_arg; + *result_out = 0; + napi_value source = LoadValue(*bridge, source_id), result = nullptr; + if (source == nullptr) return napi_invalid_arg; + auto status = unofficial_napi_create_trusted_script(bridge->env, source, &result); + if (status != napi_ok) return status; + *result_out = StoreValue(*bridge, result); + return *result_out ? napi_ok : napi_generic_failure; +} + +extern "C" int snapi_bridge_unofficial_is_executing_js(SnapiEnvState* state, int* result_out) { + auto* bridge = RequireEnvState(state); + if (bridge == nullptr || result_out == nullptr) return napi_invalid_arg; + *result_out = 0; + bool result = false; + auto status = unofficial_napi_is_executing_js(bridge->env, &result); + if (status == napi_ok) *result_out = result; + return status; +} + extern "C" int snapi_bridge_unofficial_enqueue_microtask(SnapiEnvState* env_state, uint32_t callback_id) { auto* bridge_state = RequireEnvState(env_state); diff --git a/src/snapi.rs b/src/snapi.rs index c72d54482..77b626dff 100644 --- a/src/snapi.rs +++ b/src/snapi.rs @@ -198,6 +198,14 @@ unsafe extern "C" { pub fn snapi_bridge_unofficial_retain_env(env: SnapiEnv); #[cfg(not(all(target_arch = "wasm32", feature = "js")))] pub fn snapi_bridge_unofficial_unretain_env(env: SnapiEnv); + #[cfg(not(all(target_arch = "wasm32", feature = "js")))] + pub fn snapi_bridge_unofficial_create_trusted_script( + env: SnapiEnv, + source_id: u32, + result_out: *mut u32, + ) -> i32; + #[cfg(not(all(target_arch = "wasm32", feature = "js")))] + pub fn snapi_bridge_unofficial_is_executing_js(env: SnapiEnv, result_out: *mut i32) -> i32; pub fn snapi_bridge_unofficial_enqueue_microtask(env: SnapiEnv, callback_id: u32) -> i32; pub fn snapi_bridge_unofficial_set_promise_reject_callback( env: SnapiEnv, @@ -307,8 +315,11 @@ unsafe extern "C" { realm_out: *mut u32, global_out: *mut u32, ) -> i32; - pub fn snapi_bridge_unofficial_get_realm(env: SnapiEnv, value_id: u32, realm_out: *mut u32) - -> i32; + pub fn snapi_bridge_unofficial_get_realm( + env: SnapiEnv, + value_id: u32, + realm_out: *mut u32, + ) -> i32; // Makes the realm `realm_id` (0: the env's own) current until // snapi_bridge_unofficial_leave_realm closes the scope written to // `scope_out`, as unofficial_napi_enter_realm does. diff --git a/src/snapi_js.rs b/src/snapi_js.rs index cd78544fb..fb141f04e 100644 --- a/src/snapi_js.rs +++ b/src/snapi_js.rs @@ -8037,8 +8037,9 @@ mod tests { Object.defineProperty(f, Symbol.hasInstance, { value() { throw new Error('hasInstance'); } }); \ return f; })()", )); - let throwing_ctor = - state.agent.insert(make("(function () { throw new Error('construct'); })")); + let throwing_ctor = state + .agent + .insert(make("(function () { throw new Error('construct'); })")); let revoked = state.agent.insert(make( "(() => { const { proxy, revoke } = Proxy.revocable([], {}); revoke(); return proxy; })()", )); @@ -8453,18 +8454,36 @@ mod tests { let script = state.agent.insert_primitive(source.into()); let mut out = 0; let status = unsafe { - snapi_bridge_unofficial_run_script(env, realm, script, 0, 0, 0, 0, -1, 1, 0, 0, 0, &mut out) + snapi_bridge_unofficial_run_script( + env, realm, script, 0, 0, 0, 0, -1, 1, 0, 0, 0, &mut out, + ) }; if status != NAPI_OK { return Err(status); } - Ok(unsafe { env_mut(env) }.unwrap().agent.get(out).unwrap().clone()) + Ok(unsafe { env_mut(env) } + .unwrap() + .agent + .get(out) + .unwrap() + .clone()) } fn new_realm(env: SnapiEnv, sandbox: u32) -> Result { let (mut realm, mut global) = (0, 0); let status = unsafe { - snapi_bridge_unofficial_create_realm(env, sandbox, 0, 0, 0, 1, 1, 0, &mut realm, &mut global) + snapi_bridge_unofficial_create_realm( + env, + sandbox, + 0, + 0, + 0, + 1, + 1, + 0, + &mut realm, + &mut global, + ) }; if status != NAPI_OK { return Err(status); @@ -8514,7 +8533,10 @@ mod tests { assert_eq!(realm_of(env, number), Err(NAPI_OBJECT_EXPECTED)); assert_eq!(run_in(env, other, "1").unwrap_err(), NAPI_INVALID_ARG); let mut env_global = 0; - assert_eq!(unsafe { snapi_bridge_get_global(env, &mut env_global) }, NAPI_OK); + assert_eq!( + unsafe { snapi_bridge_get_global(env, &mut env_global) }, + NAPI_OK + ); assert_eq!(realm_of(env, env_global), Ok(0)); // It may still be a sandbox, as with vm.createContext(globalThis), // and the env keeps evaluating in its own context. @@ -8560,7 +8582,17 @@ mod tests { assert_eq!( unsafe { snapi_bridge_unofficial_compile_function( - env, realm, body, 0, 0, 0, 0, 0, 0, 0, &mut compiled, + env, + realm, + body, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + &mut compiled, ) }, NAPI_OK @@ -8570,7 +8602,10 @@ mod tests { Reflect::get(state.agent.get(compiled).unwrap(), &"function".into()) .unwrap() .unchecked_into(); - assert_eq!(function.call0(&JsValue::UNDEFINED).unwrap().as_f64(), Some(10.0)); + assert_eq!( + function.call0(&JsValue::UNDEFINED).unwrap().as_f64(), + Some(10.0) + ); let source = state.agent.insert_primitive("x".into()); let open = |realm_id: u32, out: &mut u32| { @@ -8998,6 +9033,88 @@ mod tests { assert_eq!(wasm_bindgen::externref_heap_live_count(), before); } + /// Unsupported trusted-script imports still validate guest pointers and + /// zero their outputs. Exercise real Wasmer dispatch, not adapter inference. + #[wasm_bindgen_test] + fn guest_trusted_script_imports_report_unsupported_and_validate_outputs() { + use wasmer::{FunctionEnv, Imports, Instance, Memory, MemoryType, Module, Store}; + let mut store = Store::default(); + let memory = Memory::new(&mut store, MemoryType::new(1, None, false)).unwrap(); + let env = new_env(); + let mut napi_env = crate::env::NapiEnv::new( + crate::budget::ResourceBudget::unlimited(), + None, + std::sync::Arc::default(), + std::sync::Arc::default(), + ); + napi_env.memory = Some(memory.clone()); + let (guest_env, _) = napi_env.register_napi_env(env); + let fe = FunctionEnv::new(&mut store, napi_env); + let mut imports = Imports::new(); + crate::guest::napi::register_napi_imports(&mut store, &fe, &mut imports); + imports.define("env", "memory", memory.clone()); + let module = Module::new( + &store, + wat::parse_str( + r#"(module + (import "env" "memory" (memory 1)) + (import "napi_extension_wasmer_v0" "unofficial_napi_create_trusted_script" + (func $create (param i32 i32 i32) (result i32))) + (import "napi_extension_wasmer_v0" "unofficial_napi_is_executing_js" + (func $executing (param i32 i32) (result i32))) + (func (export "create") (param i32 i32) (result i32) + (call $create (local.get 0) (i32.const 0) (local.get 1))) + (func (export "executing") (param i32 i32) (result i32) + (call $executing (local.get 0) (local.get 1))))"#, + ) + .unwrap(), + ) + .unwrap(); + let instance = Instance::new(&mut store, &module, &imports).unwrap(); + let create = instance + .exports + .get_typed_function::<(u32, u32), i32>(&store, "create") + .unwrap(); + let executing = instance + .exports + .get_typed_function::<(u32, u32), i32>(&store, "executing") + .unwrap(); + memory.view(&store).write(64, &[0x7f; 4]).unwrap(); + assert_eq!( + create.call(&mut store, guest_env, 64).unwrap(), + NAPI_GENERIC_FAILURE + ); + let mut out = [0xff; 4]; + memory.view(&store).read(64, &mut out).unwrap(); + assert_eq!(out, [0; 4]); + memory.view(&store).write(64, &[0x7f]).unwrap(); + assert_eq!( + executing.call(&mut store, guest_env, 64).unwrap(), + NAPI_GENERIC_FAILURE + ); + memory.view(&store).read(64, &mut out[..1]).unwrap(); + assert_eq!(out[0], 0); + for pointer in [0, 65536, u32::MAX] { + assert_eq!( + create.call(&mut store, guest_env, pointer).unwrap(), + NAPI_INVALID_ARG + ); + assert_eq!( + executing.call(&mut store, guest_env, pointer).unwrap(), + NAPI_INVALID_ARG + ); + } + // A u32 result needs four bytes; the bool result needs only one. + assert_eq!( + create.call(&mut store, guest_env, 65535).unwrap(), + NAPI_INVALID_ARG + ); + assert_eq!( + executing.call(&mut store, guest_env, 65535).unwrap(), + NAPI_GENERIC_FAILURE + ); + } + /// A guest that uses the realm imports as a C guest does: the scope token /// comes back through its memory as a u64 and goes out again as an i64. const REALM_GUEST: &str = r#" diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 8da65708c..9e2db8693 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -347,6 +347,10 @@ add_fixture_test(${_napi_test_prefix}_test_78_termination_until_cancelled runners/test_78_termination_until_cancelled.cc ) target_compile_definitions(${_napi_test_prefix}_test_78_termination_until_cancelled PRIVATE NAPI_VERSION=10) +add_fixture_test(${_napi_test_prefix}_test_79_unofficial_trusted_script + runners/test_79_unofficial_trusted_script.cc +) + add_fixture_test(${_napi_test_prefix}_test_77_module_wrap_state runners/test_77_module_wrap_state.cc ) diff --git a/tests/programs/manifest.json b/tests/programs/manifest.json index d3565a703..6eeb4f859 100644 --- a/tests/programs/manifest.json +++ b/tests/programs/manifest.json @@ -189,6 +189,16 @@ "name": "test_realm", "description": "Realms: own globals, shared values, native functions in the env's realm, get_realm, sandbox realms, scripts, functions, modules and bytecode in a realm, entering a realm, collection of dropped realms, release with live realms", "expected_stdout": "realm has its own global\nvalues cross realms: x=7\nnative function stays in the env's realm\nget_realm finds the realm by its global\nsandbox realm: input=5 output=10\nvm results: run=4 function=30 module=5 bytecode=6\nentered realm: its global, objects and functions\ncollected 6 of 6 dropped realms\nreleased an env with live realms\nTEST_REALM_OK=1\n" + }, + { + "name": "test_execution_state", + "description": "Execution-state query through guest imports: native callbacks, promise jobs, cross-realm calls and pending exceptions", + "expected_stdout": "TEST_EXECUTION_STATE_OK=1\n" + }, + { + "name": "test_trusted_script", + "description": "unofficial_napi_create_trusted_script and unofficial_napi_is_executing_js through the guest imports", + "expected_stdout": "TEST_TRUSTED_SCRIPT_OK=1\n" } ] } diff --git a/tests/programs/test_execution_state.c b/tests/programs/test_execution_state.c new file mode 100644 index 000000000..79bd1fd86 --- /dev/null +++ b/tests/programs/test_execution_state.c @@ -0,0 +1,87 @@ +// Exercise the execution-state import without depending on trusted scripts. +#include +#include + +#include "napi_test_helpers.h" +#include "unofficial_napi.h" + +static napi_value Executing(napi_env env, napi_callback_info info) { + (void)info; + bool active = false; + napi_value result = NULL; + if (unofficial_napi_is_executing_js(env, &active) != napi_ok || + napi_get_boolean(env, active, &result) != napi_ok) return NULL; + return result; +} + +static bool ScriptIsTrue(napi_env env, const char* text) { + napi_value source = NULL, result = NULL; + bool value = false; + return napi_create_string_utf8(env, text, NAPI_AUTO_LENGTH, &source) == napi_ok && + napi_run_script(env, source, &result) == napi_ok && + napi_get_value_bool(env, result, &value) == napi_ok && value; +} + +int main(void) { + napi_env env = napi_wasm_init_env(); + CHECK_OR_FAIL(env != NULL, "env is initialized"); + bool active = true; + NAPI_CALL(env, unofficial_napi_is_executing_js(env, &active)); + CHECK_OR_FAIL(!active, "idle C entry reports false"); + CHECK_OR_FAIL(unofficial_napi_is_executing_js(env, NULL) == napi_invalid_arg, + "null result pointer is rejected"); +#ifdef __wasm__ + CHECK_OR_FAIL(unofficial_napi_is_executing_js( + env, (bool*)(uintptr_t)0xffffffffu) == napi_invalid_arg, + "out-of-bounds result pointer is rejected"); +#endif + + napi_value global = NULL, callback = NULL, result = NULL; + NAPI_CALL(env, napi_get_global(env, &global)); + NAPI_CALL(env, napi_create_function(env, "executing", NAPI_AUTO_LENGTH, + Executing, NULL, &callback)); + NAPI_CALL(env, napi_set_named_property(env, global, "executing", callback)); + CHECK_OR_FAIL(ScriptIsTrue(env, "executing() === true"), + "JavaScript caller reports true"); + NAPI_CALL(env, napi_call_function(env, global, callback, 0, NULL, &result)); + NAPI_CALL(env, napi_get_value_bool(env, result, &active)); + CHECK_OR_FAIL(!active, "direct C-to-native call reports false"); + + CHECK_OR_FAIL(ScriptIsTrue(env, + "globalThis.jobActive = false; " + "Promise.resolve().then(executing).then(value => jobActive = value); true"), + "promise jobs are queued"); + NAPI_CALL(env, unofficial_napi_event_loop_checkpoint( + env, unofficial_napi_event_loop_checkpoint_microtasks, false, NULL)); + CHECK_OR_FAIL(ScriptIsTrue(env, "jobActive === true"), + "native promise callback reports true"); + + unofficial_napi_realm_options options; + unofficial_napi_realm_options_init(&options); + unofficial_napi_realm realm = NULL; + napi_value realm_global = NULL; + NAPI_CALL(env, unofficial_napi_create_realm(env, &options, &realm, &realm_global)); + NAPI_CALL(env, napi_set_named_property(env, realm_global, "executing", callback)); + unofficial_napi_realm_scope scope = 0; + NAPI_CALL(env, unofficial_napi_enter_realm(env, realm, &scope)); + NAPI_CALL(env, unofficial_napi_is_executing_js(env, &active)); + CHECK_OR_FAIL(!active, "entering a realm alone reports false"); + CHECK_OR_FAIL(ScriptIsTrue(env, "executing() === true"), + "callback sees JavaScript in another realm"); + NAPI_CALL(env, unofficial_napi_leave_realm(env, scope)); + + napi_value source = NULL, exception = NULL; + NAPI_CALL(env, napi_create_string_utf8(env, "throw 42", NAPI_AUTO_LENGTH, &source)); + CHECK_OR_FAIL(napi_run_script(env, source, &result) == napi_pending_exception, + "script throws"); + NAPI_CALL(env, unofficial_napi_is_executing_js(env, &active)); + CHECK_OR_FAIL(!active, "throwing script has unwound"); + bool pending = false; + NAPI_CALL(env, napi_is_exception_pending(env, &pending)); + CHECK_OR_FAIL(pending, "query preserves pending exception"); + NAPI_CALL(env, napi_get_and_clear_last_exception(env, &exception)); + int32_t thrown = 0; + NAPI_CALL(env, napi_get_value_int32(env, exception, &thrown)); + CHECK_OR_FAIL(thrown == 42, "query preserves exception value"); + return PrintSuccess("TEST_EXECUTION_STATE"); +} diff --git a/tests/programs/test_trusted_script.c b/tests/programs/test_trusted_script.c new file mode 100644 index 000000000..caf6101fd --- /dev/null +++ b/tests/programs/test_trusted_script.c @@ -0,0 +1,154 @@ +// unofficial_napi_create_trusted_script and unofficial_napi_is_executing_js +// through the guest imports. +#include +#include +#include + +#include "napi_test_helpers.h" +#include "unofficial_napi.h" + +static napi_value MakeTrusted(napi_env env, napi_callback_info info) { + size_t argc = 1; + napi_value source = NULL; + napi_value result = NULL; + if (napi_get_cb_info(env, info, &argc, &source, NULL, NULL) != napi_ok || + argc != 1 || + unofficial_napi_create_trusted_script(env, source, &result) != napi_ok) { + napi_throw_type_error(env, NULL, "Expected a primitive string"); + return NULL; + } + return result; +} + +static napi_value Executing(napi_env env, napi_callback_info info) { + (void)info; + bool active = false; + napi_value result = NULL; + if (unofficial_napi_is_executing_js(env, &active) != napi_ok || + napi_get_boolean(env, active, &result) != napi_ok) { + return NULL; + } + return result; +} + +static bool ScriptIsTrue(napi_env env, const char* code) { + napi_value script = NULL; + napi_value result = NULL; + bool value = false; + if (napi_create_string_utf8(env, code, NAPI_AUTO_LENGTH, &script) != + napi_ok || + napi_run_script(env, script, &result) != napi_ok || + napi_get_value_bool(env, result, &value) != napi_ok) { + bool pending = false; + napi_value exception = NULL; + if (napi_is_exception_pending(env, &pending) == napi_ok && pending) { + napi_get_and_clear_last_exception(env, &exception); + } + return false; + } + return value; +} + +int main(void) { + napi_env env = napi_wasm_init_env(); + CHECK_OR_FAIL(env != NULL, "napi_wasm_init_env returned NULL"); + + napi_value global = NULL; + napi_value function = NULL; + NAPI_CALL(env, napi_get_global(env, &global)); + NAPI_CALL(env, napi_create_function(env, "makeTrusted", NAPI_AUTO_LENGTH, + MakeTrusted, NULL, &function)); + NAPI_CALL(env, napi_set_named_property(env, global, "makeTrusted", function)); + NAPI_CALL(env, napi_create_function(env, "executing", NAPI_AUTO_LENGTH, + Executing, NULL, &function)); + NAPI_CALL(env, napi_set_named_property(env, global, "executing", function)); + + bool active = true; + NAPI_CALL(env, unofficial_napi_is_executing_js(env, &active)); + CHECK_OR_FAIL(!active, "no JavaScript is executing at top level"); + CHECK_OR_FAIL(ScriptIsTrue(env, "executing() === true"), + "a native callback runs inside JavaScript"); + + CHECK_OR_FAIL( + ScriptIsTrue(env, "(() => { let lexical = 40; " + "return eval(makeTrusted('lexical + 2')) === 42; })()"), + "direct eval of a trusted script keeps lexical scope"); + CHECK_OR_FAIL( + ScriptIsTrue(env, "(() => { let lexical = 23; " + "const source = makeTrusted('lexical'); " + "source.toString = () => { throw 1; }; " + "return eval(source) === 23; })()"), + "direct eval ignores an author toString"); + CHECK_OR_FAIL( + ScriptIsTrue(env, "(() => { const copy = Object.create(makeTrusted('1')); " + "return eval(copy) === copy; })()"), + "the brand is not inherited"); + + // Argument validation. + napi_value number = NULL; + napi_value source = NULL; + napi_value result = NULL; + NAPI_CALL(env, napi_create_uint32(env, 1, &number)); + NAPI_CALL(env, napi_create_string_utf8(env, "1", NAPI_AUTO_LENGTH, &source)); + result = number; + CHECK_OR_FAIL(unofficial_napi_create_trusted_script(env, number, &result) == + napi_string_expected && + result == NULL, + "a non-string source is rejected"); + CHECK_OR_FAIL(unofficial_napi_create_trusted_script(env, source, NULL) == + napi_invalid_arg, + "null result pointer is rejected"); + CHECK_OR_FAIL(unofficial_napi_is_executing_js(env, NULL) == napi_invalid_arg, + "null result pointer is rejected"); +#ifdef __wasm__ + // Results outside guest memory fail with napi_invalid_arg. + CHECK_OR_FAIL(unofficial_napi_create_trusted_script( + env, source, (napi_value*)(uintptr_t)0xfffffffeu) == + napi_invalid_arg, + "out-of-bounds result pointer is rejected"); + CHECK_OR_FAIL(unofficial_napi_is_executing_js( + env, (bool*)(uintptr_t)0xffffffffu) == napi_invalid_arg, + "out-of-bounds result pointer is rejected"); +#endif + + NAPI_CALL(env, unofficial_napi_create_trusted_script(env, source, &result)); + napi_valuetype type = napi_undefined; + NAPI_CALL(env, napi_typeof(env, result, &type)); + CHECK_OR_FAIL(type == napi_object, "a trusted script is an object"); + + // Drive the realm imports too: creation uses the entered realm while eval + // uses the receiving caller's lexical scope and code-generation policy. + unofficial_napi_realm_options realm_options; + unofficial_napi_realm_options_init(&realm_options); + unofficial_napi_realm a = NULL, restricted = NULL; + napi_value a_global = NULL, restricted_global = NULL, trusted = NULL; + NAPI_CALL(env, unofficial_napi_create_realm(env, &realm_options, &a, &a_global)); + unofficial_napi_realm_scope realm_scope = 0; + NAPI_CALL(env, unofficial_napi_enter_realm(env, a, &realm_scope)); + NAPI_CALL(env, unofficial_napi_is_executing_js(env, &active)); + CHECK_OR_FAIL(!active, "entering a realm does not execute JavaScript"); + NAPI_CALL(env, napi_create_string_utf8(env, "lexical + 2", NAPI_AUTO_LENGTH, &source)); + NAPI_CALL(env, unofficial_napi_create_trusted_script(env, source, &trusted)); + NAPI_CALL(env, napi_set_named_property(env, a_global, "trusted", trusted)); + CHECK_OR_FAIL(ScriptIsTrue(env, + "Object.getPrototypeOf(Object.getPrototypeOf(trusted)) === Object.prototype"), + "trusted script is allocated in the current realm"); + CHECK_OR_FAIL(ScriptIsTrue(env, + "(() => {let lexical = 40; return eval(trusted) === 42;})()"), + "realm direct eval preserves lexical scope"); + NAPI_CALL(env, unofficial_napi_leave_realm(env, realm_scope)); + NAPI_CALL(env, napi_set_named_property(env, global, "fromOtherRealm", trusted)); + CHECK_OR_FAIL(ScriptIsTrue(env, + "(() => {let lexical = 21; return eval(fromOtherRealm) === 23;})()"), + "a trusted source from another realm uses the receiving lexical scope"); + realm_options.allow_code_gen_strings = false; + NAPI_CALL(env, unofficial_napi_create_realm(env, &realm_options, &restricted, &restricted_global)); + NAPI_CALL(env, napi_set_named_property(env, restricted_global, "trusted", trusted)); + NAPI_CALL(env, unofficial_napi_enter_realm(env, restricted, &realm_scope)); + CHECK_OR_FAIL(ScriptIsTrue(env, + "(() => {try {eval(trusted);} catch(e) {return e instanceof EvalError;} return false;})()"), + "trusted script respects the receiving realm's code-generation policy"); + NAPI_CALL(env, unofficial_napi_leave_realm(env, realm_scope)); + + return PrintSuccess("TEST_TRUSTED_SCRIPT"); +} diff --git a/tests/runners/test_79_unofficial_trusted_script.cc b/tests/runners/test_79_unofficial_trusted_script.cc new file mode 100644 index 000000000..42dccdb7b --- /dev/null +++ b/tests/runners/test_79_unofficial_trusted_script.cc @@ -0,0 +1,827 @@ +#ifdef NAPI_MODULE +#undef NAPI_MODULE +#endif +#include "node_api.h" + +#include "test_env.h" + +#include "unofficial_napi.h" + +#include + +#if defined(NAPI_TEST_ENGINE_V8) +#include +#endif + +// unofficial_napi_create_trusted_script and unofficial_napi_is_executing_js. +// Both native providers implement the query; trusted scripts require V8. +class Test79UnofficialTrustedScript : public FixtureTestBase {}; + +namespace { + +napi_value Str(napi_env env, const char* value) { + napi_value out = nullptr; + if (napi_create_string_utf8(env, value, NAPI_AUTO_LENGTH, &out) != napi_ok) return nullptr; + return out; +} + +struct MicrotaskRecord { + unsigned calls = 0; + unsigned active_calls = 0; +}; + +#if defined(NAPI_TEST_ENGINE_V8) +// makeTrusted(source) wraps a primitive string in a TrustedScript. +napi_value MakeTrusted(napi_env env, napi_callback_info info) { + size_t argc = 1; + napi_value source = nullptr; + napi_value result = nullptr; + if (napi_get_cb_info(env, info, &argc, &source, nullptr, nullptr) != napi_ok || argc != 1 || + unofficial_napi_create_trusted_script(env, source, &result) != napi_ok) { + napi_throw_type_error(env, nullptr, "Expected a primitive string"); + return nullptr; + } + return result; +} + +#endif + +// executing() reports unofficial_napi_is_executing_js. +napi_value Executing(napi_env env, napi_callback_info /*info*/) { + bool active = false; + napi_value result = nullptr; + if (unofficial_napi_is_executing_js(env, &active) != napi_ok || + napi_get_boolean(env, active, &result) != napi_ok) { + return nullptr; + } + return result; +} + +// A native function queued as a microtask runs with no JavaScript frame on +// the stack, so only the microtask checkpoint makes the VM count as active. +napi_value RecordMicrotask(napi_env env, napi_callback_info info) { + void* data = nullptr; + bool active = false; + if (napi_get_cb_info(env, info, nullptr, nullptr, nullptr, &data) != napi_ok || + unofficial_napi_is_executing_js(env, &active) != napi_ok) { + return nullptr; + } + auto* record = static_cast(data); + ++record->calls; + if (active) ++record->active_calls; + return nullptr; +} + +std::string TakeExceptionMessage(napi_env env) { + bool pending = false; + napi_value exception = nullptr; + napi_value message = nullptr; + if (napi_is_exception_pending(env, &pending) != napi_ok || !pending || + napi_get_and_clear_last_exception(env, &exception) != napi_ok) { + return ""; + } + char text[512] = {}; + size_t length = 0; + if (napi_coerce_to_string(env, exception, &message) != napi_ok || + napi_get_value_string_utf8(env, message, text, sizeof(text), &length) != napi_ok) { + return ""; + } + return std::string(text, length); +} + +// Evaluates a boolean expression in the root context. +::testing::AssertionResult IsTrue(napi_env env, const char* code) { + napi_value result = nullptr; + bool value = false; + if (napi_run_script(env, Str(env, code), &result) != napi_ok) { + return ::testing::AssertionFailure() << code << " threw " << TakeExceptionMessage(env); + } + if (napi_get_value_bool(env, result, &value) != napi_ok || !value) { + return ::testing::AssertionFailure() << code << " is not true"; + } + return ::testing::AssertionSuccess(); +} + +// Evaluates a boolean expression in an explicit realm. +::testing::AssertionResult IsTrueIn(napi_env env, + unofficial_napi_realm realm, + const char* code) { + const unofficial_napi_js_source source = unofficial_napi_js_source_from_text(Str(env, code)); + napi_value result = nullptr; + bool value = false; + if (unofficial_napi_run_script(env, + realm, + &source, + Str(env, "trusted-script.js"), + 0, + 0, + -1, + true, + false, + false, + nullptr, + &result) != napi_ok) { + return ::testing::AssertionFailure() << code << " threw " << TakeExceptionMessage(env); + } + if (napi_get_value_bool(env, result, &value) != napi_ok || !value) { + return ::testing::AssertionFailure() << code << " is not true"; + } + return ::testing::AssertionSuccess(); +} + +#if defined(NAPI_TEST_ENGINE_V8) +uint64_t UsedHeapAfterGc(napi_env env) { + for (int i = 0; i < 3; ++i) { + if (unofficial_napi_collect_garbage(env) != napi_ok) return 0; + } + unofficial_napi_heap_statistics stats; + unofficial_napi_heap_statistics_init(&stats); + if (unofficial_napi_get_heap_statistics(env, &stats) != napi_ok || + (stats.valid_fields & unofficial_napi_heap_stat_used_heap_size) == 0) { + return 0; + } + return stats.used_heap_size; +} + +unsigned g_embedder_hook_calls = 0; + +struct TokenCallbackRecord { + unsigned calls = 0; + napi_status status = napi_generic_failure; + bool active = true; +}; + +// Deprecated token hooks still run for new realms. The query remains safe +// from those hooks and does not infer JS execution from entering a realm. +void QueryFromTokenCallback(napi_env env, void* /*token*/, void* data) { + auto* record = static_cast(data); + ++record->calls; + record->status = unofficial_napi_is_executing_js(env, &record->active); +} + +// An embedder hook that leaves every source unchanged. +v8::ModifyCodeGenerationFromStringsResult EmbedderHook(v8::Local, + v8::Local, + bool) { + ++g_embedder_hook_calls; + v8::ModifyCodeGenerationFromStringsResult result; + result.codegen_allowed = true; + return result; +} + +#endif + +void InstallGlobal(napi_env env, const char* name, napi_callback callback, void* data) { + napi_value global = nullptr; + napi_value function = nullptr; + ASSERT_EQ(napi_get_global(env, &global), napi_ok); + ASSERT_EQ(napi_create_function(env, name, NAPI_AUTO_LENGTH, callback, data, &function), + napi_ok); + ASSERT_EQ(napi_set_named_property(env, global, name, function), napi_ok); +} + +} // namespace + +#if defined(NAPI_TEST_ENGINE_V8) +TEST_F(Test79UnofficialTrustedScript, DirectEvalKeepsLexicalScope) { + EnvScope s(runtime_.get()); + InstallGlobal(s.env, "makeTrusted", MakeTrusted, nullptr); + + EXPECT_TRUE(IsTrue(s.env, "(() => { let lexical = 40; " + "return eval(makeTrusted('lexical + 2')) === 42; })()")); + EXPECT_TRUE(IsTrue(s.env, "(() => { let lexical = 0; eval(makeTrusted('lexical = 17')); " + "return lexical === 17; })()")); + EXPECT_TRUE(IsTrue(s.env, "(function () { eval(makeTrusted('var trustedVar = 19')); " + "return trustedVar === 19; })()")); + EXPECT_TRUE(IsTrue(s.env, "(() => { const sentinel = {}; " + "try { eval(makeTrusted('throw sentinel')); } " + "catch (error) { return error === sentinel; } return false; })()")); + EXPECT_TRUE(IsTrue(s.env, "(() => { const original = eval; " + "return eval(makeTrusted('original === eval')) === true; })()")); + EXPECT_TRUE(IsTrue(s.env, "(() => { 'use strict'; let lexical = 3; " + "eval(makeTrusted('var strictVar = lexical')); " + "return typeof strictVar === 'undefined'; })()")); + // Indirect eval evaluates the source in global scope. + EXPECT_TRUE(IsTrue(s.env, "(() => { let lexical = 1; " + "return (0, eval)(makeTrusted('typeof lexical')) === 'undefined'; })()")); + EXPECT_TRUE(IsTrue(s.env, "eval(makeTrusted('')) === undefined")); + EXPECT_TRUE(IsTrue(s.env, "eval(makeTrusted('\"\\u{1F49C}\"')) === '\\u{1F49C}'")); + EXPECT_TRUE(IsTrue(s.env, "eval(Object.freeze(makeTrusted('31'))) === 31")); +} + +TEST_F(Test79UnofficialTrustedScript, SourceIgnoresAuthorStringConversion) { + EnvScope s(runtime_.get()); + InstallGlobal(s.env, "makeTrusted", MakeTrusted, nullptr); + + EXPECT_TRUE(IsTrue(s.env, "(() => { let lexical = 23; const source = makeTrusted('lexical'); " + "source.toString = () => { throw 1; }; " + "source[Symbol.toPrimitive] = () => { throw 2; }; " + "return eval(source) === 23; })()")); + EXPECT_TRUE(IsTrue(s.env, "(() => { let lexical = 29; const source = makeTrusted('lexical'); " + "Object.setPrototypeOf(source, { toString() { throw 1; } }); " + "return eval(source) === 29; })()")); + // The Function constructor stringifies its arguments. The default prototype + // stringifies to the source, and only for the brand; an embedder can replace + // the prototype with its own. + EXPECT_TRUE(IsTrue(s.env, "Function(makeTrusted('return 37'))() === 37")); + EXPECT_TRUE(IsTrue(s.env, "Function('input', makeTrusted('return input + 1'))(40) === 41")); + EXPECT_TRUE(IsTrue(s.env, "(() => { const source = makeTrusted('return 43'); " + "Object.setPrototypeOf(source, { toString() { return 'return 43'; } }); " + "return Function(source)() === 43; })()")); + EXPECT_TRUE(IsTrue(s.env, "String(makeTrusted('1 + 1')) === '1 + 1'")); + EXPECT_TRUE(IsTrue(s.env, "(() => { const toString = makeTrusted('').toString; " + "try { toString.call({}); } catch (error) { " + "return error instanceof TypeError; } return false; })()")); +} + +// Function converts arguments before V8's code-generation hook. Pin the +// limitation so a direct-eval guarantee is not mistaken for full Trusted Types. +TEST_F(Test79UnofficialTrustedScript, FunctionConstructorUsesOrdinaryAuthorCoercion) { + EnvScope s(runtime_.get()); + InstallGlobal(s.env, "makeTrusted", MakeTrusted, nullptr); + EXPECT_TRUE(IsTrue(s.env, "(() => {const t = makeTrusted('return 1'); t.toString = () => 'return 2'; return Function(t)() === 2;})()")); + EXPECT_TRUE(IsTrue(s.env, "(() => {const t = makeTrusted('return 1'); t[Symbol.toPrimitive] = () => 'return 3'; return Function(t)() === 3;})()")); +} + +TEST_F(Test79UnofficialTrustedScript, BrandCannotBeCopiedOrInherited) { + EnvScope s(runtime_.get()); + InstallGlobal(s.env, "makeTrusted", MakeTrusted, nullptr); + + EXPECT_TRUE(IsTrue(s.env, "(() => { const source = makeTrusted('throw 1'); " + "const child = Object.create(source); return eval(child) === child; })()")); + EXPECT_TRUE(IsTrue(s.env, "(() => { const source = makeTrusted('throw 1'); " + "const proxy = new Proxy(source, { get() { throw 2; } }); " + "return eval(proxy) === proxy; })()")); + EXPECT_TRUE(IsTrue(s.env, "(() => { const source = makeTrusted('throw 1'), copy = {}; " + "for (const key of Reflect.ownKeys(source)) " + "Object.defineProperty(copy, key, " + "Object.getOwnPropertyDescriptor(source, key)); " + "return Reflect.ownKeys(source).length === 0 && eval(copy) === copy; })()")); + // eval of anything else is unchanged: objects are returned without being + // stringified, and strings are evaluated. + EXPECT_TRUE(IsTrue(s.env, "(() => { const value = { toString() { throw 1; }, " + "[Symbol.toPrimitive]() { throw 2; } }; return eval(value) === value; })()")); + EXPECT_TRUE(IsTrue(s.env, "eval('6 * 7') === 42")); +} + +// The brand cannot be forged through the private-symbol API: a private symbol +// with the brand's old registry name names a different property. +TEST_F(Test79UnofficialTrustedScript, BrandCannotBeForgedWithPrivateSymbol) { + EnvScope s(runtime_.get()); + InstallGlobal(s.env, "makeTrusted", MakeTrusted, nullptr); + napi_value real = nullptr; + ASSERT_EQ(unofficial_napi_create_trusted_script(s.env, Str(s.env, "1"), &real), napi_ok); + + const char* names[] = {"wasmer.napi.intrinsic.TrustedScript.source.v1", "TrustedScript source"}; + for (const char* name : names) { + napi_value symbol = nullptr; + napi_value forged = nullptr; + napi_value global = nullptr; + ASSERT_EQ(unofficial_napi_create_private_symbol(s.env, name, NAPI_AUTO_LENGTH, &symbol), + napi_ok); + ASSERT_EQ(napi_create_object(s.env, &forged), napi_ok); + ASSERT_EQ(napi_set_property(s.env, forged, symbol, Str(s.env, "6 * 7")), napi_ok); + ASSERT_EQ(napi_get_global(s.env, &global), napi_ok); + ASSERT_EQ(napi_set_named_property(s.env, global, "forged", forged), napi_ok); + EXPECT_TRUE(IsTrue(s.env, "eval(forged) === forged")) << name; + // A real trusted script given the forged property is still its own source. + ASSERT_EQ(napi_set_property(s.env, real, symbol, Str(s.env, "6 * 7")), napi_ok); + ASSERT_EQ(napi_set_named_property(s.env, global, "real", real), napi_ok); + EXPECT_TRUE(IsTrue(s.env, "eval(real) === 1")) << name; + } +} + +// The isolate-wide hook is installed once. A hook the embedder installs +// afterwards is not overwritten by later trusted-script creation. +TEST_F(Test79UnofficialTrustedScript, KeepsEmbedderHookInstalledLater) { + EnvScope s(runtime_.get()); + InstallGlobal(s.env, "makeTrusted", MakeTrusted, nullptr); + EXPECT_TRUE(IsTrue(s.env, "eval(makeTrusted('2')) === 2")); + + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + ASSERT_NE(isolate, nullptr); + g_embedder_hook_calls = 0; + isolate->SetModifyCodeGenerationFromStringsCallback(EmbedderHook); + // Created after the embedder's hook: eval now follows that hook, which + // leaves the object unchanged. + EXPECT_TRUE(IsTrue(s.env, "(() => { const source = makeTrusted('3'); " + "return eval(source) === source; })()")); + EXPECT_GT(g_embedder_hook_calls, 0u); +} + +TEST_F(Test79UnofficialTrustedScript, CreateValidatesArguments) { + EnvScope s(runtime_.get()); + + napi_value number = nullptr; + napi_value object = nullptr; + napi_value result = Str(s.env, "sentinel"); + ASSERT_EQ(napi_create_uint32(s.env, 1, &number), napi_ok); + ASSERT_EQ(napi_run_script(s.env, Str(s.env, "new String('1')"), &object), napi_ok); + EXPECT_EQ(unofficial_napi_create_trusted_script(s.env, number, &result), napi_string_expected); + EXPECT_EQ(result, nullptr); + // A String object is not a primitive string and is never coerced. + EXPECT_EQ(unofficial_napi_create_trusted_script(s.env, object, &result), napi_string_expected); + EXPECT_EQ(unofficial_napi_create_trusted_script(s.env, Str(s.env, "1"), nullptr), + napi_invalid_arg); + EXPECT_EQ(unofficial_napi_create_trusted_script(s.env, nullptr, &result), napi_invalid_arg); + EXPECT_EQ(unofficial_napi_create_trusted_script(nullptr, Str(s.env, "1"), &result), + napi_invalid_arg); + + napi_value trusted = nullptr; + napi_valuetype type = napi_undefined; + ASSERT_EQ(unofficial_napi_create_trusted_script(s.env, Str(s.env, "1"), &trusted), napi_ok); + ASSERT_EQ(napi_typeof(s.env, trusted, &type), napi_ok); + EXPECT_EQ(type, napi_object); +} + +// Creating trusted scripts retains nothing once they are unreachable. A new +// template per call left every instantiation in the context's template cache +// (about 750 KB after 20k calls). +TEST_F(Test79UnofficialTrustedScript, CreationDoesNotRetainMemory) { + EnvScope s(runtime_.get()); + napi_value source = Str(s.env, "1"); + napi_value warm = nullptr; + ASSERT_EQ(unofficial_napi_create_trusted_script(s.env, source, &warm), napi_ok); + + const uint64_t before = UsedHeapAfterGc(s.env); + ASSERT_NE(before, 0u); + for (int i = 0; i < 20000; ++i) { + napi_handle_scope scope = nullptr; + napi_value trusted = nullptr; + ASSERT_EQ(napi_open_handle_scope(s.env, &scope), napi_ok); + ASSERT_EQ(unofficial_napi_create_trusted_script(s.env, source, &trusted), napi_ok); + ASSERT_EQ(napi_close_handle_scope(s.env, scope), napi_ok); + } + const uint64_t after = UsedHeapAfterGc(s.env); + ASSERT_NE(after, 0u); + EXPECT_LT(after, before + 128 * 1024); +} + +// A trusted script does not bypass a context that disallows code generation +// from strings, and eval of an unbranded object stays a no-op there. +TEST_F(Test79UnofficialTrustedScript, RespectsDisabledCodeGeneration) { + EnvScope s(runtime_.get()); + + napi_value sandbox = nullptr; + napi_value context = nullptr; + napi_value trusted = nullptr; + ASSERT_EQ(napi_create_object(s.env, &sandbox), napi_ok); + unofficial_napi_realm_options options; + unofficial_napi_realm_options_init(&options); + options.sandbox_or_null = sandbox; + options.allow_code_gen_strings = false; + unofficial_napi_realm realm = nullptr; + ASSERT_EQ(unofficial_napi_create_realm(s.env, &options, &realm, &context), napi_ok); + ASSERT_EQ(unofficial_napi_create_trusted_script(s.env, Str(s.env, "throw 1"), &trusted), + napi_ok); + ASSERT_EQ(napi_set_named_property(s.env, sandbox, "trusted", trusted), napi_ok); + + EXPECT_TRUE(IsTrueIn(s.env, realm, + "(() => { try { eval(trusted); } catch (error) { " + "return error instanceof EvalError; } return false; })()")); + EXPECT_TRUE(IsTrueIn(s.env, realm, + "(() => { try { Function(trusted); } catch (error) { " + "return error instanceof EvalError; } return false; })()")); + EXPECT_TRUE(IsTrueIn(s.env, realm, + "(() => { try { eval('1'); } catch (error) { " + "return error instanceof EvalError; } return false; })()")); + EXPECT_TRUE(IsTrueIn(s.env, realm, + "(() => { const object = { toString() { throw 1; } }; " + "return eval(object) === object; })()")); + + // The root context still allows it. + InstallGlobal(s.env, "makeTrusted", MakeTrusted, nullptr); + EXPECT_TRUE(IsTrue(s.env, "eval(makeTrusted('5')) === 5")); +} + +#endif + +TEST_F(Test79UnofficialTrustedScript, IsExecutingJsReportsFramesAndMicrotasks) { + EnvScope s(runtime_.get()); + MicrotaskRecord record; + InstallGlobal(s.env, "executing", Executing, nullptr); + + bool active = true; + ASSERT_EQ(unofficial_napi_is_executing_js(s.env, &active), napi_ok); + EXPECT_FALSE(active); + EXPECT_EQ(unofficial_napi_is_executing_js(s.env, nullptr), napi_invalid_arg); + EXPECT_EQ(unofficial_napi_is_executing_js(nullptr, &active), napi_invalid_arg); + + EXPECT_TRUE(IsTrue(s.env, "executing() === true")); + EXPECT_TRUE(IsTrue(s.env, "Object.defineProperty({}, 'x', { get: executing }).x === true")); + + // Only JavaScript frames count: a native function called from C, with no + // JavaScript frame below it, reports false. + napi_value global = nullptr; + napi_value executing = nullptr; + napi_value reported = nullptr; + bool reported_active = true; + ASSERT_EQ(napi_get_global(s.env, &global), napi_ok); + ASSERT_EQ(napi_get_named_property(s.env, global, "executing", &executing), napi_ok); + ASSERT_EQ(napi_call_function(s.env, global, executing, 0, nullptr, &reported), napi_ok); + ASSERT_EQ(napi_get_value_bool(s.env, reported, &reported_active), napi_ok); + EXPECT_FALSE(reported_active); + + // Builtin call/bind frames alone also do not count as user JavaScript. + napi_value bound = nullptr; + ASSERT_EQ(napi_run_script(s.env, Str(s.env, "Function.prototype.call.bind(executing)"), &bound), + napi_ok); + ASSERT_EQ(napi_call_function(s.env, global, bound, 0, nullptr, &reported), napi_ok); + ASSERT_EQ(napi_get_value_bool(s.env, reported, &reported_active), napi_ok); + EXPECT_FALSE(reported_active); + + napi_value microtask = nullptr; + ASSERT_EQ(napi_create_function( + s.env, "microtask", NAPI_AUTO_LENGTH, RecordMicrotask, &record, µtask), + napi_ok); + ASSERT_EQ(unofficial_napi_enqueue_microtask(s.env, microtask), napi_ok); + ASSERT_EQ(unofficial_napi_is_executing_js(s.env, &active), napi_ok); + EXPECT_FALSE(active); // A queued job is not executing yet. + EXPECT_EQ(record.calls, 0u); + ASSERT_EQ(unofficial_napi_event_loop_checkpoint( + s.env, unofficial_napi_event_loop_checkpoint_microtasks, false, nullptr), + napi_ok); + EXPECT_EQ(record.calls, 1u); + EXPECT_EQ(record.active_calls, 1u); + ASSERT_EQ(unofficial_napi_is_executing_js(s.env, &active), napi_ok); + EXPECT_FALSE(active); + + // The query neither runs JavaScript nor consumes a pending exception. + napi_value ignored = nullptr; + napi_value exception = nullptr; + bool pending = false; + bool same = false; + ASSERT_EQ(napi_run_script(s.env, Str(s.env, "throw globalThis"), &ignored), + napi_pending_exception); + active = true; + ASSERT_EQ(unofficial_napi_is_executing_js(s.env, &active), napi_ok); + EXPECT_FALSE(active); + ASSERT_EQ(napi_is_exception_pending(s.env, &pending), napi_ok); + EXPECT_TRUE(pending); + ASSERT_EQ(napi_get_and_clear_last_exception(s.env, &exception), napi_ok); + ASSERT_EQ(napi_strict_equals(s.env, exception, global, &same), napi_ok); + EXPECT_TRUE(same); +} + +#if defined(NAPI_TEST_ENGINE_V8) +TEST_F(Test79UnofficialTrustedScript, IsExecutingJsFromContextTokenCallback) { + TokenCallbackRecord record; + EnvScope s(runtime_.get()); + unofficial_napi_env_hooks hooks{}; + hooks.size = sizeof(hooks); + hooks.version = UNOFFICIAL_NAPI_ENV_HOOKS_VERSION; + hooks.data = &record; + hooks.context_token_assign_callback = QueryFromTokenCallback; + uint64_t accepted = 0; + ASSERT_EQ(unofficial_napi_attach_env(s.env, &hooks, &accepted), napi_ok); + + napi_value sandbox = nullptr; + napi_value context = nullptr; + ASSERT_EQ(napi_create_object(s.env, &sandbox), napi_ok); + unofficial_napi_realm_options options; + unofficial_napi_realm_options_init(&options); + options.sandbox_or_null = sandbox; + unofficial_napi_realm realm = nullptr; + ASSERT_EQ(unofficial_napi_create_realm(s.env, &options, &realm, &context), napi_ok); + EXPECT_EQ(record.calls, 1u); + EXPECT_EQ(record.status, napi_ok); + EXPECT_FALSE(record.active); +} +#endif + +// A native callback from the root context still sees JavaScript frames and +// microtask checkpoints that belong to another context. +TEST_F(Test79UnofficialTrustedScript, IsExecutingJsSeesOtherContexts) { + EnvScope s(runtime_.get()); + MicrotaskRecord record; + + napi_value sandbox = nullptr; + napi_value context = nullptr; + napi_value executing = nullptr; + napi_value microtask = nullptr; + ASSERT_EQ(napi_create_object(s.env, &sandbox), napi_ok); + // Own microtask queue: run_script drains it after evaluation. + unofficial_napi_realm_options options; + unofficial_napi_realm_options_init(&options); + options.sandbox_or_null = sandbox; + options.own_microtask_queue = true; + unofficial_napi_realm realm = nullptr; + ASSERT_EQ(unofficial_napi_create_realm(s.env, &options, &realm, &context), napi_ok); + ASSERT_EQ(napi_create_function( + s.env, "executing", NAPI_AUTO_LENGTH, Executing, nullptr, &executing), + napi_ok); + ASSERT_EQ(napi_create_function( + s.env, "microtask", NAPI_AUTO_LENGTH, RecordMicrotask, &record, µtask), + napi_ok); + ASSERT_EQ(napi_set_named_property(s.env, sandbox, "executing", executing), napi_ok); + ASSERT_EQ(napi_set_named_property(s.env, sandbox, "microtask", microtask), napi_ok); + + EXPECT_TRUE(IsTrueIn(s.env, realm, "executing() === true")); + // A reaction job is queued in its handler's realm. Binding the context's + // own Function.prototype.call queues the root callback in this context's + // queue, and the bound builtin adds no JavaScript frame. + EXPECT_TRUE(IsTrueIn(s.env, realm, + "Promise.resolve().then(Function.prototype.call.bind(microtask)), true")); + // QuickJS uses its runtime job queue; V8 has already drained the realm's + // own queue. Both queries must see the callback executing in its root realm. + ASSERT_EQ(unofficial_napi_event_loop_checkpoint( + s.env, unofficial_napi_event_loop_checkpoint_microtasks, false, nullptr), + napi_ok); + EXPECT_EQ(record.calls, 1u); + EXPECT_EQ(record.active_calls, 1u); + + bool active = true; + ASSERT_EQ(unofficial_napi_is_executing_js(s.env, &active), napi_ok); + EXPECT_FALSE(active); +} + +#if defined(NAPI_TEST_ENGINE_QUICKJS) +TEST_F(Test79UnofficialTrustedScript, TrustedScriptUnsupported) { + EnvScope s(runtime_.get()); + + napi_value result = Str(s.env, "sentinel"); + EXPECT_EQ(unofficial_napi_create_trusted_script(s.env, Str(s.env, "1"), &result), + napi_generic_failure); + EXPECT_EQ(result, nullptr); + EXPECT_EQ(unofficial_napi_create_trusted_script(s.env, Str(s.env, "1"), nullptr), + napi_invalid_arg); + +} +#endif + +namespace { +unofficial_napi_realm MakeRealm(napi_env env, napi_value* global, bool allow_strings = true) { + unofficial_napi_realm_options options; + unofficial_napi_realm_options_init(&options); + options.allow_code_gen_strings = allow_strings; + unofficial_napi_realm realm = nullptr; + EXPECT_EQ(unofficial_napi_create_realm(env, &options, &realm, global), napi_ok); + return realm; +} +} + +#if defined(NAPI_TEST_ENGINE_V8) +TEST_F(Test79UnofficialTrustedScript, CreationUsesCurrentRealmAndEvalUsesCallersScope) { + EnvScope s(runtime_.get()); + napi_value a_global = nullptr, b_global = nullptr, trusted = nullptr; + auto a = MakeRealm(s.env, &a_global); + auto b = MakeRealm(s.env, &b_global); + ASSERT_NE(a, nullptr); + ASSERT_NE(b, nullptr); + unofficial_napi_realm_scope scope = 0; + ASSERT_EQ(unofficial_napi_enter_realm(s.env, a, &scope), napi_ok); + ASSERT_EQ(unofficial_napi_create_trusted_script(s.env, Str(s.env, "lexical + 2"), &trusted), napi_ok); + ASSERT_EQ(unofficial_napi_leave_realm(s.env, scope), napi_ok); + ASSERT_EQ(napi_set_named_property(s.env, a_global, "trusted", trusted), napi_ok); + ASSERT_EQ(napi_set_named_property(s.env, b_global, "trusted", trusted), napi_ok); + EXPECT_TRUE(IsTrueIn(s.env, a, "Object.getPrototypeOf(Object.getPrototypeOf(trusted)) === Object.prototype")); + EXPECT_TRUE(IsTrueIn(s.env, b, "Object.getPrototypeOf(Object.getPrototypeOf(trusted)) !== Object.prototype")); + EXPECT_TRUE(IsTrueIn(s.env, b, "(() => {let lexical = 40; return eval(trusted) === 42;})()")); + napi_value type_error = nullptr; + ASSERT_EQ(napi_get_named_property(s.env, a_global, "TypeError", &type_error), napi_ok); + ASSERT_EQ(napi_set_named_property(s.env, b_global, "OriginTypeError", type_error), napi_ok); + EXPECT_TRUE(IsTrueIn(s.env, b, "(() => {try {trusted.toString.call({});} catch(e) {return e instanceof OriginTypeError && !(e instanceof TypeError);} return false;})()")); +} + +TEST_F(Test79UnofficialTrustedScript, NativeFactoryKeepsItsCreationRealmWhenCalledElsewhere) { + EnvScope s(runtime_.get()); + napi_value a_global = nullptr, b_global = nullptr, factory = nullptr, a_object = nullptr; + auto a = MakeRealm(s.env, &a_global); + auto b = MakeRealm(s.env, &b_global); + ASSERT_NE(a, nullptr); + ASSERT_NE(b, nullptr); + unofficial_napi_realm_scope scope = 0; + ASSERT_EQ(unofficial_napi_enter_realm(s.env, a, &scope), napi_ok); + ASSERT_EQ(napi_create_function(s.env, "makeTrusted", NAPI_AUTO_LENGTH, MakeTrusted, nullptr, &factory), napi_ok); + ASSERT_EQ(unofficial_napi_leave_realm(s.env, scope), napi_ok); + ASSERT_EQ(napi_get_named_property(s.env, a_global, "Object", &a_object), napi_ok); + ASSERT_EQ(napi_set_named_property(s.env, b_global, "OriginObject", a_object), napi_ok); + ASSERT_EQ(napi_set_named_property(s.env, b_global, "makeTrusted", factory), napi_ok); + EXPECT_TRUE(IsTrueIn(s.env, b, "(() => {const t = makeTrusted('lexical + 2'); let lexical = 40; return Object.getPrototypeOf(Object.getPrototypeOf(t)) === OriginObject.prototype && eval(t) === 42;})()")); +} + +TEST_F(Test79UnofficialTrustedScript, ReceivingRealmControlsCodeGenerationPolicy) { + EnvScope s(runtime_.get()); + napi_value a_global = nullptr, b_global = nullptr, trusted = nullptr; + auto a = MakeRealm(s.env, &a_global); + auto b = MakeRealm(s.env, &b_global, false); + ASSERT_NE(a, nullptr); + ASSERT_NE(b, nullptr); + unofficial_napi_realm_scope scope = 0; + ASSERT_EQ(unofficial_napi_enter_realm(s.env, a, &scope), napi_ok); + ASSERT_EQ(unofficial_napi_create_trusted_script(s.env, Str(s.env, "6 * 7"), &trusted), napi_ok); + ASSERT_EQ(unofficial_napi_leave_realm(s.env, scope), napi_ok); + ASSERT_EQ(napi_set_named_property(s.env, a_global, "trusted", trusted), napi_ok); + ASSERT_EQ(napi_set_named_property(s.env, b_global, "trusted", trusted), napi_ok); + EXPECT_TRUE(IsTrueIn(s.env, a, "eval(trusted) === 42")); + EXPECT_TRUE(IsTrueIn(s.env, b, "(() => {try {eval(trusted);} catch(e) {return e instanceof EvalError;} return false;})()")); + EXPECT_TRUE(IsTrueIn(s.env, b, "(() => {try {Function(trusted);} catch(e) {return e instanceof EvalError;} return false;})()")); +} + +#endif + +TEST_F(Test79UnofficialTrustedScript, EnteringRealmAloneDoesNotMeanJsIsExecuting) { + EnvScope s(runtime_.get()); + napi_value global = nullptr; + auto realm = MakeRealm(s.env, &global); + ASSERT_NE(realm, nullptr); + unofficial_napi_realm_scope scope = 0; + ASSERT_EQ(unofficial_napi_enter_realm(s.env, realm, &scope), napi_ok); + bool active = true; + EXPECT_EQ(unofficial_napi_is_executing_js(s.env, &active), napi_ok); + EXPECT_FALSE(active); + ASSERT_EQ(unofficial_napi_leave_realm(s.env, scope), napi_ok); +} + +TEST_F(Test79UnofficialTrustedScript, SuspendedCoroutinesDoNotCountAsExecuting) { + EnvScope s(runtime_.get()); + InstallGlobal(s.env, "executing", Executing, nullptr); + EXPECT_TRUE(IsTrue(s.env, + "globalThis.generator = (function* () {yield executing(); return executing()})(); " + "generator.next().value === true")); + bool active = true; + ASSERT_EQ(unofficial_napi_is_executing_js(s.env, &active), napi_ok); + EXPECT_FALSE(active); + EXPECT_TRUE(IsTrue(s.env, "generator.next().value === true")); + EXPECT_TRUE(IsTrue(s.env, + "globalThis.resumeAsync = null; globalThis.asyncActive = false; " + "(async () => {await new Promise(resolve => resumeAsync = resolve); " + "asyncActive = executing()})(); true")); + ASSERT_EQ(unofficial_napi_is_executing_js(s.env, &active), napi_ok); + EXPECT_FALSE(active); + EXPECT_TRUE(IsTrue(s.env, "resumeAsync(), true")); + ASSERT_EQ(unofficial_napi_event_loop_checkpoint( + s.env, unofficial_napi_event_loop_checkpoint_microtasks, false, nullptr), + napi_ok); + EXPECT_TRUE(IsTrue(s.env, "asyncActive === true")); + ASSERT_EQ(unofficial_napi_is_executing_js(s.env, &active), napi_ok); + EXPECT_FALSE(active); +} + +namespace { +napi_value ThrowFromJob(napi_env env, napi_callback_info info) { + RecordMicrotask(env, info); + auto status = napi_throw_error(env, nullptr, "job failure"); + EXPECT_TRUE(status == napi_ok || status == napi_pending_exception); + return nullptr; +} + +napi_value TerminateFromJs(napi_env env, napi_callback_info info) { + RecordMicrotask(env, info); + EXPECT_EQ(unofficial_napi_terminate_execution(env), napi_ok); + bool active = false; + EXPECT_EQ(unofficial_napi_is_executing_js(env, &active), napi_ok); + EXPECT_TRUE(active); // The JavaScript caller has not unwound yet. + return nullptr; +} + +void QueryDuringCleanup(void* data) { + auto* env = static_cast(data); + bool active = true; + EXPECT_EQ(unofficial_napi_is_executing_js(*env, &active), napi_ok); + EXPECT_FALSE(active); +} +} // namespace + +TEST_F(Test79UnofficialTrustedScript, QueryUnwindsAfterThrowingJob) { + EnvScope s(runtime_.get()); + MicrotaskRecord record; + napi_value task = nullptr; + ASSERT_EQ(napi_create_function(s.env, "throwFromJob", NAPI_AUTO_LENGTH, ThrowFromJob, + &record, &task), napi_ok); + ASSERT_EQ(unofficial_napi_enqueue_microtask(s.env, task), napi_ok); + // Providers differ in reporting uncaught microtask errors; execution state + // must unwind regardless, and the query must preserve any pending error. + auto status = unofficial_napi_event_loop_checkpoint( + s.env, unofficial_napi_event_loop_checkpoint_microtasks, false, nullptr); + EXPECT_TRUE(status == napi_ok || status == napi_pending_exception); + EXPECT_EQ(record.calls, 1u); + EXPECT_EQ(record.active_calls, 1u); + bool pending_before = false, pending_after = false, active = true; + ASSERT_EQ(napi_is_exception_pending(s.env, &pending_before), napi_ok); + ASSERT_EQ(unofficial_napi_is_executing_js(s.env, &active), napi_ok); + EXPECT_FALSE(active); + ASSERT_EQ(napi_is_exception_pending(s.env, &pending_after), napi_ok); + EXPECT_EQ(pending_before, pending_after); + if (pending_after) { + napi_value exception = nullptr; + ASSERT_EQ(napi_get_and_clear_last_exception(s.env, &exception), napi_ok); + } +} + +TEST_F(Test79UnofficialTrustedScript, QuerySurvivesTerminationAndCleanup) { + napi_env cleanup_env = nullptr; + { + EnvScope s(runtime_.get()); + cleanup_env = s.env; + ASSERT_EQ(napi_add_env_cleanup_hook(s.env, QueryDuringCleanup, &cleanup_env), napi_ok); + MicrotaskRecord record; + InstallGlobal(s.env, "terminateFromJs", TerminateFromJs, &record); + napi_value ignored = nullptr; + EXPECT_EQ(napi_run_script(s.env, Str(s.env, "terminateFromJs()"), &ignored), + napi_pending_exception); + EXPECT_EQ(record.calls, 1u); + EXPECT_EQ(record.active_calls, 1u); + bool active = true; + EXPECT_EQ(unofficial_napi_is_executing_js(s.env, &active), napi_ok); + EXPECT_FALSE(active); + EXPECT_EQ(unofficial_napi_cancel_terminate_execution(s.env), napi_ok); + napi_value global = nullptr, terminate = nullptr; + ASSERT_EQ(napi_get_global(s.env, &global), napi_ok); + ASSERT_EQ(napi_get_named_property(s.env, global, "terminateFromJs", &terminate), napi_ok); + ASSERT_EQ(unofficial_napi_enqueue_microtask(s.env, terminate), napi_ok); + EXPECT_EQ(unofficial_napi_event_loop_checkpoint( + s.env, unofficial_napi_event_loop_checkpoint_microtasks, false, nullptr), + napi_pending_exception); + EXPECT_EQ(record.calls, 2u); + EXPECT_EQ(record.active_calls, 2u); + active = true; + EXPECT_EQ(unofficial_napi_is_executing_js(s.env, &active), napi_ok); + EXPECT_FALSE(active); + EXPECT_EQ(unofficial_napi_cancel_terminate_execution(s.env), napi_ok); + EXPECT_TRUE(IsTrue(s.env, "1 === 1")); + } +} + +#if defined(NAPI_TEST_ENGINE_V8) +TEST_F(Test79UnofficialTrustedScript, CreationRefusesTerminationAndQueryKeepsPendingException) { + EnvScope s(runtime_.get()); + napi_value source = Str(s.env, "42"), result = source; + ASSERT_EQ(unofficial_napi_terminate_execution(s.env), napi_ok); + EXPECT_EQ(unofficial_napi_create_trusted_script(s.env, source, &result), napi_pending_exception); + EXPECT_EQ(result, nullptr); + bool active = true, pending = false; + EXPECT_EQ(unofficial_napi_is_executing_js(s.env, &active), napi_ok); + EXPECT_FALSE(active); + EXPECT_EQ(napi_is_exception_pending(s.env, &pending), napi_ok); + EXPECT_TRUE(pending); + ASSERT_EQ(unofficial_napi_cancel_terminate_execution(s.env), napi_ok); + ASSERT_EQ(unofficial_napi_create_trusted_script(s.env, source, &result), napi_ok); +} + +TEST_F(Test79UnofficialTrustedScript, SharedTemplateDoesNotRetainFirstCreationRealm) { + EnvScope s(runtime_.get()); + napi_ref weak = nullptr; + napi_handle_scope handles = nullptr; + ASSERT_EQ(napi_open_handle_scope(s.env, &handles), napi_ok); + napi_value global = nullptr, trusted = nullptr; + auto realm = MakeRealm(s.env, &global); + ASSERT_NE(realm, nullptr); + ASSERT_EQ(napi_create_reference(s.env, global, 0, &weak), napi_ok); + unofficial_napi_realm_scope scope = 0; + ASSERT_EQ(unofficial_napi_enter_realm(s.env, realm, &scope), napi_ok); + ASSERT_EQ(unofficial_napi_create_trusted_script(s.env, Str(s.env, "42"), &trusted), napi_ok); + ASSERT_EQ(unofficial_napi_leave_realm(s.env, scope), napi_ok); + ASSERT_EQ(napi_close_handle_scope(s.env, handles), napi_ok); + for (int attempt = 0; attempt < 3; ++attempt) ASSERT_EQ(unofficial_napi_collect_garbage(s.env), napi_ok); + napi_value retained = nullptr; + ASSERT_EQ(napi_get_reference_value(s.env, weak, &retained), napi_ok); + EXPECT_EQ(retained, nullptr); + ASSERT_EQ(napi_delete_reference(s.env, weak), napi_ok); + ASSERT_EQ(unofficial_napi_create_trusted_script(s.env, Str(s.env, "43"), &trusted), napi_ok); +} + +namespace { +struct CleanupRecord { + napi_env env = nullptr; + unsigned calls = 0; +}; +void TrustedScriptDuringCleanup(void* data) { + auto* record = static_cast(data); + bool active = true; + EXPECT_EQ(unofficial_napi_is_executing_js(record->env, &active), napi_ok); + EXPECT_FALSE(active); + napi_value trusted = nullptr, global = nullptr; + EXPECT_EQ(unofficial_napi_create_trusted_script(record->env, Str(record->env, "42"), &trusted), napi_ok); + EXPECT_EQ(napi_get_global(record->env, &global), napi_ok); + EXPECT_EQ(napi_set_named_property(record->env, global, "cleanupTrusted", trusted), napi_ok); + EXPECT_TRUE(IsTrue(record->env, "eval(cleanupTrusted) === 42")); + ++record->calls; +} +} + +TEST_F(Test79UnofficialTrustedScript, AgentStateRemainsUsableDuringCleanupHooks) { + CleanupRecord record; + { + EnvScope s(runtime_.get()); + record.env = s.env; + EXPECT_EQ(napi_add_env_cleanup_hook(s.env, TrustedScriptDuringCleanup, &record), napi_ok); + } + EXPECT_EQ(record.calls, 1u); +} + +TEST_F(Test79UnofficialTrustedScript, QuerySeesJsAcrossDifferentSecurityTokens) { + EnvScope s(runtime_.get()); + napi_value global = nullptr, callback = nullptr; + auto realm = MakeRealm(s.env, &global); + ASSERT_NE(realm, nullptr); + ASSERT_EQ(napi_create_function(s.env, "executing", NAPI_AUTO_LENGTH, Executing, nullptr, &callback), napi_ok); + ASSERT_EQ(napi_set_named_property(s.env, global, "executing", callback), napi_ok); + unofficial_napi_realm_scope scope = 0; + ASSERT_EQ(unofficial_napi_enter_realm(s.env, realm, &scope), napi_ok); + auto* isolate = v8::Isolate::GetCurrent(); + isolate->GetCurrentContext()->SetSecurityToken(v8::String::NewFromUtf8Literal(isolate, "another origin")); + ASSERT_EQ(unofficial_napi_leave_realm(s.env, scope), napi_ok); + EXPECT_TRUE(IsTrueIn(s.env, realm, "executing() === true")); +} +#endif diff --git a/v8/src/internal/napi_v8_agent.h b/v8/src/internal/napi_v8_agent.h index 4e672b8a5..9bdd8b414 100644 --- a/v8/src/internal/napi_v8_agent.h +++ b/v8/src/internal/napi_v8_agent.h @@ -52,6 +52,14 @@ struct napi_agent__ { v8::Global buffer_private_key; v8::Global type_tag_private_key; + // Trusted-script brand/hook installation and reusable code-like template. + // One per engine, shared by every realm. Private::New keeps the brand + // distinct from any key an embedder can create by name. + v8::Global trusted_script_key; + v8::Global trusted_script_template; + // Includes own queues while a callback switches the current N-API realm. + unsigned microtask_checkpoints = 0; + // Embedder hooks from unofficial_napi_attach_env, attached once. bool embedder_hooks_attached = false; unofficial_napi_fatal_error_callback fatal_error_callback = nullptr; @@ -90,4 +98,18 @@ struct napi_agent__ { std::vector active_profiles; }; +// Tracks every provider-driven checkpoint, including a realm's own queue. +// Callbacks may switch N-API realms while that queue is still draining. +class napi_microtask_checkpoint_scope__ { + public: + explicit napi_microtask_checkpoint_scope__(napi_agent__* agent) : agent_(agent) { + ++agent_->microtask_checkpoints; + } + ~napi_microtask_checkpoint_scope__() { --agent_->microtask_checkpoints; } + napi_microtask_checkpoint_scope__(const napi_microtask_checkpoint_scope__&) = delete; + napi_microtask_checkpoint_scope__& operator=(const napi_microtask_checkpoint_scope__&) = delete; + private: + napi_agent__* agent_; +}; + #endif // NAPI_V8_AGENT_H_ diff --git a/v8/src/js_native_api_v8.cc b/v8/src/js_native_api_v8.cc index 11418932b..f507a46aa 100644 --- a/v8/src/js_native_api_v8.cc +++ b/v8/src/js_native_api_v8.cc @@ -1076,6 +1076,8 @@ napi_agent__::~napi_agent__() { wrap_private_key.Reset(); buffer_private_key.Reset(); type_tag_private_key.Reset(); + trusted_script_key.Reset(); + trusted_script_template.Reset(); if (From(isolate) == this) { isolate->SetData(kNapiAgentDataSlot, nullptr); } diff --git a/v8/src/unofficial_napi.cc b/v8/src/unofficial_napi.cc index 76d8ab8d7..cac21e6ee 100644 --- a/v8/src/unofficial_napi.cc +++ b/v8/src/unofficial_napi.cc @@ -40,6 +40,51 @@ struct unofficial_napi_profile__ { namespace { +// The brand and reusable template belong to the engine's agent. A private +// key made by New cannot be forged through create_private_symbol/ForApi. +v8::Local TrustedScriptKey(v8::Isolate* isolate) { + auto* agent = napi_agent__::From(isolate); + return agent != nullptr ? agent->trusted_script_key.Get(isolate) : v8::Local(); +} + +v8::MaybeLocal TrustedScriptSource(v8::Local context, + v8::Local value) { + auto* isolate = context->GetIsolate(); + if (!value->IsObject() || value->IsProxy()) return {}; + auto object = value.As(); + auto key = TrustedScriptKey(isolate); + v8::Local source; + if (key.IsEmpty() || !object->IsCodeLike(isolate) || + !object->GetPrivate(context, key).ToLocal(&source) || !source->IsString()) return {}; + return source.As(); +} + +v8::ModifyCodeGenerationFromStringsResult TrustedCodeGeneration( + v8::Local context, v8::Local source, bool) { + v8::ModifyCodeGenerationFromStringsResult result; + v8::Local trusted; + if (TrustedScriptSource(context, source).ToLocal(&trusted)) { + result.codegen_allowed = context->IsCodeGenerationFromStringsAllowed(); + if (result.codegen_allowed) result.modified_source = trusted; + } else { + // eval(non-string) must return its argument unchanged, including when + // string codegen is disabled. Never stringify an unbranded object here. + result.codegen_allowed = !source->IsString() || + context->IsCodeGenerationFromStringsAllowed(); + } + return result; +} + +void TrustedScriptToString(const v8::FunctionCallbackInfo& info) { + v8::Local source; + if (TrustedScriptSource(info.GetIsolate()->GetCurrentContext(), info.This()).ToLocal(&source)) { + info.GetReturnValue().Set(source); + } else { + info.GetIsolate()->ThrowException(v8::Exception::TypeError( + v8::String::NewFromUtf8Literal(info.GetIsolate(), "Illegal TrustedScript invocation"))); + } +} + struct SharedRuntime { std::unique_ptr platform; std::string engine_flags; @@ -2255,6 +2300,7 @@ bool DrainMicrotasksForEnv(napi_env env, bool* host_task_admitted) { if (napi_v8_terminating(env)) return false; v8::Local context = env->main_context(); v8::MicrotaskQueue* queue = context.IsEmpty() ? nullptr : context->GetMicrotaskQueue(); + napi_microtask_checkpoint_scope__ checkpoint(env->agent); if (queue != nullptr) { queue->PerformCheckpoint(env->isolate); } else { @@ -2476,6 +2522,71 @@ void NAPI_CDECL unofficial_napi_message_drop(unofficial_napi_message message) { delete reinterpret_cast(message); } +napi_status NAPI_CDECL unofficial_napi_create_trusted_script( + napi_env env, napi_value source, napi_value* result) { + if (env == nullptr || env->isolate == nullptr || source == nullptr || result == nullptr) + return napi_invalid_arg; + *result = nullptr; + NAPI_V8_RETURN_IF_TERMINATING(env); + auto raw_source = napi_v8_unwrap_value(source); + if (raw_source.IsEmpty() || !raw_source->IsString()) return napi_string_expected; + auto* isolate = env->isolate; + v8::EscapableHandleScope handles(isolate); + auto context = env->context(); + v8::Context::Scope context_scope(context); + // One code-like template per agent. A fresh template per call would + // leave each instantiation in the context's template cache. + v8::Local shape; + if (env->agent->trusted_script_template.IsEmpty()) { + shape = v8::FunctionTemplate::New(isolate)->InstanceTemplate(); + shape->SetCodeLike(); + env->agent->trusted_script_template.Reset(isolate, shape); + } else { + shape = env->agent->trusted_script_template.Get(isolate); + } + const bool first_on_isolate = env->agent->trusted_script_key.IsEmpty(); + if (first_on_isolate) { + env->agent->trusted_script_key.Reset(isolate, v8::Private::New(isolate, + v8::String::NewFromUtf8Literal(isolate, "TrustedScript source"))); + } + auto key = env->agent->trusted_script_key.Get(isolate); + // Install the hook once per isolate, with its brand. A hook the embedder + // installs afterwards replaces it, and is not overwritten here again. + if (first_on_isolate) { + isolate->SetModifyCodeGenerationFromStringsCallback(TrustedCodeGeneration); + } + v8::Local object; + if (!shape->NewInstance(context).ToLocal(&object) || + !object->SetPrivate(context, key, raw_source).FromMaybe(false)) + return napi_generic_failure; + // A native default stringifier makes Function(trustedSource) work before + // an embedder replaces the prototype with its own TrustedScript WebIDL one. + auto prototype = v8::Object::New(isolate); + v8::Local stringify; + if (!v8::Function::New(context, TrustedScriptToString).ToLocal(&stringify) || + !prototype->DefineOwnProperty(context, + v8::String::NewFromUtf8Literal(isolate, "toString"), stringify, + v8::DontEnum).FromMaybe(false) || + !object->SetPrototype(context, prototype).FromMaybe(false)) return napi_generic_failure; + *result = napi_v8_wrap_value(env, handles.Escape(object)); + return *result ? napi_ok : napi_generic_failure; +} + +napi_status NAPI_CDECL unofficial_napi_is_executing_js(napi_env env, bool* result) { + if (env == nullptr || env->isolate == nullptr || result == nullptr) return napi_invalid_arg; + *result = false; + auto* isolate = env->isolate; + v8::HandleScope handles(isolate); + auto stack = v8::StackTrace::CurrentStackTrace(isolate, 1, + v8::StackTrace::kExposeFramesAcrossSecurityOrigins); + auto* queue = env->context()->GetMicrotaskQueue(); + *result = stack->GetFrameCount() != 0 || + (queue != nullptr && queue->IsRunningMicrotasks()) || + v8::MicrotasksScope::IsRunningMicrotasks(isolate) || + env->agent->microtask_checkpoints != 0; + return napi_ok; +} + napi_status NAPI_CDECL unofficial_napi_enqueue_microtask(napi_env env, napi_value callback) { if (env == nullptr || env->isolate == nullptr || callback == nullptr) return napi_invalid_arg; v8::Local raw = napi_v8_unwrap_value(callback); diff --git a/v8/src/unofficial_napi_contextify.cc b/v8/src/unofficial_napi_contextify.cc index 955a77684..2cafe1199 100644 --- a/v8/src/unofficial_napi_contextify.cc +++ b/v8/src/unofficial_napi_contextify.cc @@ -2289,6 +2289,10 @@ napi_status NAPI_CDECL unofficial_napi_run_script( maybe_result = script->Run(target_context); if (!maybe_result.IsEmpty() && target_queue != nullptr) { + // A root callback can run from this queue while env->context() is + // another context. unofficial_napi_is_executing_js reads this depth, + // without locks, instead of scanning every context's queue. + napi_microtask_checkpoint_scope__ checkpoint(env->agent); target_queue->PerformCheckpoint(isolate); } }