From 8b358ec06e1415464707a1387889e666ea206111 Mon Sep 17 00:00:00 2001 From: Yagiz Nizipli Date: Tue, 17 Sep 2024 16:12:32 -0400 Subject: [PATCH] fix invalid invocation on getRandomValues() --- src/node/crypto.ts | 3 +-- .../api/node/tests/crypto_random-test.js | 24 +++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/node/crypto.ts b/src/node/crypto.ts index b9347afd97f..06eb9af62a6 100644 --- a/src/node/crypto.ts +++ b/src/node/crypto.ts @@ -4,8 +4,7 @@ // import { ERR_METHOD_NOT_IMPLEMENTED } from 'node-internal:internal_errors'; -// eslint-disable-next-line @typescript-eslint/unbound-method -export const getRandomValues = crypto.getRandomValues; +export const getRandomValues = crypto.getRandomValues.bind(crypto); export const subtle = crypto.subtle; export const webcrypto = crypto; diff --git a/src/workerd/api/node/tests/crypto_random-test.js b/src/workerd/api/node/tests/crypto_random-test.js index c99b0e61a09..45a63aea28c 100644 --- a/src/workerd/api/node/tests/crypto_random-test.js +++ b/src/workerd/api/node/tests/crypto_random-test.js @@ -413,3 +413,27 @@ export const timingSafeEqualTest = { timingSafeEqual(new Uint8Array(1), new Uint8Array(1)); }, }; + +// Ref: https://github.com/cloudflare/workerd/issues/2716 +export const getRandomValuesIllegalInvocation = { + async test() { + const crypto = await import('node:crypto'); + { + // The following assertion doesn't fail as of Node.js v20.17.0 + const getRandomValues = crypto.getRandomValues; + strictEqual(getRandomValues(new Uint8Array(6)).length, 6); + } + throws( + () => { + // This ensures that we are replicating Node.js behavior as of v20.17.0 + const getRandomValues = crypto.webcrypto.getRandomValues; + strictEqual(getRandomValues(new Uint8Array(6)).length, 6); + }, + { + name: 'TypeError', + message: /Illegal invocation/, + } + ); + strictEqual(crypto.getRandomValues(new Uint8Array(6)).length, 6); + }, +};