diff --git a/modules/express/README.md b/modules/express/README.md index ba67162198..20a8fa1f28 100644 --- a/modules/express/README.md +++ b/modules/express/README.md @@ -264,6 +264,7 @@ BitGo Express is able to take configuration options from either command line arg | N/A | --lightningSignerFileSystemPath | `BITGO_LIGHTNING_SIGNER_FILE_SYSTEM_PATH` | N/A | Local path specifying how to contact the lightning signer node. | | N/A | --keepalivetimeout | `BITGO_KEEP_ALIVE_TIMEOUT` | N/A | BitGo Express server KeepAliveTimeout node. | | N/A | --headerstimeout | `BITGO_HEADERS_TIMEOUT` | N/A | BitGo Express server HeadersTimeout node. | +| N/A | --argon2concurrency | `BITGO_ARGON2_CONCURRENCY` | 16 | Max concurrent Argon2id hashes (password-based v2 encrypt/decrypt and sessions) across requests in this process. Hashes beyond the limit wait in a FIFO queue of up to 500; further calls fail with `AsyncWorkQueueFullError` until a place frees up. Default ~64 MiB per hash, so 16 is about 1 GiB in flight and 4 is about 256 MiB. Not a total RSS cap, and each worker or process has its own limit. CLI overrides the env var. | | N/A | --disablepincerts | `BITGO_DISABLE_PIN_CERTS` | false | Disable the default domain-scoped CA bundle restriction for BitGo hostnames. See [Domain-scoped CA trust for BitGo connections](#domain-scoped-ca-trust-for-bitgo-connections). | \[0]: BitGo will also check the additional environment variables for some options for backwards compatibility, but these environment variables should be considered deprecated: diff --git a/modules/express/src/args.ts b/modules/express/src/args.ts index b97e3f84e6..35c78741ec 100644 --- a/modules/express/src/args.ts +++ b/modules/express/src/args.ts @@ -127,4 +127,9 @@ parser.addArgument(['--keepalivetimeout'], { parser.addArgument(['--headerstimeout'], { help: 'headers timeout in milliseconds', }); + +parser.addArgument(['--argon2concurrency'], { + type: 'int', + help: 'Max concurrent Argon2id hashes (default 16).', +}); export const args = () => parser.parseArgs(); diff --git a/modules/express/src/clientRoutes.ts b/modules/express/src/clientRoutes.ts index 25876c03af..917bfa3a44 100755 --- a/modules/express/src/clientRoutes.ts +++ b/modules/express/src/clientRoutes.ts @@ -505,6 +505,9 @@ async function decryptPrivKey(bg: BitGo, encryptedPrivKey: string, walletPw: str try { return await bg.decrypt({ password: walletPw, input: encryptedPrivKey }); } catch (e) { + if (e instanceof Error && e.name === 'AsyncWorkQueueFullError') { + throw e; + } const detail = e instanceof Error ? e.message : String(e); if (/not valid JSON|unknown envelope version|salt must be|iv must be/i.test(detail)) { throw new Error(`Error when trying to decrypt private key: ${detail}`); @@ -1944,6 +1947,7 @@ function prepareBitGo(config: Config) { env, customRootURI: customRootUri, customBitcoinNetwork, + argon2Concurrency: config.argon2Concurrency, accessToken, userAgent, ...(useProxyUrl diff --git a/modules/express/src/config.ts b/modules/express/src/config.ts index cc3d01efaf..f7a9607542 100644 --- a/modules/express/src/config.ts +++ b/modules/express/src/config.ts @@ -54,6 +54,8 @@ export interface Config { lightningSignerFileSystemPath?: string; keepAliveTimeout?: number; headersTimeout?: number; + /** Max concurrent Argon2id hashes in the SDK queue. Defaults to the SDK default (16) when unset. */ + argon2Concurrency?: number; } export const ArgConfig = (args): Partial => ({ @@ -82,35 +84,50 @@ export const ArgConfig = (args): Partial => ({ lightningSignerFileSystemPath: args.lightningSignerFileSystemPath, keepAliveTimeout: args.keepalivetimeout, headersTimeout: args.headerstimeout, + argon2Concurrency: args.argon2concurrency, }); -export const EnvConfig = (): Partial => ({ - port: Number(readEnvVar('BITGO_PORT')), - bind: readEnvVar('BITGO_BIND'), - ipc: readEnvVar('BITGO_IPC'), - env: readEnvVar('BITGO_ENV') as EnvironmentName, - debugNamespace: (readEnvVar('BITGO_DEBUG_NAMESPACE') || '').split(','), - keyPath: readEnvVar('BITGO_KEYPATH'), - crtPath: readEnvVar('BITGO_CRTPATH'), - sslKey: readEnvVar('BITGO_SSL_KEY'), - sslCert: readEnvVar('BITGO_SSL_CERT'), - logFile: readEnvVar('BITGO_LOGFILE'), - disableSSL: readEnvVar('BITGO_DISABLE_SSL', 'BITGO_DISABLESSL', 'DISABLESSL', 'DISABLE_SSL') ? true : undefined, - disableProxy: readEnvVar('BITGO_DISABLE_PROXY', 'DISABLE_PROXY') ? true : undefined, - disableEnvCheck: readEnvVar('BITGO_DISABLE_ENV_CHECK', 'DISABLE_ENV_CHECK') ? true : undefined, - disablePinCerts: readBooleanEnvVar('BITGO_DISABLE_PIN_CERTS'), - timeout: Number(readEnvVar('BITGO_TIMEOUT')), - customRootUri: readEnvVar('BITGO_CUSTOM_ROOT_URI'), - customBitcoinNetwork: readEnvVar('BITGO_CUSTOM_BITCOIN_NETWORK') as V1Network, - authVersion: Number(readEnvVar('BITGO_AUTH_VERSION')), - externalSignerUrl: readEnvVar('BITGO_EXTERNAL_SIGNER_URL'), - signerMode: readEnvVar('BITGO_SIGNER_MODE') ? true : undefined, - signerFileSystemPath: readEnvVar('BITGO_SIGNER_FILE_SYSTEM_PATH'), - signerRegistryFilePath: readEnvVar('BITGO_SIGNER_REGISTRY_FILE_PATH'), - lightningSignerFileSystemPath: readEnvVar('BITGO_LIGHTNING_SIGNER_FILE_SYSTEM_PATH'), - keepAliveTimeout: Number(readEnvVar('BITGO_KEEP_ALIVE_TIMEOUT')), - headersTimeout: Number(readEnvVar('BITGO_HEADERS_TIMEOUT')), -}); +export const EnvConfig = (): Partial => { + const argon2ConcurrencyEnv = readEnvVar('BITGO_ARGON2_CONCURRENCY'); + let argon2Concurrency: number | undefined; + if (argon2ConcurrencyEnv !== undefined) { + const trimmed = argon2ConcurrencyEnv.trim(); + const parsed = Number(trimmed); + if (!/^\d+$/.test(trimmed) || !Number.isSafeInteger(parsed) || parsed <= 0) { + throw new Error('BITGO_ARGON2_CONCURRENCY must be a positive safe integer'); + } + argon2Concurrency = parsed; + } + + return { + port: Number(readEnvVar('BITGO_PORT')), + bind: readEnvVar('BITGO_BIND'), + ipc: readEnvVar('BITGO_IPC'), + env: readEnvVar('BITGO_ENV') as EnvironmentName, + debugNamespace: (readEnvVar('BITGO_DEBUG_NAMESPACE') || '').split(','), + keyPath: readEnvVar('BITGO_KEYPATH'), + crtPath: readEnvVar('BITGO_CRTPATH'), + sslKey: readEnvVar('BITGO_SSL_KEY'), + sslCert: readEnvVar('BITGO_SSL_CERT'), + logFile: readEnvVar('BITGO_LOGFILE'), + disableSSL: readEnvVar('BITGO_DISABLE_SSL', 'BITGO_DISABLESSL', 'DISABLESSL', 'DISABLE_SSL') ? true : undefined, + disableProxy: readEnvVar('BITGO_DISABLE_PROXY', 'DISABLE_PROXY') ? true : undefined, + disableEnvCheck: readEnvVar('BITGO_DISABLE_ENV_CHECK', 'DISABLE_ENV_CHECK') ? true : undefined, + disablePinCerts: readBooleanEnvVar('BITGO_DISABLE_PIN_CERTS'), + timeout: Number(readEnvVar('BITGO_TIMEOUT')), + customRootUri: readEnvVar('BITGO_CUSTOM_ROOT_URI'), + customBitcoinNetwork: readEnvVar('BITGO_CUSTOM_BITCOIN_NETWORK') as V1Network, + authVersion: Number(readEnvVar('BITGO_AUTH_VERSION')), + externalSignerUrl: readEnvVar('BITGO_EXTERNAL_SIGNER_URL'), + signerMode: readEnvVar('BITGO_SIGNER_MODE') ? true : undefined, + signerFileSystemPath: readEnvVar('BITGO_SIGNER_FILE_SYSTEM_PATH'), + signerRegistryFilePath: readEnvVar('BITGO_SIGNER_REGISTRY_FILE_PATH'), + lightningSignerFileSystemPath: readEnvVar('BITGO_LIGHTNING_SIGNER_FILE_SYSTEM_PATH'), + keepAliveTimeout: Number(readEnvVar('BITGO_KEEP_ALIVE_TIMEOUT')), + headersTimeout: Number(readEnvVar('BITGO_HEADERS_TIMEOUT')), + argon2Concurrency, + }; +}; export const DefaultConfig: Config = { port: 3080, @@ -199,6 +216,7 @@ function mergeConfigs(...configs: Partial[]): Config { lightningSignerFileSystemPath: get('lightningSignerFileSystemPath'), keepAliveTimeout: get('keepAliveTimeout'), headersTimeout: get('headersTimeout'), + ...(get('argon2Concurrency') !== undefined ? { argon2Concurrency: get('argon2Concurrency') } : {}), }; } diff --git a/modules/express/src/expressApp.ts b/modules/express/src/expressApp.ts index f02eccadaf..bbf8cc00e8 100644 --- a/modules/express/src/expressApp.ts +++ b/modules/express/src/expressApp.ts @@ -232,6 +232,13 @@ function checkPreconditions(config: Config) { const needsTLS = !ipc && env === 'prod' && bind !== 'localhost' && !disableSSL; + if ( + config.argon2Concurrency !== undefined && + !(Number.isSafeInteger(config.argon2Concurrency) && config.argon2Concurrency > 0) + ) { + throw new Error('argon2Concurrency must be a positive safe integer'); + } + // make sure keyPath and crtPath are set when running over TLS if (needsTLS && !(keyPath && crtPath) && !(sslKey && sslCert)) { throw new TlsConfigurationError('Must enable TLS when running against prod and listening on external interfaces!'); diff --git a/modules/express/test/unit/bitgoExpress.ts b/modules/express/test/unit/bitgoExpress.ts index d12a60b12a..61b93dcbd6 100644 --- a/modules/express/test/unit/bitgoExpress.ts +++ b/modules/express/test/unit/bitgoExpress.ts @@ -12,6 +12,7 @@ import { Environments } from 'bitgo'; import { SSL_OP_NO_TLSv1 } from 'constants'; import { TlsConfigurationError, NodeEnvironmentError } from '../../src/errors'; +import type { Config } from '../../src/config'; import { app as expressApp, startup, createServer, createBaseUri, prepareIpc } from '../../src/expressApp'; @@ -579,6 +580,17 @@ describe('Bitgo Express', function () { readValidStub.restore(); }); + it('should reject an invalid argon2Concurrency before serving requests', function () { + const base = { env: 'test', bind: 'localhost' } satisfies Partial; + should(() => expressApp({ ...base, argon2Concurrency: 0 } as Config)).throw( + 'argon2Concurrency must be a positive safe integer' + ); + should(() => expressApp({ ...base, argon2Concurrency: 1.5 } as Config)).throw( + 'argon2Concurrency must be a positive safe integer' + ); + should(() => expressApp({ ...base, argon2Concurrency: 4 } as Config)).not.throw(); + }); + it('should set keepAliveTimeout and headersTimeout if specified in config for HTTP server', async function () { const createServerStub = sinon.stub(http, 'createServer').callsFake(() => { return { listen: sinon.stub(), setTimeout: sinon.stub() }; diff --git a/modules/express/test/unit/clientRoutes/signPayload.ts b/modules/express/test/unit/clientRoutes/signPayload.ts index b8fb7992fe..9f51c5ec1d 100644 --- a/modules/express/test/unit/clientRoutes/signPayload.ts +++ b/modules/express/test/unit/clientRoutes/signPayload.ts @@ -389,6 +389,34 @@ describe('With the handler to sign an arbitrary payload in external signing mode envStub.restore(); }); + it('should surface AsyncWorkQueueFullError instead of reporting a wrong passphrase', async () => { + const readFileStub = sinon.stub(fs.promises, 'readFile').resolves(validPrv); + const envStub = sinon.stub(process, 'env').value({ [`WALLET_${walletId}_PASSPHRASE`]: 'anyPassphrase' }); + const queueFull = Object.assign(new Error('Async work queue is full'), { name: 'AsyncWorkQueueFullError' }); + const decryptStub = sinon.stub(bitgo, 'decrypt').rejects(queueFull); + + const req = { + bitgo, + body: { + walletId, + payload, + }, + decoded: { + walletId, + payload, + }, + config: { + signerFileSystemPath: 'signerFileSystemPath', + }, + } as unknown as ExpressApiRouteRequest<'express.v2.ofc.extSignPayload', 'post'>; + + await handleV2OFCSignPayloadInExtSigningMode(req).should.be.rejectedWith(queueFull); + + decryptStub.restore(); + readFileStub.restore(); + envStub.restore(); + }); + it('should throw error when trying to decrypt with invalid wallet passphrase in body', async () => { const readFileStub = sinon.stub(fs.promises, 'readFile').resolves(validPrv); diff --git a/modules/express/test/unit/config.ts b/modules/express/test/unit/config.ts index 5304738735..2bbcb43d18 100644 --- a/modules/express/test/unit/config.ts +++ b/modules/express/test/unit/config.ts @@ -2,6 +2,7 @@ /// // eslint-disable-next-line /// +import assert from 'assert'; import * as should from 'should'; import * as sinon from 'sinon'; @@ -311,4 +312,52 @@ describe('Config:', () => { argvStub.restore(); } }); + + it('should parse BITGO_ARGON2_CONCURRENCY and let the CLI flag take precedence', () => { + const envStub = sinon.stub(process, 'env').value({ BITGO_ARGON2_CONCURRENCY: '4' }); + try { + const { config: envConfig } = proxyquire('../../src/config', { './args': { args: () => ({}) } }); + assert.strictEqual(envConfig().argon2Concurrency, 4); + + const { config: cliConfig } = proxyquire('../../src/config', { + './args': { args: () => ({ argon2concurrency: 2 }) }, + }); + assert.strictEqual(cliConfig().argon2Concurrency, 2); + } finally { + envStub.restore(); + } + }); + + it('should leave argon2Concurrency unset when BITGO_ARGON2_CONCURRENCY is missing or empty', () => { + for (const env of [{}, { BITGO_ARGON2_CONCURRENCY: '' }]) { + const envStub = sinon.stub(process, 'env').value(env); + try { + const { config: proxyConfig } = proxyquire('../../src/config', { './args': { args: () => ({}) } }); + assert.strictEqual(proxyConfig().argon2Concurrency, undefined); + } finally { + envStub.restore(); + } + } + }); + + it('should reject malformed BITGO_ARGON2_CONCURRENCY values instead of dropping them', () => { + for (const raw of ['abc', '0', '-1', '1.5', ' ', '9007199254740992']) { + const envStub = sinon.stub(process, 'env').value({ BITGO_ARGON2_CONCURRENCY: raw }); + try { + const { config: proxyConfig } = proxyquire('../../src/config', { './args': { args: () => ({}) } }); + assert.throws(() => proxyConfig(), /BITGO_ARGON2_CONCURRENCY must be a positive safe integer/); + } finally { + envStub.restore(); + } + } + }); + + it('should parse --argon2concurrency from argv', () => { + const argvStub = sinon.stub(process, 'argv').value([process.argv[0], process.argv[1], '--argon2concurrency', '2']); + try { + assert.strictEqual(args.args().argon2concurrency, 2); + } finally { + argvStub.restore(); + } + }); }); diff --git a/modules/sdk-api/src/argon2Limiter.ts b/modules/sdk-api/src/argon2Limiter.ts new file mode 100644 index 0000000000..43778091ce --- /dev/null +++ b/modules/sdk-api/src/argon2Limiter.ts @@ -0,0 +1,4 @@ +import { AsyncWorkQueue } from './asyncWorkQueue'; + +/** Argon2id hashes allowed to run at once; further hashes wait (up to 500) in FIFO order. */ +export const argon2Queue = new AsyncWorkQueue(16, 500); diff --git a/modules/sdk-api/src/asyncWorkQueue.ts b/modules/sdk-api/src/asyncWorkQueue.ts new file mode 100644 index 0000000000..3dc56fa84c --- /dev/null +++ b/modules/sdk-api/src/asyncWorkQueue.ts @@ -0,0 +1,50 @@ +/** + * Runs async jobs with at most `concurrency` in flight. Jobs beyond that wait in a FIFO + * list of at most `maxWaiting` entries; further calls reject immediately. + */ +export class AsyncWorkQueue { + private active = 0; + private readonly waiters: Array<() => void> = []; + + constructor(private concurrency: number, private readonly maxWaiting: number) {} + + async run(job: () => Promise): Promise { + // Fast path: a slot is free. drain() always fills free slots from the waiter list first, + // so a free slot implies no waiter is queued behind it. + if (this.active < this.concurrency) { + this.active++; + } else { + if (this.waiters.length >= this.maxWaiting) { + throw Object.assign(new Error('Async work queue is full'), { name: 'AsyncWorkQueueFullError' }); + } + await new Promise((resolve) => this.waiters.push(resolve)); + } + + try { + return await job(); + } finally { + this.active--; + this.drain(); + } + } + + setConcurrency(value: number): void { + if (value === this.concurrency) { + return; + } + this.concurrency = value; + this.drain(); + } + + private drain(): void { + while (this.active < this.concurrency) { + const next = this.waiters.shift(); + if (!next) { + return; + } + // The resumed job takes its slot here, so a new arrival cannot overtake it. + this.active++; + next(); + } + } +} diff --git a/modules/sdk-api/src/bitgoAPI.ts b/modules/sdk-api/src/bitgoAPI.ts index 0b4e55699e..b68a7606ee 100644 --- a/modules/sdk-api/src/bitgoAPI.ts +++ b/modules/sdk-api/src/bitgoAPI.ts @@ -44,6 +44,7 @@ import { verifyResponseAsync, } from './api'; import { decrypt, encrypt } from './encrypt'; +import { argon2Queue } from './argon2Limiter'; import { createEncryptionSession } from './encryptionSession'; import { verifyAddress } from './v1/verifyAddress'; import { @@ -308,6 +309,13 @@ export class BitGoAPI implements BitGoBase { throw new Error('invalid argument'); } + if ( + params.argon2Concurrency !== undefined && + !(Number.isSafeInteger(params.argon2Concurrency) && params.argon2Concurrency > 0) + ) { + throw new Error('argon2Concurrency must be a positive safe integer'); + } + // By default, we operate on the test server. // Deprecate useProduction in the future let env: EnvironmentName; @@ -468,6 +476,9 @@ export class BitGoAPI implements BitGoBase { this._customProxyAgent = params.customProxyAgent; this._tlsPolicy = params.tlsPolicy; this._hmacAuthStrategy = params.hmacAuthStrategy ?? new DefaultHmacAuthStrategy(); + if (params.argon2Concurrency !== undefined) { + argon2Queue.setConcurrency(params.argon2Concurrency); + } // Only fetch constants from constructor if clientConstants was not provided if (!clientConstants) { diff --git a/modules/sdk-api/src/encryptV2.ts b/modules/sdk-api/src/encryptV2.ts index 6c232a7291..9a914429ff 100644 --- a/modules/sdk-api/src/encryptV2.ts +++ b/modules/sdk-api/src/encryptV2.ts @@ -2,6 +2,7 @@ import { argon2id } from '@bitgo/argon2'; import { base64String, boundedInt, decodeWithCodec } from '@bitgo/sdk-core'; import { randomBytes, webcrypto } from 'crypto'; import * as t from 'io-ts'; +import { argon2Queue } from './argon2Limiter'; /** Web Crypto subtle — browser global in DOM; Node/Electron main must use `webcrypto`. */ const subtle = globalThis.crypto?.subtle ?? webcrypto.subtle; @@ -92,15 +93,17 @@ async function argon2Hash( salt: Uint8Array, params: { memorySize: number; iterations: number; parallelism: number } ): Promise { - return argon2id({ - password, - salt, - memorySize: params.memorySize, - iterations: params.iterations, - parallelism: params.parallelism, - hashLength: ARGON2_DEFAULTS.hashLength, - outputType: 'binary', - }); + return argon2Queue.run(() => + argon2id({ + password, + salt, + memorySize: params.memorySize, + iterations: params.iterations, + parallelism: params.parallelism, + hashLength: ARGON2_DEFAULTS.hashLength, + outputType: 'binary', + }) + ); } async function argon2ToAesKey( diff --git a/modules/sdk-api/src/types.ts b/modules/sdk-api/src/types.ts index e4b500282c..ebf373d966 100644 --- a/modules/sdk-api/src/types.ts +++ b/modules/sdk-api/src/types.ts @@ -87,6 +87,14 @@ export interface BitGoAPIOptions { * `upgradeEncryption`. */ upgradeEncryptionOnSign?: boolean; + /** + * Maximum number of Argon2id hashes running at once, shared by all clients in this JS isolate. + * Hashes beyond the limit wait in a FIFO queue of up to 500 entries; further calls fail with + * `AsyncWorkQueueFullError`. Must be a positive safe integer. Defaults to 16 (about 64 MiB of + * WASM memory per default-parameter hash, so about 1 GiB in flight). Accepted decrypts can use + * up to 256 MiB each. Not a total RSS cap. The most recently set value applies to all clients. + */ + argon2Concurrency?: number; getAdditionalHeadersCb?: AdditionalHeadersCallback; requestIdPrefix?: string; evm?: { diff --git a/modules/sdk-api/test/unit/asyncWorkQueue.ts b/modules/sdk-api/test/unit/asyncWorkQueue.ts new file mode 100644 index 0000000000..67e061ceec --- /dev/null +++ b/modules/sdk-api/test/unit/asyncWorkQueue.ts @@ -0,0 +1,130 @@ +import assert from 'assert'; + +import { AsyncWorkQueue } from '../../src/asyncWorkQueue'; + +function deferred(): { promise: Promise; resolve: () => void } { + let resolve!: () => void; + const promise = new Promise((res) => { + resolve = res; + }); + return { promise, resolve }; +} + +/** Lets pending promise continuations run so start counts are observable. */ +async function flush(): Promise { + await new Promise((resolve) => setImmediate(resolve)); +} + +describe('AsyncWorkQueue', () => { + it('runs at most `concurrency` jobs and starts waiters in FIFO order', async () => { + const queue = new AsyncWorkQueue(2, 10); + const gates = [0, 1, 2, 3].map(() => deferred()); + const started: number[] = []; + const runs = gates.map((gate, i) => + queue.run(async () => { + started.push(i); + await gate.promise; + return i; + }) + ); + + await flush(); + assert.deepStrictEqual(started, [0, 1]); + + gates[0].resolve(); + await flush(); + assert.deepStrictEqual(started, [0, 1, 2]); + + gates[1].resolve(); + await flush(); + assert.deepStrictEqual(started, [0, 1, 2, 3]); + + gates[2].resolve(); + gates[3].resolve(); + assert.deepStrictEqual(await Promise.all(runs), [0, 1, 2, 3]); + }); + + it('frees the slot when a job rejects or throws synchronously', async () => { + const queue = new AsyncWorkQueue(1, 10); + const boom = new Error('boom'); + + await assert.rejects( + queue.run(() => Promise.reject(boom)), + boom + ); + await assert.rejects( + queue.run(() => { + throw boom; + }), + boom + ); + assert.strictEqual(await queue.run(async () => 'ok'), 'ok'); + }); + + it('rejects immediately when the waiting list is full, without starting the job', async () => { + const queue = new AsyncWorkQueue(1, 1); + const gate = deferred(); + const running = queue.run(() => gate.promise); + const waiting = queue.run(async () => 'waiter'); + + let overflowStarted = false; + await assert.rejects( + queue.run(async () => { + overflowStarted = true; + }), + { name: 'AsyncWorkQueueFullError', message: 'Async work queue is full' } + ); + assert.strictEqual(overflowStarted, false); + + gate.resolve(); + await running; + assert.strictEqual(await waiting, 'waiter'); + }); + + it('accepts exactly maxWaiting waiters and frees a place when one starts', async () => { + const queue = new AsyncWorkQueue(1, 500); + const gate = deferred(); + const running = queue.run(() => gate.promise); + const waiters = Array.from({ length: 500 }, (_, i) => queue.run(async () => i)); + + await assert.rejects( + queue.run(async () => -1), + { name: 'AsyncWorkQueueFullError' } + ); + + gate.resolve(); + await running; + assert.strictEqual(await queue.run(async () => 'replacement'), 'replacement'); + assert.deepStrictEqual( + await Promise.all(waiters), + Array.from({ length: 500 }, (_, i) => i) + ); + }); + + it('lowering keeps admitted jobs; raising starts waiters up to the new limit', async () => { + const queue = new AsyncWorkQueue(2, 10); + const gates = [0, 1, 2, 3].map(() => deferred()); + const started: number[] = []; + const runs = gates.map((gate, i) => + queue.run(async () => { + started.push(i); + await gate.promise; + }) + ); + + await flush(); + assert.deepStrictEqual(started, [0, 1]); + + queue.setConcurrency(1); + gates[0].resolve(); + await flush(); + assert.deepStrictEqual(started, [0, 1]); + + queue.setConcurrency(3); + await flush(); + assert.deepStrictEqual(started, [0, 1, 2, 3]); + + gates.forEach((gate) => gate.resolve()); + await Promise.all(runs); + }); +}); diff --git a/modules/sdk-api/test/unit/encrypt.ts b/modules/sdk-api/test/unit/encrypt.ts index 697836218d..cb3b7a9a01 100644 --- a/modules/sdk-api/test/unit/encrypt.ts +++ b/modules/sdk-api/test/unit/encrypt.ts @@ -1,7 +1,10 @@ +import argon2 = require('@bitgo/argon2'); import assert from 'assert'; import { randomBytes, webcrypto } from 'crypto'; +import * as sinon from 'sinon'; import { decrypt, decryptV2, encrypt, encryptV2, V2Envelope, createEncryptionSession } from '../../src'; +import { argon2Queue } from '../../src/argon2Limiter'; import { BitGoAPI } from '../../src/bitgoAPI'; const subtle = globalThis.crypto?.subtle ?? webcrypto.subtle; @@ -639,4 +642,82 @@ describe('encryption methods tests', () => { await assert.rejects(() => session.encrypt(plaintext), /destroyed/); }); }); + + describe('argon2Concurrency', () => { + const password = 'argon-pw'; + const plaintext = 'argon-plaintext'; + let started: number; + let releases: Array<() => void>; + + /** Each stubbed hash waits for its own release, so the test controls when slots free. */ + function holdHashes(): void { + started = 0; + releases = []; + sinon.stub(argon2, 'argon2id').callsFake((async () => { + started++; + await new Promise((resolve) => releases.push(resolve)); + return new Uint8Array(32); + }) as never); + } + + async function flush(): Promise { + await new Promise((resolve) => setImmediate(resolve)); + } + + /** Release every hash that has started so far. */ + function releaseAll(): void { + const pending = releases; + releases = []; + pending.forEach((release) => release()); + } + + afterEach(() => { + sinon.restore(); + argon2Queue.setConcurrency(16); + }); + + it('caps concurrent hashes at 16 by default across encrypt calls', async () => { + holdHashes(); + const runs = Array.from({ length: 20 }, () => encryptV2(password, plaintext)); + await flush(); + assert.strictEqual(started, 16); + + releaseAll(); + await flush(); + assert.strictEqual(started, 20); + releaseAll(); + await Promise.all(runs); + }); + + it('uses the most recent argon2Concurrency and rejects invalid values', async () => { + new BitGoAPI({ env: 'test', argon2Concurrency: 2 }); + assert.throws(() => new BitGoAPI({ env: 'test', argon2Concurrency: 0 }), { + message: 'argon2Concurrency must be a positive safe integer', + }); + // The invalid construction above must not have changed the cap set by the line before it. + holdHashes(); + const runs = Array.from({ length: 5 }, () => encryptV2(password, plaintext)); + await flush(); + assert.strictEqual(started, 2); + + releaseAll(); + await flush(); + releaseAll(); + await flush(); + releaseAll(); + await Promise.all(runs); + }); + + it('rejects the active hash and still runs the next queued hash at cap 1', async () => { + argon2Queue.setConcurrency(1); + const stub = sinon.stub(argon2, 'argon2id'); + stub.onFirstCall().rejects(new Error('kdf failed')); + stub.onSecondCall().resolves(new Uint8Array(32) as never); + + const first = encryptV2(password, plaintext); + const second = encryptV2(password, plaintext); + await assert.rejects(first, /kdf failed/); + assert.strictEqual(JSON.parse(await second).v, 2); + }); + }); });