GeezerVison is showing github.com — crypto: reset random caches across snapshots · nodejs/node@acffa61
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: lib/internal/crypto/random.js +30Lines changed: 30 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -21,6 +21,7 @@ const { | 21 | 21 | NumberPrototypeToString, | 22 | 22 | StringFromCharCodeApply, | 23 | 23 | StringPrototypePadStart, | | 24 | + TypedArrayPrototypeFill, | 24 | 25 | TypedArrayPrototypeGetBuffer, | 25 | 26 | TypedArrayPrototypeGetByteLength, | 26 | 27 | TypedArrayPrototypeGetLength, | @@ -74,6 +75,14 @@ const { | 74 | 75 |
| 75 | 76 | const { FastBuffer } = require('internal/buffer'); | 76 | 77 |
| | 78 | +const { | | 79 | + namespace: { | | 80 | + isBuildingSnapshot, | | 81 | + }, | | 82 | + addAfterUserSerializeCallback, | | 83 | + addBeforeUserDeserializeCallback, | | 84 | +} = require('internal/v8/startup_snapshot'); | | 85 | + | 77 | 86 | const kMaxInt32 = 2 ** 31 - 1; | 78 | 87 | const kMaxPossibleLength = MathMin(kMaxLength, kMaxInt32); | 79 | 88 |
| @@ -379,6 +388,27 @@ let uuidData; | 379 | 388 | let uuidNotBuffered; | 380 | 389 | let uuidBatch = 0; | 381 | 390 |
| | 391 | +if (isBuildingSnapshot()) { | | 392 | + const resetRandomCaches = () => { | | 393 | + TypedArrayPrototypeFill(randomCache, 0); | | 394 | + randomCacheOffset = randomCache.length; | | 395 | + if (uuidData !== undefined) { | | 396 | + TypedArrayPrototypeFill(uuidData, 0); | | 397 | + uuidData = undefined; | | 398 | + } | | 399 | + if (uuidNotBuffered !== undefined) { | | 400 | + TypedArrayPrototypeFill(uuidNotBuffered, 0); | | 401 | + uuidNotBuffered = undefined; | | 402 | + } | | 403 | + uuidBatch = 0; | | 404 | + }; | | 405 | + // Clear cached random data after user serialization callbacks. | | 406 | + addAfterUserSerializeCallback(resetRandomCaches); | | 407 | + // Microtasks and exit handlers can refill the caches after serialization | | 408 | + // callbacks, so also reset them before any user deserialization callbacks. | | 409 | + addBeforeUserDeserializeCallback(resetRandomCaches); | | 410 | +} | | 411 | + | 382 | 412 | let hexBytesCache; | 383 | 413 | function getHexBytes() { | 384 | 414 | if (hexBytesCache === undefined) { | |
Collapse file Copy file name to clipboardExpand all lines: lib/internal/v8/startup_snapshot.js +16-1Lines changed: 16 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -35,8 +35,14 @@ function throwIfBuildingSnapshot(reason) { | 35 | 35 | } | 36 | 36 |
| 37 | 37 | const deserializeCallbacks = []; | | 38 | +const beforeUserDeserializeCallbacks = []; | 38 | 39 | let deserializeCallbackIsSet = false; | 39 | 40 | function runDeserializeCallbacks() { | | 41 | + for (let i = 0; i < beforeUserDeserializeCallbacks.length; i++) { | | 42 | + const { 0: callback, 1: data } = beforeUserDeserializeCallbacks[i]; | | 43 | + callback(data); | | 44 | + } | | 45 | + beforeUserDeserializeCallbacks.length = 0; | 40 | 46 | for (let i = 0; i < deserializeCallbacks.length; i++) { | 41 | 47 | const { 0: callback, 1: data } = deserializeCallbacks[i]; | 42 | 48 | callback(data); | @@ -45,6 +51,14 @@ function runDeserializeCallbacks() { | 45 | 51 | } | 46 | 52 |
| 47 | 53 | function addDeserializeCallback(callback, data) { | | 54 | + addDeserializeCallbackImpl(deserializeCallbacks, callback, data); | | 55 | +} | | 56 | + | | 57 | +function addBeforeUserDeserializeCallback(callback, data) { | | 58 | + addDeserializeCallbackImpl(beforeUserDeserializeCallbacks, callback, data); | | 59 | +} | | 60 | + | | 61 | +function addDeserializeCallbackImpl(callbacks, callback, data) { | 48 | 62 | throwIfNotBuildingSnapshot(); | 49 | 63 | validateFunction(callback, 'callback'); | 50 | 64 | if (!deserializeCallbackIsSet) { | @@ -55,7 +69,7 @@ function addDeserializeCallback(callback, data) { | 55 | 69 | setDeserializeCallback(runDeserializeCallbacks); | 56 | 70 | deserializeCallbackIsSet = true; | 57 | 71 | } | 58 | | - deserializeCallbacks.push([callback, data]); | | 72 | + callbacks.push([callback, data]); | 59 | 73 | } | 60 | 74 |
| 61 | 75 | const serializeCallbacks = []; | @@ -130,4 +144,5 @@ module.exports = { | 130 | 144 | isBuildingSnapshot, | 131 | 145 | }, | 132 | 146 | addAfterUserSerializeCallback, | | 147 | + addBeforeUserDeserializeCallback, | 133 | 148 | }; |
Collapse file Copy file name to clipboard +96Lines changed: 96 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +'use strict'; | | 2 | + | | 3 | +const assert = require('node:assert'); | | 4 | +const { | | 5 | + addDeserializeCallback, | | 6 | + addSerializeCallback, | | 7 | + setDeserializeMainFunction, | | 8 | +} = require('node:v8').startupSnapshot; | | 9 | + | | 10 | +// Register before loading crypto to ensure its cleanup takes precedence even | | 11 | +// over user callbacks that were registered earlier. | | 12 | +let deserialized; | | 13 | +addDeserializeCallback(() => { | | 14 | + deserialized = sample(); | | 15 | +}); | | 16 | + | | 17 | +const { | | 18 | + randomInt, | | 19 | + randomUUID, | | 20 | + randomUUIDv7, | | 21 | +} = require('node:crypto'); | | 22 | + | | 23 | +const buildValues = []; | | 24 | +const max = 2 ** 48 - 1; | | 25 | + | | 26 | +function primeCaches() { | | 27 | + buildValues.push( | | 28 | + randomUUID(), | | 29 | + randomInt(max), | | 30 | + randomUUID({ disableEntropyCache: true }), | | 31 | + ); | | 32 | +} | | 33 | + | | 34 | +switch (process.env.NODE_TEST_CRYPTO_RANDOM_MODE) { | | 35 | + case 'uuid': | | 36 | + primeCaches(); | | 37 | + break; | | 38 | + case 'uuidv7': | | 39 | + buildValues.push( | | 40 | + randomUUIDv7(), | | 41 | + randomInt(max), | | 42 | + randomUUIDv7({ disableEntropyCache: true }), | | 43 | + ); | | 44 | + break; | | 45 | + case 'object-url': | | 46 | + URL.revokeObjectURL(URL.createObjectURL(new Blob(['snapshot']))); | | 47 | + break; | | 48 | + case 'async': | | 49 | + randomInt(max, (err, value) => { | | 50 | + assert.ifError(err); | | 51 | + buildValues.push(value); | | 52 | + }); | | 53 | + break; | | 54 | + case 'serialize': | | 55 | + primeCaches(); | | 56 | + // A user callback can refill the caches after an earlier cleanup callback. | | 57 | + addSerializeCallback(primeCaches); | | 58 | + break; | | 59 | + case 'microtask': | | 60 | + primeCaches(); | | 61 | + addSerializeCallback(() => queueMicrotask(primeCaches)); | | 62 | + break; | | 63 | + case 'next-tick': | | 64 | + primeCaches(); | | 65 | + addSerializeCallback(() => process.nextTick(primeCaches)); | | 66 | + break; | | 67 | + case 'exit': | | 68 | + primeCaches(); | | 69 | + process.once('exit', primeCaches); | | 70 | + break; | | 71 | + case 'unprimed': | | 72 | + break; | | 73 | + default: | | 74 | + assert.fail('Unknown cache priming mode'); | | 75 | +} | | 76 | + | | 77 | +function sample() { | | 78 | + return { | | 79 | + uuid: Array.from({ length: 4 }, () => randomUUID()), | | 80 | + // Exclude the timestamp and version so clock changes cannot hide replay. | | 81 | + uuidv7: Array.from({ length: 4 }, () => randomUUIDv7().slice(15)), | | 82 | + webcrypto: Array.from({ length: 4 }, () => globalThis.crypto.randomUUID()), | | 83 | + int: Array.from({ length: 4 }, () => randomInt(max)), | | 84 | + }; | | 85 | +} | | 86 | + | | 87 | +setDeserializeMainFunction(async () => { | | 88 | + const main = sample(); | | 89 | + main.asyncInt = await Promise.all(Array.from({ length: 4 }, () => new Promise((resolve, reject) => { | | 90 | + randomInt(max, (err, value) => { | | 91 | + if (err) reject(err); | | 92 | + else resolve(value); | | 93 | + }); | | 94 | + }))); | | 95 | + console.log(JSON.stringify({ buildValues, deserialized, main })); | | 96 | +}); |
Collapse file Copy file name to clipboard +30Lines changed: 30 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +'use strict'; | | 2 | + | | 3 | +const common = require('../common'); | | 4 | +if (!common.hasCrypto) | | 5 | + common.skip('missing crypto'); | | 6 | + | | 7 | +const assert = require('node:assert'); | | 8 | +const fixtures = require('../common/fixtures'); | | 9 | +const tmpdir = require('../common/tmpdir'); | | 10 | +const { buildSnapshot, runWithSnapshot } = require('../common/snapshot'); | | 11 | + | | 12 | +const entry = fixtures.path('snapshot', 'crypto-random-cache.js'); | | 13 | + | | 14 | +tmpdir.refresh(); | | 15 | +for (const mode of [ | | 16 | + 'uuid', 'uuidv7', 'object-url', 'async', 'serialize', | | 17 | + 'microtask', 'next-tick', 'exit', 'unprimed', | | 18 | +]) { | | 19 | + buildSnapshot(entry, { NODE_TEST_CRYPTO_RANDOM_MODE: mode }); | | 20 | + const a = JSON.parse(runWithSnapshot().stdout); | | 21 | + const b = JSON.parse(runWithSnapshot().stdout); | | 22 | + | | 23 | + // Values retained by the application at build time are intentionally shared. | | 24 | + assert.deepStrictEqual(a.buildValues, b.buildValues); | | 25 | + for (const phase of ['deserialized', 'main']) { | | 26 | + for (const api of Object.keys(a[phase])) { | | 27 | + assert.notDeepStrictEqual(a[phase][api], b[phase][api], `${mode}: ${phase} ${api}`); | | 28 | + } | | 29 | + } | | 30 | +} |
|