Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions modules/express/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
5 changes: 5 additions & 0 deletions modules/express/src/args.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
4 changes: 4 additions & 0 deletions modules/express/src/clientRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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}`);
Expand Down Expand Up @@ -1944,6 +1947,7 @@ function prepareBitGo(config: Config) {
env,
customRootURI: customRootUri,
customBitcoinNetwork,
argon2Concurrency: config.argon2Concurrency,
accessToken,
userAgent,
...(useProxyUrl
Expand Down
72 changes: 45 additions & 27 deletions modules/express/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<Config> => ({
Expand Down Expand Up @@ -82,35 +84,50 @@ export const ArgConfig = (args): Partial<Config> => ({
lightningSignerFileSystemPath: args.lightningSignerFileSystemPath,
keepAliveTimeout: args.keepalivetimeout,
headersTimeout: args.headerstimeout,
argon2Concurrency: args.argon2concurrency,
});

export const EnvConfig = (): Partial<Config> => ({
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<Config> => {
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,
Expand Down Expand Up @@ -199,6 +216,7 @@ function mergeConfigs(...configs: Partial<Config>[]): Config {
lightningSignerFileSystemPath: get('lightningSignerFileSystemPath'),
keepAliveTimeout: get('keepAliveTimeout'),
headersTimeout: get('headersTimeout'),
...(get('argon2Concurrency') !== undefined ? { argon2Concurrency: get('argon2Concurrency') } : {}),
};
}

Expand Down
7 changes: 7 additions & 0 deletions modules/express/src/expressApp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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!');
Expand Down
12 changes: 12 additions & 0 deletions modules/express/test/unit/bitgoExpress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand Down Expand Up @@ -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<Config>;
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() };
Expand Down
28 changes: 28 additions & 0 deletions modules/express/test/unit/clientRoutes/signPayload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
49 changes: 49 additions & 0 deletions modules/express/test/unit/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
/// <reference types="mocha" />
// eslint-disable-next-line
/// <reference types="node" />
import assert from 'assert';
import * as should from 'should';
import * as sinon from 'sinon';

Expand Down Expand Up @@ -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();
}
});
});
4 changes: 4 additions & 0 deletions modules/sdk-api/src/argon2Limiter.ts
Original file line number Diff line number Diff line change
@@ -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);
50 changes: 50 additions & 0 deletions modules/sdk-api/src/asyncWorkQueue.ts
Original file line number Diff line number Diff line change
@@ -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<T>(job: () => Promise<T>): Promise<T> {
// 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<void>((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();
}
}
}
11 changes: 11 additions & 0 deletions modules/sdk-api/src/bitgoAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand Down
21 changes: 12 additions & 9 deletions modules/sdk-api/src/encryptV2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -92,15 +93,17 @@ async function argon2Hash(
salt: Uint8Array,
params: { memorySize: number; iterations: number; parallelism: number }
): Promise<Uint8Array> {
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(
Expand Down
Loading