From 643c49eb833a2d56b2d4ecf61a582602c90ac370 Mon Sep 17 00:00:00 2001 From: David Kaplan Date: Fri, 4 Dec 2026 12:34:54 -0500 Subject: [PATCH] feat: verify CoinCover safe roots at creation and mint - Keychain carries the provider's signedPayload and signature alongside provider and keyId. - createSafeKeys verifies every provider-held backup root before the triplets are assembled; a bad proof archives the safe and throws, so it never finalizes. - The onchain createWallet path re-verifies the root and checks the minted backup child is its soft derivation at the wallet path before returning the wallet. Stacked on the verifier (WCN-4832) and the provider option (WCN-3884). Ticket: WCN-4946 --- .../sdk-core/src/bitgo/keychain/iKeychains.ts | 12 +++ modules/sdk-core/src/bitgo/safe/safe.ts | 89 +++++++++++++++++- modules/sdk-core/src/bitgo/safe/safes.ts | 71 +++++++++++++++ modules/sdk-core/test/unit/bitgo/safe/safe.ts | 90 +++++++++++++++++++ .../sdk-core/test/unit/bitgo/safe/safes.ts | 42 +++++++++ 5 files changed, 303 insertions(+), 1 deletion(-) diff --git a/modules/sdk-core/src/bitgo/keychain/iKeychains.ts b/modules/sdk-core/src/bitgo/keychain/iKeychains.ts index 176b16f44c..b4f76cee33 100644 --- a/modules/sdk-core/src/bitgo/keychain/iKeychains.ts +++ b/modules/sdk-core/src/bitgo/keychain/iKeychains.ts @@ -61,6 +61,18 @@ export interface Keychain { * provider holds. @experimental */ keyId?: string; + /** + * The provider's issuance-proof payload for this backup root (`signedPayload` in wallet-platform). + * Set only on a provider-issued safe backup root alongside `provider` and `keyId`. + * The SDK re-verifies it with `signature` before the root may be used. @experimental + */ + signedPayload?: string; + /** + * The provider's base64 DER P-256 signature over `signedPayload`, as wallet-platform returned it. + * Set only on a provider-issued safe backup root alongside `provider` and `keyId`. + * The SDK re-verifies it before the root may be used. @experimental + */ + signature?: string; commonPub?: string; commonKeychain?: string; keyShares?: ApiKeyShare[]; diff --git a/modules/sdk-core/src/bitgo/safe/safe.ts b/modules/sdk-core/src/bitgo/safe/safe.ts index 9abb080d36..cfda0db03f 100644 --- a/modules/sdk-core/src/bitgo/safe/safe.ts +++ b/modules/sdk-core/src/bitgo/safe/safe.ts @@ -5,11 +5,13 @@ * changes) before the public release. */ import * as t from 'io-ts'; +import { bip32 } from '@bitgo/utxo-lib'; import { FreezeSafeBody, SafeData, SafeShareData, SafeShareState, type RootKeyType } from '@bitgo/public-types'; import { IBaseCoin } from '../baseCoin'; import { BitGoBase } from '../bitgoBase'; import { ApiResponseError, IncorrectPasswordError } from '../errors'; -import { decryptKeychainPrivateKey, type Keychain } from '../keychain'; +import { Environments } from '../environments'; +import { decryptKeychainPrivateKey, type IKeychains, type Keychain } from '../keychain'; import { ECDSAUtils, parseSafeMpcKeyEnvelopes, EDDSAUtils } from '../utils'; import { boundedInt, decodeWithCodec } from '../utils/codecs'; import { postWithCodec } from '../utils/postWithCodec'; @@ -42,11 +44,16 @@ import { buildSafeBip44Path, deriveAndSelfCheckSafeChildHardened, deriveSafeChildEd25519Hardened, + deriveSoftPathRelative, DerivedFromParentWithHardenedPath, + getEd25519MultisigCoinEncoders, getSafeBip44CoinType, onchainSlotForCoin, + toSoftTwinPath, tssSlotForCoin, } from '@bitgo/sdk-lib-safes'; +import { verifyCoinCoverSafeRootProof } from './coincoverRootProof'; +import { softDeriveChildPubEd25519AtPath } from './derivableEd25519Pub'; const SafeRootKeySlot = t.keyof({ secp256k1Multisig: null, @@ -232,9 +239,89 @@ export class Safe implements ISafe { multisigType, keys, }).result(); + + // CoinCover holds some safes' backup roots. Re-verify the root's issuance proof and the backup + // child the server derived from it before handing back a wallet that would sign with it. One + // root fetch is the only extra cost for non-CoinCover safes. + if (slot === 'secp256k1Multisig' || slot === 'ed25519Multisig') { + const backupRootId = rootIdFromSafe(safeData, slot, 1); + if (backupRootId !== undefined) { + const backupRoot = await keychains.get({ id: backupRootId }); + if (backupRoot.provider === 'coincover') { + const walletKeys = + typeof response === 'object' && response !== null && 'keys' in response ? response.keys : undefined; + await this.assertCoinCoverBackupChild({ keychains, coin, slot, backupRoot, walletKeys, path }); + } + } + } return new Wallet(this.bitgo, coin, response); } + /** + * Re-verify a CoinCover-backed safe's backup root and prove the minted backup child is its soft + * derivation at `path` (the user child is hardened; co-signers derive at the soft twin). Throws + * before any wallet is returned when either check fails. + */ + private async assertCoinCoverBackupChild(params: { + keychains: IKeychains; + coin: IBaseCoin; + slot: 'secp256k1Multisig' | 'ed25519Multisig'; + backupRoot: Keychain; + walletKeys: unknown; + path: DerivedFromParentWithHardenedPath; + }): Promise { + const { keychains, coin, slot, backupRoot, walletKeys, path } = params; + const { pub, keyId, signedPayload, signature } = backupRoot; + if (pub === undefined || keyId === undefined || signedPayload === undefined || signature === undefined) { + throw new Error(`CoinCover backup root for ${slot} is missing its issuance proof; refusing to return the wallet`); + } + await verifyCoinCoverSafeRootProof({ + pub, + slot, + keyId, + signedPayload, + signature, + enterpriseId: this.enterpriseId(), + safeId: this.id(), + attestationPublicKeys: Environments[this.bitgo.getEnv()].coinCoverAttestationPublicKeys, + }); + + const keyIds: unknown[] = Array.isArray(walletKeys) ? walletKeys : []; + if (keyIds.length !== 3) { + throw new Error(`minted ${slot} wallet did not return its [user, backup, bitgo] key ids`); + } + const backupChildId = keyIds[1]; + if (typeof backupChildId !== 'string') { + throw new Error(`minted ${slot} wallet did not return a backup child key id`); + } + const backupChild = await keychains.get({ id: backupChildId }); + if (backupChild.pub === undefined) { + throw new Error(`minted ${slot} wallet backup child ${backupChildId} has no pub`); + } + + const softPath = toSoftTwinPath(path); + let derivedPub: string; + let mintedPub: string; + if (slot === 'secp256k1Multisig') { + derivedPub = deriveSoftPathRelative(bip32.fromBase58(pub), softPath).publicKey.toString('hex'); + mintedPub = bip32.fromBase58(backupChild.pub).publicKey.toString('hex'); + } else { + const encoders = getEd25519MultisigCoinEncoders(coin.getChain()); + if (encoders === undefined) { + throw new Error( + `cannot verify the CoinCover backup child for ${slot}: coin '${coin.getChain()}' has no ed25519 multisig encoders` + ); + } + derivedPub = encoders.encodePub(await softDeriveChildPubEd25519AtPath(pub, softPath)); + mintedPub = backupChild.pub; + } + if (derivedPub !== mintedPub) { + throw new Error( + `Safe wallet minted for ${slot} at ${path}: the backup child does not derive from the CoinCover backup root` + ); + } + } + /** * TSS wallet mint: decrypt the user root blob, run the user/BitGo hard-derive * ceremony, register the ordered child documents, then mint. diff --git a/modules/sdk-core/src/bitgo/safe/safes.ts b/modules/sdk-core/src/bitgo/safe/safes.ts index 05a00e4d46..35d31e3f3a 100644 --- a/modules/sdk-core/src/bitgo/safe/safes.ts +++ b/modules/sdk-core/src/bitgo/safe/safes.ts @@ -16,6 +16,7 @@ import { } from '@bitgo/public-types'; import { BitGoBase } from '../bitgoBase'; import { ApiResponseError } from '../errors'; +import { Environments } from '../environments'; import { decodeWithCodec } from '../utils/codecs'; import { decodeEd25519StrKeyPublicKey, @@ -39,6 +40,7 @@ import { SafeMultisigRootKeyOptions, SafeMultisigRootKeys, } from './iSafes'; +import { verifyCoinCoverSafeRootProof } from './coincoverRootProof'; import { coinForRoot, SAFE_ROOT_SLOTS } from './rootCoin'; import { Safe } from './safe'; import type { SafeKeychainRoots } from './keycard'; @@ -125,6 +127,38 @@ function prepareExternalBackupPub( return pub; } +/** + * Verify the issuance proof a KRS returns with a safe backup root. Wallet platform saying a root + * came from the provider is not enough; every proof part is required — a missing piece fails closed + * rather than skipping the check. + */ +async function verifyCoinCoverBackupRoot(params: { + backupKeychain: Keychain; + slot: MultisigRootKeyType; + enterpriseId: string; + safeId: string; + attestationPublicKeys: readonly string[]; +}): Promise { + const { backupKeychain, slot, enterpriseId, safeId, attestationPublicKeys } = params; + const { provider, pub, keyId, signedPayload, signature } = backupKeychain; + if (provider !== 'coincover') { + throw new Error('the registered root is not identified as a CoinCover root'); + } + if (pub === undefined || keyId === undefined || signedPayload === undefined || signature === undefined) { + throw new Error('the registered root is missing its pub, key id, signed payload or signature'); + } + await verifyCoinCoverSafeRootProof({ + pub, + slot, + keyId, + signedPayload, + signature, + enterpriseId, + safeId, + attestationPublicKeys, + }); +} + /** * 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 @@ -372,6 +406,43 @@ export class Safes implements ISafes { } } + // A provider-held backup root is not trusted because wallet platform returned it: verify the + // provider's issuance proof before the root is assembled into the triplets, so a bad root can + // never reach finalize. Runs after registration so a failure follows the same abandonment path. + for (const registration of settledTriplets) { + if (registration.providerBackup !== true || provider !== 'coincover') { + continue; + } + const slot = registration.slot; + const backupKeychain: Keychain | undefined = registration.triplet.backupKeychain; + if (backupKeychain === undefined) { + throw new Error(`internal error: ${slot} backup keychain was not registered`); + } + if (slot !== 'secp256k1Multisig' && slot !== 'ed25519Multisig') { + throw new Error(`internal error: ${slot} cannot hold a CoinCover backup root`); + } + try { + await verifyCoinCoverBackupRoot({ + backupKeychain, + slot, + enterpriseId: enterprise, + safeId, + attestationPublicKeys: Environments[this.bitgo.getEnv()].coinCoverAttestationPublicKeys, + }); + } catch (e) { + const reasonText = e instanceof Error ? e.message : String(e); + try { + await this.archiveSafe(safeId); + } catch (archiveError) { + // The primary error carries the verification failure; note it if the cleanup also failed. + } + throw new Error( + `unable to verify the CoinCover backup root for ${slot}: ${reasonText}. The safe (${safeId}) has been ` + + 'archived; no backup root was registered for it' + ); + } + } + const hot: RootKeysByType = {}; const rootKeychains: SafeKeychainRoots = {}; for (const { slot, triplet } of settledTriplets) { diff --git a/modules/sdk-core/test/unit/bitgo/safe/safe.ts b/modules/sdk-core/test/unit/bitgo/safe/safe.ts index 705d0220a3..c1d2e75cfa 100644 --- a/modules/sdk-core/test/unit/bitgo/safe/safe.ts +++ b/modules/sdk-core/test/unit/bitgo/safe/safe.ts @@ -1,9 +1,13 @@ import * as sinon from 'sinon'; import 'should'; +import { createHash } from 'crypto'; +import { p256 } from '@noble/curves/p256'; +import { bip32 } from '@bitgo/utxo-lib'; import { SafeData } from '@bitgo/public-types'; import { ECDSAUtils, EDDSAUtils, + Environments, IncorrectPasswordError, buildSafeMpcKeyEnvelopes, Safe, @@ -48,6 +52,7 @@ describe('Safe', function () { post: sinon.stub(), put: sinon.stub(), get: sinon.stub(), + getEnv: sinon.stub().returns('test'), }; safeData = { id: 'test-safe-id', @@ -277,6 +282,91 @@ describe('Safe', function () { addArgs.should.not.have.property('derivedFromParentWithSeed'); }); + it('refuses to return a wallet whose backup child does not derive from the CoinCover root', async function () { + // Fixed scalar mirrors the WCN-4832 verifier fixtures. + const attestationPrivateKey = Buffer.from( + 'c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721', + 'hex' + ); + const attestationPublicKeyHex = Buffer.from(p256.getPublicKey(attestationPrivateKey, true)).toString('hex'); + const backupRoot = bip32.fromSeed(Buffer.alloc(32, 0x31)).neutered(); + const signedPayload = JSON.stringify({ + external_customer_id: 'test-enterprise-id', + external_package_id: 'test-safe-id', + key_id: 'cc-key-id', + public_key: Buffer.concat([backupRoot.publicKey, backupRoot.chainCode]).toString('hex'), + }); + const signature = Buffer.from( + p256 + .sign(createHash('sha256').update(Buffer.from(signedPayload, 'utf8')).digest(), attestationPrivateKey, { + lowS: false, + }) + .toDERRawBytes() + ).toString('base64'); + // A valid xpub that is not the root's soft child at m/44/0/1/0. + const wrongChildPub = bip32.fromSeed(Buffer.alloc(32, 0x32)).derivePath('m/44/0/1/0').neutered().toBase58(); + + keychainsGet.callsFake(async ({ id }: { id: string }) => { + if (id === 'backup-root-id') { + return { + id, + source: 'backup', + pub: backupRoot.toBase58(), + provider: 'coincover', + keyId: 'cc-key-id', + signedPayload, + signature, + type: 'independent', + }; + } + if (id === 'backup-child-id') { + return { id, pub: wrongChildPub, type: 'independent' }; + } + return { + id: 'user-root-id', + source: 'user', + encryptedPrv: `enc:${ROOT_XPRV}`, + pub: 'root-xpub', + type: 'independent', + }; + }); + mockBitGo.post.returns({ + send: sinon.stub().returns({ + result: sinon.stub().resolves({ + id: 'wallet-id', + coin: 'tbtc', + keys: ['child-key-id', 'backup-child-id', 'bitgo-child-id'], + type: 'hot', + multisigType: 'onchain', + enterprise: 'test-enterprise-id', + safe: 'test-safe-id', + }), + }), + }); + + // The environment config is the SDK's pinned-key source, so inject this test's attestation key. + const testEnv = Environments.test as { coinCoverAttestationPublicKeys: readonly string[] }; + const previousAttestationKeys = testEnv.coinCoverAttestationPublicKeys; + testEnv.coinCoverAttestationPublicKeys = [attestationPublicKeyHex]; + let wallet: unknown; + let error: unknown; + try { + wallet = await safe.createWallet({ coin: 'tbtc', label: 'desk 1', passphrase: 'pw' }); + } catch (e) { + error = e; + } finally { + testEnv.coinCoverAttestationPublicKeys = previousAttestationKeys; + } + + (wallet === undefined).should.be.true(); + if (!(error instanceof Error)) { + throw new Error('expected createWallet to throw'); + } + error.message.should.match( + /Safe wallet minted for secp256k1Multisig at m\/44'\/0'\/1'\/0': the backup child does not derive from the CoinCover backup root/ + ); + }); + it('rejects a server coinType that differs from local statics before registering anything', async function () { derivationQuery.returns({ result: sinon.stub().resolves({ slot: 'secp256k1Multisig', coinType: 60, account: 0 }), diff --git a/modules/sdk-core/test/unit/bitgo/safe/safes.ts b/modules/sdk-core/test/unit/bitgo/safe/safes.ts index c2ff72c12b..37ab02ce98 100644 --- a/modules/sdk-core/test/unit/bitgo/safe/safes.ts +++ b/modules/sdk-core/test/unit/bitgo/safe/safes.ts @@ -569,6 +569,48 @@ describe('Safes', function () { }); }); + describe('CoinCover backup roots', function () { + const archiveOk = () => { + const send = sinon.stub().returns({ result: sinon.stub().resolves({ ...safeDataWire, status: 'archived' }) }); + mockBitGo.post.returns({ send }); + }; + + it('archives the safe when the provider backup root proof does not verify', async function () { + keychainsByCoin['tbtc'] = makeKeychains('tbtc'); + // The provider returned a root with a proof wallet platform claims is CoinCover's; the + // environment has no pinned attestation keys, so it must not be trusted. + keychainsByCoin['tbtc'].createBackup = sinon.stub().resolves({ + id: 'tbtc-backup', + pub: EXTERNAL_XPUB, + provider: 'coincover', + keyId: 'cc-key-id', + signedPayload: JSON.stringify({ + external_customer_id: 'test-enterprise-id', + external_package_id: 'safe-1', + key_id: 'cc-key-id', + public_key: '00'.repeat(64), + }), + signature: Buffer.alloc(70, 1).toString('base64'), + }); + archiveOk(); + + await safes + .createSafeKeys({ + label: 'my safe', + passphrase: 'pw', + safeId: 'safe-1', + backupKeyProvider: { provider: 'coincover' }, + externalBackupSlots: ['secp256k1Multisig'], + enabledRootSlots: ['secp256k1Multisig'], + }) + .should.be.rejectedWith( + /unable to verify the CoinCover backup root for secp256k1Multisig:.*has been archived; no backup root was registered for it/ + ); + + sinon.assert.calledWith(mockBitGo.post, '/enterprise/test-enterprise-id/safes/safe-1/archive'); + }); + }); + 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');