From 19d1f5a2e57b1ff5849d1365b29da3092ccb6f0a Mon Sep 17 00:00:00 2001 From: Vibhav Simha G Date: Wed, 18 Nov 2026 16:05:26 +0530 Subject: [PATCH] fix(sdk-core): opt rotation walk into slim key list Keychains.list() gains an optional envelopeOnly flag forwarded as the `envelopeOnly=true` query param; the legacy updatePassword walk opts in and pipelines the next page's fetch while the current page re-encrypts (shaving ~2s/page of client crypto off the serial round-trip). Progress event ordering and per-record outcomes are unchanged; old servers ignoring the param keep today's behavior. Safe-mode rotation is untouched. Ticket: WCI-2309 --- .../sdk-core/src/bitgo/keychain/iKeychains.ts | 8 + .../sdk-core/src/bitgo/keychain/keychains.ts | 32 ++-- .../test/unit/bitgo/keychain/keychains.ts | 153 ++++++++++++++++++ 3 files changed, 184 insertions(+), 9 deletions(-) diff --git a/modules/sdk-core/src/bitgo/keychain/iKeychains.ts b/modules/sdk-core/src/bitgo/keychain/iKeychains.ts index b8b8b8b1ca..fe9fd7d566 100644 --- a/modules/sdk-core/src/bitgo/keychain/iKeychains.ts +++ b/modules/sdk-core/src/bitgo/keychain/iKeychains.ts @@ -102,6 +102,14 @@ export interface ListKeychainOptions { * the same keys for any coin's keychains()), so any coin may be used for the walk. */ safeId?: string; + /** + * Opt-in slim response for the password-rotation walk (WCI-2309). Forwarded as the + * `envelopeOnly=true` query param; the server then returns a slim key shape (a subset + * of `Keychain` sufficient for password rotation: id, pub, type, source, the caller's + * encryptedPrv, coinSpecific.ofc.features). Older servers ignore the param and return + * full keychains, so opting in degrades gracefully. + */ + envelopeOnly?: boolean; } export type KeychainPasswordUpdateStatus = 'updated' | 'skipped'; diff --git a/modules/sdk-core/src/bitgo/keychain/keychains.ts b/modules/sdk-core/src/bitgo/keychain/keychains.ts index 51aa181873..f23fe7af25 100644 --- a/modules/sdk-core/src/bitgo/keychain/keychains.ts +++ b/modules/sdk-core/src/bitgo/keychain/keychains.ts @@ -114,6 +114,14 @@ export class Keychains implements IKeychains { } queryObject.safeId = params.safeId; } + if (!_.isUndefined(params.envelopeOnly)) { + if (!_.isBoolean(params.envelopeOnly)) { + throw new Error('invalid envelopeOnly argument, expecting boolean'); + } + if (params.envelopeOnly) { + queryObject.envelopeOnly = 'true'; + } + } return this.bitgo.get(this.baseCoin.url('/key')).query(queryObject).result(); } @@ -182,13 +190,24 @@ export class Keychains implements IKeychains { }; const observationId = (key: Keychain): string | undefined => key.type === 'tss' || Keychains.isMultiUserKey(key) ? key.id : key.pub; - let prevId; - let keysLeft = true; - while (keysLeft) { - const result: ListKeychainsResult = await this.list({ limit: 500, prevId }); + // The prefetch runs while the previous page's crypto is still awaited; attach a no-op + // catch immediately so a rejected fetch cannot become an unhandled rejection before + // the next iteration awaits it (Node's default handler would kill the process). + const startFetch = (prevId?: string): Promise => { + const fetch = this.list({ limit: 500, envelopeOnly: true, ...(prevId ? { prevId } : {}) }); + fetch.catch(_.noop); + return fetch; + }; + let pendingFetch: Promise | undefined = startFetch(); + while (pendingFetch !== undefined) { + const result: ListKeychainsResult = await pendingFetch; if (total === undefined && result.totalCount !== undefined) { total = result.totalCount; } + // Pipeline: start the next page's fetch while this page's re-encryption runs. + // Page N's records are all processed before page N+1's, so progress-event order + // stays deterministic. Last page → no prefetch. + pendingFetch = result.nextBatchPrevId ? startFetch(result.nextBatchPrevId) : undefined; for (const key of result.keys) { const oldEncryptedPrv = key.encryptedPrv; if (_.isUndefined(oldEncryptedPrv)) { @@ -236,11 +255,6 @@ export class Keychains implements IKeychains { notifyProgress('skipped', observationId(key)); } } - if (result.nextBatchPrevId) { - prevId = result.nextBatchPrevId; - } else { - keysLeft = false; - } } return changedKeys; } diff --git a/modules/sdk-core/test/unit/bitgo/keychain/keychains.ts b/modules/sdk-core/test/unit/bitgo/keychain/keychains.ts index 1233919604..9291e43cb3 100644 --- a/modules/sdk-core/test/unit/bitgo/keychain/keychains.ts +++ b/modules/sdk-core/test/unit/bitgo/keychain/keychains.ts @@ -496,3 +496,156 @@ describe('Keychains.list safeId filter', function () { sinon.assert.calledWith(query, { safeId: 'safe-123' }); }); }); + +describe('Keychains.list envelopeOnly', function () { + function buildListKeychains() { + const query = sinon.stub(); + const chain = { query, result: sinon.stub().resolves({ keys: [] }) }; + query.returns(chain); + const get = sinon.stub().returns(chain); + const bitgo = { get } as unknown as BitGoBase; + const baseCoin = { url: sinon.stub().callsFake((path: string) => path) } as unknown as IBaseCoin; + return { listKeychains: new Keychains(bitgo, baseCoin), query }; + } + + it('forwards envelopeOnly=true as a query parameter', async function () { + const { listKeychains, query } = buildListKeychains(); + await listKeychains.list({ envelopeOnly: true }); + sinon.assert.calledWith(query, { envelopeOnly: 'true' }); + }); + + it('omits the parameter when envelopeOnly is false or undefined', async function () { + const { listKeychains, query } = buildListKeychains(); + await listKeychains.list({ envelopeOnly: false }); + sinon.assert.calledWith(query, {}); + await listKeychains.list({}); + sinon.assert.calledWith(query, {}); + }); + + it('rejects a non-boolean envelopeOnly', async function () { + const { listKeychains } = buildListKeychains(); + await listKeychains + // @ts-expect-error exercising the runtime guard + .list({ envelopeOnly: 'true' }) + .should.be.rejectedWith('invalid envelopeOnly argument, expecting boolean'); + }); +}); + +describe('Keychains.updatePassword (legacy mode, slim walk)', function () { + const OLD_PASSWORD = 'old-passphrase'; + const NEW_PASSWORD = 'new-passphrase'; + + let keychains: Keychains; + let decryptStub: sinon.SinonStub; + + // getEncryptionVersion re-parses the old envelope in the legacy path, so it must be JSON. + function key(id: string, overrides: Partial = {}): Keychain { + return { + id, + pub: `pub-${id}`, + type: 'independent', + encryptedPrv: JSON.stringify({ v: 1, iv: 'iv-' + id, ct: 'ct-' + id }), + ...overrides, + }; + } + + beforeEach(function () { + decryptStub = sinon.stub().callsFake(async ({ password }: { input: string; password: string }) => { + if (password !== OLD_PASSWORD) { + throw new Error('incorrect password'); + } + return 'plain-prv'; + }); + const bitgo = { + decrypt: decryptStub, + createEncryptionSession: sinon + .stub() + .resolves({ encrypt: sinon.stub().resolves('new-envelope'), destroy: sinon.stub() }), + encrypt: sinon.stub().resolves('new-envelope'), + setRequestTracer: sinon.stub(), + } as unknown as BitGoBase; + const baseCoin = { url: sinon.stub().callsFake((path: string) => path) } as unknown as IBaseCoin; + keychains = new Keychains(bitgo, baseCoin); + }); + + it('opts the walk into the slim key list and rotates a slim response', async function () { + // Slim shape: only the fields the rotation walk consumes. + const slimKey = key('slim-1'); + const listStub = sinon.stub(keychains, 'list').callsFake(async (params: ListKeychainOptions = {}) => ({ + keys: params.prevId === undefined ? [slimKey] : [], + nextBatchPrevId: params.prevId === undefined ? 'page-2' : undefined, + })); + + const changedKeys = await keychains.updatePassword({ oldPassword: OLD_PASSWORD, newPassword: NEW_PASSWORD }); + + changedKeys.should.deepEqual({ 'pub-slim-1': 'new-envelope' }); + sinon.assert.calledWithExactly(listStub.firstCall, { limit: 500, envelopeOnly: true }); + sinon.assert.calledWithExactly(listStub.secondCall, { limit: 500, envelopeOnly: true, prevId: 'page-2' }); + }); + + it('starts the next page fetch before finishing the current page', async function () { + // Page 2's fetch must be issued while page 1's re-encryption is still running. + let listCalls = 0; + let listCallsAtDecrypt = -1; + sinon.stub(keychains, 'list').callsFake(async (params: ListKeychainOptions = {}) => { + listCalls++; + const keys = params.prevId === undefined ? [key('page1')] : [key('page2')]; + return { keys, nextBatchPrevId: params.prevId === undefined ? 'page-2' : undefined }; + }); + decryptStub.callsFake(async (args: { input: string; password: string }) => { + if (args.input.includes('page1')) { + listCallsAtDecrypt = listCalls; + } + if (args.password !== OLD_PASSWORD) { + throw new Error('incorrect password'); + } + return 'plain-prv'; + }); + + await keychains.updatePassword({ oldPassword: OLD_PASSWORD, newPassword: NEW_PASSWORD }); + + (listCallsAtDecrypt >= 2).should.be.true(); + }); + + it('still rotates full (old-server) responses when the param is ignored', async function () { + const fullKey = key('full-1', { commonKeychain: 'a'.repeat(64) }); + sinon.stub(keychains, 'list').resolves({ keys: [fullKey], nextBatchPrevId: undefined }); + + const changedKeys = await keychains.updatePassword({ oldPassword: OLD_PASSWORD, newPassword: NEW_PASSWORD }); + + changedKeys.should.deepEqual({ 'pub-full-1': 'new-envelope' }); + }); + + it('keys slim responses by id for tss and ofc multi-user keys, by pub otherwise', async function () { + const tssKey = key('tss-1', { type: 'tss' }); + const ofcKey = key('ofc-1', { + coinSpecific: { ofc: { features: ['multi-user-key'] } }, + }); + const plainKey = key('plain-1'); + sinon.stub(keychains, 'list').resolves({ keys: [tssKey, ofcKey, plainKey], nextBatchPrevId: undefined }); + + const changedKeys = await keychains.updatePassword({ oldPassword: OLD_PASSWORD, newPassword: NEW_PASSWORD }); + + changedKeys.should.deepEqual({ + // tss and ofc multi-user keys are identified by id; plain keys by pub. + 'tss-1': 'new-envelope', + 'ofc-1': 'new-envelope', + 'pub-plain-1': 'new-envelope', + }); + }); + + it('still rejects with the fetch error when a later page fails', async function () { + // The pipelined prefetch must not swallow fetch failures: the walk rejects + // before processing any record of the failing page, after finishing page 1. + sinon.stub(keychains, 'list').callsFake(async (params: ListKeychainOptions = {}) => { + if (params.prevId === undefined) { + return { keys: [key('page1')], nextBatchPrevId: 'page-2' }; + } + throw new Error('page 2 fetch failed'); + }); + + await keychains + .updatePassword({ oldPassword: OLD_PASSWORD, newPassword: NEW_PASSWORD }) + .should.be.rejectedWith('page 2 fetch failed'); + }); +});