From 43116ea957fdb157ca122f5b7dfc9b4126ac1933 Mon Sep 17 00:00:00 2001 From: Noe Gutierrez Date: Fri, 4 Dec 2026 16:37:42 -0800 Subject: [PATCH] feat(sdk-api,sdk-core): cooperatively yield during password rotation Add an opt-in `yieldEvery` boundary to every password-rotation loop: - BitGoAPI.changePassword, sdk-api v1 keychains, sdk-core legacy v2, and sdk-core safeId mode accept `yieldEvery?: number`, validated as a positive safe integer at each independently callable public entry. - After every N listed keychain records (updated, skipped, and missing-envelope alike), the loop yields to a new macrotask so the host event loop can process I/O, worker messages, or repaints between bounded stretches of keychain crypto. Omitted/undefined preserves the existing behavior exactly (no timer is ever allocated). - Safe mode stays progress-silent but honors the same record boundary, so the option is never silently ignored on safeId rotations. - Make requestPatch worker-safe: set User-Agent only when XMLHttpRequest is unavailable (Node), not merely when `window` is unavailable. Dedicated workers expose XHR but not window and must never attempt to set User-Agent. WCN-2084 --- modules/sdk-api/src/bitgoAPI.ts | 14 +- modules/sdk-api/src/types.ts | 7 + modules/sdk-api/src/v1/keychains.ts | 10 ++ modules/sdk-api/test/unit/bitgoAPI.ts | 89 ++++++++++- modules/sdk-api/test/unit/v1/keychains.ts | 44 ++++++ .../sdk-core/src/bitgo/keychain/iKeychains.ts | 8 + .../sdk-core/src/bitgo/keychain/keychains.ts | 143 ++++++++++-------- modules/sdk-core/src/common.ts | 16 ++ .../test/unit/bitgo/keychain/keychains.ts | 129 ++++++++++++++++ 9 files changed, 389 insertions(+), 71 deletions(-) diff --git a/modules/sdk-api/src/bitgoAPI.ts b/modules/sdk-api/src/bitgoAPI.ts index 40fb9ac2f71..cbde27b8c6e 100644 --- a/modules/sdk-api/src/bitgoAPI.ts +++ b/modules/sdk-api/src/bitgoAPI.ts @@ -712,10 +712,11 @@ export class BitGoAPI implements BitGoBase { // prevent IE from caching requests req.set('If-Modified-Since', 'Mon, 26 Jul 1997 05:00:00 GMT'); - if (typeof window === 'undefined' && this._userAgent) { - // If not in the browser, set the User-Agent. Browsers don't allow - // setting of User-Agent, so we must disable this when run in the - // browser (browserify sets process.browser). + if (typeof XMLHttpRequest === 'undefined' && this._userAgent) { + // Set the User-Agent only in XHR-less runtimes (Node). Browsers don't allow setting of + // User-Agent, so we must disable this when XMLHttpRequest is available. Detection must + // be based on XHR rather than `window`: dedicated workers have no `window` but still + // run in a browser/XHR context where setting User-Agent fails. req.set('User-Agent', this._userAgent); } @@ -2114,6 +2115,7 @@ export class BitGoAPI implements BitGoBase { newPassword, encryptionVersion, progressCallback, + yieldEvery, }: ChangePasswordOptions): Promise { if (!_.isString(oldPassword)) { throw new Error('expected string oldPassword'); @@ -2123,6 +2125,8 @@ export class BitGoAPI implements BitGoBase { throw new Error('expected string newPassword'); } + common.validateYieldEvery(yieldEvery); + const user = this.user(); if (typeof user !== 'object' || !user.username) { throw new Error('missing required object user'); @@ -2200,6 +2204,7 @@ export class BitGoAPI implements BitGoBase { encryptionVersion, encryptionSession, progressCallback: makeKeychainProgressCallback('v1'), + yieldEvery, }); // Every v1 entry emits exactly one progress event, so the returned map's size is // the v1 contribution to the denominator; v2 events below add it to their total. @@ -2212,6 +2217,7 @@ export class BitGoAPI implements BitGoBase { encryptionVersion, encryptionSession, progressCallback: makeKeychainProgressCallback('v2'), + yieldEvery, }); // A v1-only account emits no v2 event, so its total would stay undefined for the diff --git a/modules/sdk-api/src/types.ts b/modules/sdk-api/src/types.ts index ebf373d966a..9dd30c6d7f8 100644 --- a/modules/sdk-api/src/types.ts +++ b/modules/sdk-api/src/types.ts @@ -322,6 +322,13 @@ export interface ChangePasswordOptions { encryptionVersion?: EncryptionVersion; /** Optional observer invoked as the password rotation progresses through keychains and finalization. */ progressCallback?: PasswordRotationProgressCallback; + /** + * Opt-in cooperative-yielding boundary: after every N listed keychain records handled by a + * rotation loop, yield to a new macrotask so the host event loop can process I/O, worker + * messages, or repaints between bounded stretches of keychain crypto. Must be a positive safe + * integer. When omitted, the existing behavior is preserved exactly. + */ + yieldEvery?: number; } /** diff --git a/modules/sdk-api/src/v1/keychains.ts b/modules/sdk-api/src/v1/keychains.ts index bc8d98d38cf..bb58a485551 100644 --- a/modules/sdk-api/src/v1/keychains.ts +++ b/modules/sdk-api/src/v1/keychains.ts @@ -183,6 +183,7 @@ Keychains.prototype.list = function (params, callback) { Keychains.prototype.updatePassword = function (params, callback) { return async function coUpdatePassword() { common.validateParams(params, ['oldPassword', 'newPassword'], [], callback); + common.validateYieldEvery(params.yieldEvery); // @ts-expect-error - no implicit this const encrypted = await this.bitgo.post(this.bitgo.url('/user/encrypted')).result(); const newKeychains = {}; @@ -198,6 +199,11 @@ Keychains.prototype.updatePassword = function (params, callback) { // ignore observer exceptions so a throwing callback never affects rotation results } }; + // Opt-in cooperative-yielding boundary: every `yieldEvery` listed records — updated and + // skipped alike — yields to a new macrotask so the host event loop can process I/O, worker + // messages, or repaints between bounded stretches of keychain crypto. `undefined` preserves + // the existing behavior exactly. + let processedRecords = 0; for (const [xpub, oldEncryptedXprv] of Object.entries((encrypted as any).keychains)) { try { const decryptedPrv = await self.bitgo.decrypt({ @@ -217,6 +223,10 @@ Keychains.prototype.updatePassword = function (params, callback) { newKeychains[xpub] = oldEncryptedXprv as string; notifyProgress('skipped', xpub); } + processedRecords++; + if (params.yieldEvery !== undefined && processedRecords % params.yieldEvery === 0) { + await new Promise((resolve) => setTimeout(resolve, 0)); + } } return { keychains: newKeychains, version: (encrypted as any).version }; } diff --git a/modules/sdk-api/test/unit/bitgoAPI.ts b/modules/sdk-api/test/unit/bitgoAPI.ts index a77a0cb6b2b..c7e5fdf470c 100644 --- a/modules/sdk-api/test/unit/bitgoAPI.ts +++ b/modules/sdk-api/test/unit/bitgoAPI.ts @@ -406,15 +406,15 @@ describe('Constructor', function () { sinon.restore(); }); - it('should set User-Agent header when running in Node.js (typeof window === undefined)', async function () { + it('should set User-Agent header when running in Node.js (no XMLHttpRequest)', async function () { const bitgo = new BitGoAPI({ env: 'custom', customRootURI: 'https://app.example.local', userAgent: 'TestAgent/1.0', }); - // Ensure we're in a Node.js environment by verifying window is undefined - (typeof window).should.equal('undefined'); + // Ensure we're in a Node.js environment by verifying XMLHttpRequest is undefined + (typeof XMLHttpRequest).should.equal('undefined'); const scope = nock('https://app.example.local') .get('/api/v1/ping') @@ -433,10 +433,11 @@ describe('Constructor', function () { scope.isDone().should.be.true(); }); - it('should not set User-Agent header when running in browser (typeof window !== undefined)', async function () { - // Mock the window object to simulate browser environment + it('should not set User-Agent header when running in browser (window and XMLHttpRequest available)', async function () { + // Mock the browser globals: window and XMLHttpRequest const windowStub = { location: 'mock' }; (global as any).window = windowStub; + (global as any).XMLHttpRequest = class MockXMLHttpRequest {}; try { const bitgo = new BitGoAPI({ @@ -467,8 +468,48 @@ describe('Constructor', function () { scope.isDone().should.be.true(); } finally { - // Clean up the global window mock + // Clean up the global browser mocks delete (global as any).window; + delete (global as any).XMLHttpRequest; + } + }); + + it('should not set User-Agent header in a dedicated worker runtime (no window, XMLHttpRequest available)', async function () { + // Dedicated workers expose XMLHttpRequest but not `window`; user-agent detection must be + // XHR-based rather than window-based so worker requests never attempt to set User-Agent. + (typeof window).should.equal('undefined'); + (global as any).XMLHttpRequest = class MockXMLHttpRequest {}; + + try { + const bitgo = new BitGoAPI({ + env: 'custom', + customRootURI: 'https://app.example.local', + userAgent: 'TestAgent/1.0', + }); + + const scope = nock('https://app.example.local') + .get('/api/v1/ping') + .reply(function () { + // Verify User-Agent header is NOT set to our custom value + const userAgent = this.req.headers['user-agent']; + if (userAgent && userAgent.includes('TestAgent/1.0')) { + throw new Error('User-Agent should not be set in a dedicated worker'); + } + return [200, { status: 'ok' }]; + }); + + await bitgo.ping({ + reqId: { + toString: () => 'test-123', + inc: () => { + /* mock */ + }, + } as any, + }); + + scope.isDone().should.be.true(); + } finally { + delete (global as any).XMLHttpRequest; } }); }); @@ -1345,6 +1386,42 @@ describe('Constructor', function () { sinon.assert.calledWithMatch(v1UpdatePasswordStub, { encryptionVersion: 2 }); sinon.assert.calledWithMatch(v2UpdatePasswordStub, { encryptionVersion: 2 }); }); + it('forwards yieldEvery to both v1 and v2 keychains().updatePassword calls', async function () { + nock(ROOT).get('/api/v2/user/checkBatchingPasswordFlow').query(true).reply(200, { isBatchingFlowEnabled: false }); + nock(ROOT) + .post('/api/v1/user/changepassword', (body: any) => !!body.keychains && !!body.v2_keychains) + .reply(200, {}); + + await bitgo.changePassword({ oldPassword: 'oldpw', newPassword: 'newpw', yieldEvery: 1 }); + + sinon.assert.calledWithMatch(v1UpdatePasswordStub, { yieldEvery: 1 }); + sinon.assert.calledWithMatch(v2UpdatePasswordStub, { yieldEvery: 1 }); + }); + it('passes yieldEvery: undefined to both lower-level calls when not requested', async function () { + nock(ROOT).get('/api/v2/user/checkBatchingPasswordFlow').query(true).reply(200, { isBatchingFlowEnabled: false }); + nock(ROOT) + .post('/api/v1/user/changepassword', (body: any) => !!body.keychains && !!body.v2_keychains) + .reply(200, {}); + + await bitgo.changePassword({ oldPassword: 'oldpw', newPassword: 'newpw' }); + + // sinon records untyped args; the shape is pinned by the calledWithMatch assertions above. + const v1Params = v1UpdatePasswordStub.firstCall.args[0] as { yieldEvery?: number }; + const v2Params = v2UpdatePasswordStub.firstCall.args[0] as { yieldEvery?: number }; + // the key is forwarded but carries no value, preserving the no-yield behavior exactly + (v1Params.yieldEvery === undefined).should.be.true(); + (v2Params.yieldEvery === undefined).should.be.true(); + }); + it('rejects invalid yieldEvery values at the public entry before any rotation work', async function () { + const invalidValues: unknown[] = [0, -1, 1.5, NaN, Number.MAX_SAFE_INTEGER + 1, '1']; + for (const yieldEvery of invalidValues) { + await bitgo + .changePassword({ oldPassword: 'oldpw', newPassword: 'newpw', yieldEvery: yieldEvery as number }) + .should.be.rejectedWith('yieldEvery must be a positive safe integer'); + } + sinon.assert.notCalled(v1UpdatePasswordStub); + sinon.assert.notCalled(v2UpdatePasswordStub); + }); it('creates one encryption session, passes it to both keychain update calls, and destroys it', async function () { nock(ROOT).get('/api/v2/user/checkBatchingPasswordFlow').query(true).reply(200, { isBatchingFlowEnabled: false }); nock(ROOT) diff --git a/modules/sdk-api/test/unit/v1/keychains.ts b/modules/sdk-api/test/unit/v1/keychains.ts index c68bacdef50..362d6afecd2 100644 --- a/modules/sdk-api/test/unit/v1/keychains.ts +++ b/modules/sdk-api/test/unit/v1/keychains.ts @@ -22,6 +22,8 @@ type V1KeychainsCtor = new (bitgo: V1Bitgo) => { newPassword: string; encryptionVersion?: number; encryptionSession?: IEncryptionSession; + progressCallback?: (progress: { status: 'updated' | 'skipped'; currentKeychainId: string }) => void; + yieldEvery?: number; }): Promise; }; @@ -119,4 +121,46 @@ describe('v1 Keychains.updatePassword', function () { result.keychains.xpubV1.should.equal('re-encrypted'); result.keychains.xpubV2.should.equal('re-encrypted'); }); + + it('yields to the event loop between records when yieldEvery: 1 is provided', async function () { + const stored = { xpubA: v1Envelope, xpubB: v1Envelope, xpubC: v1Envelope }; + nock(ROOT).post('/api/v1/user/encrypted').reply(200, { version: 25, keychains: stored }); + + const encryptStub = sinon.stub().resolves('re-encrypted'); + const keychains = new Keychains(makeBitgo(stored, { [v1Envelope]: 'plain-v1' }, encryptStub)); + + const timeline: string[] = []; + await keychains.updatePassword({ + oldPassword: 'oldpw', + newPassword: 'newpw', + yieldEvery: 1, + progressCallback: (progress) => { + timeline.push(`progress:${progress.currentKeychainId}`); + if (timeline.length === 1) { + // A zero-delay timer scheduled from the first progress callback is enqueued before + // the loop's own yield timer, so with a per-record boundary it must run before the + // second record begins. Without yielding it would run after every record. + setTimeout(() => timeline.push('macrotask'), 0); + } + }, + }); + + timeline.should.deepEqual(['progress:xpubA', 'macrotask', 'progress:xpubB', 'progress:xpubC']); + }); + + it('rejects invalid yieldEvery values before touching any keychain', async function () { + const stored = { xpubA: v1Envelope }; + nock(ROOT).post('/api/v1/user/encrypted').reply(200, { version: 25, keychains: stored }); + + const encryptStub = sinon.stub().resolves('re-encrypted'); + const keychains = new Keychains(makeBitgo(stored, { [v1Envelope]: 'plain-v1' }, encryptStub)); + + const invalidValues: unknown[] = [0, -1, 1.5, NaN, Number.MAX_SAFE_INTEGER + 1, '1']; + for (const yieldEvery of invalidValues) { + await keychains + .updatePassword({ oldPassword: 'oldpw', newPassword: 'newpw', yieldEvery: yieldEvery as number }) + .should.be.rejectedWith('yieldEvery must be a positive safe integer'); + } + encryptStub.called.should.equal(false); + }); }); diff --git a/modules/sdk-core/src/bitgo/keychain/iKeychains.ts b/modules/sdk-core/src/bitgo/keychain/iKeychains.ts index 176b16f44c3..421b9178e9a 100644 --- a/modules/sdk-core/src/bitgo/keychain/iKeychains.ts +++ b/modules/sdk-core/src/bitgo/keychain/iKeychains.ts @@ -169,6 +169,14 @@ export interface UpdatePasswordOptions { * invokes it. */ progressCallback?: KeychainPasswordUpdateProgressCallback; + /** + * Opt-in cooperative-yielding boundary: after every N listed keychain records handled by a rotation + * loop (updated, skipped, or missing-envelope), yield to a new macrotask (`setTimeout(..., 0)`) so the + * host event loop can process I/O, worker messages, or repaints between bounded stretches of keychain + * crypto. Must be a positive safe integer. When omitted, no yield timer is ever created and the existing + * behavior is preserved exactly. + */ + yieldEvery?: number; } export interface UpdateSingleKeychainPasswordOptions { diff --git a/modules/sdk-core/src/bitgo/keychain/keychains.ts b/modules/sdk-core/src/bitgo/keychain/keychains.ts index f23fe7af25d..5dcb007086f 100644 --- a/modules/sdk-core/src/bitgo/keychain/keychains.ts +++ b/modules/sdk-core/src/bitgo/keychain/keychains.ts @@ -173,6 +173,7 @@ export class Keychains implements IKeychains { async updatePassword(params: UpdatePasswordOptions): Promise; async updatePassword(params: UpdatePasswordOptions): Promise { common.validateParams(params, ['oldPassword', 'newPassword'], ['safeId']); + common.validateYieldEvery(params.yieldEvery); if (!_.isUndefined(params.safeId)) { return this.updateSafePassword(params as UpdatePasswordOptions & { safeId: string }); } @@ -199,6 +200,12 @@ export class Keychains implements IKeychains { return fetch; }; let pendingFetch: Promise | undefined = startFetch(); + // Opt-in cooperative-yielding boundary: every `yieldEvery` listed keychain records — + // updated, skipped, and missing-envelope alike — yields to a new macrotask so the host + // event loop can process I/O, worker messages, or repaints between bounded stretches of + // keychain crypto. `undefined` preserves the existing behavior exactly (no timer is ever + // allocated and no await is inserted). + let processedRecords = 0; while (pendingFetch !== undefined) { const result: ListKeychainsResult = await pendingFetch; if (total === undefined && result.totalCount !== undefined) { @@ -217,42 +224,46 @@ export class Keychains implements IKeychains { // silently dropped — it is counted by the list total, and the walk still // leaves it untouched (no re-encryption, no entry in the changedKeys map). notifyProgress('skipped', observationId(key)); - continue; - } - try { - const updatedKeychain = await this.updateSingleKeychainPassword({ - keychain: key, - oldPassword: params.oldPassword, - newPassword: params.newPassword, - encryptionVersion: params.encryptionVersion, - encryptionSession: params.encryptionSession, - }); - if (updatedKeychain.encryptedPrv) { - // Both TSS and multi-user-ofc keys have multiple public keys in their key document and thus need to use objectID - const changedKeyIdentifier = - updatedKeychain.type === 'tss' || Keychains.isMultiUserKey(updatedKeychain) - ? updatedKeychain.id - : updatedKeychain.pub; - if (changedKeyIdentifier) { - changedKeys[changedKeyIdentifier] = updatedKeychain.encryptedPrv; - notifyProgress('updated', changedKeyIdentifier); + } else { + try { + const updatedKeychain = await this.updateSingleKeychainPassword({ + keychain: key, + oldPassword: params.oldPassword, + newPassword: params.newPassword, + encryptionVersion: params.encryptionVersion, + encryptionSession: params.encryptionSession, + }); + if (updatedKeychain.encryptedPrv) { + // Both TSS and multi-user-ofc keys have multiple public keys in their key document and thus need to use objectID + const changedKeyIdentifier = + updatedKeychain.type === 'tss' || Keychains.isMultiUserKey(updatedKeychain) + ? updatedKeychain.id + : updatedKeychain.pub; + if (changedKeyIdentifier) { + changedKeys[changedKeyIdentifier] = updatedKeychain.encryptedPrv; + notifyProgress('updated', changedKeyIdentifier); + } else { + notifyProgress('skipped', observationId(key)); + } } else { notifyProgress('skipped', observationId(key)); } - } else { + } catch (e) { + // A decrypt failure is usually not a wrong password — the keychain may be + // encrypted under a different passphrase. updateSingleKeychainPassword wraps + // such failures as 'failed to update keychain password: ...'; rethrow the rest. + if ( + !e.message.includes('private key is incorrect') && + !e.message.includes('failed to update keychain password') + ) { + throw e; + } notifyProgress('skipped', observationId(key)); } - } catch (e) { - // A decrypt failure is usually not a wrong password — the keychain may be - // encrypted under a different passphrase. updateSingleKeychainPassword wraps - // such failures as 'failed to update keychain password: ...'; rethrow the rest. - if ( - !e.message.includes('private key is incorrect') && - !e.message.includes('failed to update keychain password') - ) { - throw e; - } - notifyProgress('skipped', observationId(key)); + } + processedRecords++; + if (params.yieldEvery !== undefined && processedRecords % params.yieldEvery === 0) { + await new Promise((resolve) => setTimeout(resolve, 0)); } } } @@ -278,42 +289,52 @@ export class Keychains implements IKeychains { try { let prevId: string | undefined; let keysLeft = true; + // Opt-in cooperative-yielding boundary, same contract as the legacy loop: every + // `yieldEvery` listed records (including missing-envelope records that are skipped + // without re-encryption) yields to a new macrotask. Safe mode remains progress-silent, + // but the boundary still applies so the opt-in option is never silently ignored here. + // `undefined` preserves the existing behavior exactly. + let processedRecords = 0; while (keysLeft) { const result: ListKeychainsResult = await this.list({ limit: 500, prevId, safeId: params.safeId }); for (const key of result.keys) { const oldEncryptedPrv = key.encryptedPrv; - if (_.isUndefined(oldEncryptedPrv)) { - // Public-only multisig children and MPC child backup/bitgo placeholders carry no - // user-held envelope — nothing to rotate. - continue; - } - // One session (one Argon2 run) is shared across the whole fan-out; created lazily so - // a safe with nothing to rotate pays no KDF. - if (!session) { - session = - params.encryptionSession ?? - (await this.bitgo.createEncryptionSession(params.newPassword, params.encryptionVersion)); - ownSession = !params.encryptionSession; + if (!_.isUndefined(oldEncryptedPrv)) { + // One session (one Argon2 run) is shared across the whole fan-out; created lazily so + // a safe with nothing to rotate pays no KDF. + if (!session) { + session = + params.encryptionSession ?? + (await this.bitgo.createEncryptionSession(params.newPassword, params.encryptionVersion)); + ownSession = !params.encryptionSession; + } + let decryptedPrv: string; + try { + decryptedPrv = await this.bitgo.decrypt({ input: oldEncryptedPrv, password: params.oldPassword }); + } catch (e) { + // Deliberate divergence from the legacy path's skip-and-continue: a key that no + // longer decrypts with the old passphrase would silently split the passphrase space + // if left behind. + const errorDetail = e instanceof Error ? e.message : String(e); + throw new IncorrectPasswordError( + `failed to decrypt keychain ${key.id} with the old passphrase: ${errorDetail}` + ); + } + updates.push({ + keyId: key.id, + encryptedPrv: await session.encrypt(decryptedPrv), + // Compare-and-swap against the exact envelope we decrypted, so an in-flight mint + // racing the rotation is detected instead of silently mixing envelopes. + expectedOldEncryptedPrv: oldEncryptedPrv, + }); } - let decryptedPrv: string; - try { - decryptedPrv = await this.bitgo.decrypt({ input: oldEncryptedPrv, password: params.oldPassword }); - } catch (e) { - // Deliberate divergence from the legacy path's skip-and-continue: a key that no - // longer decrypts with the old passphrase would silently split the passphrase space - // if left behind. - const errorDetail = e instanceof Error ? e.message : String(e); - throw new IncorrectPasswordError( - `failed to decrypt keychain ${key.id} with the old passphrase: ${errorDetail}` - ); + // Public-only multisig children and MPC child backup/bitgo placeholders carry no + // user-held envelope — nothing to rotate, but they still count toward the yield + // boundary so the loop's spacing is a function of listed records, not outcomes. + processedRecords++; + if (params.yieldEvery !== undefined && processedRecords % params.yieldEvery === 0) { + await new Promise((resolve) => setTimeout(resolve, 0)); } - updates.push({ - keyId: key.id, - encryptedPrv: await session.encrypt(decryptedPrv), - // Compare-and-swap against the exact envelope we decrypted, so an in-flight mint - // racing the rotation is detected instead of silently mixing envelopes. - expectedOldEncryptedPrv: oldEncryptedPrv, - }); } if (result.nextBatchPrevId) { prevId = result.nextBatchPrevId; diff --git a/modules/sdk-core/src/common.ts b/modules/sdk-core/src/common.ts index d991474994c..e4b8bd0b2d3 100644 --- a/modules/sdk-core/src/common.ts +++ b/modules/sdk-core/src/common.ts @@ -32,6 +32,22 @@ export function getNetwork(): V1Network { return bitcoinNetwork; } +/** + * Validate the opt-in cooperative-yielding boundary for password-rotation loops. + * Accepts `undefined` (existing behavior preserved exactly) or a positive safe integer. + * + * @param value the caller-supplied `yieldEvery` option + * @throws Error when the value is defined but not a positive safe integer + */ +export function validateYieldEvery(value: number | undefined): void { + if (value === undefined) { + return; + } + if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) { + throw new Error('yieldEvery must be a positive safe integer'); + } +} + /** * Helper function to validate the input parameters to an SDK method. * Only validates for strings - if parameter is different, check that manually diff --git a/modules/sdk-core/test/unit/bitgo/keychain/keychains.ts b/modules/sdk-core/test/unit/bitgo/keychain/keychains.ts index bb5c269db1a..41c70c5a0e5 100644 --- a/modules/sdk-core/test/unit/bitgo/keychain/keychains.ts +++ b/modules/sdk-core/test/unit/bitgo/keychain/keychains.ts @@ -476,6 +476,72 @@ describe('Keychains.updatePassword (safe mode)', function () { changedKeys.should.deepEqual({ 'pub-good': 'new-envelope' }); sinon.assert.notCalled(put); }); + + it('yields between listed records when yieldEvery is provided', async function () { + stubListPages([[key('root-1'), key('root-2'), key('root-3')]]); + + const timeline: string[] = []; + sessionEncrypt.callsFake(async (plaintext: string) => { + timeline.push(`encrypt:${plaintext}`); + if (timeline.length === 1) { + // A zero-delay timer scheduled from the first re-encryption is enqueued before the + // loop's own yield timer, so with a per-record boundary it must run before the second + // record begins. + setTimeout(() => timeline.push('macrotask'), 0); + } + return `enc:${plaintext}`; + }); + + await keychains.updatePassword({ + oldPassword: OLD_PASSWORD, + newPassword: NEW_PASSWORD, + safeId: SAFE_ID, + yieldEvery: 1, + }); + + timeline.should.deepEqual(['encrypt:prv-root-1', 'macrotask', 'encrypt:prv-root-2', 'encrypt:prv-root-3']); + }); + + it('counts missing-envelope records toward the yieldEvery boundary', async function () { + stubListPages([[key('no-env', { encryptedPrv: undefined }), key('root-2'), key('root-3')]]); + + const timeline: string[] = []; + sessionEncrypt.callsFake(async (plaintext: string) => { + timeline.push(`encrypt:${plaintext}`); + if (timeline.length === 1) { + setTimeout(() => timeline.push('macrotask'), 0); + } + return `enc:${plaintext}`; + }); + + await keychains.updatePassword({ + oldPassword: OLD_PASSWORD, + newPassword: NEW_PASSWORD, + safeId: SAFE_ID, + // the missing-envelope record is record 1 and 'root-2' is record 2, so the boundary + // fires after root-2 only if missing-envelope records are counted + yieldEvery: 2, + }); + + timeline.should.deepEqual(['encrypt:prv-root-2', 'macrotask', 'encrypt:prv-root-3']); + }); + + it('rejects invalid yieldEvery values before touching any keychain', async function () { + stubListPages([[key('root-1')]]); + + const invalidValues: unknown[] = [0, -1, 1.5, NaN, Number.MAX_SAFE_INTEGER + 1, '1']; + for (const yieldEvery of invalidValues) { + await keychains + .updatePassword({ + oldPassword: OLD_PASSWORD, + newPassword: NEW_PASSWORD, + safeId: SAFE_ID, + yieldEvery: yieldEvery as number, + }) + .should.be.rejectedWith('yieldEvery must be a positive safe integer'); + } + sinon.assert.notCalled(put); + }); }); describe('Keychains.list safeId filter', function () { @@ -666,4 +732,67 @@ describe('Keychains.updatePassword (legacy mode, slim walk)', function () { changedKeys.should.deepEqual({}); events.should.deepEqual([{ status: 'skipped', currentKeychainId: 'pub-slim-no-env' }]); }); + + it('yields between listed records when yieldEvery is provided', async function () { + sinon.stub(keychains, 'list').resolves({ keys: [key('a'), key('b'), key('c')], nextBatchPrevId: undefined }); + + const timeline: string[] = []; + await keychains.updatePassword({ + oldPassword: OLD_PASSWORD, + newPassword: NEW_PASSWORD, + yieldEvery: 1, + progressCallback: (p) => { + timeline.push(`progress:${p.currentKeychainId}`); + if (timeline.length === 1) { + // A zero-delay timer scheduled from the first progress callback is enqueued before + // the loop's own yield timer, so with a per-record boundary it must run before the + // second record begins. + setTimeout(() => timeline.push('macrotask'), 0); + } + }, + }); + + timeline.should.deepEqual(['progress:pub-a', 'macrotask', 'progress:pub-b', 'progress:pub-c']); + }); + + it('counts skipped missing-envelope records toward the yieldEvery boundary', async function () { + const noEnvelope: Keychain = { id: 'slim-no-env', pub: 'pub-slim-no-env', type: 'independent' }; + sinon.stub(keychains, 'list').resolves({ + keys: [noEnvelope, key('a'), key('b')], + nextBatchPrevId: undefined, + }); + + const timeline: string[] = []; + await keychains.updatePassword({ + oldPassword: OLD_PASSWORD, + newPassword: NEW_PASSWORD, + // noEnvelope is record 1 and key('a') is record 2, so the boundary fires after 'a' only + // if missing-envelope records are counted + yieldEvery: 2, + progressCallback: (p) => { + timeline.push(`progress:${p.currentKeychainId}`); + if (timeline.length === 1) { + setTimeout(() => timeline.push('macrotask'), 0); + } + }, + }); + + timeline.should.deepEqual(['progress:pub-slim-no-env', 'progress:pub-a', 'macrotask', 'progress:pub-b']); + }); + + it('rejects invalid yieldEvery values before touching any keychain', async function () { + sinon.stub(keychains, 'list').resolves({ keys: [key('a')], nextBatchPrevId: undefined }); + + const invalidValues: unknown[] = [0, -1, 1.5, NaN, Number.MAX_SAFE_INTEGER + 1, '1']; + for (const yieldEvery of invalidValues) { + await keychains + .updatePassword({ + oldPassword: OLD_PASSWORD, + newPassword: NEW_PASSWORD, + yieldEvery: yieldEvery as number, + }) + .should.be.rejectedWith('yieldEvery must be a positive safe integer'); + } + sinon.assert.notCalled(decryptStub); + }); });