diff --git a/modules/express/src/clientRoutes.ts b/modules/express/src/clientRoutes.ts index 917bfa3a44..3dd772b91a 100755 --- a/modules/express/src/clientRoutes.ts +++ b/modules/express/src/clientRoutes.ts @@ -5,6 +5,7 @@ import { logger } from '@bitgo/logger'; import { CommitmentShareRecord, CreateNetworkConnectionParams, + CreateSafeOptions, CustomCommitmentGeneratingFunction, CustomGShareGeneratingFunction, CustomKShareGeneratingFunction, @@ -837,6 +838,9 @@ export async function handleV2GenerateSafe( label: req.decoded.label, passphrase: req.decoded.passphrase, ...(req.decoded.multisigRoots === undefined ? {} : { multisigRoots: req.decoded.multisigRoots }), + ...(req.decoded.backupKeyProvider === undefined + ? {} + : { backupKeyProvider: req.decoded.backupKeyProvider as CreateSafeOptions['backupKeyProvider'] }), }); return safe.toJSON(); } @@ -869,6 +873,7 @@ export async function handleV2GenerateSafeKeys(req: ExpressApiRouteRequest<'expr safeId: req.decoded.safeId, enabledRootSlots: req.decoded.enabledRootSlots, multisigRoots: req.decoded.multisigRoots, + backupKeyProvider: req.decoded.backupKeyProvider as CreateSafeOptions['backupKeyProvider'], externalBackupSlots: req.decoded.externalBackupSlots, }); // The root triplets are client-side keycard material (encrypted private keys); the express diff --git a/modules/express/src/typedRoutes/api/v2/generateSafe.ts b/modules/express/src/typedRoutes/api/v2/generateSafe.ts index 56956f7653..fcd7427fa3 100644 --- a/modules/express/src/typedRoutes/api/v2/generateSafe.ts +++ b/modules/express/src/typedRoutes/api/v2/generateSafe.ts @@ -1,5 +1,6 @@ import * as t from 'io-ts'; import { httpRoute, httpRequest, optional } from '@api-ts/io-ts-http'; +import { MultisigRootKeyType } from '@bitgo/public-types'; import { BitgoExpressError } from '../../schemas/error'; /** @@ -21,6 +22,24 @@ export const SafeMultisigRoots = t.partial({ ed25519Multisig: SafeMultisigRootKeyOptions, }); +/** + * KRS-held backup roots: the provider mints and custodies the backup root for the named multisig + * slots; the SDK never sees its private key. Mutually exclusive with `multisigRoots` — rejected in + * `sdk-core` before the safe is created. `slots` defaults to both multisig slots. + */ +export const SafeBackupKeyProvider = t.intersection([ + t.type({ + /** Registered KRS provider name, e.g. `coincover` */ + provider: t.string, + }), + // `optional()` inside `t.type` yields a required key typed `| undefined`, which a JSON body + // cannot carry; `t.partial` makes `slots` genuinely absent-able. + t.partial({ + /** Multisig slots whose backup root the provider holds; defaults to both multisig slots */ + slots: t.array(MultisigRootKeyType), + }), +]); + /** * Path parameters for one-shot Safe generation. */ @@ -45,6 +64,11 @@ export const GenerateSafeBody = { * initialize, so it also needs the external backup root feature enabled for the enterprise. */ multisigRoots: optional(SafeMultisigRoots), + /** + * KRS-held backup roots. A provider is used instead of `multisigRoots`, never with it; `slots` + * defaults to both multisig slots. + */ + backupKeyProvider: optional(SafeBackupKeyProvider), } as const; /** diff --git a/modules/express/src/typedRoutes/api/v2/generateSafeKeys.ts b/modules/express/src/typedRoutes/api/v2/generateSafeKeys.ts index 5572f006d3..787f802011 100644 --- a/modules/express/src/typedRoutes/api/v2/generateSafeKeys.ts +++ b/modules/express/src/typedRoutes/api/v2/generateSafeKeys.ts @@ -2,7 +2,7 @@ import * as t from 'io-ts'; import { httpRoute, httpRequest, optional } from '@api-ts/io-ts-http'; import { MultisigRootKeyType, RootKeyType } from '@bitgo/public-types'; import { BitgoExpressError } from '../../schemas/error'; -import { SafeMultisigRoots } from './generateSafe'; +import { SafeBackupKeyProvider, SafeMultisigRoots } from './generateSafe'; /** * Path parameters for Phase-2-only Safe key ceremonies. @@ -26,6 +26,8 @@ export const GenerateSafeKeysBody = { enabledRootSlots: optional(t.array(RootKeyType)), /** Bring-your-own backup key per multisig slot. Must match `externalBackupSlots` exactly. */ multisigRoots: optional(SafeMultisigRoots), + /** KRS-held backup roots for the external slots. Mutually exclusive with `multisigRoots`. */ + backupKeyProvider: optional(SafeBackupKeyProvider), /** The safe's external backup slots as returned by initialize. Omit when every backup root is local. */ externalBackupSlots: optional(t.array(MultisigRootKeyType)), } as const; diff --git a/modules/express/test/unit/typedRoutes/generateSafe.ts b/modules/express/test/unit/typedRoutes/generateSafe.ts index c5b281827a..52cb9ed072 100644 --- a/modules/express/test/unit/typedRoutes/generateSafe.ts +++ b/modules/express/test/unit/typedRoutes/generateSafe.ts @@ -88,6 +88,55 @@ describe('Generate Safe Typed Routes Tests', function () { generateSafeStub.firstCall.args[0].should.deepEqual({ label, passphrase, multisigRoots }); }); + it('should forward backupKeyProvider (KRS-held backup root) to the SDK', async function () { + const label = 'Test Safe'; + const passphrase = 'mySecurePassphrase123'; + const backupKeyProvider = { provider: 'coincover', slots: ['secp256k1Multisig'] }; + const generateSafeStub = sinon + .stub(Safes.prototype, 'generateSafe') + .resolves({ safe: stubSafe({ toJSON: () => mockSafeJson(label) }), rootKeychains: {} }); + + const res = await agent + .post(`/api/v2/enterprise/${ENTERPRISE_ID}/safes/generate`) + .send({ label, passphrase, backupKeyProvider }); + + res.status.should.equal(200); + generateSafeStub.should.have.been.calledOnce(); + generateSafeStub.firstCall.args[0].should.deepEqual({ label, passphrase, backupKeyProvider }); + }); + + it('should return 400 when backupKeyProvider.slots contains an MPC slot', async function () { + const res = await agent.post(`/api/v2/enterprise/${ENTERPRISE_ID}/safes/generate`).send({ + label: 'Test Safe', + passphrase: 'password', + backupKeyProvider: { provider: 'coincover', slots: ['ecdsaMpc'] }, + }); + + res.status.should.equal(400); + res.body.should.have.property('error'); + }); + + it('should propagate the backupKeyProvider + multisigRoots mutual-exclusion rejection', async function () { + sinon + .stub(Safes.prototype, 'generateSafe') + .rejects( + new Error( + 'backupKeyProvider and multisigRoots are mutually exclusive: the backup roots are either KRS-held or caller-supplied, not both' + ) + ); + + const res = await agent.post(`/api/v2/enterprise/${ENTERPRISE_ID}/safes/generate`).send({ + label: 'Test Safe', + passphrase: 'password', + multisigRoots: { secp256k1Multisig: { backupXpub: 'xpub-backup' } }, + backupKeyProvider: { provider: 'coincover' }, + }); + + res.status.should.equal(500); + res.body.should.have.property('error'); + res.body.error.should.match(/mutually exclusive/); + }); + it('should return 400 when a multisigRoots backupXpub is not a string', async function () { const res = await agent.post(`/api/v2/enterprise/${ENTERPRISE_ID}/safes/generate`).send({ label: 'Test Safe', @@ -312,6 +361,22 @@ describe('Generate Safe Typed Routes Tests', function () { createSafeKeysStub.firstCall.args[0].externalBackupSlots?.should.deepEqual(['secp256k1Multisig']); }); + it('should forward backupKeyProvider to the SDK', async function () { + const backupKeyProvider = { provider: 'coincover', slots: ['secp256k1Multisig'] }; + const createSafeKeysStub = sinon.stub(Safes.prototype, 'createSafeKeys').resolves(rootKeys); + + const res = await agent.post(`/api/v2/enterprise/${ENTERPRISE_ID}/safes/${SAFE_ID}/keys/generate`).send({ + passphrase: 'password', + backupKeyProvider, + externalBackupSlots: ['secp256k1Multisig'], + }); + + res.status.should.equal(200); + createSafeKeysStub.should.have.been.calledOnce(); + createSafeKeysStub.firstCall.args[0].should.have.property('backupKeyProvider'); + createSafeKeysStub.firstCall.args[0].backupKeyProvider?.should.deepEqual(backupKeyProvider); + }); + it('should return 400 when externalBackupSlots contains an MPC slot', async function () { const res = await agent.post(`/api/v2/enterprise/${ENTERPRISE_ID}/safes/${SAFE_ID}/keys/generate`).send({ passphrase: 'password', diff --git a/modules/sdk-core/src/bitgo/safe/iSafe.ts b/modules/sdk-core/src/bitgo/safe/iSafe.ts index d2c6be585c..bd5b8162bb 100644 --- a/modules/sdk-core/src/bitgo/safe/iSafe.ts +++ b/modules/sdk-core/src/bitgo/safe/iSafe.ts @@ -30,6 +30,11 @@ export interface InitializeSafeOptions { * Omit when every backup root is local. */ externalBackupSlots?: MultisigRootKeyType[]; + /** + * KRS provider holding the declared slots' backup roots, e.g. `coincover`. Omit when the + * external backup roots are caller-supplied (BYOK) or there are none. + */ + backupKeyProvider?: string; } /** @experimental */ diff --git a/modules/sdk-core/src/bitgo/safe/iSafes.ts b/modules/sdk-core/src/bitgo/safe/iSafes.ts index 5c7be0d30d..0dc474596e 100644 --- a/modules/sdk-core/src/bitgo/safe/iSafes.ts +++ b/modules/sdk-core/src/bitgo/safe/iSafes.ts @@ -34,6 +34,27 @@ export interface CreateSafeOptions { * through it. Supply a caller-generated composite pub to control the chain code yourself. */ multisigRoots?: SafeMultisigRootKeys; + /** + * Backup root held by a key recovery service (KRS). Mutually exclusive with `multisigRoots`: + * a safe's backup roots are either generated locally (neither option), caller-supplied BYOK + * (`multisigRoots`), or KRS-held (`backupKeyProvider`) — never a mix. + * + * `slots` names the multisig slots whose backup root the provider holds and defaults to both + * multisig slots; the server rejects a slot the safe does not enable. `provider` must be a + * registered KRS provider (`krsProviders`). + */ + backupKeyProvider?: BackupKeyProviderOptions; +} + +/** + * Options for a KRS-held multisig backup root. + * @experimental + */ +export interface BackupKeyProviderOptions { + /** Registered KRS provider name, e.g. `coincover`. */ + provider: 'coincover'; + /** Multisig slots whose backup root the provider holds; defaults to both multisig slots. */ + slots?: MultisigRootKeyType[]; } /** diff --git a/modules/sdk-core/src/bitgo/safe/safes.ts b/modules/sdk-core/src/bitgo/safe/safes.ts index 05a00e4d46..fcbf1dea74 100644 --- a/modules/sdk-core/src/bitgo/safe/safes.ts +++ b/modules/sdk-core/src/bitgo/safe/safes.ts @@ -15,6 +15,7 @@ import { SafeData, } from '@bitgo/public-types'; import { BitGoBase } from '../bitgoBase'; +import { krsProviders } from '../config'; import { ApiResponseError } from '../errors'; import { decodeWithCodec } from '../utils/codecs'; import { @@ -50,6 +51,8 @@ import type { SafeKeychainRoots } from './keycard'; type MultisigRootCeremonyResult = { triplet: Omit & { backupKeychain?: Keychain }; externalBackupPub?: string; + /** Set when the slot's backup root is held by `backupKeyProvider`; registered in phase 2. */ + providerBackup?: boolean; }; /** @@ -125,6 +128,67 @@ function prepareExternalBackupPub( return pub; } +/** + * Validates the `backupKeyProvider` option before initialize and returns the slots it names, in + * canonical order. When `slots` is omitted both multisig slots are named, because the wire contract + * requires a non-empty `externalBackupSlots` alongside `backupKeyProvider` and the enabled slots are + * only known after initialize; the server rejects a slot the safe does not enable, and its echo is + * authoritative for every later step. Throws for a provider that is not registered, or an MPC slot, + * so an MPC ceremony can never see the option. + */ +function backupKeyProviderSlots(params: CreateSafeOptions): MultisigRootKeyType[] { + const { backupKeyProvider, multisigRoots } = params; + if (backupKeyProvider === undefined) { + return []; + } + if (multisigRoots !== undefined) { + throw new Error( + 'backupKeyProvider and multisigRoots are mutually exclusive: the backup roots are either KRS-held or caller-supplied, not both' + ); + } + if (!(backupKeyProvider.provider in krsProviders)) { + throw new Error( + `backupKeyProvider.provider must be a registered KRS provider (${Object.keys(krsProviders).join(', ')}); got: ${ + backupKeyProvider.provider + }` + ); + } + const slots: readonly MultisigRootKeyType[] = backupKeyProvider.slots ?? MULTISIG_ROOT_SLOTS; + const unsupported = slots.filter((slot) => !MULTISIG_ROOT_SLOTS.some((multisigSlot) => multisigSlot === slot)); + if (unsupported.length > 0) { + throw new Error( + `backupKeyProvider.slots only supports the multisig slots (${MULTISIG_ROOT_SLOTS.join( + ', ' + )}); got: ${unsupported.join(', ')}` + ); + } + return MULTISIG_ROOT_SLOTS.filter((slot) => slots.includes(slot)); +} + +/** The multisig slots among the enabled root slots; absent (older WP) means every slot is enabled. */ +function enabledMultisigSlots(enabledRootSlots: RootKeyType[] | undefined): MultisigRootKeyType[] { + const enabled = new Set(enabledRootSlots ?? SAFE_ROOT_SLOTS); + return MULTISIG_ROOT_SLOTS.filter((slot) => enabled.has(slot)); +} + +/** + * Runs `fn` again on a 5xx server error, up to `attempts` calls in total. Provider-held roots are + * scoped to (provider, safeId), so retrying a request that the server may have committed does not + * mint a second root. + */ +async function retryOnServerError(fn: () => Promise, attempts = 3): Promise { + for (let attempt = 1; ; attempt++) { + try { + return await fn(); + } catch (e) { + const status = e instanceof ApiResponseError ? e.status : undefined; + if (attempt >= attempts || status === undefined || status < 500) { + throw e; + } + } + } +} + /** * Collection accessor for a single enterprise's safes, mirroring Wallets / Enterprises. * Safe routes are enterprise-scoped (/api/v2/enterprise/:eId/safes), so the accessor is @@ -157,6 +221,8 @@ export class Safes implements ISafes { * * With `multisigRoots`, the listed multisig slots take a caller-supplied backup root public key * (BYOK) instead of a locally generated backup key; they are declared to the server at initialize. + * With `backupKeyProvider`, the provider holds those slots' backup roots instead; leaving its + * `slots` unset defaults to the enabled multisig slots, which the server decides at initialize. * * If a key ceremony fails, `createSafeKeys` archives the safe before throwing, so a failed run * leaves no half-created safe behind — create a new safe and retry. @@ -164,21 +230,34 @@ export class Safes implements ISafes { */ async generateSafe(params: CreateSafeOptions): Promise { // Validate before initialize so a bad option never leaves a half-created safe behind. - const externalBackupSlots = externalBackupSlotsOf(params.multisigRoots); - for (const slot of externalBackupSlots) { - // A malformed key must fail before the safe exists: nothing is registered yet, so the caller's - // keys are not burned and the same ones work on the replacement safe. - prepareExternalBackupPub(slot, coinForRoot(this.bitgo, slot), params.multisigRoots![slot]!); + const providerSlots = backupKeyProviderSlots(params); + const provider = params.backupKeyProvider?.provider; + const externalBackupSlots = provider === undefined ? externalBackupSlotsOf(params.multisigRoots) : providerSlots; + if (provider === undefined) { + for (const slot of externalBackupSlots) { + // A malformed key must fail before the safe exists: nothing is registered yet, so the caller's + // keys are not burned and the same ones work on the replacement safe. + prepareExternalBackupPub(slot, coinForRoot(this.bitgo, slot), params.multisigRoots![slot]!); + } } const safe = await this.initializeSafe({ label: params.label, ...(externalBackupSlots.length > 0 ? { externalBackupSlots } : {}), + ...(provider === undefined ? {} : { backupKeyProvider: provider }), }); + // The server's echo is authoritative; when it does not echo (older WP) fall back to the slots + // the caller named, or to the enabled multisig slots when they were left to default. + const declaredExternalSlots = + provider !== undefined && safe.externalBackupSlots === undefined + ? externalBackupSlots.length > 0 + ? externalBackupSlots + : enabledMultisigSlots(safe.enabledRootSlots) + : safe.externalBackupSlots; const created = await this.createSafeKeys({ ...params, safeId: safe.id, enabledRootSlots: safe.enabledRootSlots, - externalBackupSlots: safe.externalBackupSlots, + externalBackupSlots: declaredExternalSlots, }); const finalized = await this.finalizeSafe(safe.id, { rootKeys: created.rootKeys }); return { safe: finalized, rootKeychains: created.rootKeychains }; @@ -186,7 +265,7 @@ export class Safes implements ISafes { /** * Phase 1 — initialize a safe (metadata only, no key material). - * POST /api/v2/enterprise/:eId/safes { label, externalBackupSlots? } + * POST /api/v2/enterprise/:eId/safes { label, externalBackupSlots?, backupKeyProvider? } * Response is `{ id, status }` plus optional `enabledRootSlots` and `externalBackupSlots` * (absent on older WP). * @experimental @@ -219,18 +298,45 @@ export class Safes implements ISafes { * `multisigRoots` must agree with the `externalBackupSlots` the server recorded at initialize (a * slot with a supplied backup key that was not declared, or the reverse, throws before any key is * created, and the safe is archived). + * + * With `backupKeyProvider`, every declared external slot's backup root is held by that provider + * (mutually exclusive with `multisigRoots`): no local backup is generated and the provider root is + * registered through `keychains.createBackup` after the other ceremonies succeed. * @experimental */ async createSafeKeys(params: CreateSafeOptions & SafeCreationHandle): Promise { - const { safeId, passphrase, passcodeEncryptionCode, enabledRootSlots, multisigRoots } = params; + const { safeId, passphrase, passcodeEncryptionCode, enabledRootSlots, multisigRoots, backupKeyProvider } = params; const enterprise = this.enterpriseId; + const provider = backupKeyProvider?.provider; + const providerHeld = provider !== undefined; + + if (providerHeld && multisigRoots !== undefined) { + throw new Error( + 'backupKeyProvider and multisigRoots are mutually exclusive: the backup roots are either KRS-held or caller-supplied, not both' + ); + } const suppliedSlots = externalBackupSlotsOf(multisigRoots); - const declaredSlots = new Set(params.externalBackupSlots ?? []); + const declaredSlots = new Set( + params.externalBackupSlots ?? (providerHeld ? enabledMultisigSlots(enabledRootSlots) : []) + ); + const nonMultisigDeclared = [...declaredSlots].filter( + (slot) => !MULTISIG_ROOT_SLOTS.some((multisigSlot) => multisigSlot === slot) + ); + if (providerHeld && nonMultisigDeclared.length > 0) { + throw new Error( + `backupKeyProvider only supports the multisig slots (${MULTISIG_ROOT_SLOTS.join( + ', ' + )}); got: ${nonMultisigDeclared.join(', ')}` + ); + } + // A provider-held slot has no caller-supplied pub, so the BYOK matching rules do not apply; the + // only requirement is that every declared slot is enabled (MPC slots were rejected above). + const externalSlots = providerHeld ? MULTISIG_ROOT_SLOTS.filter((slot) => declaredSlots.has(slot)) : suppliedSlots; const notDeclared = suppliedSlots.filter((slot) => !declaredSlots.has(slot)); - const notSupplied = [...declaredSlots].filter((slot) => !suppliedSlots.includes(slot)); + const notSupplied = providerHeld ? [] : [...declaredSlots].filter((slot) => !suppliedSlots.includes(slot)); const notEnabled = - enabledRootSlots === undefined ? [] : suppliedSlots.filter((slot) => !enabledRootSlots.includes(slot)); + enabledRootSlots === undefined ? [] : externalSlots.filter((slot) => !enabledRootSlots.includes(slot)); if (notDeclared.length > 0 || notSupplied.length > 0 || notEnabled.length > 0) { const problems = [ notDeclared.length > 0 ? `backup key supplied but not declared at initialize: ${notDeclared.join(', ')}` : '', @@ -238,9 +344,14 @@ export class Safes implements ISafes { ? `declared at initialize but no backup key supplied: ${notSupplied.join(', ')}` + ' (if the safe was created against a wallet platform deployment that does not support external backup roots, it will not echo them at initialize)' : '', - notEnabled.length > 0 ? `backup key supplied for a slot that is not enabled: ${notEnabled.join(', ')}` : '', + notEnabled.length > 0 + ? `${ + providerHeld ? 'backup root declared' : 'backup key supplied' + } for a slot that is not enabled: ${notEnabled.join(', ')}` + : '', ].filter((problem) => problem !== ''); - let message = `multisigRoots does not match the safe's external backup slots (${problems.join('; ')}).`; + const optionName = providerHeld ? 'backupKeyProvider' : 'multisigRoots'; + let message = `${optionName} does not match the safe's external backup slots (${problems.join('; ')}).`; // No key exists yet, but leave no initializing safe behind. try { await this.archiveSafe(safeId); @@ -268,6 +379,7 @@ export class Safes implements ISafes { // Ordered by scheme: the two multisig roots first, then the two MPC roots. const enabled = new Set(enabledRootSlots ?? SAFE_ROOT_SLOTS); const slots = SAFE_ROOT_SLOTS.filter((slot) => enabled.has(slot)); + const providerSlots = new Set(providerHeld ? externalSlots : []); const ceremonies: Record Promise> = { // Phase 2.1 — multisig roots (①④): local user/backup keypairs + BitGo key, all safeId-tagged. secp256k1Multisig: () => @@ -277,7 +389,8 @@ export class Safes implements ISafes { passphrase, enterprise, passcodeEncryptionCode, - preparedExternal.secp256k1Multisig + preparedExternal.secp256k1Multisig, + providerSlots.has('secp256k1Multisig') ), ed25519Multisig: () => this.createMultisigRoot( @@ -286,7 +399,8 @@ export class Safes implements ISafes { passphrase, enterprise, passcodeEncryptionCode, - preparedExternal.ed25519Multisig + preparedExternal.ed25519Multisig, + providerSlots.has('ed25519Multisig') ), // Phase 2.2 — MPC roots (②③): the existing DKLS (②) and EdDSA (③) ceremonies, safeId threaded. ecdsaMpc: async () => ({ @@ -299,8 +413,13 @@ export class Safes implements ISafes { const results = await Promise.allSettled(slots.map((slot) => ceremonies[slot]())); // Single pass over the settled results: rejections are collected per-slot for the error below; - // a fulfilled BYOK ceremony defers its pub registration to phase 2. - const settledTriplets: { slot: RootKeyType; triplet: KeychainsTriplet; externalBackupPub?: string }[] = []; + // a fulfilled BYOK or provider-held ceremony defers its backup registration to phase 2. + const settledTriplets: { + slot: RootKeyType; + triplet: KeychainsTriplet; + externalBackupPub?: string; + providerBackup?: boolean; + }[] = []; const failures: string[] = []; results.forEach((result, i) => { if (result.status === 'fulfilled') { @@ -308,6 +427,7 @@ export class Safes implements ISafes { slot: slots[i], triplet: result.value.triplet as KeychainsTriplet, externalBackupPub: result.value.externalBackupPub, + providerBackup: result.value.providerBackup, }); } else { const reason = result.reason instanceof Error ? result.reason.message : String(result.reason); @@ -330,7 +450,10 @@ export class Safes implements ISafes { let message = `Safe key generation failed for ${failures.length} root ceremony/ies ` + `[${failures.join('; ')}]. The safe (${safeId}) has been archived; create a new safe and retry.`; - if (suppliedSlots.length > 0) { + if (providerHeld) { + // Provider roots bind only in phase 2 too, so nothing was registered with the provider yet. + message += ' No backup root was registered with the provider, so a retry starts clean.'; + } else if (suppliedSlots.length > 0) { // BYOK pubs bind only in phase 2, so a failure here left every caller key unbound. message += ' No backup xpub was registered, so the same keys work on the new safe.'; } @@ -340,10 +463,34 @@ export class Safes implements ISafes { throw new Error(message); } - // Phase 2 — the caller's backup pub binds only after every other ceremony succeeded: any - // failure above archives the safe with no pub bound, so the same xpubs work on the replacement - // safe. Registrations run sequentially so a failure names exactly which pubs are consumed. + // Phase 2 — an external backup root (a caller pub or a provider-held root) binds only after + // every other ceremony succeeded: any failure above archives the safe with nothing bound, so the + // same keys work on the replacement safe. Registrations run sequentially so a failure names + // exactly which roots are consumed. for (const registration of settledTriplets) { + if (registration.providerBackup === true) { + // The provider mints and custody-splits its own backup root for the safe; a 5xx is retried + // because the creation is scoped to (provider, safeId) and cannot mint a second root. + try { + registration.triplet.backupKeychain = await retryOnServerError(() => + coinForRoot(this.bitgo, registration.slot).keychains().createBackup({ provider, safeId }) + ); + } catch (e) { + const reasonText = e instanceof Error ? e.message : String(e); + const requestId = e instanceof ApiResponseError ? e.requestId : undefined; + try { + await this.archiveSafe(safeId); + } catch (archiveError) { + // The primary error carries the registration failure; note it if the cleanup also failed. + } + throw new Error( + `unable to register the ${provider} backup root for ${registration.slot}: ${reasonText}` + + `${requestId ? ` (requestId: ${requestId})` : ''}. The safe (${safeId}) has been archived; ` + + 'backup roots registered before this failure are consumed — create a new safe and retry' + ); + } + continue; + } if (registration.externalBackupPub === undefined) { continue; } @@ -421,8 +568,10 @@ export class Safes implements ISafes { * Phase 2.1 helper — mint one onchain-multisig root (cold model, as wallet creation does today): * generate user/backup keypairs locally, encrypt with `passphrase`, register via POST /:coin/key * with `safeId`; the BitGo key is created through the same route's `source:'bitgo'` path. - * With `external`, the backup is the caller-supplied public key (BYOK) added as a pub-only - * `source: 'backup'` key, and no backup private key is generated or encrypted. + * With `externalBackupPub`, the backup is the caller-supplied public key (BYOK) added as a + * pub-only `source: 'backup'` key. With `providerBackup`, the provider holds the backup root. + * Either way no backup private key is generated or encrypted here, and the backup registration is + * deferred to `createSafeKeys` phase 2. * Returns the [user, backup, bitgo] keychain triplet. * @experimental */ @@ -432,7 +581,8 @@ export class Safes implements ISafes { passphrase: string, enterprise: string, passcodeEncryptionCode?: string, - externalBackupPub?: string + externalBackupPub?: string, + providerBackup = false ): Promise { const coin = coinForRoot(this.bitgo, slot); const keychains = coin.keychains(); @@ -445,13 +595,13 @@ export class Safes implements ISafes { safeId, originalPasscodeEncryptionCode: passcodeEncryptionCode, }); - // The caller's backup pub binds only after every other ceremony succeeded, so the registration - // is deferred to createSafeKeys phase 2 — any earlier failure archives the safe with the pub - // still unbound and usable on a replacement safe. + // An external backup root (caller pub or provider-held) binds only after every other ceremony + // succeeded, so its registration is deferred to createSafeKeys phase 2 — any earlier failure + // archives the safe with the root still unbound and usable on a replacement safe. const backupKeychainPromise: Promise = - externalBackupPub === undefined - ? keychains.createBackup({ passphrase, safeId, originalPasscodeEncryptionCode: passcodeEncryptionCode }) - : Promise.resolve(undefined); + externalBackupPub !== undefined || providerBackup + ? Promise.resolve(undefined) + : keychains.createBackup({ passphrase, safeId, originalPasscodeEncryptionCode: passcodeEncryptionCode }); const bitgoKeychainPromise = keychains.createBitGo({ enterprise, safeId }); const [userKeychain, localBackupKeychain, bitgoKeychain] = await Promise.all([ @@ -476,7 +626,7 @@ export class Safes implements ISafes { } if (localBackupKeychain === undefined) { - return { triplet: { userKeychain, bitgoKeychain }, externalBackupPub }; + return { triplet: { userKeychain, bitgoKeychain }, externalBackupPub, providerBackup }; } // createBackup echoes the locally generated plaintext `prv`; the keycard needs only the diff --git a/modules/sdk-core/test/unit/bitgo/safe/safes.ts b/modules/sdk-core/test/unit/bitgo/safe/safes.ts index c2ff72c12b..c154c77d2c 100644 --- a/modules/sdk-core/test/unit/bitgo/safe/safes.ts +++ b/modules/sdk-core/test/unit/bitgo/safe/safes.ts @@ -3,7 +3,16 @@ import 'should'; import { InitializeSafeResponse } from '@bitgo/public-types'; import { bip32 } from '@bitgo/utxo-lib'; import type { IBaseCoin } from '../../../../src/bitgo/baseCoin'; -import { Enterprise, Safe, SafeKeys, Safes, SafeMultisigRootKeys, encodeEd25519StrKeyPublicKey } from '../../../../src'; +import { + ApiResponseError, + CreateSafeOptions, + Enterprise, + Safe, + SafeKeys, + Safes, + SafeMultisigRootKeys, + encodeEd25519StrKeyPublicKey, +} from '../../../../src'; /** A derivable slot-④ root: raw 32-byte public key plus raw 32-byte chain code in base32. */ const COMPOSITE_BACKUP_PUB = @@ -59,6 +68,24 @@ describe('Safes', function () { result.externalBackupSlots?.should.deepEqual(['secp256k1Multisig']); }); + it('sends backupKeyProvider with the declared external slots', async function () { + const wire = { id: 'test-safe-id', status: 'initializing', externalBackupSlots: ['secp256k1Multisig'] }; + const send = sinon.stub().returns({ result: sinon.stub().resolves(wire) }); + mockBitGo.post.returns({ send }); + + await safes.initializeSafe({ + label: 'my safe', + externalBackupSlots: ['secp256k1Multisig'], + backupKeyProvider: 'coincover', + }); + + sinon.assert.calledWithExactly(send, { + label: 'my safe', + externalBackupSlots: ['secp256k1Multisig'], + backupKeyProvider: 'coincover', + }); + }); + it('rejects an MPC slot in externalBackupSlots before sending anything', async function () { const send = sinon.stub().returns({ result: sinon.stub().resolves({}) }); mockBitGo.post.returns({ send }); @@ -569,6 +596,100 @@ describe('Safes', function () { }); }); + describe('provider-held (KRS) backup roots', function () { + const providerParams = { + label: 'my safe', + passphrase: 'pw', + safeId: 'safe-1', + backupKeyProvider: { provider: 'coincover' as const }, + externalBackupSlots: ['secp256k1Multisig' as const], + enabledRootSlots: ['secp256k1Multisig' as const], + }; + + it('registers the provider backup root instead of generating a local backup', async function () { + const result = await safes.createSafeKeys(providerParams); + + const btc = keychainsByCoin['tbtc']; + sinon.assert.calledOnce(btc.createBackup); + sinon.assert.calledWithExactly(btc.createBackup, { provider: 'coincover', safeId: 'safe-1' }); + // no caller pub is registered either — the provider holds the backup root + sinon.assert.neverCalledWith(btc.add, sinon.match({ source: 'backup' })); + result.rootKeys.hot.secp256k1Multisig?.should.deepEqual(['tbtc-user', 'tbtc-backup', 'tbtc-bitgo']); + // the safe is only archived on failure + sinon.assert.notCalled(mockBitGo.post); + }); + + it('defaults the provider slots to the enabled multisig slots', async function () { + await safes.createSafeKeys({ + label: 'my safe', + passphrase: 'pw', + safeId: 'safe-1', + backupKeyProvider: { provider: 'coincover' }, + enabledRootSlots: ['secp256k1Multisig', 'ecdsaMpc'], + }); + + sinon.assert.calledWithExactly(keychainsByCoin['tbtc'].createBackup, { + provider: 'coincover', + safeId: 'safe-1', + }); + // the ed25519Multisig root is not enabled, so no provider root is minted for it + keychainsByCoin.should.not.have.property('txlm'); + sinon.assert.notCalled(mockBitGo.post); + }); + + it('retries a 5xx provider registration before archiving', async function () { + keychainsByCoin['tbtc'] = makeKeychains('tbtc'); + keychainsByCoin['tbtc'].createBackup = sinon + .stub() + .onFirstCall() + .rejects(new ApiResponseError('krs unavailable', 503)) + .onSecondCall() + .resolves({ id: 'tbtc-backup' }); + + const result = await safes.createSafeKeys(providerParams); + + sinon.assert.calledTwice(keychainsByCoin['tbtc'].createBackup); + sinon.assert.notCalled(mockBitGo.post); + result.rootKeys.hot.secp256k1Multisig?.should.deepEqual(['tbtc-user', 'tbtc-backup', 'tbtc-bitgo']); + }); + + it('archives the safe when the provider registration fails', async function () { + keychainsByCoin['tbtc'] = makeKeychains('tbtc'); + keychainsByCoin['tbtc'].createBackup = sinon.stub().rejects(new Error('krs rejected the request')); + const send = sinon.stub().returns({ result: sinon.stub().resolves({ ...safeDataWire, status: 'archived' }) }); + mockBitGo.post.returns({ send }); + + await safes + .createSafeKeys(providerParams) + .should.be.rejectedWith( + /unable to register the coincover backup root for secp256k1Multisig: krs rejected the request.*has been archived/ + ); + sinon.assert.calledWith(mockBitGo.post, '/enterprise/test-enterprise-id/safes/safe-1/archive'); + }); + + it('rejects a KRS-held slot that is not an enabled slot', async function () { + const send = sinon.stub().returns({ result: sinon.stub().resolves({ ...safeDataWire, status: 'archived' }) }); + mockBitGo.post.returns({ send }); + + await safes + .createSafeKeys({ + ...providerParams, + enabledRootSlots: ['ed25519Multisig'], + }) + .should.be.rejectedWith(/backup root declared for a slot that is not enabled: secp256k1Multisig/); + }); + + it('rejects backupKeyProvider together with multisigRoots', async function () { + await safes + .createSafeKeys({ + ...providerParams, + multisigRoots: { secp256k1Multisig: { backupXpub: EXTERNAL_XPUB } }, + }) + .should.be.rejectedWith(/backupKeyProvider and multisigRoots are mutually exclusive/); + keychainsByCoin.should.be.empty(); + }); + }); + it('archives the safe and throws listing every failed ceremony', async function () { // Two ceremonies fail (an MPC and a multisig root). keychainsByCoin['hteth'] = makeKeychains('hteth'); @@ -711,6 +832,80 @@ describe('Safes', function () { }); }); + it('forwards backupKeyProvider to initialize and resolves the defaulted slots from enabledRootSlots', async function () { + const initializing: InitializeSafeResponse = { + id: 'test-safe-id', + status: 'initializing', + enabledRootSlots: ['secp256k1Multisig', 'ed25519Multisig', 'ecdsaMpc'], + }; + const initStub = sinon.stub(safes, 'initializeSafe').resolves(initializing); + const keysStub = sinon.stub(safes, 'createSafeKeys').resolves({ rootKeys: { hot: {} }, rootKeychains: {} }); + sinon.stub(safes, 'finalizeSafe').resolves({} as Safe); + + await safes.generateSafe({ label: 'my safe', passphrase: 'pw', backupKeyProvider: { provider: 'coincover' } }); + + // The wire contract needs a non-empty externalBackupSlots alongside backupKeyProvider, so an + // omitted `slots` is sent as both multisig slots; the server rejects one it did not enable. + sinon.assert.calledWith(initStub, { + label: 'my safe', + backupKeyProvider: 'coincover', + externalBackupSlots: ['secp256k1Multisig', 'ed25519Multisig'], + }); + sinon.assert.calledWithMatch(keysStub, { + label: 'my safe', + passphrase: 'pw', + safeId: 'test-safe-id', + backupKeyProvider: { provider: 'coincover' }, + // the enabled multisig slots, not the MPC slot + externalBackupSlots: ['secp256k1Multisig', 'ed25519Multisig'], + }); + }); + + it('rejects backupKeyProvider together with multisigRoots before initializing', async function () { + const initStub = sinon.stub(safes, 'initializeSafe'); + + await safes + .generateSafe({ + label: 'my safe', + passphrase: 'pw', + multisigRoots: { secp256k1Multisig: { backupXpub: EXTERNAL_XPUB } }, + backupKeyProvider: { provider: 'coincover' }, + }) + .should.be.rejectedWith(/backupKeyProvider and multisigRoots are mutually exclusive/); + sinon.assert.notCalled(initStub); + }); + + it('rejects an unregistered backupKeyProvider before initializing', async function () { + const initStub = sinon.stub(safes, 'initializeSafe'); + + await safes + .generateSafe({ + label: 'my safe', + passphrase: 'pw', + // Negative test: a provider name the type forbids, to pin the runtime guard. + backupKeyProvider: { provider: 'not-a-krs' } as unknown as CreateSafeOptions['backupKeyProvider'], + }) + .should.be.rejectedWith(/backupKeyProvider.provider must be a registered KRS provider/); + sinon.assert.notCalled(initStub); + }); + + it('rejects an MPC slot in backupKeyProvider.slots before initializing', async function () { + const initStub = sinon.stub(safes, 'initializeSafe'); + + await safes + .generateSafe({ + label: 'my safe', + passphrase: 'pw', + // Negative test: an MPC slot the type forbids, to pin the runtime guard. + backupKeyProvider: { + provider: 'coincover', + slots: ['ecdsaMpc'], + } as unknown as CreateSafeOptions['backupKeyProvider'], + }) + .should.be.rejectedWith(/backupKeyProvider.slots only supports the multisig slots/); + sinon.assert.notCalled(initStub); + }); + it('rejects an invalid multisigRoots before initializing, so no safe is created', async function () { const initStub = sinon.stub(safes, 'initializeSafe');