forked from Lilly-Protocol/lily-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi-key-auth.middleware.test.ts
More file actions
51 lines (43 loc) · 1.63 KB
/
Copy pathapi-key-auth.middleware.test.ts
File metadata and controls
51 lines (43 loc) · 1.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
import { describe, it, expect, vi, beforeEach } from "vitest";
import type { Request, Response, NextFunction } from "express";
import { apiKeyAuth } from "./api-key-auth.middleware";
vi.mock("../../config/env", () => ({
securityConfig: {
authApiKey: "test-secret-key-12345",
authApiKeyHeader: "x-api-key",
},
}));
vi.mock("../../config/logger", () => ({
logger: { warn: vi.fn() },
}));
describe("apiKeyAuth constant-time comparison", () => {
let req: Partial<Request>;
let res: Partial<Response>;
let next: NextFunction;
beforeEach(() => {
req = { get: vi.fn() };
res = {};
next = vi.fn();
});
it("accepts matching key", () => {
(req.get as any).mockReturnValue("test-secret-key-12345");
apiKeyAuth(req as Request, res as Response, next);
expect(next).toHaveBeenCalledWith();
expect(next).not.toHaveBeenCalledWith(expect.objectContaining({ statusCode: 403 }));
});
it("rejects wrong-length key with 403", () => {
(req.get as any).mockReturnValue("short");
apiKeyAuth(req as Request, res as Response, next);
expect(next).toHaveBeenCalledWith(expect.objectContaining({ statusCode: 403 }));
});
it("rejects near-miss key with 403", () => {
(req.get as any).mockReturnValue("test-secret-key-12346");
apiKeyAuth(req as Request, res as Response, next);
expect(next).toHaveBeenCalledWith(expect.objectContaining({ statusCode: 403 }));
});
it("rejects missing key with 401", () => {
(req.get as any).mockReturnValue(undefined);
apiKeyAuth(req as Request, res as Response, next);
expect(next).toHaveBeenCalledWith(expect.objectContaining({ statusCode: 401 }));
});
});