refactor: improve error message when key use mismatches the operation

This commit is contained in:
Filip Skokan 2019-12-06 15:35:15 +01:00
parent cfe3dbab28
commit 8976027c97
5 changed files with 29 additions and 0 deletions

View file

@ -89,6 +89,10 @@ class Encrypt {
const enc = jweHeader.enc
let alg = jweHeader.alg
if (key.use === 'sig') {
throw new TypeError('a key with "use":"sig" is not usable for encryption')
}
if (alg === 'dir') {
check(key, 'encrypt', enc)
} else if (alg) {

View file

@ -69,6 +69,10 @@ class Sign {
[PROCESS_RECIPIENT] (recipient) {
const { key, protectedHeader, unprotectedHeader } = recipient
if (key.use === 'enc') {
throw new TypeError('a key with "use":"enc" is not usable for signing')
}
const joseHeader = {
protected: protectedHeader || {},
unprotected: unprotectedHeader || {}

View file

@ -568,3 +568,10 @@ test('JWE general fails with decryption error', t => {
JWE.decrypt(jwe, k3)
}, { instanceOf: errors.JWEDecryptionFailed, code: 'ERR_JWE_DECRYPTION_FAILED' })
})
test('"sig" key is not usable for signing', t => {
const k = generateSync('oct', 256, { use: 'sig' })
t.throws(() => {
JWE.encrypt('foo', k)
}, { instanceOf: TypeError, message: 'a key with "use":"sig" is not usable for encryption' })
})

View file

@ -281,3 +281,10 @@ test('invalid tokens', t => {
)
}, { instanceOf: errors.JOSEInvalidEncoding, code: 'ERR_JOSE_INVALID_ENCODING', message: 'input is not a valid base64url encoded string' })
})
test('"enc" key is not usable for signing', t => {
const k = generateSync('oct', 256, { use: 'enc' })
t.throws(() => {
JWS.sign({}, k)
}, { instanceOf: TypeError, message: 'a key with "use":"enc" is not usable for signing' })
})

View file

@ -187,3 +187,10 @@ test('when options arent in effect', t => {
}
t.deepEqual(payload, JWT.decode(JWT.sign(payload, key, { iat: false })))
})
test('"enc" key is not usable for signing', t => {
const k = JWK.generateSync('oct', 256, { use: 'enc' })
t.throws(() => {
JWT.sign({}, k)
}, { instanceOf: TypeError, message: 'a key with "use":"enc" is not usable for signing' })
})