-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapi-key-auth.guard.spec.ts
More file actions
310 lines (265 loc) · 9.03 KB
/
Copy pathapi-key-auth.guard.spec.ts
File metadata and controls
310 lines (265 loc) · 9.03 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import {
ExecutionContext,
HttpException,
HttpStatus,
UnauthorizedException,
} from "@nestjs/common";
import { Reflector } from "@nestjs/core";
import { Test, TestingModule } from "@nestjs/testing";
import { ApiKeyService } from "../api-key/api-key.service";
import { ApiKeyAuthGuard } from "./api-key-auth.guard";
describe("ApiKeyAuthGuard", () => {
let guard: ApiKeyAuthGuard;
let reflector: Reflector;
let apiKeyService: ApiKeyService;
const mockApiKeyService = {
validateApiKey: jest.fn(),
};
const createMockExecutionContext = (
headers: Record<string, string> = {},
user?: object,
ip = "127.0.0.1",
): ExecutionContext => {
const mockRequest = {
headers,
user,
ip,
};
return {
switchToHttp: () => ({
getRequest: () => mockRequest,
}),
getHandler: () => ({}),
getClass: () => ({}),
} as unknown as ExecutionContext;
};
beforeEach(async () => {
jest.clearAllMocks();
const module: TestingModule = await Test.createTestingModule({
providers: [
ApiKeyAuthGuard,
{
provide: Reflector,
useValue: {
getAllAndOverride: jest.fn(),
},
},
{
provide: ApiKeyService,
useValue: mockApiKeyService,
},
],
}).compile();
guard = module.get<ApiKeyAuthGuard>(ApiKeyAuthGuard);
reflector = module.get<Reflector>(Reflector);
apiKeyService = module.get<ApiKeyService>(ApiKeyService);
});
afterEach(() => {
guard.onModuleDestroy();
});
it("should return true if endpoint does not allow API key auth", async () => {
(reflector.getAllAndOverride as jest.Mock).mockReturnValue(undefined);
const context = createMockExecutionContext();
const result = await guard.canActivate(context);
expect(result).toBe(true);
expect(apiKeyService.validateApiKey).not.toHaveBeenCalled();
});
it("should return true if user is already authenticated", async () => {
(reflector.getAllAndOverride as jest.Mock).mockReturnValue({
allowApiKey: true,
});
const context = createMockExecutionContext({}, { sub: "testuser" });
const result = await guard.canActivate(context);
expect(result).toBe(true);
expect(apiKeyService.validateApiKey).not.toHaveBeenCalled();
});
it("should throw UnauthorizedException if no API key header and no authenticated user", async () => {
(reflector.getAllAndOverride as jest.Mock).mockReturnValue({
allowApiKey: true,
});
const context = createMockExecutionContext({});
await expect(guard.canActivate(context)).rejects.toThrow(
UnauthorizedException,
);
expect(apiKeyService.validateApiKey).not.toHaveBeenCalled();
});
it("should return true if no API key header but user is already authenticated", async () => {
(reflector.getAllAndOverride as jest.Mock).mockReturnValue({
allowApiKey: true,
});
const context = createMockExecutionContext({}, { sub: "testuser" });
const result = await guard.canActivate(context);
expect(result).toBe(true);
expect(apiKeyService.validateApiKey).not.toHaveBeenCalled();
});
it("should throw UnauthorizedException for invalid API key", async () => {
(reflector.getAllAndOverride as jest.Mock).mockReturnValue({
allowApiKey: true,
});
mockApiKeyService.validateApiKey.mockResolvedValue(null);
const context = createMockExecutionContext({ "x-api-key": "invalidkey" });
await expect(guard.canActivate(context)).rejects.toThrow(
UnauthorizedException,
);
expect(apiKeyService.validateApiKey).toHaveBeenCalledWith("invalidkey");
});
it("should set apiKeyGroupId and apiKeyPrefix for valid API key", async () => {
(reflector.getAllAndOverride as jest.Mock).mockReturnValue({
allowApiKey: true,
});
mockApiKeyService.validateApiKey.mockResolvedValue({
groupId: "group-abc",
keyPrefix: "aBcDeFgH",
});
const mockRequest: Record<string, unknown> = {
headers: { "x-api-key": "validkey" },
};
const context = {
switchToHttp: () => ({
getRequest: () => mockRequest,
}),
getHandler: () => ({}),
getClass: () => ({}),
} as unknown as ExecutionContext;
const result = await guard.canActivate(context);
expect(result).toBe(true);
expect(mockRequest.user).toBeUndefined();
expect(mockRequest.apiKeyGroupId).toBe("group-abc");
expect(mockRequest.apiKeyPrefix).toBe("aBcDeFgH");
});
describe("failed-attempt throttling", () => {
beforeEach(() => {
(reflector.getAllAndOverride as jest.Mock).mockReturnValue({
allowApiKey: true,
});
mockApiKeyService.validateApiKey.mockResolvedValue(null);
});
it("should allow up to 20 failed attempts from the same IP", async () => {
for (let i = 0; i < 20; i++) {
const context = createMockExecutionContext(
{ "x-api-key": `bad-key-${i}` },
undefined,
"10.0.0.1",
);
await expect(guard.canActivate(context)).rejects.toThrow(
UnauthorizedException,
);
}
expect(apiKeyService.validateApiKey).toHaveBeenCalledTimes(20);
});
it("should block the 21st failed attempt with 429", async () => {
// Exhaust the 20-attempt limit
for (let i = 0; i < 20; i++) {
const context = createMockExecutionContext(
{ "x-api-key": `bad-key-${i}` },
undefined,
"10.0.0.2",
);
await expect(guard.canActivate(context)).rejects.toThrow(
UnauthorizedException,
);
}
// 21st attempt should be blocked before reaching validateApiKey
const context = createMockExecutionContext(
{ "x-api-key": "bad-key-21" },
undefined,
"10.0.0.2",
);
await expect(guard.canActivate(context)).rejects.toThrow(
new HttpException(
"Too many failed API key attempts",
HttpStatus.TOO_MANY_REQUESTS,
),
);
// validateApiKey should NOT have been called for the 21st attempt
expect(apiKeyService.validateApiKey).toHaveBeenCalledTimes(20);
});
it("should track different IPs independently", async () => {
// Exhaust limit for IP A
for (let i = 0; i < 20; i++) {
const context = createMockExecutionContext(
{ "x-api-key": `bad-key-${i}` },
undefined,
"10.0.0.3",
);
await expect(guard.canActivate(context)).rejects.toThrow(
UnauthorizedException,
);
}
// IP B should still be allowed
const contextB = createMockExecutionContext(
{ "x-api-key": "bad-key-b" },
undefined,
"10.0.0.4",
);
await expect(guard.canActivate(contextB)).rejects.toThrow(
UnauthorizedException,
);
expect(apiKeyService.validateApiKey).toHaveBeenCalledTimes(21);
});
it("should reset failure counter on successful validation", async () => {
// Record some failures
for (let i = 0; i < 10; i++) {
const context = createMockExecutionContext(
{ "x-api-key": `bad-key-${i}` },
undefined,
"10.0.0.5",
);
await expect(guard.canActivate(context)).rejects.toThrow(
UnauthorizedException,
);
}
// Successful validation should reset the counter
mockApiKeyService.validateApiKey.mockResolvedValueOnce({
groupId: "group-reset",
keyPrefix: "validkey",
});
const mockRequest = {
headers: { "x-api-key": "valid-key" },
user: undefined,
ip: "10.0.0.5",
};
const successContext = {
switchToHttp: () => ({
getRequest: () => mockRequest,
}),
getHandler: () => ({}),
getClass: () => ({}),
} as unknown as ExecutionContext;
const result = await guard.canActivate(successContext);
expect(result).toBe(true);
// After reset, should be able to fail 20 more times
mockApiKeyService.validateApiKey.mockResolvedValue(null);
for (let i = 0; i < 20; i++) {
const context = createMockExecutionContext(
{ "x-api-key": `bad-key-again-${i}` },
undefined,
"10.0.0.5",
);
await expect(guard.canActivate(context)).rejects.toThrow(
UnauthorizedException,
);
}
// 21st after reset should be blocked
const blockedContext = createMockExecutionContext(
{ "x-api-key": "bad-key-blocked" },
undefined,
"10.0.0.5",
);
await expect(guard.canActivate(blockedContext)).rejects.toThrow(
HttpException,
);
});
it("should not affect non-API-key-auth routes", async () => {
(reflector.getAllAndOverride as jest.Mock).mockReturnValue(undefined);
const context = createMockExecutionContext(
{ "x-api-key": "some-key" },
undefined,
"10.0.0.6",
);
const result = await guard.canActivate(context);
expect(result).toBe(true);
expect(apiKeyService.validateApiKey).not.toHaveBeenCalled();
});
});
});