crypto: optimize key slot caching

Cache constructor-known KeyObject types in the existing private slot
until a native handle is needed. Prime normal CryptoKey slot arrays
from constructor arguments while retaining the native fallback for
transferred keys.

Signed-off-by: Filip Skokan <panva.ip@gmail.com>
PR-URL: https://github.com/nodejs/node/pull/65518
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Yagiz Nizipli <yagiz@nizipli.com>
This commit is contained in:
Filip Skokan authored and Antoine du Hamel committed 2026-09-19 12:07:53 +02:00
1 parent 21fed10bb0
commit c63aa331b4
3 files changed
+71 -40

No files matched your search

+44 -19
View File
@@ -117,12 +117,13 @@ for (const m of [[kKeyEncodingPKCS1, 'pkcs1'], [kKeyEncodingPKCS8, 'pkcs8'],
[kKeyEncodingSPKI, 'spki'], [kKeyEncodingSEC1, 'sec1']])
encodingNames[m[0]] = m[1];
// KeyObject state lives on the native NativeKeyObject base class. JS reads
// the native type enum and a KeyObjectHandle in one call and caches that
// slot tuple in a private field so no forgeable own Symbols are exposed on
// public KeyObject instances.
// KeyObject state lives on the native NativeKeyObject base class. JS caches
// the constructor-known type enum in a private field, then replaces it with
// the native type and KeyObjectHandle tuple when the handle is first needed.
// No forgeable own Symbols are exposed on public KeyObject instances.
let getKeyObjectSlots; // Populated by the createNativeKeyObjectClass callback.
let isKeyObject;
let getKeyObjectTypeValue;
const kKeyObjectSlotType = 0;
const kKeyObjectSlotHandle = 1;
@@ -162,12 +163,18 @@ const {
#slots;
constructor(type, handle) {
if (type !== 'secret' && type !== 'public' && type !== 'private')
throw new ERR_INVALID_ARG_VALUE('type', type);
let keyType;
switch (type) {
case 'secret': keyType = kKeyTypeSecret; break;
case 'public': keyType = kKeyTypePublic; break;
case 'private': keyType = kKeyTypePrivate; break;
default: throw new ERR_INVALID_ARG_VALUE('type', type);
}
if (typeof handle !== 'object' || !(handle instanceof KeyObjectHandle))
throw new ERR_INVALID_ARG_TYPE('handle', 'object', handle);
super(handle);
this.#slots = keyType;
}
get type() {
@@ -232,12 +239,23 @@ const {
if (key == null || typeof key !== 'object') return false;
return #slots in key || isNativeKeyObject(key);
};
getKeyObjectTypeValue = (key) => {
if (!key || typeof key !== 'object')
throw new ERR_INVALID_THIS('KeyObject');
if (#slots in key) {
const cached = key.#slots;
if (typeof cached === 'number') return cached;
if (cached !== undefined) return cached[kKeyObjectSlotType];
}
return getKeyObjectSlots(key)[kKeyObjectSlotType];
};
getKeyObjectSlots = (key) => {
if (!key || typeof key !== 'object')
throw new ERR_INVALID_THIS('KeyObject');
if (#slots in key) {
const cached = key.#slots;
if (cached !== undefined) return cached;
if (cached !== undefined && typeof cached !== 'number') return cached;
}
const slots = nativeGetKeyObjectSlots(key);
key.#slots = slots;
@@ -961,7 +979,7 @@ function keyObjectTypeToString(type) {
* @returns {'secret' | 'public' | 'private'}
*/
function getKeyObjectType(key) {
return keyObjectTypeToString(getKeyObjectSlots(key)[kKeyObjectSlotType]);
return keyObjectTypeToString(getKeyObjectTypeValue(key));
}
/**
@@ -1062,11 +1080,11 @@ function getKeyObjectAsymmetricKeyDetails(key) {
// -> CryptoKey.prototype
// -> Object.prototype
//
// All five internal slots are read from C++ in a single call via
// `getCryptoKeySlots`. The resulting array is cached in a private
// class field on `InternalCryptoKey` so that it is invisible to
// reflection (`Object.getOwnPropertySymbols` etc.) and leaves each
// CryptoKey's hidden class pristine. The `getCryptoKey{Type,
// Normal construction caches all five internal slots in a private class
// field on `InternalCryptoKey`. Partially initialized transferred keys read
// them from C++ in a single `getCryptoKeySlots` call on first access. The
// cache is invisible to reflection (`Object.getOwnPropertySymbols` etc.) and
// leaves each CryptoKey's hidden class pristine. The `getCryptoKey{Type,
// Extractable,Algorithm,Usages,Handle}` helpers index into that
// array and convert native enums/masks back to Web Crypto strings.
// The internal algorithm object is stored as a null-prototype clone
@@ -1175,6 +1193,15 @@ const {
if (algorithm !== undefined)
algorithm = cloneInternalAlgorithm(algorithm);
super(handle, algorithm, usagesMask, extractable);
if (algorithm !== undefined) {
this.#slots = [
handle.getKeyType(),
extractable,
algorithm,
usagesMask,
handle,
];
}
}
static {
@@ -1215,12 +1242,10 @@ const {
return [CryptoKey, InternalCryptoKey];
});
// The helpers below return a CryptoKey's internal slot value,
// populating the per-instance cache on first access via a single
// native call. The public `type` getter converts the native enum to
// the Web Crypto string. The `usages` helper converts the native usage
// mask to Web Crypto strings. The public `algorithm` / `usages` getters
// on `CryptoKey.prototype` cache their returned objects.
// The helpers below return a CryptoKey's internal slot value. The public
// `type` getter converts the native enum to the Web Crypto string. The
// `usages` helper converts the native usage mask to Web Crypto strings. The
// public `algorithm` / `usages` getters cache their returned objects.
/**
* Returns the value of a CryptoKey's `[[type]]` internal slot.
+10 -6
View File
@@ -171,11 +171,12 @@ JavaScript needs access to those operations and is kept out of user-visible
A `KeyObject` is the public Node.js-specific API for keys. It extends a
native `NativeKeyObject`, which stores `KeyObjectData` for structured
cloning. The JavaScript API surface reads its key type and a
`KeyObjectHandle` through a hidden native-backed slot tuple, caching that
tuple in a private field outside user-visible own properties. Derived
metadata, such as symmetric key size and asymmetric key details, is read
from the cached handle and appended lazily to the same private-field cache.
cloning. The JavaScript constructor caches the known key type in a private
field outside user-visible own properties. When a `KeyObjectHandle` is first
needed, JavaScript replaces that value with a hidden native-backed slot tuple.
Derived metadata, such as symmetric key size and asymmetric key details, is
read from the cached handle and appended lazily to the same private-field
cache.
#### `CryptoKey`
@@ -183,7 +184,10 @@ A `CryptoKey` is the Web Crypto API key type. In the Node.js implementation,
public `CryptoKey` instances are backed by a native `NativeCryptoKey`, not by
a `KeyObject`. `NativeCryptoKey` stores the same `KeyObjectData`
representation as `KeyObject`, plus the Web Crypto internal slots
(`[[extractable]]`, `[[algorithm]]`, and `[[usages]]`).
(`[[extractable]]`, `[[algorithm]]`, and `[[usages]]`). Normal construction
primes a private JavaScript slot cache from the constructor arguments.
Partially initialized transferred keys populate that cache from the native
slots on first access.
### `CryptoJob`
@@ -52,23 +52,25 @@ async function roundTripViaMessageChannel(key) {
return received;
}
async function roundTripViaWorker(key) {
const worker = new Worker(`
'use strict';
const { parentPort } = require('node:worker_threads');
const { types: { isKeyObject } } = require('node:util');
function workerMain() {
const { parentPort } = require('node:worker_threads');
const { types: { isKeyObject: workerIsKeyObject } } = require('node:util');
parentPort.once('message', ({ key, expectedType }) => {
try {
if (!isKeyObject(key) || key.type !== expectedType) {
throw new Error('KeyObject slot mismatch in worker');
}
parentPort.postMessage({ key });
} catch (err) {
parentPort.postMessage({ error: err.stack || err.message });
parentPort.once('message', ({ key, expectedType }) => {
try {
if (!workerIsKeyObject(key) || key.type !== expectedType) {
throw new Error('KeyObject slot mismatch in worker');
}
});
`, { eval: true });
parentPort.postMessage({ key });
} catch (err) {
parentPort.postMessage({ error: err.stack || err.message });
}
});
}
async function roundTripViaWorker(key) {
const worker = new Worker(
`'use strict';(${workerMain.toString()})()`, { eval: true });
worker.postMessage({ key, expectedType: key.type });
const [msg] = await once(worker, 'message');