Repository navigation
Expand file tree
/
Copy pathcommand-handler.test.ts
More file actions
529 lines (421 loc) · 13.9 KB
/
Copy pathcommand-handler.test.ts
File metadata and controls
529 lines (421 loc) · 13.9 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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
import { describe, it, expect, vi, beforeEach } from "vitest";
import { Writable } from "node:stream";
import type { Logger } from "./logger.js";
vi.mock("fs", async () => {
const actual = await vi.importActual<typeof import("fs")>("fs");
return {
...actual,
default: {
...actual,
existsSync: vi.fn(() => true),
mkdirSync: vi.fn(),
},
};
});
let execCallback: Function;
let execChild: any;
vi.mock("node:child_process", () => ({
exec: vi.fn((_cmd: string, _opts: any, cb: Function) => {
execCallback = cb;
execChild = {
on: vi.fn(),
stdout: { on: vi.fn() },
stderr: { on: vi.fn() },
};
return execChild;
}),
}));
import fs from "fs";
import { exec } from "node:child_process";
import CommandHandler from "./command-handler.js";
import type { Command } from "./types.js";
const mockLogger: Logger = {
log: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
};
function createHandler(
command: Command,
abortController = new AbortController(),
onStdout?: (stdout: string) => void,
onStderr?: (stderr: string) => void,
secrets: string[] = [],
) {
return new CommandHandler({
command,
secrets,
logger: mockLogger,
abortController,
onStdout,
onStderr,
});
}
describe("CommandHandler", () => {
beforeEach(() => {
vi.clearAllMocks();
});
describe("directory creation", () => {
it("creates cwd directory when it does not exist", async () => {
vi.mocked(fs.existsSync).mockReturnValueOnce(false);
const handler = createHandler({ command: "echo", cwd: "/tmp/test-dir" });
const promise = handler.execute();
execCallback(null, "ok", "");
const closeHandler = execChild.on.mock.calls.find(
(c: unknown[]) => c[0] === "close",
)[1];
closeHandler(0);
await promise;
expect(fs.mkdirSync).toHaveBeenCalledWith("/tmp/test-dir", {
recursive: true,
});
});
it("does not create cwd directory when it already exists", async () => {
vi.mocked(fs.existsSync).mockReturnValueOnce(true);
const handler = createHandler({ command: "echo", cwd: "/tmp/existing" });
const promise = handler.execute();
execCallback(null, "", "");
const closeHandler = execChild.on.mock.calls.find(
(c: unknown[]) => c[0] === "close",
)[1];
closeHandler(0);
await promise;
expect(fs.mkdirSync).not.toHaveBeenCalled();
});
it("skips directory creation when cwd is not specified", async () => {
const handler = createHandler({ command: "echo" });
const promise = handler.execute();
execCallback(null, "", "");
const closeHandler = execChild.on.mock.calls.find(
(c: unknown[]) => c[0] === "close",
)[1];
closeHandler(0);
await promise;
expect(fs.existsSync).not.toHaveBeenCalled();
expect(fs.mkdirSync).not.toHaveBeenCalled();
});
});
describe("command execution", () => {
it("calls exec with the right command and cwd", () => {
const handler = createHandler({
command: "ls",
cwd: "/work",
});
handler.execute();
expect(exec).toHaveBeenCalledWith(
"ls",
expect.objectContaining({
cwd: "/work",
}),
expect.any(Function),
);
});
it("uses process.cwd() when cwd is not specified", () => {
const handler = createHandler({ command: "pwd" });
handler.execute();
expect(exec).toHaveBeenCalledWith(
"pwd",
expect.objectContaining({ cwd: process.cwd() }),
expect.any(Function),
);
});
it("merges command env on top of process.env", () => {
const handler = createHandler({
command: "echo",
cwd: "/work",
env: { MY_VAR: "hello", OTHER: "world" },
});
handler.execute();
expect(exec).toHaveBeenCalledWith(
"echo",
expect.objectContaining({
env: { ...process.env, MY_VAR: "hello", OTHER: "world" },
}),
expect.any(Function),
);
});
it("uses only process.env when command env is undefined", () => {
const handler = createHandler({ command: "echo", cwd: "/work" });
handler.execute();
expect(exec).toHaveBeenCalledWith(
"echo",
expect.objectContaining({
env: { ...process.env },
}),
expect.any(Function),
);
});
it("passes abort signal to exec", () => {
const ac = new AbortController();
const handler = createHandler({ command: "sleep" }, ac);
handler.execute();
expect(exec).toHaveBeenCalledWith(
"sleep",
expect.objectContaining({ signal: ac.signal }),
expect.any(Function),
);
});
});
describe("exit handling", () => {
it("resolves with exitCode 0 on successful close", async () => {
const handler = createHandler({ command: "true" });
const promise = handler.execute();
execCallback(null, "output", "");
const closeHandler = execChild.on.mock.calls.find(
(c: unknown[]) => c[0] === "close",
)[1];
closeHandler(0);
const result = await promise;
expect(result).toEqual({ exitCode: 0, stdout: "output" });
});
it("resolves with exitCode 1 on close with code 1", async () => {
const handler = createHandler({ command: "false" });
const promise = handler.execute();
execCallback(null, "", "");
const closeHandler = execChild.on.mock.calls.find(
(c: unknown[]) => c[0] === "close",
)[1];
closeHandler(1);
const result = await promise;
expect(result).toEqual({ exitCode: 1, stdout: undefined });
});
it("resolves with exitCode 1 and error when callback reports code 1", async () => {
const handler = createHandler({ command: "failing" });
const promise = handler.execute();
const err = Object.assign(new Error("exit 1"), { code: 1 });
execCallback(err, "", "some error");
const result = await promise;
expect(result.exitCode).toBe(1);
expect(result.error).toBeDefined();
});
it("resolves with non-0/1 exit codes from close event", async () => {
const handler = createHandler({ command: "segfault" });
const promise = handler.execute();
execCallback(null, "", "");
const closeHandler = execChild.on.mock.calls.find(
(c: unknown[]) => c[0] === "close",
)[1];
closeHandler(139);
const result = await promise;
expect(result).toEqual({ exitCode: 139, stdout: undefined });
});
it("resolves when callback reports a non-1 error code", async () => {
const handler = createHandler({ command: "crash" });
const promise = handler.execute();
const err = Object.assign(new Error("killed"), { code: 137 });
execCallback(err, "", "");
const result = await promise;
expect(result.exitCode).toBe(137);
expect(result.error).toBeDefined();
});
});
describe("stream output", () => {
it("writes stdout to the stdout stream", async () => {
const onStdout = vi.fn();
const handler = createHandler(
{ command: "echo" },
new AbortController(),
onStdout,
);
const promise = handler.execute();
const stdoutDataHandler = execChild.stdout.on.mock.calls.find(
(c: unknown[]) => c[0] === "data",
)[1];
stdoutDataHandler("hello world");
execCallback(null, "", "");
const closeHandler = execChild.on.mock.calls.find(
(c: unknown[]) => c[0] === "close",
)[1];
closeHandler(0);
await promise;
expect(onStdout).toHaveBeenCalledWith("hello world");
});
it("writes stderr to the stderr stream", async () => {
const onStderr = vi.fn();
const handler = createHandler(
{ command: "warn" },
new AbortController(),
undefined,
onStderr,
);
const promise = handler.execute();
const stderrDataHandler = execChild.stderr.on.mock.calls.find(
(c: unknown[]) => c[0] === "data",
)[1];
stderrDataHandler("warning message");
execCallback(null, "", "");
const closeHandler = execChild.on.mock.calls.find(
(c: unknown[]) => c[0] === "close",
)[1];
closeHandler(0);
await promise;
expect(onStderr).toHaveBeenCalledWith("warning message");
});
it("redacts secrets from stdout", async () => {
const onStdout = vi.fn();
const handler = createHandler(
{ command: "echo" },
new AbortController(),
onStdout,
undefined,
["s3cret"],
);
const promise = handler.execute();
const stdoutDataHandler = execChild.stdout.on.mock.calls.find(
(c: unknown[]) => c[0] === "data",
)[1];
stdoutDataHandler("token is s3cret ok");
execCallback(null, "", "");
const closeHandler = execChild.on.mock.calls.find(
(c: unknown[]) => c[0] === "close",
)[1];
closeHandler(0);
await promise;
expect(onStdout).toHaveBeenCalledWith("token is [REDACTED] ok");
});
it("redacts secrets from stderr", async () => {
const onStderr = vi.fn();
const handler = createHandler(
{ command: "warn" },
new AbortController(),
undefined,
onStderr,
["hunter2"],
);
const promise = handler.execute();
const stderrDataHandler = execChild.stderr.on.mock.calls.find(
(c: unknown[]) => c[0] === "data",
)[1];
stderrDataHandler("error: hunter2 leaked");
execCallback(null, "", "");
const closeHandler = execChild.on.mock.calls.find(
(c: unknown[]) => c[0] === "close",
)[1];
closeHandler(0);
await promise;
expect(onStderr).toHaveBeenCalledWith("error: [REDACTED] leaked");
});
it("redacts multiple secrets from output", async () => {
const onStdout = vi.fn();
const handler = createHandler(
{ command: "echo" },
new AbortController(),
onStdout,
undefined,
["aaa", "bbb"],
);
const promise = handler.execute();
const stdoutDataHandler = execChild.stdout.on.mock.calls.find(
(c: unknown[]) => c[0] === "data",
)[1];
stdoutDataHandler("aaa and bbb");
execCallback(null, "", "");
const closeHandler = execChild.on.mock.calls.find(
(c: unknown[]) => c[0] === "close",
)[1];
closeHandler(0);
await promise;
expect(onStdout).toHaveBeenCalledWith("[REDACTED] and [REDACTED]");
});
it("passes redacted data to onStdout callback", async () => {
const onStdout = vi.fn();
const handler = new CommandHandler({
command: { command: "echo" },
secrets: ["xyz"],
logger: mockLogger,
abortController: new AbortController(),
onStdout: onStdout,
});
const promise = handler.execute();
const stdoutDataHandler = execChild.stdout.on.mock.calls.find(
(c: unknown[]) => c[0] === "data",
)[1];
stdoutDataHandler("value=xyz");
execCallback(null, "", "");
const closeHandler = execChild.on.mock.calls.find(
(c: unknown[]) => c[0] === "close",
)[1];
closeHandler(0);
await promise;
expect(onStdout).toHaveBeenCalledWith("value=[REDACTED]");
});
it("does not redact when no secrets provided", async () => {
const onStdout = vi.fn();
const handler = createHandler(
{ command: "echo" },
new AbortController(),
onStdout,
);
const promise = handler.execute();
const stdoutDataHandler = execChild.stdout.on.mock.calls.find(
(c: unknown[]) => c[0] === "data",
)[1];
stdoutDataHandler("nothing secret here");
execCallback(null, "", "");
const closeHandler = execChild.on.mock.calls.find(
(c: unknown[]) => c[0] === "close",
)[1];
closeHandler(0);
await promise;
expect(onStdout).toHaveBeenCalledWith("nothing secret here");
});
it("does not write empty stdout", async () => {
const onStdout = vi.fn();
const handler = createHandler(
{ command: "silent" },
new AbortController(),
onStdout,
);
const promise = handler.execute();
execCallback(null, "", "");
const closeHandler = execChild.on.mock.calls.find(
(c: unknown[]) => c[0] === "close",
)[1];
closeHandler(0);
await promise;
expect(onStdout).not.toHaveBeenCalled();
});
});
describe("stdout capture", () => {
it("includes stdout in the result on success", async () => {
const handler = createHandler({ command: "echo hello" });
const promise = handler.execute();
execCallback(null, "hello\n", "");
const closeHandler = execChild.on.mock.calls.find(
(c: unknown[]) => c[0] === "close",
)[1];
closeHandler(0);
const result = await promise;
expect(result.exitCode).toBe(0);
expect(result.stdout).toBe("hello\n");
});
it("returns undefined stdout when command produces no output", async () => {
const handler = createHandler({ command: "true" });
const promise = handler.execute();
execCallback(null, "", "");
const closeHandler = execChild.on.mock.calls.find(
(c: unknown[]) => c[0] === "close",
)[1];
closeHandler(0);
const result = await promise;
expect(result.stdout).toBeUndefined();
});
it("redacts secrets from captured stdout", async () => {
const handler = createHandler(
{ command: "echo" },
new AbortController(),
undefined,
undefined,
["my-secret"],
);
const promise = handler.execute();
execCallback(null, "token=my-secret here", "");
const closeHandler = execChild.on.mock.calls.find(
(c: unknown[]) => c[0] === "close",
)[1];
closeHandler(0);
const result = await promise;
expect(result.stdout).toBe("token=[REDACTED] here");
});
});
});