server: secret-key middleware tests

This commit is contained in:
Max Leiter 2022-04-06 09:15:21 -07:00
parent c6f89a28ad
commit 6c39d1c7c0
No known key found for this signature in database
GPG key ID: A3512F2F2F17EBDA
2 changed files with 50 additions and 0 deletions

View file

@ -0,0 +1,46 @@
// import * as request from 'supertest'
// import { app } from '../../../app'
import { NextFunction, Response } from "express"
import { UserJwtRequest } from "@lib/middleware/jwt"
import secretKey from "@lib/middleware/secret-key"
import config from "@lib/config"
describe("secret-key middlware", () => {
let mockRequest: Partial<UserJwtRequest>
let mockResponse: Partial<Response>
let nextFunction: NextFunction = jest.fn()
beforeEach(() => {
mockRequest = {}
mockResponse = {
sendStatus: jest.fn()
}
})
it("should return 401 if no x-secret-key header", async () => {
const res = mockResponse as Response
secretKey(mockRequest as UserJwtRequest, res, nextFunction)
expect(res.sendStatus).toHaveBeenCalledWith(401)
})
it("should return 401 if x-secret-key does not match server", async () => {
const defaultSecretKey = config.secret_key
const req = mockRequest as UserJwtRequest
req.headers = {
authorization: "Bearer",
"x-secret-key": defaultSecretKey + "1"
}
secretKey(req, mockResponse as Response, nextFunction)
expect(mockResponse.sendStatus).toBeCalledWith(401)
})
it("should call next() if x-secret-key matches server", async () => {
const req = mockRequest as UserJwtRequest
req.headers = {
authorization: "Bearer",
"x-secret-key": config.secret_key
}
secretKey(req, mockResponse as Response, nextFunction)
expect(nextFunction).toBeCalled()
})
})

View file

@ -6,6 +6,10 @@ export default function authenticateToken(
res: Response, res: Response,
next: NextFunction next: NextFunction
) { ) {
if (!(req.headers && req.headers["x-secret-key"])) {
return res.sendStatus(401)
}
const requestKey = req.headers["x-secret-key"] const requestKey = req.headers["x-secret-key"]
if (requestKey !== config.secret_key) { if (requestKey !== config.secret_key) {
return res.sendStatus(401) return res.sendStatus(401)