forked from 1Password/op-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.test.ts
467 lines (402 loc) · 11 KB
/
cli.test.ts
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
import child_process from "child_process";
import * as lookpath from "lookpath";
import {
camelToHyphen,
CLI,
cli,
CLIError,
createFieldAssignment,
createFlags,
defaultClientInfo,
ExecutionError,
parseFlagValue,
semverToInt,
ValidationError,
} from "./cli";
jest.mock("child_process");
jest.mock("lookpath");
const fakeOpPath = "/path/to/op";
type cliCallArgs = [
string,
string[],
{
stdio: string;
input: string;
env: Record<string, string>;
},
];
const expectOpCommand = (
received: {
call: cliCallArgs;
},
expected: string,
): void => {
const actual = `${received.call[0]} ${received.call[1].join(" ")}`;
expected = `op ${expected} --format=json`;
expect(actual).toBe(expected);
};
export const executeSpy = (
params: Parameters<typeof cli.execute>,
{
error = null,
stderr = "",
stdout = "{}",
}: {
error?: null | Error;
stderr?: string;
stdout?: string;
} = {},
) => {
jest.spyOn<any, any>(child_process, "spawnSync").mockReturnValue({
error,
stderr,
stdout,
});
const response = cli.execute(...params);
const spy = child_process.spawnSync as jest.Mock;
const call = spy.mock.calls[0] as cliCallArgs;
spy.mockReset();
return {
call,
response,
};
};
describe("ValidationError", () => {
describe("not-found", () => {
it("sets the correct message", () => {
const error = new ValidationError("not-found");
expect(error.message).toBe("Could not find `op` executable");
});
});
describe("version", () => {
const requiredVersion = "3.2.1";
const currentVersion = "1.2.3";
it("sets the correct message", () => {
const error = new ValidationError(
"version",
requiredVersion,
currentVersion,
);
expect(error.message).toBe(
`CLI version ${currentVersion} does not satisfy required version ${requiredVersion}`,
);
});
it("attaches the current and required versions", () => {
const error = new ValidationError(
"version",
requiredVersion,
currentVersion,
);
expect(error.requiredVersion).toBe(requiredVersion);
expect(error.currentVersion).toBe(currentVersion);
});
});
});
describe("CLIError", () => {
const dateTime = "2022/06/04 17:59:15";
const message = "authorization prompt dismissed, please try again";
it("attaches the status code", () => {
const error = new CLIError("", 1);
expect(error.status).toBe(1);
});
it("parses an error message from op CLI", () => {
const error = new CLIError(`[ERROR] ${dateTime} ${message}`, 1);
expect(error.timestamp).toEqual(new Date(dateTime));
expect(error.message).toEqual(message);
});
it("gracefully handles not being able to parse op error", () => {
const invalidError = "invalid error";
const error = new CLIError(invalidError, 1);
expect(error.timestamp).toBeUndefined();
expect(error.message).toEqual("Unknown error");
expect(error.originalMessage).toEqual(invalidError);
});
});
describe("semverToInt", () => {
it("converts a semver string to build number", () => {
expect(semverToInt("0.1.2")).toBe("000102");
expect(semverToInt("1.2.3")).toBe("010203");
expect(semverToInt("12.2.39")).toBe("120239");
expect(semverToInt("2.1.284")).toBe("0201284");
});
});
describe("camelToHyphen", () => {
it("converts camel case to hyphens", () => {
expect(camelToHyphen("someFlag")).toEqual("some-flag");
});
it("correctly handles pascal case", () => {
expect(camelToHyphen("SomeFlag")).toEqual("some-flag");
});
});
describe("parseFlagValue", () => {
it("parses string type values", () => {
expect(parseFlagValue("foo")).toEqual("=foo");
});
it("parses string array type values", () => {
expect(parseFlagValue(["foo", "bar"])).toEqual("=foo,bar");
});
it("parses boolean type values", () => {
expect(parseFlagValue(true)).toEqual("");
});
it("parses type field selector values", () => {
expect(
parseFlagValue({
type: ["OTP"],
}),
).toEqual("=type=OTP");
});
it("parses label field selector values", () => {
expect(
parseFlagValue({
label: ["username", "password"],
}),
).toEqual("=label=username,label=password");
});
});
describe("createFlags", () => {
it("creates flags from a flag object", () => {
expect(createFlags({ someFlag: "foo" })).toEqual(["--some-flag=foo"]);
});
it("ignores null and falsey values", () => {
expect(
createFlags({ someFlag: "foo", anotherFlag: false, andAnother: null }),
).toEqual(["--some-flag=foo"]);
});
});
describe("createFieldAssignment", () => {
it("creates a field assignment from a field assignment object", () => {
expect(createFieldAssignment(["username", "text", "foo"])).toEqual(
"username[text]=foo",
);
expect(createFieldAssignment(["password", "concealed", "abc123"])).toEqual(
"password[concealed]=abc123",
);
});
});
describe("cli", () => {
describe("setClientInfo", () => {
it("allows you to specify custom user agent details", () => {
const clientInfo = {
name: "foo-bar",
id: "FOO",
build: "120239",
};
cli.setClientInfo(clientInfo);
const execute = executeSpy([["foo"]]);
expect(execute.call[2].env).toEqual(
expect.objectContaining({
OP_INTEGRATION_NAME: clientInfo.name,
OP_INTEGRATION_ID: clientInfo.id,
OP_INTEGRATION_BUILDNUMBER: clientInfo.build,
}),
);
// Reset client info
cli.setClientInfo(defaultClientInfo);
});
});
describe("connect", () => {
it("does not set connect env vars if not supplied", () => {
cli.connect = undefined;
const execute = executeSpy([["foo"]]);
const envVars = Object.keys(execute.call[2].env);
expect(envVars).not.toContain("OP_CONNECT_HOST");
expect(envVars).not.toContain("OP_CONNECT_TOKEN");
});
it("passes connect env vars if supplied", () => {
cli.connect = {
host: "https://connect.myserver.com",
token: "1kjhd9872hd981865s",
};
const execute = executeSpy([["foo"]]);
expect(execute.call[2].env).toEqual(
expect.objectContaining({
OP_CONNECT_HOST: cli.connect.host,
OP_CONNECT_TOKEN: cli.connect.token,
}),
);
// Reset connect info
cli.connect = undefined;
});
});
describe("validate", () => {
it("throws an error when the op cli is not found", async () => {
const lookpathSpy = jest
.spyOn(lookpath, "lookpath")
.mockResolvedValue(undefined);
await expect(cli.validate()).rejects.toEqual(
new ValidationError("not-found"),
);
lookpathSpy.mockRestore();
});
it("throws an error when the cli does not meet the version requirements", async () => {
const lookpathSpy = jest
.spyOn(lookpath, "lookpath")
.mockResolvedValue(fakeOpPath);
const spawnSpy = jest
.spyOn<any, any>(child_process, "spawnSync")
.mockReturnValue({
error: null,
stderr: "",
stdout: "1.0.0",
});
await expect(cli.validate()).rejects.toEqual(
new ValidationError("version", CLI.recommendedVersion, "1.0.0"),
);
lookpathSpy.mockRestore();
spawnSpy.mockRestore();
});
it("does not throw when cli is fully valid", async () => {
CLI.recommendedVersion = ">=2.0.0";
const lookpathSpy = jest
.spyOn(lookpath, "lookpath")
.mockResolvedValue(fakeOpPath);
const spawnSpy = jest
.spyOn<any, any>(child_process, "spawnSync")
.mockReturnValue({
error: null,
stderr: "",
stdout: "2.1.0",
});
await expect(cli.validate()).resolves.toBeUndefined();
lookpathSpy.mockRestore();
spawnSpy.mockRestore();
});
it("can handle beta versions", async () => {
CLI.recommendedVersion = ">=2.0.0";
const lookpathSpy = jest
.spyOn(lookpath, "lookpath")
.mockResolvedValue(fakeOpPath);
const spawnSpy = jest
.spyOn<any, any>(child_process, "spawnSync")
.mockReturnValue({
error: null,
stderr: "",
stdout: "2.0.1.beta.12",
});
await expect(cli.validate()).resolves.toBeUndefined();
lookpathSpy.mockRestore();
spawnSpy.mockRestore();
});
it("can take a custom version", async () => {
const lookpathSpy = jest
.spyOn(lookpath, "lookpath")
.mockResolvedValue(fakeOpPath);
const spawnSpy = jest
.spyOn<any, any>(child_process, "spawnSync")
.mockReturnValue({
error: null,
stderr: "",
stdout: "2.1.0",
});
await expect(cli.validate(">=2.0.0")).resolves.toBeUndefined();
lookpathSpy.mockRestore();
spawnSpy.mockRestore();
});
});
describe("execute", () => {
it("constructs and calls an op command", () => {
const execute = executeSpy([
["example", "command"],
{
args: ["howdy"],
flags: { foo: "bar", lorem: true, howdy: ["dolor", "sit"] },
},
]);
expectOpCommand(
execute,
`example command howdy --foo=bar --lorem --howdy=dolor,sit`,
);
});
it("handles field assignment arguments", () => {
const execute = executeSpy([
["foo"],
{
args: [
["username", "text", "foo"],
["password", "concealed", "abc123"],
],
},
]);
expectOpCommand(
execute,
`foo username[text]=foo password[concealed]=abc123`,
);
});
it("throws on invalid args", () => {
expect(() =>
executeSpy([
["foo"],
{
args: [null],
},
]),
).toThrowError(new TypeError("Invalid argument"));
});
it("sanitizes input in commands, arguments, and flags", () => {
const execute = executeSpy([
['"foo'],
{
args: ['bar"'],
flags: { $lorem: "`ipsum`" },
},
]);
expectOpCommand(execute, `\\"foo bar\\" --\\$lorem=\\\`ipsum\\\``);
});
it("sanitizes field assignments", () => {
const execute = executeSpy([
["foo"],
{
args: [
// @ts-expect-error we're testing invalid input
["$username", "'text'", "\\foo"],
],
},
]);
expectOpCommand(execute, `foo \\$username[\\'text\\']=\\\\foo`);
});
it("throws if there's an error", () => {
const message = "bar";
expect(() =>
executeSpy([["foo"]], { error: new Error(message) }),
).toThrowError(new ExecutionError(message, 0));
});
it("throws if there's a stderr", () => {
const stderr = "bar";
expect(() => executeSpy([["foo"]], { stderr })).toThrowError(
new CLIError(stderr, 0),
);
});
it("parses command JSON responses by default", () => {
const data = { foo: "bar" };
const execute = executeSpy([["foo"]], { stdout: JSON.stringify(data) });
expect(execute.response).toEqual(data);
});
it("can also return non-JSON responses", () => {
const message = "some message";
const execute = executeSpy([["foo"], { json: false }], {
stdout: message,
});
expect(execute.response).toEqual(message);
});
it("passes in user agent env vars, using default client info", () => {
const execute = executeSpy([["foo"]]);
expect(execute.call[2].env).toEqual(
expect.objectContaining({
OP_INTEGRATION_NAME: defaultClientInfo.name,
OP_INTEGRATION_ID: defaultClientInfo.id,
OP_INTEGRATION_BUILDNUMBER: defaultClientInfo.build,
}),
);
});
});
describe("globalFlags", () => {
it("applies global flags to a command", () => {
cli.globalFlags = {
account: "my.b5test.com",
isoTimestamps: true,
};
const execute = executeSpy([["foo"]]);
expectOpCommand(execute, `foo --account=my.b5test.com --iso-timestamps`);
});
});
});