Skip to content

Commit

Permalink
fix: do not 'in' operator when importing keys as string
Browse files Browse the repository at this point in the history
  • Loading branch information
panva committed Mar 4, 2019
1 parent d5fc18e commit be3f4e4
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
4 changes: 2 additions & 2 deletions lib/jwk/import.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const importKey = (key, parameters) => {
break
default:
}
} else if ('kty' in key && key.kty === 'oct') { // symmetric key <Object>
} else if (typeof key === 'object' && 'kty' in key && key.kty === 'oct') { // symmetric key <Object>
try {
secret = createSecretKey(base64url.decodeToBuffer(key.k))
} catch (err) {
Expand All @@ -49,7 +49,7 @@ const importKey = (key, parameters) => {
}
}
parameters = mergedParameters(parameters, key)
} else if ('kty' in key) { // assume JWK formatted asymmetric key <Object>
} else if (typeof key === 'object' && 'kty' in key) { // assume JWK formatted asymmetric key <Object>
let parsedJWK
try {
parsedJWK = jwkToPem(key)
Expand Down
32 changes: 32 additions & 0 deletions test/jwk/import.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,25 @@ test('parameters must be a plain object', t => {
})
})

Object.entries(fixtures.PEM).forEach(([type, { private: priv, public: pub }]) => {
test(`${type} private can be imported as a string`, t => {
const k = importKey(priv.toString('ascii'))
t.true(k.private)
})
test(`${type} public can be imported as a string`, t => {
const k = importKey(pub.toString('ascii'))
t.true(k.public)
})
test(`${type} private can be imported as a buffer`, t => {
const k = importKey(priv)
t.true(k.private)
})
test(`${type} public can be imported as a buffer`, t => {
const k = importKey(pub)
t.true(k.public)
})
})

test('failed to import throws an error', t => {
t.throws(() => {
importKey({
Expand All @@ -44,3 +63,16 @@ test('failed to import throws an error', t => {
})
}, { instanceOf: errors.JWKImportFailed, code: 'ERR_JWK_IMPORT_FAILED' })
})

;[
`-----BEGIN PRIVATE KEY-----\nMC4CAQAwBQYDK2VwBCIEIHXLsXm1lsq5HtyqJwQyFmpfEluuf0KOqP6DqMgGxxDL\n-----END PRIVATE KEY-----`,
`-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAEXRYV3v5ucrHVR3mKqyPXxXqU34lASwc7Y7MoOvaqcs=\n-----END PUBLIC KEY-----`,
`-----BEGIN PRIVATE KEY-----\nMEcCAQAwBQYDK2VxBDsEObxytD95dGN3Hxk7kVk+Lig1rGYTRr3YdaHjRog++Sgk\nQD7KwKmxroBURtkE2N0JbQ3ctdrpGRB5DQ==\n-----END PRIVATE KEY-----`,
`-----BEGIN PUBLIC KEY-----\nMEMwBQYDK2VxAzoAIESY3jnpGdB5UVJDCznrv0vmBFIzgSMu+gafsbCX1rFtsJwR\nM6XUDQiEY7dk6rmm/Fktyawna5EA\n-----END PUBLIC KEY-----`
].forEach((unsupported, i) => {
test.skip(`fails to import unsupported PEM ${i + 1}/4`, t => {
t.throws(() => {
importKey(unsupported)
}, { instanceOf: errors.JWKImportFailed, code: 'ERR_JWK_IMPORT_FAILED' })
})
})

0 comments on commit be3f4e4

Please sign in to comment.