1
1
const { expect } = require ( 'chai' ) ;
2
2
const sinon = require ( 'sinon' ) ;
3
3
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' ) ;
5
9
6
10
describe ( 'getJwks' , ( ) => {
7
11
it ( 'should fetch JWKS keys from authority' , async ( ) => {
@@ -27,3 +31,45 @@ describe('getJwks', () => {
27
31
stub . restore ( ) ;
28
32
} ) ;
29
33
} ) ;
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