Skip to content

AsnParser.parse() fails to recognise some ArrayBuffers #71

@gnarea

Description

@gnarea

The problem

Upgrading @​peculiar/webcrypto from 1.3.3 to 1.4.0 causes the following error:

TypeError: Wrong type of 'data' argument

    at Function.parse (/home/gus/repos/awala-keystore-gcp-js/node_modules/@peculiar/asn1-schema/build/cjs/parser.js:23:19)
    at EcPrivateKey.getKey (/home/gus/repos/awala-keystore-gcp-js/node_modules/@peculiar/webcrypto/build/webcrypto.js:1404:37)
    at EcPrivateKey.toJSON (/home/gus/repos/awala-keystore-gcp-js/node_modules/@peculiar/webcrypto/build/webcrypto.js:1407:26)
    at Function.toJSON (/home/gus/repos/awala-keystore-gcp-js/node_modules/@peculiar/json-schema/build/index.js:254:24)
    at Function.exportKey (/home/gus/repos/awala-keystore-gcp-js/node_modules/@peculiar/webcrypto/build/webcrypto.js:1616:50)
    at EcdhProvider.onExportKey (/home/gus/repos/awala-keystore-gcp-js/node_modules/@peculiar/webcrypto/build/webcrypto.js:1777:25)
    at EcdhProvider.exportKey (/home/gus/repos/awala-keystore-gcp-js/node_modules/webcrypto-core/build/webcrypto-core.js:223:33)
    at SubtleCrypto.exportKey (/home/gus/repos/awala-keystore-gcp-js/node_modules/webcrypto-core/build/webcrypto-core.js:1465:39)
    at CryptoEngine.exportKey (/home/gus/repos/awala-keystore-gcp-js/node_modules/pkijs/build/CryptoEngine.js:650:32)
    at derSerializePrivateKey (/home/gus/repos/awala-keystore-gcp-js/node_modules/@relaycorp/relaynet-core/src/lib/crypto_wrappers/keys.ts:97:38)

The root cause

The following check fails sometimes even though data is indeed an ArrayBuffer:

if (data instanceof ArrayBuffer) {

Here's what the WebStorm debugger shows (which I've double-checked with console.log()):

asn1-1
asn1-2
asn1-3

This behaviour is valid according to:

So the culprit seems to be JS realms, which I'm guessing in the case of Node.js can only happen when asn1-schema is used by multiple libraries in the same process, along with some of the recent changes to @peculiar/webcrypto.

How to reproduce

Unfortunately, it's quite hard to reproduce this as you need a relatively complex dependency tree to reproduce it. But if you want to reliably reproduce this locally, you can run npm test in relaycorp/awala-keystore-cloud-js#13 and check the broken tests.

This is the relevant dependency sub-tree for the repo above:

Potential solution

Check .toString() if instanceof returns false: https://github.com/fengyuanchen/is-array-buffer/blob/9ea7fb638e79f8938161b3b7370cb965d8e93a8b/index.ts#L15

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions