Skip to content

Commit

Permalink
fix: fail to import invalid PEM formatted strings and buffers
Browse files Browse the repository at this point in the history
  • Loading branch information
panva committed Apr 23, 2019
1 parent 23b874c commit 857dc2b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
6 changes: 5 additions & 1 deletion lib/jwk/import.js
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,11 @@ const importKey = (key, parameters) => {
publicKey = createPublicKey(key)
} catch (err) {}
try {
secret = createSecretKey(Buffer.isBuffer(key) ? key : Buffer.from(key))
// this is to filter out invalid PEM keys and certs, i'll rather have them fail import then
// have them imported as symmetric "oct" keys
if (!key.includes('-----BEGIN')) {
secret = createSecretKey(Buffer.isBuffer(key) ? key : Buffer.from(key))
}
} catch (err) {}
}

Expand Down
10 changes: 10 additions & 0 deletions test/jwk/import.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,16 @@ test('parameters must be a plain object', t => {
})

Object.entries(fixtures.PEM).forEach(([type, { private: priv, public: pub }]) => {
test(`fails to import ${type} as invalid string`, t => {
t.throws(() => {
importKey(priv.toString('ascii').replace(/\n/g, ''))
}, { instanceOf: errors.JWKImportFailed, code: 'ERR_JWK_IMPORT_FAILED' })
})
test(`fails to import ${type} as invalid buffer`, t => {
t.throws(() => {
importKey(Buffer.from(priv.toString('ascii').replace(/\n/g, '')))
}, { instanceOf: errors.JWKImportFailed, code: 'ERR_JWK_IMPORT_FAILED' })
})
test(`${type} private can be imported as a string`, t => {
const k = importKey(priv.toString('ascii'))
t.true(k.private)
Expand Down

0 comments on commit 857dc2b

Please sign in to comment.