diff --git a/modules/sdk-api/src/bitgoAPI.ts b/modules/sdk-api/src/bitgoAPI.ts index 0b4e55699e..997f0acedc 100644 --- a/modules/sdk-api/src/bitgoAPI.ts +++ b/modules/sdk-api/src/bitgoAPI.ts @@ -2227,8 +2227,8 @@ export class BitGoAPI implements BitGoBase { password: hmacNewPassword, }; - // Calculate payload size in KB - const payloadSizeBytes = JSON.stringify(updatePasswordParams).length; + // sized per-entry: a full stringify crashes on heavy accounts before batching can run + const payloadSizeBytes = this.computeChangePasswordPayloadSize(updatePasswordParams); const payloadSizeKB = Math.ceil(payloadSizeBytes / 1024); // Check if batching flow is enabled @@ -2255,11 +2255,16 @@ export class BitGoAPI implements BitGoBase { // Call changepassword API without keychains for batching flow. Awaited outside the // check/upload try-catch above, so a rejection here still propagates to the caller // with no legacy-POST fallback, exactly as before. + // Verified server-side against the total staged — a partial or TTL-expired upload + // fails loudly instead of flipping the password. + const expectedKeychainCount = + Object.keys(updatePasswordParams.keychains).length + Object.keys(updatePasswordParams.v2_keychains).length; const result = await this.post(this.url('/user/changepassword')) .send({ version: updatePasswordParams.version, oldPassword: updatePasswordParams.oldPassword, password: updatePasswordParams.password, + expectedKeychainCount, }) .result(); emitProgress({ phase: 'finalizing', status: 'completed' }); @@ -2566,6 +2571,29 @@ export class BitGoAPI implements BitGoBase { return bins; } + /** + * Approximate serialized size, in bytes, of the changePassword update payload: + * scalar fields via JSON.stringify plus per-entry byte lengths for the keychain + * maps, the same idiom packKeychainsFFD uses. Approximation is sufficient — the + * server compares this size, KB-rounded, against its batching threshold — while + * a full stringify of hundreds of MB of re-encrypted key material would throw + * RangeError above V8's max string length, crashing the rotation before the + * batching check could run. + */ + private computeChangePasswordPayloadSize(params: { + keychains: Record; + v2_keychains: Record; + [key: string]: unknown; + }): number { + const { keychains, v2_keychains, ...scalars } = params; + const keyMaterialBytes = (map: Record): number => + Object.entries(map).reduce( + (sum, [id, value]) => sum + Buffer.byteLength(id, 'utf8') + Buffer.byteLength(value, 'utf8'), + 0 + ); + return JSON.stringify(scalars).length + keyMaterialBytes(keychains) + keyMaterialBytes(v2_keychains); + } + /** * Process keychain password updates in batches with retry logic. * Uses First Fit Decreasing (FFD) bin packing to ensure no batch exceeds @@ -2593,15 +2621,28 @@ export class BitGoAPI implements BitGoBase { bins.push({ v1Batch: {}, v2Batch: {}, sizeBytes: 0 }); } - for (let i = 0; i < bins.length; i++) { + const BATCH_CONCURRENCY = 4; // WCI-2309 probe: ~6 Mbps at 4 streams vs ~1.7 single-stream + + // Computed once after the empty-bins guard; binCount >= 1 from here on. + const binCount = bins.length; + const workerCount = Math.min(BATCH_CONCURRENCY, binCount); + const keychainsUrl = this.url('/user/keychains', 2); + + let nextBin = 0; + let firstError: Error | undefined; + + // Same retry loop, PUT, and error strings as the sequential version — only dispatch is + // concurrent; nextBin++ on the single-threaded event loop is exactly-once. A sibling's + // terminal failure abandons this bin's remaining retries. + const processBin = async (i: number): Promise => { const { v1Batch, v2Batch } = bins[i]; let retryCount = 0; let success = false; - while (retryCount < maxRetries && !success) { + while (retryCount < maxRetries && !success && !firstError) { try { - const response = await this.put(this.url('/user/keychains', 2)) + const response = await this.put(keychainsUrl) .send({ keychains: v1Batch, v2_keychains: v2Batch, @@ -2626,6 +2667,30 @@ export class BitGoAPI implements BitGoBase { } } } + }; + + // A terminal failure stops new pulls; in-flight bins settle (idempotent staging + // upserts, retries abandoned). First error rethrows after all workers finish. + const worker = async (): Promise => { + while (!firstError) { + const i = nextBin++; + if (i >= binCount) { + return; + } + try { + await processBin(i); + } catch (error) { + if (!firstError) { + firstError = error instanceof Error ? error : new Error(String(error)); + } + return; + } + } + }; + + await Promise.all(Array.from({ length: workerCount }, () => worker())); + if (firstError) { + throw firstError; } } } diff --git a/modules/sdk-api/test/unit/bitgoAPI.ts b/modules/sdk-api/test/unit/bitgoAPI.ts index a962f21789..a77a0cb6b2 100644 --- a/modules/sdk-api/test/unit/bitgoAPI.ts +++ b/modules/sdk-api/test/unit/bitgoAPI.ts @@ -1,7 +1,7 @@ import * as assert from 'assert'; -import 'should'; import { BitGoAPI } from '../../src/bitgoAPI'; import { ProxyAgent } from 'proxy-agent'; +import * as should from 'should'; import * as sinon from 'sinon'; import nock from 'nock'; import type { IHmacAuthStrategy } from '@bitgo/sdk-hmac'; @@ -976,6 +976,54 @@ describe('Constructor', function () { }); }); + describe('computeChangePasswordPayloadSize', function () { + let bitgo: BitGoAPI; + + before(function () { + bitgo = new BitGoAPI({ env: 'custom', customRootURI: 'https://app.example.local' }); + }); + + function payloadSize(params: { + keychains: Record; + v2_keychains: Record; + version?: number; + oldPassword: string; + password: string; + }): number { + return (bitgo as any).computeChangePasswordPayloadSize(params); + } + + it('equals the scalar scaffold when both maps are empty', function () { + const params = { keychains: {}, v2_keychains: {}, version: 2, oldPassword: 'old', password: 'new' }; + payloadSize(params).should.equal(JSON.stringify({ version: 2, oldPassword: 'old', password: 'new' }).length); + }); + + it('equals scalar scaffold plus per-entry id/value byte lengths', function () { + const keychains = { k1: 'v'.repeat(1000), 'id"q': 'x'.repeat(500), plain: 'base64+/=envelope' }; + const v2Keychains = { xpub: 'y'.repeat(2000) }; + const params = { keychains, v2_keychains: v2Keychains, version: 2, oldPassword: 'old', password: 'new' }; + const scalars = JSON.stringify({ version: 2, oldPassword: 'old', password: 'new' }).length; + const material = [...Object.entries(keychains), ...Object.entries(v2Keychains)].reduce( + (sum, [id, value]) => sum + Buffer.byteLength(id, 'utf8') + Buffer.byteLength(value, 'utf8'), + 0 + ); + payloadSize(params).should.equal(scalars + material); + }); + + it('sizes a payload larger than V8 max string length without materializing it', function () { + // 600 MiB of key material — past V8's 536,870,888-char string cap, where a full + // stringify would throw RangeError: Invalid string length + const oneMiB = 'x'.repeat(1024 * 1024); + const keychains: Record = {}; + for (let i = 0; i < 600; i++) { + keychains[`id${i}`] = oneMiB; + } + const params = { keychains, v2_keychains: {}, version: 1, oldPassword: 'old', password: 'new' }; + const size = payloadSize(params); + (size >= 600 * 1024 * 1024).should.be.true(); + }); + }); + describe('processKeychainPasswordUpdatesInBatches', function () { const ROOT = 'https://app.example.local'; let bitgo: BitGoAPI; @@ -1062,6 +1110,111 @@ describe('Constructor', function () { await runBatches({}, {}, 1024); scope.isDone().should.be.true(); }); + + it('uploads bins concurrently, capping in-flight PUTs at 4', async function () { + // 12 entries at ~1000 bytes each with a 1 KB cap => 12 single-entry bins + const v2Keychains: Record = {}; + for (let i = 0; i < 12; i++) { + v2Keychains[`vk${i}`] = 'x'.repeat(1000); + } + + let inFlight = 0; + let maxInFlight = 0; + let saturated = false; + const releases: Array<(result: [number, Record]) => void> = []; + const putBodies: Record[] = []; + nock(ROOT) + .put('/api/v2/user/keychains') + .times(12) + .reply((uri, body) => { + if (typeof body === 'object' && body !== null) { + putBodies.push(body); + } + if (saturated) { + return [200, {}] as [number, Record]; + } + inFlight++; + maxInFlight = Math.max(maxInFlight, inFlight); + return new Promise((resolve) => { + releases.push(resolve); + }); + }); + + const batchesDone = runBatches({}, v2Keychains, 1); + // wait until the pool saturates (4 PUTs held in flight) + for (let waited = 0; inFlight < 4 && waited < 200; waited++) { + await new Promise((resolve) => setTimeout(resolve, 10)); + } + inFlight.should.equal(4); + saturated = true; + releases.splice(0).forEach((resolve) => resolve([200, {}])); + await batchesDone; + maxInFlight.should.equal(4); + + const seenCounts: Record = {}; + for (const body of putBodies) { + const v2Batch = typeof body === 'object' && body !== null ? body.v2_keychains : undefined; + for (const key of Object.keys((v2Batch as Record | undefined) ?? {})) { + seenCounts[key] = (seenCounts[key] ?? 0) + 1; + } + } + for (const key of Object.keys(v2Keychains)) { + seenCounts[key].should.equal(1); + } + }); + + it('dispatches every bin exactly once under concurrency', async function () { + // 8 entries at ~1000 bytes each with a 1 KB cap => 8 single-entry bins + const v2Keychains: Record = {}; + for (let i = 0; i < 8; i++) { + v2Keychains[`vk${i}`] = 'x'.repeat(1000); + } + + let putCount = 0; + const mergedV2: Record = {}; + nock(ROOT) + .put('/api/v2/user/keychains') + .times(8) + .reply((uri, body) => { + putCount++; + const v2Batch = typeof body === 'object' && body !== null ? body.v2_keychains : undefined; + Object.assign(mergedV2, (v2Batch as Record | undefined) ?? {}); + return [200, {}] as [number, Record]; + }); + + await runBatches({}, v2Keychains, 1); + + putCount.should.equal(8); + mergedV2.should.deepEqual(v2Keychains); + }); + + it('stops dispatching new bins and rethrows the first terminal error', async function () { + // 10 entries at ~1000 bytes each with a 1 KB cap => 10 single-entry bins + const v2Keychains: Record = {}; + for (let i = 0; i < 10; i++) { + v2Keychains[`vk${i}`] = 'x'.repeat(1000); + } + + let putCount = 0; + nock(ROOT) + .put('/api/v2/user/keychains') + .times(10) + .reply(() => { + putCount++; + return [500, { error: 'internal error' }] as [number, Record]; + }); + + let thrownError: Error | undefined; + try { + await runBatches({}, v2Keychains, 1, 1); + } catch (e) { + thrownError = e as Error; + } + should.exist(thrownError); + thrownError!.message.should.match(/Batch \d+ failed after 1 retries/); + // 4 workers each pull one bin; a terminal failure stops all further pulls + putCount.should.equal(4); + }); }); describe('changePassword batching flow', function () { @@ -1120,7 +1273,10 @@ describe('Constructor', function () { const batchPutScope = nock(ROOT).put('/api/v2/user/keychains').reply(200, {}); const changePassScope = nock(ROOT) - .post('/api/v1/user/changepassword', (body: any) => !body.keychains && !body.v2_keychains) + .post( + '/api/v1/user/changepassword', + (body: Record) => !body.keychains && !body.v2_keychains && body.expectedKeychainCount === 2 + ) .reply(200, {}); await bitgo.changePassword({ oldPassword: 'oldpw', newPassword: 'newpw' }); @@ -1140,7 +1296,10 @@ describe('Constructor', function () { .put('/api/v2/user/keychains', { keychains: {}, v2_keychains: {} }) .reply(200, {}); const changePassScope = nock(ROOT) - .post('/api/v1/user/changepassword', (body: any) => !body.keychains && !body.v2_keychains) + .post( + '/api/v1/user/changepassword', + (body: Record) => !body.keychains && !body.v2_keychains && body.expectedKeychainCount === 0 + ) .reply(200, {}); await bitgo.changePassword({ oldPassword: 'oldpw', newPassword: 'newpw' }); batchPutScope.isDone().should.be.true(); @@ -1151,7 +1310,11 @@ describe('Constructor', function () { nock(ROOT).get('/api/v2/user/checkBatchingPasswordFlow').query(true).reply(200, { isBatchingFlowEnabled: false }); const legacyScope = nock(ROOT) - .post('/api/v1/user/changepassword', (body: any) => !!body.keychains && !!body.v2_keychains) + .post( + '/api/v1/user/changepassword', + (body: Record) => + !!body.keychains && !!body.v2_keychains && body.expectedKeychainCount === undefined + ) .reply(200, {}); await bitgo.changePassword({ oldPassword: 'oldpw', newPassword: 'newpw' }); 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..bb5c269db1 100644 --- a/modules/sdk-core/test/unit/bitgo/keychain/keychains.ts +++ b/modules/sdk-core/test/unit/bitgo/keychain/keychains.ts @@ -496,3 +496,174 @@ 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'); + }); + + it('reports a slim key without an envelope as skipped, not an error', async function () { + // S3-residency / listed-but-no-envelope records: the slim shape is exactly + // { id, pub, type, source } with no encryptedPrv — the walk must report the + // record skipped and leave it out of changedKeys, never throw. + const noEnvelope: Keychain = { id: 'slim-no-env', pub: 'pub-slim-no-env', type: 'independent' }; + const events: { status: string; currentKeychainId?: string }[] = []; + sinon.stub(keychains, 'list').resolves({ keys: [noEnvelope], nextBatchPrevId: undefined }); + + const changedKeys = await keychains.updatePassword({ + oldPassword: OLD_PASSWORD, + newPassword: NEW_PASSWORD, + progressCallback: (p) => events.push({ status: p.status, currentKeychainId: p.currentKeychainId }), + }); + + changedKeys.should.deepEqual({}); + events.should.deepEqual([{ status: 'skipped', currentKeychainId: 'pub-slim-no-env' }]); + }); +});