From f5b08864b8eff8e585faff040e4e806155170845 Mon Sep 17 00:00:00 2001 From: jiabaow <60721007+jiabaow@users.noreply.github.com> Date: Wed, 29 May 2024 10:01:35 -0700 Subject: [PATCH] test validateKey (#2485) add validateKey.test.ts --- packages/server/package.json | 3 +- .../server/test/utils/validateKey.test.ts | 41 +++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) create mode 100644 packages/server/test/utils/validateKey.test.ts diff --git a/packages/server/package.json b/packages/server/package.json index e5bf5e2c..01e432f6 100644 --- a/packages/server/package.json +++ b/packages/server/package.json @@ -40,7 +40,8 @@ "cypress:open": "cypress open", "cypress:run": "cypress run", "e2e": "start-server-and-test dev http://localhost:3000 cypress:run", - "cypress:ci": "START_SERVER_AND_TEST_INSECURE=1 start-server-and-test start https-get://localhost:3000 cypress:run" + "cypress:ci": "START_SERVER_AND_TEST_INSECURE=1 start-server-and-test start https-get://localhost:3000 cypress:run", + "test": "jest" }, "keywords": [], "homepage": "https://flowiseai.com", diff --git a/packages/server/test/utils/validateKey.test.ts b/packages/server/test/utils/validateKey.test.ts new file mode 100644 index 00000000..7d1e3cdf --- /dev/null +++ b/packages/server/test/utils/validateKey.test.ts @@ -0,0 +1,41 @@ +import { Request } from 'express' +import { ChatFlow } from '../../src/database/entities/ChatFlow' +import { utilValidateKey } from '../../src/utils/validateKey' +import { compareKeys, getAPIKeys } from '../../src/utils/apiKey' + +jest.mock('../../src/utils/apiKey') + +describe('utilValidateKey', () => { + let req: Partial + let chatflow: ChatFlow + + beforeEach(() => { + req = { + headers: {} + } + chatflow = { + apikeyid: null + } as ChatFlow + }) + + it('should return true if chatflow.apikeyid is not set', async () => { + const result = await utilValidateKey(req as Request, chatflow) + expect(result).toBe(true) + }) + + it('should return false if chatflow.apikeyid is set but authorization header is missing', async () => { + chatflow.apikeyid = 'some-api-key-id' + const result = await utilValidateKey(req as Request, chatflow) + expect(result).toBe(false) + }) + + it('should return false if supplied key does not match the expected key', async () => { + chatflow.apikeyid = 'some-api-key-id' + req.headers['authorization'] = 'Bearer invalid-key' + ;(getAPIKeys as jest.Mock).mockResolvedValue([{ id: 'some-api-key-id', apiSecret: 'expected-secret-key' }]) + ;(compareKeys as jest.Mock).mockImplementation((expected, supplied) => expected === supplied) + + const result = await utilValidateKey(req as Request, chatflow) + expect(result).toBe(false) + }) +})