Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions test/verify.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,37 @@ describe('verify', function() {
});
});

describe('with a malformed PEM public key', function () {
const token = jwt.sign({ foo: 'bar' }, priv, { algorithm: 'RS256' });
const malformedPem = pub.toString().replace(/\n[A-Za-z0-9+/]{10}/, '\n');

it('should report the key parsing error instead of "invalid algorithm"', function () {
let error;
try {
jwt.verify(token, malformedPem);
} catch (e) {
error = e;
}
expect(error).to.be.instanceOf(JsonWebTokenError);
expect(error.message).to.match(/^secretOrPublicKey is not a valid PEM key: /);
expect(error.inner).to.be.instanceOf(Error);
});

it('should report the key parsing error when the key is a Buffer', function () {
expect(function () {
jwt.verify(token, Buffer.from(malformedPem));
}).to.throw(JsonWebTokenError, /secretOrPublicKey is not a valid PEM key/);
});

it('should report the key parsing error to the callback', function (done) {
jwt.verify(token, malformedPem, function (err) {
expect(err).to.be.instanceOf(JsonWebTokenError);
expect(err.message).to.match(/secretOrPublicKey is not a valid PEM key/);
done();
});
});
});

it('should not be able to verify unsigned token', function () {
const header = { alg: 'none' };
const payload = { iat: Math.floor(Date.now() / 1000 ) };
Expand Down
9 changes: 8 additions & 1 deletion verify.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ if (PS_SUPPORTED) {
RSA_KEY_ALGS.splice(RSA_KEY_ALGS.length, 0, 'PS256', 'PS384', 'PS512');
}

function looksLikePem(key) {
return (typeof key === 'string' || Buffer.isBuffer(key)) && key.includes('-----BEGIN');
}

module.exports = function (jwtString, secretOrPublicKey, options, callback) {
if ((typeof options === 'function') && !callback) {
callback = options;
Expand Down Expand Up @@ -120,7 +124,10 @@ module.exports = function (jwtString, secretOrPublicKey, options, callback) {
if (secretOrPublicKey != null && !(secretOrPublicKey instanceof KeyObject)) {
try {
secretOrPublicKey = createPublicKey(secretOrPublicKey);
} catch (_) {
} catch (err) {
if (looksLikePem(secretOrPublicKey)) {
return done(new JsonWebTokenError('secretOrPublicKey is not a valid PEM key: ' + err.message, err));
}
try {
secretOrPublicKey = createSecretKey(typeof secretOrPublicKey === 'string' ? Buffer.from(secretOrPublicKey) : secretOrPublicKey);
} catch (_) {
Expand Down