File
Blob: src/workerd/api/tests/unsafe-test.js
| 1 | // Copyright (c) 2023 Cloudflare, Inc. |
| 2 | // Licensed under the Apache 2.0 license found in the LICENSE file or at: |
| 3 | // https://opensource.org/licenses/Apache-2.0 |
| 4 | import { strictEqual, throws } from 'node:assert'; |
| 5 | |
| 6 | export const basics = { |
| 7 | test(ctx, env) { |
| 8 | strictEqual(env.unsafe.eval('1'), 1); |
| 9 | |
| 10 | // eval does not capture outer scope. |
| 11 | let _m = 1; |
| 12 | throws(() => env.unsafe.eval('m')); |
| 13 | |
| 14 | throws(() => env.unsafe.eval(' throw new Error("boom"); ', 'foo'), { |
| 15 | message: 'boom', |
| 16 | stack: /at foo/, |
| 17 | }); |
| 18 | |
| 19 | // Regular dynamic eval is still not allowed |
| 20 | throws(() => eval('')); |
| 21 | }, |
| 22 | }; |
| 23 | |
| 24 | export const newFunction = { |
| 25 | test(ctx, env) { |
| 26 | const fn = env.unsafe.newFunction('return m', 'bar', 'm'); |
| 27 | strictEqual(fn.length, 1); |
| 28 | strictEqual(fn.name, 'bar'); |
| 29 | strictEqual(fn(), undefined); |
| 30 | strictEqual(fn(1), 1); |
| 31 | strictEqual(fn(fn), fn); |
| 32 | }, |
| 33 | }; |
| 34 | |
| 35 | export const newAsyncFunction = { |
| 36 | async test(ctx, env) { |
| 37 | const fn = env.unsafe.newAsyncFunction('return await m', 'bar', 'm'); |
| 38 | strictEqual(fn.length, 1); |
| 39 | strictEqual(fn.name, 'bar'); |
| 40 | strictEqual(await fn(), undefined); |
| 41 | strictEqual(await fn(1), 1); |
| 42 | strictEqual(await fn(fn), fn); |
| 43 | strictEqual(await fn(Promise.resolve(1)), 1); |
| 44 | }, |
| 45 | }; |
| 46 | |
| 47 | export const newAsyncFunction2 = { |
| 48 | async test(ctx, env) { |
| 49 | const fn = env.unsafe.newAsyncFunction('return await arguments[0]'); |
| 50 | strictEqual(fn.length, 0); |
| 51 | strictEqual(fn.name, 'anonymous'); |
| 52 | strictEqual(await fn(), undefined); |
| 53 | strictEqual(await fn(1), 1); |
| 54 | strictEqual(await fn(fn), fn); |
| 55 | strictEqual(await fn(Promise.resolve(1)), 1); |
| 56 | }, |
| 57 | }; |
| 58 | |
| 59 | export const newWasmModule = { |
| 60 | async test(ctx, env) { |
| 61 | throws( |
| 62 | () => env.unsafe.newWasmModule([]), |
| 63 | new TypeError( |
| 64 | "Failed to execute 'newWasmModule' on 'UnsafeEval': parameter 1 is not of type 'ArrayBuffer or ArrayBufferView'." |
| 65 | ) |
| 66 | ); |
| 67 | // Fails to construct: missing magic number |
| 68 | throws(() => env.unsafe.newWasmModule(new Uint8Array([]))); |
| 69 | // Test that we can successfully construct a minimal valid Wasm module: magic |
| 70 | // number 0asm + version |
| 71 | const result = env.unsafe.newWasmModule( |
| 72 | new Uint8Array([0, 97, 115, 109, 1, 0, 0, 0]) |
| 73 | ); |
| 74 | strictEqual(result.constructor, WebAssembly.Module); |
| 75 | }, |
| 76 | }; |