-
Notifications
You must be signed in to change notification settings - Fork 144
Expand file tree
/
Copy pathtimeout-fix.test.ts
More file actions
234 lines (202 loc) · 8.45 KB
/
Copy pathtimeout-fix.test.ts
File metadata and controls
234 lines (202 loc) · 8.45 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
/**
* Tests for auth timeout bug fixes:
*
* Bug 1 (detect-region.ts): Region probe only sent Bearer auth — keys that
* only work with x-api-key would fail all probes, fall back to 'global',
* and every subsequent request would time out or 401.
*
* Bug 2 (refresh.ts): Token refresh had no timeout — a slow/unreachable auth
* server caused the CLI to hang indefinitely.
*
* Bug 3 (handler.ts): Timeout errors showed a generic "try --timeout" hint
* with no guidance about wrong-region or auth issues.
*/
import { describe, it, expect, afterEach } from 'bun:test';
import { createMockServer, jsonResponse, type MockServer } from '../helpers/mock-server';
import { CLIError } from '../../src/errors/base';
import { ExitCode } from '../../src/errors/codes';
// ---------------------------------------------------------------------------
// Bug 1 — detect-region probes both Bearer and x-api-key auth styles
// ---------------------------------------------------------------------------
describe('detect-region: probeRegion auth style fallback', () => {
let server: MockServer;
afterEach(() => server?.close());
it('succeeds when endpoint only accepts Bearer token', async () => {
server = createMockServer({
routes: {
'/v1/token_plan/remains': (req) => {
if (req.headers.get('Authorization') === 'Bearer bearer-only-key') {
return jsonResponse({ base_resp: { status_code: 0 } });
}
return jsonResponse({ error: 'unauthorized' }, 401);
},
},
});
// Patch REGIONS to point at our mock server
const { REGIONS } = await import('../../src/config/schema');
const origGlobal = REGIONS.global;
(REGIONS as Record<string, string>).global = server.url;
try {
const { detectRegion } = await import('../../src/config/detect-region');
const region = await detectRegion('bearer-only-key');
expect(region).toBe('global');
} finally {
(REGIONS as Record<string, string>).global = origGlobal;
}
});
it('succeeds when endpoint only accepts x-api-key header', async () => {
server = createMockServer({
routes: {
'/v1/token_plan/remains': (req) => {
if (req.headers.get('x-api-key') === 'xapikey-only-key') {
return jsonResponse({ base_resp: { status_code: 0 } });
}
return jsonResponse({ error: 'unauthorized' }, 401);
},
},
});
const { REGIONS } = await import('../../src/config/schema');
const origGlobal = REGIONS.global;
(REGIONS as Record<string, string>).global = server.url;
try {
const { detectRegion } = await import('../../src/config/detect-region');
const region = await detectRegion('xapikey-only-key');
expect(region).toBe('global');
} finally {
(REGIONS as Record<string, string>).global = origGlobal;
}
});
it('falls back to global when key is invalid for all auth styles and regions', async () => {
server = createMockServer({
routes: {
'/v1/token_plan/remains': () =>
jsonResponse({ error: 'unauthorized' }, 401),
},
});
const { REGIONS } = await import('../../src/config/schema');
const origGlobal = REGIONS.global;
const origCn = REGIONS.cn;
(REGIONS as Record<string, string>).global = server.url;
(REGIONS as Record<string, string>).cn = server.url;
try {
const { detectRegion } = await import('../../src/config/detect-region');
const region = await detectRegion('bad-key');
expect(region).toBe('global'); // graceful fallback
} finally {
(REGIONS as Record<string, string>).global = origGlobal;
(REGIONS as Record<string, string>).cn = origCn;
}
});
});
// ---------------------------------------------------------------------------
// Bug 2 — token refresh has a 10-second timeout and clear error messages
// ---------------------------------------------------------------------------
describe('refreshAccessToken: timeout and error handling', () => {
let server: MockServer;
afterEach(() => server?.close());
it('throws a CLIError with AUTH exit code when refresh endpoint returns non-ok', async () => {
server = createMockServer({
routes: {
'/v1/oauth/token': () => jsonResponse({ error: 'invalid_grant' }, 400),
},
});
// Temporarily redirect TOKEN_URL to our mock
const mod = await import('../../src/auth/refresh');
// We test the real function against a mock server via a wrapper
// that overrides the fetch to hit our local server instead.
const origFetch = globalThis.fetch;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input.toString();
if (url.includes('oauth/token')) {
return origFetch(`${server.url}/v1/oauth/token`, init);
}
return origFetch(input, init);
};
try {
await expect(mod.refreshAccessToken('expired-refresh-token')).rejects.toMatchObject({
exitCode: ExitCode.AUTH,
});
} finally {
globalThis.fetch = origFetch;
}
});
it('returns a fresh token when refresh succeeds', async () => {
server = createMockServer({
routes: {
'/v1/oauth/token': () =>
jsonResponse({
access_token: 'new-access-token',
refresh_token: 'new-refresh-token',
expires_in: 3600,
token_type: 'Bearer',
}),
},
});
const mod = await import('../../src/auth/refresh');
const origFetch = globalThis.fetch;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(globalThis as any).fetch = async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input.toString();
if (url.includes('oauth/token')) {
return origFetch(`${server.url}/v1/oauth/token`, init);
}
return origFetch(input, init);
};
try {
const tokens = await mod.refreshAccessToken('valid-refresh-token');
expect(tokens.access_token).toBe('new-access-token');
expect(tokens.expires_in).toBe(3600);
} finally {
globalThis.fetch = origFetch;
}
});
it('ensureFreshToken returns cached token when not near expiry', async () => {
const mod = await import('../../src/auth/refresh');
const token = await mod.ensureFreshToken({
access_token: 'still-valid',
refresh_token: 'refresh',
expires_at: new Date(Date.now() + 60 * 60 * 1000).toISOString(), // 1h from now
token_type: 'Bearer',
});
expect(token).toBe('still-valid');
});
});
// ---------------------------------------------------------------------------
// Bug 3 — timeout error message includes auth / region diagnostic hints
// ---------------------------------------------------------------------------
describe('handleError: timeout message includes region/auth hint', () => {
it('AbortError message contains region override hint', async () => {
const { handleError } = await import('../../src/errors/handler');
const abortErr = new DOMException('The operation was aborted.', 'AbortError');
let captured = '';
const origWrite = process.stderr.write.bind(process.stderr);
const origExit = process.exit;
(process.stderr as NodeJS.WriteStream).write = (chunk: unknown) => {
captured += String(chunk);
return true;
};
(process as unknown as Record<string, unknown>).exit = () => { throw new Error('exit'); };
try {
handleError(abortErr);
} catch {
// mocked process.exit throws — expected
} finally {
(process.stderr as NodeJS.WriteStream).write = origWrite;
(process as unknown as Record<string, unknown>).exit = origExit;
}
expect(captured).toContain('mmx auth status');
expect(captured).toContain('region');
});
it('CLIError with TIMEOUT exit code shows correct hint', () => {
const err = new CLIError('Request timed out.', ExitCode.TIMEOUT,
'Try increasing --timeout (e.g. --timeout 60).\n' +
'If this happens on every request with a valid API key, you may be hitting the wrong region.\n' +
'Run: mmx auth status — to check your credentials and region.\n' +
'Run: mmx config set region global (or cn) — to override the region.',
);
expect(err.exitCode).toBe(ExitCode.TIMEOUT);
expect(err.hint).toContain('mmx auth status');
expect(err.hint).toContain('mmx config set region');
});
});