-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathlogin.test.ts
More file actions
411 lines (348 loc) · 13.1 KB
/
login.test.ts
File metadata and controls
411 lines (348 loc) · 13.1 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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
import {
existsSync,
mkdirSync,
readFileSync,
rmSync,
writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
afterEach,
beforeEach,
describe,
expect,
it,
type MockInstance,
vi,
} from 'vitest';
import {
captureTestEnv,
expectExit1,
mockExitThrow,
setNonInteractive,
setupOutputSpies,
} from '../../helpers';
// Mock the Resend SDK – default: valid key; override via mockDomainListResult
let mockDomainListResult: { data: unknown; error: unknown } = {
data: { data: [] },
error: null,
};
vi.mock('resend', () => ({
Resend: class MockResend {
constructor(public key: string) {}
domains = {
list: vi.fn(async () => mockDomainListResult),
};
},
}));
describe('login command', () => {
const restoreEnv = captureTestEnv();
let errorSpy: MockInstance | undefined;
let exitSpy: MockInstance | undefined;
let tmpDir: string;
beforeEach(() => {
mockDomainListResult = { data: { data: [] }, error: null };
tmpDir = join(
tmpdir(),
`resend-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
);
mkdirSync(tmpDir, { recursive: true });
process.env.XDG_CONFIG_HOME = tmpDir;
// Force file backend so tests don't interact with real OS keychain
process.env.RESEND_CREDENTIAL_STORE = 'file';
});
afterEach(async () => {
restoreEnv();
errorSpy?.mockRestore();
errorSpy = undefined;
exitSpy?.mockRestore();
exitSpy = undefined;
try {
const { loginCommand } = await import('../../../src/commands/auth/login');
(loginCommand as { parent?: unknown }).parent = null;
} catch {
// ignore if module not loaded
}
rmSync(tmpDir, { recursive: true, force: true });
});
it('rejects key that fails API validation', async () => {
mockDomainListResult = {
data: null,
error: {
statusCode: 400,
message: 'API key is invalid',
name: 'validation_error',
},
};
setNonInteractive();
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
exitSpy = mockExitThrow();
const { loginCommand } = await import('../../../src/commands/auth/login');
await expectExit1(() =>
loginCommand.parseAsync(['--key', 're_fake_invalid_key'], {
from: 'user',
}),
);
const output = errorSpy?.mock.calls[0][0] as string;
expect(output).toContain('validation_failed');
// Credentials file must not be created for an invalid key
const configPath = join(tmpDir, 'resend', 'credentials.json');
expect(existsSync(configPath)).toBe(false);
});
it('rejects key not starting with re_', async () => {
setNonInteractive();
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
exitSpy = mockExitThrow();
const { loginCommand } = await import('../../../src/commands/auth/login');
await expectExit1(() =>
loginCommand.parseAsync(['--key', 'bad_key'], { from: 'user' }),
);
const output = errorSpy?.mock.calls.flat().join(' ') ?? '';
expect(output).toContain('invalid_key_format');
});
it('rejects empty or whitespace-only key with missing_key in non-interactive', async () => {
setNonInteractive();
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
exitSpy = mockExitThrow();
const { loginCommand } = await import('../../../src/commands/auth/login');
await expectExit1(() =>
loginCommand.parseAsync(['--key', ' '], { from: 'user' }),
);
const output = errorSpy?.mock.calls.flat().join(' ') ?? '';
expect(output).toContain('missing_key');
});
it('trims API key before storing', async () => {
setNonInteractive();
const { loginCommand } = await import('../../../src/commands/auth/login');
await loginCommand.parseAsync(['--key', ' re_trimmed_key_456 '], {
from: 'user',
});
const configPath = join(tmpDir, 'resend', 'credentials.json');
const data = JSON.parse(readFileSync(configPath, 'utf-8'));
expect(data.profiles.default.api_key).toBe('re_trimmed_key_456');
});
it('stores valid key to credentials.json and sets active_profile', async () => {
setupOutputSpies();
const { loginCommand } = await import('../../../src/commands/auth/login');
await loginCommand.parseAsync(['--key', 're_valid_test_key_123'], {
from: 'user',
});
const configPath = join(tmpDir, 'resend', 'credentials.json');
const data = JSON.parse(readFileSync(configPath, 'utf-8'));
expect(data.profiles.default.api_key).toBe('re_valid_test_key_123');
expect(data.active_profile).toBe('default');
});
it('requires --key in non-interactive mode', async () => {
setupOutputSpies();
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
exitSpy = mockExitThrow();
const { loginCommand } = await import('../../../src/commands/auth/login');
await expectExit1(() => loginCommand.parseAsync([], { from: 'user' }));
expect(errorSpy).toBeDefined();
const output = errorSpy?.mock.calls[0][0] as string;
expect(output).toContain('missing_key');
});
it('errors with missing_key when --json is set but --key is omitted even in TTY', async () => {
Object.defineProperty(process.stdin, 'isTTY', {
value: true,
writable: true,
});
Object.defineProperty(process.stdout, 'isTTY', {
value: true,
writable: true,
});
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
exitSpy = mockExitThrow();
const { Command } = await import('@commander-js/extra-typings');
const { loginCommand } = await import('../../../src/commands/auth/login');
const program = new Command()
.option('--profile <name>')
.option('--team <name>')
.option('--json')
.option('--api-key <key>')
.option('-q, --quiet')
.addCommand(loginCommand);
await expectExit1(() =>
program.parseAsync(['login', '--json'], { from: 'user' }),
);
const raw = errorSpy?.mock.calls.map((c) => c[0]).join(' ');
expect(raw).toContain('missing_key');
loginCommand.parent = null;
});
it('non-interactive login stores as default when profiles exist', async () => {
// Pre-populate credentials with an existing profile
const configDir = join(tmpDir, 'resend');
mkdirSync(configDir, { recursive: true });
writeFileSync(
join(configDir, 'credentials.json'),
JSON.stringify({
active_profile: 'production',
profiles: { production: { api_key: 're_old_key_1234' } },
}),
);
setupOutputSpies();
const { loginCommand } = await import('../../../src/commands/auth/login');
await loginCommand.parseAsync(['--key', 're_new_key_5678'], {
from: 'user',
});
const configPath = join(tmpDir, 'resend', 'credentials.json');
const data = JSON.parse(readFileSync(configPath, 'utf-8'));
expect(data.profiles.default.api_key).toBe('re_new_key_5678');
expect(data.profiles.production.api_key).toBe('re_old_key_1234');
// Original behavior: no --profile means we store to default but do not switch active
expect(data.active_profile).toBe('production');
});
it('auto-switches to profile specified via --profile flag', async () => {
setupOutputSpies();
const { Command } = await import('@commander-js/extra-typings');
const { loginCommand } = await import('../../../src/commands/auth/login');
const program = new Command()
.option('--profile <name>')
.option('--team <name>')
.option('--json')
.option('--api-key <key>')
.option('-q, --quiet')
.addCommand(loginCommand);
// First store a default key
const configDir = join(tmpDir, 'resend');
mkdirSync(configDir, { recursive: true });
writeFileSync(
join(configDir, 'credentials.json'),
JSON.stringify({
active_profile: 'default',
profiles: { default: { api_key: 're_old_key_1234' } },
}),
);
await program.parseAsync(
['login', '--key', 're_staging_key_123', '--profile', 'staging'],
{ from: 'user' },
);
const configPath = join(tmpDir, 'resend', 'credentials.json');
const data = JSON.parse(readFileSync(configPath, 'utf-8'));
expect(data.active_profile).toBe('staging');
expect(data.profiles.staging.api_key).toBe('re_staging_key_123');
});
it('rejects invalid profile name with invalid_profile_name', async () => {
setNonInteractive();
errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
exitSpy = mockExitThrow();
const { Command } = await import('@commander-js/extra-typings');
const { loginCommand } = await import('../../../src/commands/auth/login');
const program = new Command()
.option('--profile <name>')
.option('--json')
.option('--api-key <key>')
.option('-q, --quiet')
.addCommand(loginCommand);
await expectExit1(() =>
program.parseAsync(
['login', '--key', 're_valid_123', '--profile', 'invalid name!'],
{ from: 'user' },
),
);
const output = errorSpy?.mock.calls.flat().join(' ') ?? '';
expect(output).toContain('invalid_profile_name');
});
it('trims --profile before storing', async () => {
setupOutputSpies();
const { Command } = await import('@commander-js/extra-typings');
const { loginCommand } = await import('../../../src/commands/auth/login');
const program = new Command()
.option('--profile <name>')
.option('--team <name>')
.option('--json')
.option('--api-key <key>')
.option('-q, --quiet')
.addCommand(loginCommand);
await program.parseAsync(
['login', '--key', 're_trim_profile_key', '--profile', ' myprofile '],
{ from: 'user' },
);
const configPath = join(tmpDir, 'resend', 'credentials.json');
const data = JSON.parse(readFileSync(configPath, 'utf-8'));
expect(data.profiles.myprofile).toBeDefined();
expect(data.profiles.myprofile.api_key).toBe('re_trim_profile_key');
expect(data.active_profile).toBe('myprofile');
});
it('--json output includes success, config_path, and profile', async () => {
setupOutputSpies();
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
const { Command } = await import('@commander-js/extra-typings');
const { loginCommand } = await import('../../../src/commands/auth/login');
const program = new Command()
.option('--profile <name>')
.option('--json')
.option('--api-key <key>')
.option('-q, --quiet')
.addCommand(loginCommand);
await program.parseAsync(
['login', '--key', 're_json_output_key', '--profile', 'prod', '--json'],
{ from: 'user' },
);
expect(logSpy).toHaveBeenCalled();
const out = logSpy.mock.calls.flat().join('\n');
const parsed = JSON.parse(out);
expect(parsed.success).toBe(true);
expect(parsed.config_path).toBeDefined();
expect(parsed.profile).toBe('prod');
});
it('accepts sending-only key and stores permission', async () => {
mockDomainListResult = {
data: null,
error: {
statusCode: 401,
message: 'This API key is restricted to only send emails',
name: 'restricted_api_key',
},
};
setupOutputSpies();
const { loginCommand } = await import('../../../src/commands/auth/login');
await loginCommand.parseAsync(['--key', 're_sending_only_key_123'], {
from: 'user',
});
const configPath = join(tmpDir, 'resend', 'credentials.json');
const data = JSON.parse(readFileSync(configPath, 'utf-8'));
expect(data.profiles.default.api_key).toBe('re_sending_only_key_123');
expect(data.profiles.default.permission).toBe('sending_access');
});
it('stores full_access permission for valid full access key', async () => {
setupOutputSpies();
const { loginCommand } = await import('../../../src/commands/auth/login');
await loginCommand.parseAsync(['--key', 're_full_access_key_123'], {
from: 'user',
});
const configPath = join(tmpDir, 'resend', 'credentials.json');
const data = JSON.parse(readFileSync(configPath, 'utf-8'));
expect(data.profiles.default.api_key).toBe('re_full_access_key_123');
expect(data.profiles.default.permission).toBe('full_access');
});
it('--json output includes permission for sending-only key', async () => {
mockDomainListResult = {
data: null,
error: {
statusCode: 401,
message: 'This API key is restricted to only send emails',
name: 'restricted_api_key',
},
};
setupOutputSpies();
const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
const { Command } = await import('@commander-js/extra-typings');
const { loginCommand } = await import('../../../src/commands/auth/login');
const program = new Command()
.option('--profile <name>')
.option('--json')
.option('--api-key <key>')
.option('-q, --quiet')
.addCommand(loginCommand);
await program.parseAsync(
['login', '--key', 're_sending_key', '--profile', 'ci', '--json'],
{ from: 'user' },
);
const out = logSpy.mock.calls.flat().join('\n');
const parsed = JSON.parse(out);
expect(parsed.success).toBe(true);
expect(parsed.permission).toBe('sending_access');
});
});