Gathering detailed insights and metrics for mock-jwks
Gathering detailed insights and metrics for mock-jwks
Gathering detailed insights and metrics for mock-jwks
Gathering detailed insights and metrics for mock-jwks
A tool to mock the auth0 authentication service for development of microservices CONSUMING auth0 jwts
npm install mock-jwks
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
58 Stars
399 Commits
20 Forks
4 Watching
9 Branches
5 Contributors
Updated on 18 Sept 2024
TypeScript (99.39%)
Shell (0.61%)
Cumulative downloads
Total Downloads
Last day
-10.5%
10,631
Compared to previous day
Last week
-0.5%
54,537
Compared to previous week
Last month
-0.3%
233,895
Compared to previous month
Last year
-8.2%
3,361,616
Compared to previous year
5
21
A tool to mock a JWKS authentication service for development of microservices CONSUMING authentication and authorization jwts.
As of version 2 and march 2023 this package is a pure esm package. I made an example on how to use the module. Use version 1 for a commonjs version.
If you use jwts for authentication and authorization of your users against your microservices, you want to automatically unit test the authentication in your microservice for security. Happy and unhappy paths. Doing this while actually using a running JWKS deployment (like the auth0 backend) is slow and annoying, so e.g. auth0 suggest you mock their api. This turns out to be somewhat difficult, especially in the case of using RSA for signing of the tokens and not wanting to heavily dependency inject the middleware for authentication in your koa or express app. This is why I made this tool, which requires less changes to your code.
Consider a basic express
app (works also with koa
, hapi
or graphql
):
1// api.js 2import express from 'express' 3import { expressjwt } from 'express-jwt' 4import jwksRsa from 'jwks-rsa' 5export const createApp = ({ jwksUri }) => 6 express() 7 .use( 8 // We set up the jwksRsa client as usual (with production host) 9 expressjwt({ 10 secret: jwksRsa.expressJwtSecret({ 11 cache: false, // We switch off caching to show how things work in ours tests. 12 jwksUri, 13 }), 14 audience: 'private', 15 issuer: 'master', 16 algorithms: ['RS256'], 17 }) 18 ) 19 .get('/', (_, res) => res.send('Authenticated'))
You can test this app like so:
1// authentication.test.js 2// @ts-check 3import { createJWKSMock } from 'mock-jwks' 4import { createApp } from './api.js' 5import supertest from 'supertest' 6import { describe, expect, test, onTestFinished } from 'vitest' 7 8// This creates the local PKI 9const jwksMock = createJWKSMock('https://levino.eu.auth0.com') 10// We start our app. 11const app = createApp({ 12 jwksUri: 'https://levino.eu.auth0.com/.well-known/jwks.json', 13}) 14 15describe('Some tests for authentication for our api', () => { 16 test('should not get access without correct token', async () => { 17 // We start intercepting queries (see below) 18 onTestFinished(jwksMock.start()) 19 const { status } = await supertest(app).get('/') 20 expect(status).toEqual(401) 21 }) 22 23 test('should get access with mock token when jwksMock is running', async () => { 24 // Again we start intercepting queries 25 onTestFinished(jwksMock.start()) 26 const access_token = jwksMock.token({ 27 aud: 'private', 28 iss: 'master', 29 }) 30 const { status } = await supertest(app) 31 .get('/') 32 .set('Authorization', `Bearer ${access_token}`) 33 expect(status).toEqual(200) 34 }) 35 test('should not get access with mock token when jwksMock is not running', async () => { 36 // Now we do not intercept queries. The queries of the middleware for the JKWS will 37 // go to the production server and the local key will be invalid. 38 const access_token = jwksMock.token({ 39 aud: 'private', 40 iss: 'master', 41 }) 42 const { status } = await supertest(app) 43 .get('/') 44 .set('Authorization', `Bearer ${access_token}`) 45 expect(status).toEqual(500) 46 }) 47}) 48test('Another example with a non-auth0-style jkwsUri', async () => { 49 const jwksMock = createJWKSMock( 50 'https://keycloak.somedomain.com', 51 '/auth/realm/application/protocol/openid-connect/certs' 52 ) 53 // We start our app. 54 const app = createApp({ 55 jwksUri: 56 'https://keycloak.somedomain.com/auth/realm/application/protocol/openid-connect/certs', 57 }) 58 const request = supertest(app) 59 onTestFinished(jwksMock.start()) 60 const access_token = jwksMock.token({ 61 aud: 'private', 62 iss: 'master', 63 }) 64 const { status } = await request 65 .get('/') 66 .set('Authorization', `Bearer ${access_token}`) 67 expect(status).toEqual(200) 68})
You can also find this example in the repo.
Internally this library uses Mock Server Worker (MSW) to create network mocks
for the JWKS keyset. Instead of letting mock-jwks
run its own msw
instance,
you can add the required handlers to your running instance.
In this case, instead of calling start()/stop()
, provide the mswHandler
to
to your existing server instance:
1// @ts-check 2/** 3 * @typedef 4 */ 5import createJWKSMock from 'mock-jwks' 6import { createApp } from './api.js' 7import supertest from 'supertest' 8import { beforeAll, beforeEach, describe, expect, test } from 'vitest' 9import { setupServer } from 'msw/node' 10 11const jwksMock = createJWKSMock('https://levino.eu.auth0.com') 12const app = createApp({ 13 jwksUri: 'https://levino.eu.auth0.com/.well-known/jwks.json', 14}) 15 16describe('Some tests for authentication for our api', () => { 17 /** @type {import('msw/node').SetupServerApi} */ 18 let mswServer 19 beforeAll(() => { 20 mswServer = setupServer() 21 mswServer.listen({ 22 onUnhandledRequest: 'bypass', // We silence the warnings of msw for unhandled requests. Not necessary for things to work. 23 }) 24 return () => mswServer.close() 25 }) 26 27 beforeEach(() => { 28 mswServer.resetHandlers() 29 }) 30 31 test('Can get access with mock token when handler is attached to msw', async () => { 32 // arrange 33 mswServer.use(jwksMock.mswHandler) 34 const access_token = jwksMock.token({ 35 aud: 'private', 36 iss: 'master', 37 }) 38 39 // act 40 const { status } = await supertest(app) 41 .get('/') 42 .set('Authorization', `Bearer ${access_token}`) 43 44 // assert 45 expect(status).toEqual(200) 46 }) 47 test('Cannot get access with mock token when handler is not attached to msw', async () => { 48 // Now we do not intercept queries. The queries of the middleware for the JKWS will 49 // go to the production server and the local key will be invalid. 50 // arrange 51 const access_token = jwksMock.token({ 52 aud: 'private', 53 iss: 'master', 54 }) 55 56 // act 57 const { status } = await supertest(app) 58 .get('/') 59 .set('Authorization', `Bearer ${access_token}`) 60 61 // assert 62 expect(status).toEqual(500) 63 }) 64})
You can also find this example in the repo.
createJWKSMock
will create a local PKI and generate a working JWKS.json.
Calling jwksMock.start()
will use msw to intercept all
calls to
1;`${jwksBase}${jwksPath ?? '/.well-known/jwks.json'}`
. So when the jwks-rsa
middleware gets a token to validate it will fetch the
key to verify against from our local PKI instead of the production one and as
such, the token is valid when signed with the local private key.
You found a bug or want to improve the software? Thank you for your support! Before you open a PR I kindly invite you to read about best practices and subject your contribution to them.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 1/6 approved changesets -- score normalized to 1
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
11 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More