Skip to content

Commit dad5beb

Browse files
committed
test(auth): add test for validateJwt helper function
1 parent 24cba4d commit dad5beb

File tree

1 file changed

+47
-1
lines changed

1 file changed

+47
-1
lines changed

test/testJwtAuthHandler.test.js

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,11 @@
11
const { expect } = require('chai');
22
const sinon = require('sinon');
33
const axios = require('axios');
4-
const { getJwks } = require('../src/service/passport/jwtUtils');
4+
const jwt = require('jsonwebtoken');
5+
const { jwkToBuffer } = require('jwk-to-pem');
6+
7+
const { getJwks, validateJwt } = require('../src/service/passport/jwtUtils');
8+
const { jwtAuthHandler } = require('../src/service/passport/jwtAuthHandler');
59

610
describe('getJwks', () => {
711
it('should fetch JWKS keys from authority', async () => {
@@ -27,3 +31,45 @@ describe('getJwks', () => {
2731
stub.restore();
2832
});
2933
});
34+
35+
describe('validateJwt', () => {
36+
let decodeStub, verifyStub, pemStub, getJwksStub;
37+
38+
beforeEach(() => {
39+
const jwksResponse = { keys: [{ kid: 'test-key', kty: 'RSA', n: 'abc', e: 'AQAB' }] };
40+
const getStub = sinon.stub(axios, 'get');
41+
getStub.onFirstCall().resolves({ data: { jwks_uri: 'https://mock.com/jwks' } });
42+
getStub.onSecondCall().resolves({ data: jwksResponse });
43+
44+
getJwksStub = sinon.stub().resolves(jwksResponse.keys);
45+
decodeStub = sinon.stub(jwt, 'decode');
46+
verifyStub = sinon.stub(jwt, 'verify');
47+
pemStub = sinon.stub(jwkToBuffer);
48+
49+
pemStub.returns('fake-public-key');
50+
getJwksStub.returns(jwksResponse.keys);
51+
});
52+
53+
afterEach(() => sinon.restore());
54+
55+
it('should validate a correct JWT', async () => {
56+
const mockJwk = { kid: '123', kty: 'RSA', n: 'abc', e: 'AQAB' };
57+
const mockPem = 'fake-public-key';
58+
59+
decodeStub.returns({ header: { kid: '123' } });
60+
getJwksStub.resolves([mockJwk]);
61+
pemStub.returns(mockPem);
62+
verifyStub.returns({ azp: 'client-id', sub: 'user123' });
63+
64+
const { verifiedPayload } = await validateJwt('fake.token.here', 'https://issuer.com', 'client-id', 'client-id', getJwksStub);
65+
expect(verifiedPayload.sub).to.equal('user123');
66+
});
67+
68+
it('should return error if JWT invalid', async () => {
69+
decodeStub.returns(null); // Simulate broken token
70+
71+
const { error } = await validateJwt('bad.token', 'https://issuer.com', 'client-id', 'client-id', getJwksStub);
72+
expect(error).to.include('Invalid JWT');
73+
});
74+
});
75+

0 commit comments

Comments
 (0)