From 6c39d1c7c0886988288ae847143b92378d07fca1 Mon Sep 17 00:00:00 2001 From: Max Leiter Date: Wed, 6 Apr 2022 09:15:21 -0700 Subject: [PATCH] server: secret-key middleware tests --- .../lib/__tests__/middleware/secret-key.ts | 46 +++++++++++++++++++ server/src/lib/middleware/secret-key.ts | 4 ++ 2 files changed, 50 insertions(+) create mode 100644 server/src/lib/__tests__/middleware/secret-key.ts diff --git a/server/src/lib/__tests__/middleware/secret-key.ts b/server/src/lib/__tests__/middleware/secret-key.ts new file mode 100644 index 00000000..39a7381c --- /dev/null +++ b/server/src/lib/__tests__/middleware/secret-key.ts @@ -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 + let mockResponse: Partial + 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() + }) +}) diff --git a/server/src/lib/middleware/secret-key.ts b/server/src/lib/middleware/secret-key.ts index 1cc5f78b..f29b039c 100644 --- a/server/src/lib/middleware/secret-key.ts +++ b/server/src/lib/middleware/secret-key.ts @@ -6,6 +6,10 @@ export default function authenticateToken( res: Response, next: NextFunction ) { + if (!(req.headers && req.headers["x-secret-key"])) { + return res.sendStatus(401) + } + const requestKey = req.headers["x-secret-key"] if (requestKey !== config.secret_key) { return res.sendStatus(401)