-
Notifications
You must be signed in to change notification settings - Fork 662
Expand file tree
/
Copy pathroute.test.ts
More file actions
261 lines (214 loc) · 9.28 KB
/
Copy pathroute.test.ts
File metadata and controls
261 lines (214 loc) · 9.28 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
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { GET } from './route';
import { RateLimiter } from '@/lib/rate-limit';
// Replace the real GitHub API with a fake function
vi.mock('../../../lib/github', async () => {
const actual = await vi.importActual<typeof import('../../../lib/github')>('../../../lib/github');
return {
...actual,
getFullDashboardData: vi.fn(),
};
});
// Run after() callbacks synchronously in tests (outside a request scope it is otherwise a no-op).
vi.mock('next/server', async (importOriginal) => {
const actual = await importOriginal<typeof import('next/server')>();
return {
...actual,
after: (fn: () => unknown) => {
void fn();
},
};
});
import { getFullDashboardData } from '../../../lib/github';
import { quotaMonitor } from '@/services/github/quota-monitor';
import { refreshPolicy } from '@/services/github/refresh-policy';
import { refreshRateLimiter } from '@/services/github/refresh-rate-limiter';
import { backgroundRefresh } from '@/services/github/background-refresh';
function makeRequest(
params: Record<string, string> = {},
headers: Record<string, string> = {}
): Request {
const url = new URL('http://localhost/api/github');
for (const [key, value] of Object.entries(params)) {
url.searchParams.set(key, value);
}
return new Request(url.toString(), {
headers: new Headers(headers),
});
}
beforeEach(() => {
vi.clearAllMocks();
vi.spyOn(RateLimiter.prototype, 'check').mockResolvedValue(true);
vi.mocked(getFullDashboardData).mockResolvedValue({
profile: { lastSyncedAt: new Date().toISOString() },
calendar: {},
lastSyncedAt: new Date().toISOString(),
} as unknown as Awaited<ReturnType<typeof getFullDashboardData>>);
quotaMonitor.reset();
refreshPolicy.reset();
refreshRateLimiter.reset();
backgroundRefresh.reset();
});
describe('Unrestricted Cache Bypass & Abuse Mitigation (Issue #1978)', () => {
// Scenario 1: Normal cached request
it('Scenario 1: serves cached data and checks SWR background refresh', async () => {
// Mock data that is stale (15 minutes ago)
const staleTime = new Date(Date.now() - 15 * 60 * 1000).toISOString();
vi.mocked(getFullDashboardData).mockResolvedValue({
profile: { lastSyncedAt: staleTime },
calendar: {},
} as unknown as Awaited<ReturnType<typeof getFullDashboardData>>);
const triggerSpy = vi.spyOn(backgroundRefresh, 'triggerRefresh');
const response = await GET(makeRequest({ username: 'torvalds' }));
expect(response.status).toBe(200);
expect(getFullDashboardData).toHaveBeenCalledWith(
'torvalds',
expect.objectContaining({ bypassCache: false })
);
expect(triggerSpy).toHaveBeenCalledWith('torvalds');
});
// Scenario 2: Single refresh request allowed
it('Scenario 2: allows a single refresh request when limits are respected', async () => {
const response = await GET(makeRequest({ username: 'torvalds', refresh: 'true' }));
expect(response.status).toBe(200);
expect(getFullDashboardData).toHaveBeenCalledWith(
'torvalds',
expect.objectContaining({ bypassCache: true })
);
expect(response.headers.get('X-Refresh-Status')).toBe('Fresh');
});
// Scenario 3: Repeated refresh within cooldown served from cache
it('Scenario 3: serves cached response for repeated refresh requests within cooldown', async () => {
// First refresh is allowed
await GET(makeRequest({ username: 'torvalds', refresh: 'true' }));
expect(getFullDashboardData).toHaveBeenLastCalledWith(
'torvalds',
expect.objectContaining({ bypassCache: true })
);
// Second refresh within cooldown (5 minutes)
const response = await GET(makeRequest({ username: 'torvalds', refresh: 'true' }));
expect(response.status).toBe(200);
// Cooldown fallback triggers cached read
expect(getFullDashboardData).toHaveBeenLastCalledWith(
'torvalds',
expect.objectContaining({ bypassCache: false })
);
expect(response.headers.get('X-Refresh-Status')).toBe('Cooldown-Served-Cached');
});
// Scenario 4: Refresh rate limit exceeded per client IP
it('Scenario 4: returns 429 when client refresh rate limit is exceeded', async () => {
// Set rate limit to 2 per window for testing
refreshRateLimiter.setLimit(2);
// Refresh 1
await GET(
makeRequest({ username: 'torvalds', refresh: 'true' }, { 'x-real-ip': '203.0.113.5' })
);
// Refresh 2
await GET(
makeRequest({ username: 'octocat', refresh: 'true' }, { 'x-real-ip': '203.0.113.5' })
);
// Refresh 3 (exceeds limit of 2)
const response = await GET(
makeRequest({ username: 'torvalds', refresh: 'true' }, { 'x-real-ip': '203.0.113.5' })
);
expect(response.status).toBe(429);
const body = await response.json();
expect(body.error).toContain('Refresh rate limit exceeded');
});
// Scenario 5: Low GitHub quota blocks refresh
it('Scenario 5: blocks manual refresh when remaining GitHub quota is low (<10%)', async () => {
// Set global remaining quota to 400 out of 5000 (8%)
quotaMonitor.setQuota(5000, 400, Date.now() + 60000);
const response = await GET(makeRequest({ username: 'torvalds', refresh: 'true' }));
expect(response.status).toBe(429);
const body = await response.json();
expect(body.error).toContain('quota is low');
expect(getFullDashboardData).not.toHaveBeenCalled();
});
// Scenario 6: Background refresh execution
it('Scenario 6: asynchronous background refresh completes successfully', async () => {
const loadSpy = vi.spyOn(backgroundRefresh, 'triggerRefresh');
// Mock data that is stale
const staleTime = new Date(Date.now() - 15 * 60 * 1000).toISOString();
vi.mocked(getFullDashboardData).mockResolvedValue({
profile: { lastSyncedAt: staleTime },
calendar: {},
} as unknown as Awaited<ReturnType<typeof getFullDashboardData>>);
await GET(makeRequest({ username: 'torvalds' }));
expect(loadSpy).toHaveBeenCalledWith('torvalds');
});
});
describe('Standard route behavior', () => {
it('returns 400 when username contains invalid characters', async () => {
const response = await GET(makeRequest({ username: '@@@@@' }));
const body = await response.json();
expect(response.status).toBe(400);
expect(body.error).toContain('Invalid parameters');
});
it('returns 400 when username contains only whitespace', async () => {
const response = await GET(makeRequest({ username: ' ' }));
const body = await response.json();
expect(response.status).toBe(400);
expect(body.error).toContain('Invalid parameters');
});
it('returns 400 when username is missing', async () => {
const response = await GET(makeRequest());
const body = await response.json();
expect(response.status).toBe(400);
expect(body.error).toContain('Invalid parameters');
});
it('returns 404 when getFullDashboardData throws User not found', async () => {
vi.mocked(getFullDashboardData).mockRejectedValue(new Error('User not found'));
const response = await GET(makeRequest({ username: 'octocat' }));
const body = await response.json();
expect(response.status).toBe(404);
expect(body.error).toContain('User not found');
});
it('returns 404 when getFullDashboardData throws a wrapped User not found error', async () => {
const underlyingError = new Error('User not found');
const wrappedError = new Error('[GitHub API] Failed to fetch profile for user "octocat"', {
cause: underlyingError,
});
vi.mocked(getFullDashboardData).mockRejectedValue(wrappedError);
const response = await GET(makeRequest({ username: 'octocat' }));
const body = await response.json();
expect(response.status).toBe(404);
expect(body.error).toContain('User not found');
});
it('returns 500 when getFullDashboardData throws a generic internal error', async () => {
vi.mocked(getFullDashboardData).mockRejectedValue(new Error('Database offline'));
const response = await GET(makeRequest({ username: 'octocat' }));
const body = await response.json();
expect(response.status).toBe(500);
expect(body.error).toBe('An unexpected error occurred. Please try again.');
});
it('returns 500 instead of hanging when an error cause chain is circular', async () => {
const firstError = new Error('Circular cause root');
const secondError = new Error('Circular cause child');
Object.defineProperty(firstError, 'cause', {
value: secondError,
configurable: true,
});
Object.defineProperty(secondError, 'cause', {
value: firstError,
configurable: true,
});
vi.mocked(getFullDashboardData).mockRejectedValue(firstError);
const response = await GET(makeRequest({ username: 'octocat' }));
const body = await response.json();
expect(response.status).toBe(500);
expect(body.error).toBe('An unexpected error occurred. Please try again.');
});
it('parses valid org parameter and passes it to getFullDashboardData', async () => {
const response = await GET(makeRequest({ username: 'octocat', org: 'github' }));
expect(response.status).toBe(200);
expect(getFullDashboardData).toHaveBeenCalledWith(
'octocat',
expect.objectContaining({
bypassCache: false,
org: 'github',
signal: expect.any(AbortSignal),
})
);
});
});