Skip to content

Commit

Permalink
test: Add basic tests for isEqual function [skip pizza] (#2558)
Browse files Browse the repository at this point in the history
  • Loading branch information
DafyddLlyr authored Dec 12, 2023
1 parent d885b24 commit 96dddb3
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
36 changes: 36 additions & 0 deletions api.planx.uk/modules/auth/middleware.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { isEqual } from "./middleware";

describe("isEqual() helper function", () => {
it("handles undefined secrets", () => {
const req = { headers: { "api-key": undefined } };
const result = isEqual(req.headers["api-key"], process.env.UNSET_SECRET!);
expect(result).toBe(false);
});

it("handles null values", () => {
const req = { headers: { "api-key": null } };
// @ts-expect-error "api-key" purposefully set to wrong type
const result = isEqual(req.headers["api-key"], null!);
expect(result).toBe(false);
});

it("handles undefined headers", () => {
const req = { headers: { "some-other-header": "test123" } };
// @ts-expect-error "api-key" purposefully not set
const result = isEqual(req.headers["api-key"]!, process.env.UNSET_SECRET!);
expect(result).toBe(false);
});

it("handles empty strings", () => {
const req = { headers: { "api-key": "" } };
expect(isEqual(req.headers["api-key"], "")).toBe(false);
});

it("matches equal values", () => {
expect(isEqual("square", "square")).toBe(true);
});

it("does not match different values", () => {
expect(isEqual("circle", "triangle")).toBe(false);
});
});
5 changes: 4 additions & 1 deletion api.planx.uk/modules/auth/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,10 @@ export const userContext = new AsyncLocalStorage<{ user: Express.User }>();
/**
* Validate that a provided string (e.g. API key) matches the expected value
*/
const isEqual = (provided = "", expected: string): boolean => {
export const isEqual = (provided = "", expected: string): boolean => {
// Reject test against falsey values - could indicate unset secret
if (!expected) return false;

const hash = crypto.createHash("SHA512");
return crypto.timingSafeEqual(
hash.copy().update(provided).digest(),
Expand Down

0 comments on commit 96dddb3

Please sign in to comment.