-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathcliManager.test.ts
More file actions
852 lines (751 loc) · 25.9 KB
/
cliManager.test.ts
File metadata and controls
852 lines (751 loc) · 25.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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
import globalAxios, { type AxiosInstance } from "axios";
import { type Api } from "coder/site/src/api/api";
import { fs as memfs, vol } from "memfs";
import EventEmitter from "node:events";
import * as fs from "node:fs";
import { type IncomingMessage } from "node:http";
import * as os from "node:os";
import * as path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import * as vscode from "vscode";
import * as cliConfig from "@/cliConfig";
import { CliManager } from "@/core/cliManager";
import * as cliUtils from "@/core/cliUtils";
import { PathResolver } from "@/core/pathResolver";
import * as pgp from "@/pgp";
import {
createMockKeyringStore,
createMockLogger,
createMockStream,
MockConfigurationProvider,
MockProgressReporter,
MockUserInteraction,
} from "../../mocks/testHelpers";
import { expectPathsEqual } from "../../utils/platform";
import type { FeatureSet } from "@/featureSet";
import type { KeyringStore } from "@/keyringStore";
vi.mock("os");
vi.mock("axios");
vi.mock("fs", async () => {
const memfs: { fs: typeof fs } = await vi.importActual("memfs");
return {
...memfs.fs,
default: memfs.fs,
};
});
vi.mock("fs/promises", async () => {
const memfs: { fs: typeof fs } = await vi.importActual("memfs");
return {
...memfs.fs.promises,
default: memfs.fs.promises,
};
});
// Mock lockfile to bypass file locking in tests
vi.mock("proper-lockfile", () => ({
lock: () => Promise.resolve(() => Promise.resolve()),
check: () => Promise.resolve(false),
}));
vi.mock("@/cliConfig", async () => {
const actual =
await vi.importActual<typeof import("@/cliConfig")>("@/cliConfig");
return {
...actual,
shouldUseKeyring: vi.fn(),
isKeyringEnabled: vi.fn(),
};
});
vi.mock("@/pgp");
vi.mock("@/vscodeProposed", () => ({
vscodeProposed: vscode,
}));
vi.mock("@/core/cliUtils", async () => {
const actual =
await vi.importActual<typeof import("@/core/cliUtils")>("@/core/cliUtils");
return {
...actual,
// No need to test script execution here
version: vi.fn(),
};
});
describe("CliManager", () => {
let manager: CliManager;
let mockConfig: MockConfigurationProvider;
let mockProgress: MockProgressReporter;
let mockUI: MockUserInteraction;
let mockApi: Api;
let mockAxios: AxiosInstance;
let mockKeyring: KeyringStore;
const TEST_VERSION = "1.2.3";
const TEST_URL = "https://test.coder.com";
const BASE_PATH = "/path/base";
const BINARY_DIR = `${BASE_PATH}/test/bin`;
const PLATFORM = "linux";
const ARCH = "amd64";
const BINARY_NAME = `coder-${PLATFORM}-${ARCH}`;
const BINARY_PATH = `${BINARY_DIR}/${BINARY_NAME}`;
const MOCK_FEATURE_SET: FeatureSet = {
vscodessh: true,
proxyLogDirectory: true,
wildcardSSH: true,
buildReason: true,
keyringAuth: true,
};
beforeEach(() => {
vi.resetAllMocks();
vol.reset();
// Core setup
mockApi = createMockApi(TEST_VERSION, TEST_URL);
mockAxios = mockApi.getAxiosInstance();
vi.mocked(globalAxios.create).mockReturnValue(mockAxios);
mockConfig = new MockConfigurationProvider();
mockProgress = new MockProgressReporter();
mockUI = new MockUserInteraction();
mockKeyring = createMockKeyringStore();
manager = new CliManager(
createMockLogger(),
new PathResolver(BASE_PATH, "/code/log"),
mockKeyring,
);
// Mock only what's necessary
vi.mocked(os.platform).mockReturnValue(PLATFORM);
vi.mocked(os.arch).mockReturnValue(ARCH);
vi.mocked(pgp.readPublicKeys).mockResolvedValue([]);
vi.mocked(cliConfig.isKeyringEnabled).mockReturnValue(true);
});
afterEach(async () => {
mockProgress?.setCancellation(false);
vi.clearAllTimers();
// memfs internally schedules some FS operations so we have to wait for them to finish
await new Promise((resolve) => setImmediate(resolve));
vol.reset();
});
describe("Configure CLI", () => {
function configure(token = "test-token") {
return manager.configure(
"dev.coder.com",
"https://coder.example.com",
token,
MOCK_FEATURE_SET,
);
}
it("should write both url and token to correct paths", async () => {
await configure("test-token");
expect(memfs.readFileSync("/path/base/dev.coder.com/url", "utf8")).toBe(
"https://coder.example.com",
);
expect(
memfs.readFileSync("/path/base/dev.coder.com/session", "utf8"),
).toBe("test-token");
});
it("should throw when URL is empty", async () => {
await expect(
manager.configure("dev.coder.com", "", "test-token", MOCK_FEATURE_SET),
).rejects.toThrow("URL is required to configure the CLI");
});
it("should write empty string for token when provided", async () => {
await configure("");
expect(memfs.readFileSync("/path/base/dev.coder.com/url", "utf8")).toBe(
"https://coder.example.com",
);
expect(
memfs.readFileSync("/path/base/dev.coder.com/session", "utf8"),
).toBe("");
});
it("should use base path directly when label is empty", async () => {
await manager.configure(
"",
"https://coder.example.com",
"token",
MOCK_FEATURE_SET,
);
expect(memfs.readFileSync("/path/base/url", "utf8")).toBe(
"https://coder.example.com",
);
expect(memfs.readFileSync("/path/base/session", "utf8")).toBe("token");
});
it("should write to keyring and skip files when featureSet enables keyring", async () => {
vi.mocked(cliConfig.shouldUseKeyring).mockReturnValue(true);
await configure("test-token");
expect(mockKeyring.setToken).toHaveBeenCalledWith(
"https://coder.example.com",
"test-token",
);
expect(memfs.existsSync("/path/base/dev.coder.com/url")).toBe(false);
expect(memfs.existsSync("/path/base/dev.coder.com/session")).toBe(false);
});
it("should throw and show error when keyring write fails", async () => {
vi.mocked(cliConfig.shouldUseKeyring).mockReturnValue(true);
vi.mocked(mockKeyring.setToken).mockImplementation(() => {
throw new Error("keyring unavailable");
});
await expect(configure("test-token")).rejects.toThrow(
"keyring unavailable",
);
expect(vscode.window.showErrorMessage).toHaveBeenCalledWith(
expect.stringContaining("keyring unavailable"),
"Open Settings",
);
expect(memfs.existsSync("/path/base/dev.coder.com/url")).toBe(false);
expect(memfs.existsSync("/path/base/dev.coder.com/session")).toBe(false);
});
});
describe("Clear Credentials", () => {
function seedCredentialFiles() {
memfs.mkdirSync("/path/base/dev.coder.com", { recursive: true });
memfs.writeFileSync("/path/base/dev.coder.com/session", "old-token");
memfs.writeFileSync(
"/path/base/dev.coder.com/url",
"https://example.com",
);
}
interface RemoveCredentialsCase {
scenario: string;
setup: () => void;
}
it.each<RemoveCredentialsCase>([
{ scenario: "normally", setup: () => {} },
{
scenario: "when keyring delete fails",
setup: () =>
vi.mocked(mockKeyring.deleteToken).mockImplementation(() => {
throw new Error("keyring unavailable");
}),
},
{
scenario: "when keyring is disabled",
setup: () =>
vi.mocked(cliConfig.isKeyringEnabled).mockReturnValue(false),
},
])("should remove credential files $scenario", async ({ setup }) => {
seedCredentialFiles();
setup();
await manager.clearCredentials("dev.coder.com");
expect(memfs.existsSync("/path/base/dev.coder.com/session")).toBe(false);
expect(memfs.existsSync("/path/base/dev.coder.com/url")).toBe(false);
});
it("should not throw when credential files don't exist", async () => {
await expect(
manager.clearCredentials("dev.coder.com"),
).resolves.not.toThrow();
expect(mockKeyring.deleteToken).toHaveBeenCalledWith("dev.coder.com");
});
it("should skip keyring delete when keyring is disabled", async () => {
vi.mocked(cliConfig.isKeyringEnabled).mockReturnValue(false);
await manager.clearCredentials("dev.coder.com");
expect(mockKeyring.deleteToken).not.toHaveBeenCalled();
});
});
describe("Binary Version Validation", () => {
it("rejects invalid server versions", async () => {
mockApi.getBuildInfo = vi.fn().mockResolvedValue({ version: "invalid" });
await expect(manager.fetchBinary(mockApi, "test")).rejects.toThrow(
"Got invalid version from deployment",
);
});
it("accepts valid semver versions", async () => {
withExistingBinary(TEST_VERSION);
const result = await manager.fetchBinary(mockApi, "test");
expectPathsEqual(result, BINARY_PATH);
});
});
describe("Existing Binary Handling", () => {
beforeEach(() => {
// Disable signature verification for these tests
mockConfig.set("coder.disableSignatureVerification", true);
});
it("reuses matching binary without downloading", async () => {
withExistingBinary(TEST_VERSION);
const result = await manager.fetchBinary(mockApi, "test");
expectPathsEqual(result, BINARY_PATH);
expect(mockAxios.get).not.toHaveBeenCalled();
// Verify binary still exists
expect(memfs.existsSync(BINARY_PATH)).toBe(true);
});
it("downloads when versions differ", async () => {
withExistingBinary("1.0.0");
withSuccessfulDownload();
const result = await manager.fetchBinary(mockApi, "test");
expectPathsEqual(result, BINARY_PATH);
expect(mockAxios.get).toHaveBeenCalled();
// Verify new binary exists
expect(memfs.existsSync(BINARY_PATH)).toBe(true);
expect(memfs.readFileSync(BINARY_PATH).toString()).toBe(
mockBinaryContent(TEST_VERSION),
);
});
it("keeps mismatched binary when downloads disabled", async () => {
mockConfig.set("coder.enableDownloads", false);
withExistingBinary("1.0.0");
const result = await manager.fetchBinary(mockApi, "test");
expectPathsEqual(result, BINARY_PATH);
expect(mockAxios.get).not.toHaveBeenCalled();
// Should still have the old version
expect(memfs.existsSync(BINARY_PATH)).toBe(true);
expect(memfs.readFileSync(BINARY_PATH).toString()).toBe(
mockBinaryContent("1.0.0"),
);
});
it("downloads fresh binary when corrupted", async () => {
withCorruptedBinary();
withSuccessfulDownload();
const result = await manager.fetchBinary(mockApi, "test");
expectPathsEqual(result, BINARY_PATH);
expect(mockAxios.get).toHaveBeenCalled();
expect(memfs.existsSync(BINARY_PATH)).toBe(true);
expect(memfs.readFileSync(BINARY_PATH).toString()).toBe(
mockBinaryContent(TEST_VERSION),
);
});
it("downloads when no binary exists", async () => {
// Ensure directory doesn't exist initially
expect(memfs.existsSync(BINARY_DIR)).toBe(false);
withSuccessfulDownload();
const result = await manager.fetchBinary(mockApi, "test");
expectPathsEqual(result, BINARY_PATH);
expect(mockAxios.get).toHaveBeenCalled();
// Verify directory was created and binary exists
expect(memfs.existsSync(BINARY_DIR)).toBe(true);
expect(memfs.existsSync(BINARY_PATH)).toBe(true);
expect(memfs.readFileSync(BINARY_PATH).toString()).toBe(
mockBinaryContent(TEST_VERSION),
);
});
it("fails when downloads disabled and no binary", async () => {
mockConfig.set("coder.enableDownloads", false);
await expect(manager.fetchBinary(mockApi, "test")).rejects.toThrow(
"Unable to download CLI because downloads are disabled",
);
expect(memfs.existsSync(BINARY_PATH)).toBe(false);
});
});
describe("Binary Download Behavior", () => {
beforeEach(() => {
mockConfig.set("coder.disableSignatureVerification", true);
});
it("downloads with correct headers", async () => {
withSuccessfulDownload();
await manager.fetchBinary(mockApi, "test");
expect(mockAxios.get).toHaveBeenCalledWith(
`/bin/${BINARY_NAME}`,
expect.objectContaining({
responseType: "stream",
headers: expect.objectContaining({
"Accept-Encoding": "identity",
"If-None-Match": '""',
}),
}),
);
});
it("uses custom binary source", async () => {
mockConfig.set("coder.binarySource", "/custom/path");
withSuccessfulDownload();
await manager.fetchBinary(mockApi, "test");
expect(mockAxios.get).toHaveBeenCalledWith(
"/custom/path",
expect.objectContaining({
responseType: "stream",
decompress: false,
validateStatus: expect.any(Function),
}),
);
});
it("uses ETag for existing binaries", async () => {
withExistingBinary("1.0.0");
withSuccessfulDownload();
await manager.fetchBinary(mockApi, "test");
// Verify ETag was computed from actual file content
expect(mockAxios.get).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({
headers: expect.objectContaining({
"If-None-Match": '"0c95a175da8afefd2b52057908a2e30ba2e959b3"',
}),
}),
);
});
it("cleans up old files before download", async () => {
// Create old temporary files and signature files
vol.mkdirSync(BINARY_DIR, { recursive: true });
memfs.writeFileSync(path.join(BINARY_DIR, "coder.old-xyz"), "old");
memfs.writeFileSync(path.join(BINARY_DIR, "coder.temp-abc"), "temp");
memfs.writeFileSync(path.join(BINARY_DIR, "coder.asc"), "signature");
memfs.writeFileSync(path.join(BINARY_DIR, "keeper.txt"), "keep");
withSuccessfulDownload();
await manager.fetchBinary(mockApi, "test");
// Verify old files were actually removed but other files kept
expect(memfs.existsSync(path.join(BINARY_DIR, "coder.old-xyz"))).toBe(
false,
);
expect(memfs.existsSync(path.join(BINARY_DIR, "coder.temp-abc"))).toBe(
false,
);
expect(memfs.existsSync(path.join(BINARY_DIR, "coder.asc"))).toBe(false);
expect(memfs.existsSync(path.join(BINARY_DIR, "keeper.txt"))).toBe(true);
});
it("moves existing binary to backup file before writing new version", async () => {
withExistingBinary("1.0.0");
withSuccessfulDownload();
await manager.fetchBinary(mockApi, "test");
// Verify the old binary was backed up
const files = readdir(BINARY_DIR);
const backupFile = files.find(
(f) => f.startsWith(BINARY_NAME) && /\.old-[a-z0-9]+$/.exec(f),
);
expect(backupFile).toBeDefined();
});
});
describe("Download HTTP Response Handling", () => {
beforeEach(() => {
mockConfig.set("coder.disableSignatureVerification", true);
});
it("handles 304 Not Modified", async () => {
withExistingBinary("1.0.0");
withHttpResponse(304);
const result = await manager.fetchBinary(mockApi, "test");
expectPathsEqual(result, BINARY_PATH);
// No change
expect(memfs.readFileSync(BINARY_PATH).toString()).toBe(
mockBinaryContent("1.0.0"),
);
});
it("handles 404 platform not supported", async () => {
withHttpResponse(404);
mockUI.setResponse(
"Coder isn't supported for your platform. Please open an issue, we'd love to support it!",
"Open an Issue",
);
await expect(manager.fetchBinary(mockApi, "test")).rejects.toThrow(
"Platform not supported",
);
expect(vscode.env.openExternal).toHaveBeenCalledWith(
expect.objectContaining({
path: expect.stringContaining(
"github.com/coder/vscode-coder/issues/new?",
),
}),
);
});
it("handles server errors", async () => {
withHttpResponse(500);
mockUI.setResponse(
"Failed to download binary. Please open an issue.",
"Open an Issue",
);
await expect(manager.fetchBinary(mockApi, "test")).rejects.toThrow(
"Failed to download binary",
);
expect(vscode.env.openExternal).toHaveBeenCalledWith(
expect.objectContaining({
path: expect.stringContaining(
"github.com/coder/vscode-coder/issues/new?",
),
}),
);
});
});
describe("Download Stream Handling", () => {
beforeEach(() => {
mockConfig.set("coder.disableSignatureVerification", true);
});
it("handles write stream errors", async () => {
withStreamError("write", "disk full");
await expect(manager.fetchBinary(mockApi, "test")).rejects.toThrow(
"Unable to download binary: disk full",
);
expect(memfs.existsSync(BINARY_PATH)).toBe(false);
});
it("handles read stream errors", async () => {
withStreamError("read", "network timeout");
await expect(manager.fetchBinary(mockApi, "test")).rejects.toThrow(
"Unable to download binary: network timeout",
);
expect(memfs.existsSync(BINARY_PATH)).toBe(false);
});
it("handles missing content-length", async () => {
withSuccessfulDownload({ headers: {} });
mockProgress.clearProgressReports();
const result = await manager.fetchBinary(mockApi, "test");
expectPathsEqual(result, BINARY_PATH);
expect(memfs.existsSync(BINARY_PATH)).toBe(true);
// Without any content-length header, increment should be undefined.
const reports = mockProgress.getProgressReports();
expect(reports).not.toHaveLength(0);
for (const report of reports) {
expect(report).toMatchObject({ increment: undefined });
}
});
it.each(["content-length", "x-original-content-length"])(
"reports progress with %s header",
async (header) => {
withSuccessfulDownload({ headers: { [header]: "1024" } });
mockProgress.clearProgressReports();
const result = await manager.fetchBinary(mockApi, "test");
expectPathsEqual(result, BINARY_PATH);
expect(memfs.existsSync(BINARY_PATH)).toBe(true);
const reports = mockProgress.getProgressReports();
expect(reports).not.toHaveLength(0);
for (const report of reports) {
expect(report).toMatchObject({ increment: expect.any(Number) });
}
},
);
});
describe("Download Progress Tracking", () => {
beforeEach(() => {
mockConfig.set("coder.disableSignatureVerification", true);
});
it("shows download progress", async () => {
withSuccessfulDownload();
await manager.fetchBinary(mockApi, "test");
expect(vscode.window.withProgress).toHaveBeenCalledWith(
expect.objectContaining({
title: `Downloading Coder CLI for ${TEST_URL}`,
}),
expect.any(Function),
);
});
it("handles user cancellation", async () => {
mockProgress.setCancellation(true);
withSuccessfulDownload();
await expect(manager.fetchBinary(mockApi, "test")).rejects.toThrow(
"Download aborted",
);
expect(memfs.existsSync(BINARY_PATH)).toBe(false);
});
});
describe("Binary Signature Verification", () => {
it("verifies valid signatures", async () => {
withSuccessfulDownload();
withSignatureResponses([200]);
const result = await manager.fetchBinary(mockApi, "test");
expectPathsEqual(result, BINARY_PATH);
expect(pgp.verifySignature).toHaveBeenCalled();
const sigFile = expectFileInDir(BINARY_DIR, ".asc");
expect(sigFile).toBeDefined();
});
it("tries fallback signature on 404", async () => {
withSuccessfulDownload();
withSignatureResponses([404, 200]);
mockUI.setResponse("Signature not found", "Download signature");
const result = await manager.fetchBinary(mockApi, "test");
expectPathsEqual(result, BINARY_PATH);
expect(mockAxios.get).toHaveBeenCalledTimes(3);
const sigFile = expectFileInDir(BINARY_DIR, ".asc");
expect(sigFile).toBeDefined();
});
it("allows running despite invalid signature", async () => {
withSuccessfulDownload();
withSignatureResponses([200]);
vi.mocked(pgp.verifySignature).mockRejectedValueOnce(
createVerificationError("Invalid signature"),
);
mockUI.setResponse("Signature does not match", "Run anyway");
const result = await manager.fetchBinary(mockApi, "test");
expectPathsEqual(result, BINARY_PATH);
expect(memfs.existsSync(BINARY_PATH)).toBe(true);
});
it("aborts on signature rejection", async () => {
withSuccessfulDownload();
withSignatureResponses([200]);
vi.mocked(pgp.verifySignature).mockRejectedValueOnce(
createVerificationError("Invalid signature"),
);
mockUI.setResponse("Signature does not match", undefined);
await expect(manager.fetchBinary(mockApi, "test")).rejects.toThrow(
"Signature verification aborted",
);
});
it("skips verification when disabled", async () => {
mockConfig.set("coder.disableSignatureVerification", true);
withSuccessfulDownload();
const result = await manager.fetchBinary(mockApi, "test");
expectPathsEqual(result, BINARY_PATH);
expect(pgp.verifySignature).not.toHaveBeenCalled();
const files = readdir(BINARY_DIR);
expect(files.find((file) => file.includes(".asc"))).toBeUndefined();
});
type SignatureErrorTestCase = [status: number, message: string];
it.each<SignatureErrorTestCase>([
[404, "Signature not found"],
[500, "Failed to download signature"],
])("allows skipping verification on %i", async (status, message) => {
withSuccessfulDownload();
withHttpResponse(status);
mockUI.setResponse(message, "Run without verification");
const result = await manager.fetchBinary(mockApi, "test");
expectPathsEqual(result, BINARY_PATH);
expect(pgp.verifySignature).not.toHaveBeenCalled();
});
it.each<SignatureErrorTestCase>([
[404, "Signature not found"],
[500, "Failed to download signature"],
])(
"aborts when user declines missing signature on %i",
async (status, message) => {
withSuccessfulDownload();
withHttpResponse(status);
mockUI.setResponse(message, undefined); // User cancels
await expect(manager.fetchBinary(mockApi, "test")).rejects.toThrow(
"Signature download aborted",
);
},
);
});
describe("File System Operations", () => {
beforeEach(() => {
mockConfig.set("coder.disableSignatureVerification", true);
});
it("creates binary directory", async () => {
expect(memfs.existsSync(BINARY_DIR)).toBe(false);
withSuccessfulDownload();
await manager.fetchBinary(mockApi, "test");
expect(memfs.existsSync(BINARY_DIR)).toBe(true);
const stats = memfs.statSync(BINARY_DIR);
expect(stats.isDirectory()).toBe(true);
});
it("validates downloaded binary version", async () => {
withSuccessfulDownload();
await manager.fetchBinary(mockApi, "test");
expect(memfs.readFileSync(BINARY_PATH).toString()).toBe(
mockBinaryContent(TEST_VERSION),
);
});
it("sets correct file permissions", async () => {
withSuccessfulDownload();
await manager.fetchBinary(mockApi, "test");
const stats = memfs.statSync(BINARY_PATH);
expect(stats.mode & 0o777).toBe(0o755);
});
});
describe("Path Pecularities", () => {
beforeEach(() => {
mockConfig.set("coder.disableSignatureVerification", true);
});
it("handles binary with spaces in path", async () => {
const pathWithSpaces = "/path with spaces/bin";
const resolver = new PathResolver(pathWithSpaces, "/log");
const manager = new CliManager(
createMockLogger(),
resolver,
createMockKeyringStore(),
);
withSuccessfulDownload();
const result = await manager.fetchBinary(mockApi, "test label");
expectPathsEqual(
result,
`${pathWithSpaces}/test label/bin/${BINARY_NAME}`,
);
});
it("handles empty deployment label", async () => {
withExistingBinary(TEST_VERSION, "/path/base/bin");
const result = await manager.fetchBinary(mockApi, "");
expectPathsEqual(result, path.join(BASE_PATH, "bin", BINARY_NAME));
});
});
function createMockApi(version: string, url: string): Api {
const axios = {
defaults: { baseURL: url },
get: vi.fn(),
} as unknown as AxiosInstance;
return {
getBuildInfo: vi.fn().mockResolvedValue({ version }),
getAxiosInstance: () => axios,
} as unknown as Api;
}
function withExistingBinary(version: string, dir: string = BINARY_DIR) {
vol.mkdirSync(dir, { recursive: true });
memfs.writeFileSync(`${dir}/${BINARY_NAME}`, mockBinaryContent(version), {
mode: 0o755,
});
// Mock version to return the specified version
vi.mocked(cliUtils.version).mockResolvedValueOnce(version);
}
function withCorruptedBinary() {
vol.mkdirSync(BINARY_DIR, { recursive: true });
memfs.writeFileSync(BINARY_PATH, "corrupted-binary-content", {
mode: 0o755,
});
// Mock version to fail
vi.mocked(cliUtils.version).mockRejectedValueOnce(new Error("corrupted"));
}
function withSuccessfulDownload(opts?: {
headers?: Record<string, unknown>;
}) {
const stream = createMockStream(mockBinaryContent(TEST_VERSION));
withHttpResponse(
200,
opts?.headers ?? { "content-length": "1024" },
stream,
);
// Mock version to return TEST_VERSION after download
vi.mocked(cliUtils.version).mockResolvedValue(TEST_VERSION);
}
function withSignatureResponses(statuses: number[]): void {
for (const status of statuses) {
const data =
status === 200 ? createMockStream("mock-signature-content") : undefined;
withHttpResponse(status, {}, data);
}
}
function withHttpResponse(
status: number,
headers: Record<string, unknown> = {},
data?: unknown,
) {
vi.mocked(mockAxios.get).mockResolvedValueOnce({
status,
headers,
data,
});
}
function withStreamError(type: "read" | "write", message: string) {
if (type === "write") {
vi.spyOn(fs, "createWriteStream").mockImplementation(() => {
const stream = new EventEmitter();
(stream as unknown as fs.WriteStream).write = vi.fn();
(stream as unknown as fs.WriteStream).close = vi.fn();
// Emit error on next tick after stream is returned
setImmediate(() => {
stream.emit("error", new Error(message));
});
return stream as ReturnType<typeof memfs.createWriteStream>;
});
// Provide a normal read stream
withHttpResponse(
200,
{ "content-length": "256" },
createMockStream("data"),
);
} else {
// Create a read stream that emits error
const errorStream = {
on: vi.fn((event: string, callback: (...args: unknown[]) => void) => {
if (event === "error") {
setImmediate(() => callback(new Error(message)));
}
return errorStream;
}),
destroy: vi.fn(),
} as unknown as IncomingMessage;
withHttpResponse(200, { "content-length": "1024" }, errorStream);
}
}
});
function createVerificationError(msg: string): pgp.VerificationError {
const error = new pgp.VerificationError(
pgp.VerificationErrorCode.Invalid,
msg,
);
vi.mocked(error.summary).mockReturnValue("Signature does not match");
return error;
}
function mockBinaryContent(version: string): string {
return `mock-binary-v${version}`;
}
function expectFileInDir(dir: string, pattern: string): string | undefined {
const files = readdir(dir);
return files.find((f) => f.includes(pattern));
}
function readdir(dir: string): string[] {
return memfs.readdirSync(dir) as string[];
}