Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor tests related to notBefore and nbf (#492) #496

Closed
wants to merge 1 commit into from
Closed
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
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
"description": "JSON Web Token implementation (symmetric and asymmetric)",
"main": "index.js",
"scripts": {
"test": "nyc --reporter=html --reporter=text mocha && nsp check && cost-of-modules"
"test:unit": "nyc --reporter=html --reporter=text mocha",
"test": "npm run test:unit && nsp check && cost-of-modules"
},
"repository": {
"type": "git",
Expand Down
9 changes: 0 additions & 9 deletions test/iat.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,4 @@ describe('iat', function () {
expect(result.exp).to.be.closeTo(iat + expiresIn, 0.2);
});

it('should work with a nbf calculated based on numeric iat', function () {
var dateNow = Math.floor(Date.now() / 1000);
var iat = dateNow - 30;
var notBefore = -50;
var token = jwt.sign({foo: 123, iat: iat}, '123', {notBefore: notBefore});
var result = jwt.verify(token, '123');
expect(result.nbf).to.equal(iat + notBefore);
});

});
51 changes: 0 additions & 51 deletions test/jwt.asymmetric_signing.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,57 +114,6 @@ describe('Asymmetric Algorithms', function(){
});
});

describe('when signing a token with not before', function () {
var token = jwt.sign({ foo: 'bar' }, priv, { algorithm: algorithm, notBefore: -10 * 3600 });

it('should be valid expiration', function (done) {
jwt.verify(token, pub, function (err, decoded) {
assert.isNotNull(decoded);
assert.isNull(err);
done();
});
});

it('should be invalid', function (done) {
// not active token
token = jwt.sign({ foo: 'bar' }, priv, { algorithm: algorithm, notBefore: '10m' });

jwt.verify(token, pub, function (err, decoded) {
assert.isUndefined(decoded);
assert.isNotNull(err);
assert.equal(err.name, 'NotBeforeError');
assert.instanceOf(err.date, Date);
assert.instanceOf(err, jwt.NotBeforeError);
done();
});
});


it('should valid when date are equals', function (done) {
var fakeClock = sinon.useFakeTimers({now: 1451908031});

token = jwt.sign({ foo: 'bar' }, priv, { algorithm: algorithm, notBefore: 0 });

jwt.verify(token, pub, function (err, decoded) {
fakeClock.uninstall();
assert.isNull(err);
assert.isNotNull(decoded);
done();
});
});

it('should NOT be invalid', function (done) {
// not active token
token = jwt.sign({ foo: 'bar' }, priv, { algorithm: algorithm, notBefore: '10m' });

jwt.verify(token, pub, { ignoreNotBefore: true }, function (err, decoded) {
assert.ok(decoded.foo);
assert.equal('bar', decoded.foo);
done();
});
});
});

describe('when signing a token with audience', function () {
var token = jwt.sign({ foo: 'bar' }, priv, { algorithm: algorithm, audience: 'urn:foo' });

Expand Down
257 changes: 257 additions & 0 deletions test/nbf.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,257 @@
'use strict';

const jwt = require('../');
const expect = require('chai').expect;
const sinon = require('sinon');
const util = require('util');

function base64UrlEncode(str) {
return Buffer.from(str).toString('base64')
.replace(/=/g, "")
.replace(/\+/g, "-")
.replace(/\//g, "_")
;
}

function signWithNoBefore(payload, notBefore) {
const options = {algorithm: 'none'};
if (notBefore !== undefined) {
options.notBefore = notBefore;
}
return jwt.sign(payload, undefined, options);
}

const noneAlgorithmHeader = 'eyJhbGciOiJub25lIiwidHlwIjoiSldUIn0';

describe('not before', function() {
describe('`jwt.sign` notBefore option validation', function () {
[
true,
false,
null,
-1.1,
1.1,
-Infinity,
Infinity,
NaN,
// TODO empty string currently fails
// '',
' ',
'invalid',
[],
['foo'],
{},
{foo: 'bar'},
].forEach((notBefore) => {
it(`should error with with value ${util.inspect(notBefore)}`, function () {
expect(() => signWithNoBefore({}, notBefore)).to.throw(
'"notBefore" should be a number of seconds or string representing a timespan'
);
});
});

// undefined needs special treatment because {} is not the same as {notBefore: undefined}
it('should error with with value undefined', function () {
expect(() =>jwt.sign({}, undefined, {notBefore: undefined, algorithm: 'none'})).to.throw(
'"notBefore" should be a number of seconds or string representing a timespan'
);
});

it ('should error when "nbf" is in payload', function() {
expect(() => signWithNoBefore({nbf: 100}, 100)).to.throw(
'Bad "options.notBefore" option the payload already has an "nbf" property.'
);
});

it('should error with a string payload', function() {
expect(() => signWithNoBefore('a string payload', 100)).to.throw(
'invalid notBefore option for string payload'
);
});

it('should error with a Buffer payload', function() {
expect(() => signWithNoBefore(new Buffer('a Buffer payload'), 100)).to.throw(
'invalid notBefore option for object payload'
);
});
});

describe('`jwt.sign` nbf claim validation', function () {
[
true,
false,
null,
undefined,
// TODO should these fail in validation?
// -Infinity,
// Infinity,
// NaN,
'',
' ',
'invalid',
[],
['foo'],
{},
{foo: 'bar'},
].forEach((nbf) => {
it(`should error with with value ${util.inspect(nbf)}`, function () {
expect(() => signWithNoBefore({nbf})).to.throw(
'"nbf" should be a number of seconds'
);
});
});
});

describe('nbf in payload validation', function () {
[
true,
false,
null,
-Infinity,
Infinity,
NaN,
'',
' ',
'invalid',
[],
['foo'],
{},
{foo: 'bar'},
].forEach((nbf) => {
it(`should error with with value ${util.inspect(nbf)}`, function () {
const encodedPayload = base64UrlEncode(JSON.stringify({nbf}));
const token = `${noneAlgorithmHeader}.${encodedPayload}.`;
expect(() => jwt.verify(token, undefined)).to.throw(
jwt.JsonWebTokenError,
'invalid nbf value'
);
});
})
});

describe('when signing and verifying a token with notBefore option', function () {
let fakeClock;
beforeEach(function() {
fakeClock = sinon.useFakeTimers({now: 60000});
});

afterEach(function() {
fakeClock.uninstall();
});


it('should set correct "nbf" with negative number of seconds', function() {
const token = signWithNoBefore({}, -10);
const decoded = jwt.decode(token);

const verified = jwt.verify(token, undefined);
expect(decoded).to.deep.equal(verified);
expect(decoded.nbf).to.equal(50);
});

it('should set correct "nbf" with positive number of seconds', function() {
const token = signWithNoBefore({}, 10);

fakeClock.tick(10000);
const decoded = jwt.decode(token);

const verified = jwt.verify(token, undefined);
expect(decoded).to.deep.equal(verified);
expect(decoded.nbf).to.equal(70);
});

it('should set correct "nbf" with zero seconds', function() {
const token = signWithNoBefore({}, 0);

const decoded = jwt.decode(token);

const verified = jwt.verify(token, undefined);
expect(decoded).to.deep.equal(verified);
expect(decoded.nbf).to.equal(60);
});

it('should set correct "nbf" with negative string timespan', function() {
const token = signWithNoBefore({}, '-10 s');

const decoded = jwt.decode(token);

const verified = jwt.verify(token, undefined);
expect(decoded).to.deep.equal(verified);
expect(decoded.nbf).to.equal(50);
});


it('should set correct "nbf" with positive string timespan', function() {
const token = signWithNoBefore({}, '10 s');

fakeClock.tick(10000);
const decoded = jwt.decode(token);

const verified = jwt.verify(token, undefined);
expect(decoded).to.deep.equal(verified);
expect(decoded.nbf).to.equal(70);
});

it('should set correct "nbf" with zero string timespan', function() {
const token = signWithNoBefore({}, '0 s');

const decoded = jwt.decode(token);

const verified = jwt.verify(token, undefined);
expect(decoded).to.deep.equal(verified);
expect(decoded.nbf).to.equal(60);
});

it('should set correct "nbf" when "iat" is passed', function () {
const token = signWithNoBefore({iat: 40}, -10);

const decoded = jwt.decode(token);

const verified = jwt.verify(token, undefined);
expect(decoded).to.deep.equal(verified);
expect(decoded.nbf).to.equal(30);
});

it('should verify "nbf" using "clockTimestamp"', function () {
const token = signWithNoBefore({}, 10);

const verified = jwt.verify(token, undefined, {clockTimestamp: 70});
expect(verified.iat).to.equal(60);
expect(verified.nbf).to.equal(70);
});

it('should verify "nbf" using "clockTolerance"', function () {
const token = signWithNoBefore({}, 5);

const verified = jwt.verify(token, undefined, {clockTolerance: 6});
expect(verified.iat).to.equal(60);
expect(verified.nbf).to.equal(65);
});

it('should ignore a not active token when "ignoreNotBefore" is true', function () {
const token = signWithNoBefore({}, '10 s');

const verified = jwt.verify(token, undefined, {ignoreNotBefore: true});
expect(verified.iat).to.equal(60);
expect(verified.nbf).to.equal(70);
});

it('should error on verify if "nbf" is after current time', function() {
const token = signWithNoBefore({nbf: 61});

expect(() => jwt.verify(token, undefined)).to.throw(
jwt.NotBeforeError,
'jwt not active'
);
});

it('should error on verify if "nbf" is after current time using clockTolerance', function () {
const token = signWithNoBefore({}, 5);

expect(() => jwt.verify(token, undefined, {clockTolerance: 4})).to.throw(
jwt.NotBeforeError,
'jwt not active'
);
});
});
});
18 changes: 0 additions & 18 deletions test/schema.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,6 @@ describe('schema', function() {
sign({ expiresIn: 10 });
});

it('should validate notBefore', function () {
expect(function () {
sign({ notBefore: '1 monkey' });
}).to.throw(/"notBefore" should be a number of seconds or string representing a timespan/);
expect(function () {
sign({ notBefore: 1.1 });
}).to.throw(/"notBefore" should be a number of seconds or string representing a timespan/);
sign({ notBefore: '10s' });
sign({ notBefore: 10 });
});

it('should validate audience', function () {
expect(function () {
sign({ audience: 10 });
Expand Down Expand Up @@ -124,13 +113,6 @@ describe('schema', function() {
sign({ exp: 10.1 });
});

it('should validate nbf', function () {
expect(function () {
sign({ nbf: '1 monkey' });
}).to.throw(/"nbf" should be a number of seconds/);
sign({ nbf: 10.1 });
});

});

});
Loading