-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathe2e_npm.rs
More file actions
547 lines (457 loc) · 17.6 KB
/
e2e_npm.rs
File metadata and controls
547 lines (457 loc) · 17.6 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
//! End-to-end tests for the npm patch lifecycle.
//!
//! These tests exercise the full CLI against the real Socket API, using the
//! **minimist@1.2.2** patch (UUID `80630680-4da6-45f9-bba8-b888e0ffd58c`),
//! which fixes CVE-2021-44906 (Prototype Pollution).
//!
//! # Prerequisites
//! - `npm` on PATH
//! - Network access to `patches-api.socket.dev` and `registry.npmjs.org`
//!
//! # Running
//! ```sh
//! cargo test -p socket-patch-cli --test e2e_npm -- --ignored
//! ```
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use sha2::{Digest, Sha256};
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
const NPM_UUID: &str = "80630680-4da6-45f9-bba8-b888e0ffd58c";
#[allow(dead_code)]
const NPM_PURL: &str = "pkg:npm/minimist@1.2.2";
/// Git SHA-256 of the *unpatched* `index.js` shipped with minimist 1.2.2.
const BEFORE_HASH: &str = "311f1e893e6eac502693fad8617dcf5353a043ccc0f7b4ba9fe385e838b67a10";
/// Git SHA-256 of the *patched* `index.js` after the security fix.
const AFTER_HASH: &str = "043f04d19e884aa5f8371428718d2a3f27a0d231afe77a2620ac6312f80aaa28";
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
fn binary() -> PathBuf {
env!("CARGO_BIN_EXE_socket-patch").into()
}
fn has_command(cmd: &str) -> bool {
Command::new(cmd)
.arg("--version")
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()
.is_ok()
}
/// Compute Git SHA-256: `SHA256("blob <len>\0" ++ content)`.
fn git_sha256(content: &[u8]) -> String {
let header = format!("blob {}\0", content.len());
let mut hasher = Sha256::new();
hasher.update(header.as_bytes());
hasher.update(content);
hex::encode(hasher.finalize())
}
fn git_sha256_file(path: &Path) -> String {
let content = std::fs::read(path).unwrap_or_else(|e| panic!("read {}: {e}", path.display()));
git_sha256(&content)
}
/// Run the CLI binary with the given args, setting `cwd` as the working dir.
/// Returns `(exit_code, stdout, stderr)`.
fn run(cwd: &Path, args: &[&str]) -> (i32, String, String) {
let out: Output = Command::new(binary())
.args(args)
.current_dir(cwd)
.env_remove("SOCKET_API_TOKEN") // force public proxy (free-tier)
.output()
.expect("failed to execute socket-patch binary");
let code = out.status.code().unwrap_or(-1);
let stdout = String::from_utf8_lossy(&out.stdout).to_string();
let stderr = String::from_utf8_lossy(&out.stderr).to_string();
(code, stdout, stderr)
}
fn assert_run_ok(cwd: &Path, args: &[&str], context: &str) -> (String, String) {
let (code, stdout, stderr) = run(cwd, args);
assert_eq!(
code, 0,
"{context} failed (exit {code}).\nstdout:\n{stdout}\nstderr:\n{stderr}"
);
(stdout, stderr)
}
fn npm_run(cwd: &Path, args: &[&str]) {
let out = Command::new("npm")
.args(args)
.current_dir(cwd)
.output()
.expect("failed to run npm");
assert!(
out.status.success(),
"npm {args:?} failed (exit {:?}).\nstdout:\n{}\nstderr:\n{}",
out.status.code(),
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr),
);
}
/// Write a minimal package.json (avoids `npm init -y` which rejects temp dir
/// names that start with `.` or contain invalid characters).
fn write_package_json(cwd: &Path) {
std::fs::write(
cwd.join("package.json"),
r#"{"name":"e2e-test","version":"0.0.0","private":true}"#,
)
.expect("write package.json");
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
/// Full lifecycle: get → verify → list → rollback → apply → remove.
#[test]
#[ignore]
fn test_npm_full_lifecycle() {
if !has_command("npm") {
eprintln!("SKIP: npm not found on PATH");
return;
}
let dir = tempfile::tempdir().unwrap();
let cwd = dir.path();
// -- Setup: create a project and install minimist@1.2.2 ----------------
write_package_json(cwd);
npm_run(cwd, &["install", "minimist@1.2.2"]);
let index_js = cwd.join("node_modules/minimist/index.js");
assert!(index_js.exists(), "minimist/index.js must exist after npm install");
// Confirm the original file matches the expected before-hash.
assert_eq!(
git_sha256_file(&index_js),
BEFORE_HASH,
"freshly installed index.js should have the expected beforeHash"
);
// -- GET: download + apply patch ---------------------------------------
assert_run_ok(cwd, &["get", NPM_UUID], "get");
// Manifest should exist and contain the patch.
let manifest_path = cwd.join(".socket/manifest.json");
assert!(manifest_path.exists(), ".socket/manifest.json should exist after get");
let manifest: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&manifest_path).unwrap()).unwrap();
let patch = &manifest["patches"][NPM_PURL];
assert!(patch.is_object(), "manifest should contain {NPM_PURL}");
assert_eq!(patch["uuid"].as_str().unwrap(), NPM_UUID);
// The file should now be patched.
assert_eq!(
git_sha256_file(&index_js),
AFTER_HASH,
"index.js should match afterHash after get"
);
// -- LIST: verify JSON output ------------------------------------------
let (stdout, _) = assert_run_ok(cwd, &["list", "--json"], "list --json");
let list: serde_json::Value = serde_json::from_str(&stdout).unwrap();
let patches = list["patches"].as_array().expect("patches should be an array");
assert_eq!(patches.len(), 1);
assert_eq!(patches[0]["uuid"].as_str().unwrap(), NPM_UUID);
assert_eq!(patches[0]["purl"].as_str().unwrap(), NPM_PURL);
let vulns = patches[0]["vulnerabilities"]
.as_array()
.expect("vulnerabilities array");
assert!(!vulns.is_empty(), "patch should report at least one vulnerability");
// Verify the vulnerability details match CVE-2021-44906
let has_cve = vulns.iter().any(|v| {
v["cves"]
.as_array()
.map_or(false, |cves| cves.iter().any(|c| c == "CVE-2021-44906"))
});
assert!(has_cve, "vulnerability list should include CVE-2021-44906");
// -- ROLLBACK: restore original file -----------------------------------
assert_run_ok(cwd, &["rollback"], "rollback");
assert_eq!(
git_sha256_file(&index_js),
BEFORE_HASH,
"index.js should match beforeHash after rollback"
);
// -- APPLY: re-apply from manifest ------------------------------------
assert_run_ok(cwd, &["apply"], "apply");
assert_eq!(
git_sha256_file(&index_js),
AFTER_HASH,
"index.js should match afterHash after re-apply"
);
// -- REMOVE: rollback + remove from manifest ---------------------------
assert_run_ok(cwd, &["remove", NPM_UUID], "remove");
// File should be back to original.
assert_eq!(
git_sha256_file(&index_js),
BEFORE_HASH,
"index.js should match beforeHash after remove"
);
// Manifest should have no patches left.
let manifest: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&manifest_path).unwrap()).unwrap();
assert!(
manifest["patches"].as_object().unwrap().is_empty(),
"manifest should be empty after remove"
);
}
/// `apply --dry-run` should not modify files on disk.
#[test]
#[ignore]
fn test_npm_dry_run() {
if !has_command("npm") {
eprintln!("SKIP: npm not found on PATH");
return;
}
let dir = tempfile::tempdir().unwrap();
let cwd = dir.path();
write_package_json(cwd);
npm_run(cwd, &["install", "minimist@1.2.2"]);
let index_js = cwd.join("node_modules/minimist/index.js");
assert_eq!(git_sha256_file(&index_js), BEFORE_HASH);
// Download the patch *without* applying.
assert_run_ok(cwd, &["get", NPM_UUID, "--no-apply"], "get --no-apply");
// File should still be original.
assert_eq!(
git_sha256_file(&index_js),
BEFORE_HASH,
"file should not change after get --no-apply"
);
// Dry-run should succeed but leave file untouched.
assert_run_ok(cwd, &["apply", "--dry-run"], "apply --dry-run");
assert_eq!(
git_sha256_file(&index_js),
BEFORE_HASH,
"file should not change after apply --dry-run"
);
// Real apply should work.
assert_run_ok(cwd, &["apply"], "apply");
assert_eq!(
git_sha256_file(&index_js),
AFTER_HASH,
"file should match afterHash after real apply"
);
}
/// Global lifecycle: scan → get → list → rollback → apply → remove using `-g --global-prefix`.
#[test]
#[ignore]
fn test_npm_global_lifecycle() {
if !has_command("npm") {
eprintln!("SKIP: npm not found on PATH");
return;
}
let global_dir = tempfile::tempdir().unwrap();
let cwd_dir = tempfile::tempdir().unwrap();
let cwd = cwd_dir.path();
// -- Setup: install minimist@1.2.2 globally into a temp prefix ----------
let out = Command::new("npm")
.args(["install", "-g", "--prefix", global_dir.path().to_str().unwrap(), "minimist@1.2.2"])
.output()
.expect("failed to run npm install -g");
assert!(
out.status.success(),
"npm install -g failed.\nstdout:\n{}\nstderr:\n{}",
String::from_utf8_lossy(&out.stdout),
String::from_utf8_lossy(&out.stderr),
);
// On Unix, npm -g --prefix puts packages under <prefix>/lib/node_modules/
// On Windows, it's <prefix>/node_modules/
let nm_path = if cfg!(windows) {
global_dir.path().join("node_modules")
} else {
global_dir.path().join("lib/node_modules")
};
let index_js = nm_path.join("minimist/index.js");
assert!(
index_js.exists(),
"minimist/index.js must exist after global install at {}",
index_js.display()
);
assert_eq!(
git_sha256_file(&index_js),
BEFORE_HASH,
"globally installed index.js should have the expected beforeHash"
);
let nm_str = nm_path.to_str().unwrap();
// -- SCAN: verify scan -g finds the package ------------------------------
let (stdout, _) = assert_run_ok(
cwd,
&["scan", "-g", "--global-prefix", nm_str, "--json"],
"scan -g --json",
);
let scan: serde_json::Value = serde_json::from_str(&stdout).unwrap();
let scanned = scan["scannedPackages"]
.as_u64()
.expect("scannedPackages should be a number");
assert!(scanned >= 1, "scan should find at least 1 package, got {scanned}");
// -- GET: download + apply patch globally --------------------------------
assert_run_ok(
cwd,
&["get", NPM_UUID, "-g", "--global-prefix", nm_str],
"get -g",
);
let manifest_path = cwd.join(".socket/manifest.json");
assert!(manifest_path.exists(), "manifest should exist after get");
assert_eq!(
git_sha256_file(&index_js),
AFTER_HASH,
"index.js should match afterHash after global get"
);
// -- LIST: verify patch in output ----------------------------------------
let (stdout, _) = assert_run_ok(cwd, &["list", "--json"], "list --json");
let list: serde_json::Value = serde_json::from_str(&stdout).unwrap();
let patches = list["patches"].as_array().expect("patches array");
assert_eq!(patches.len(), 1);
assert_eq!(patches[0]["uuid"].as_str().unwrap(), NPM_UUID);
// -- ROLLBACK: restore original file globally ----------------------------
assert_run_ok(
cwd,
&["rollback", "-g", "--global-prefix", nm_str],
"rollback -g",
);
assert_eq!(
git_sha256_file(&index_js),
BEFORE_HASH,
"index.js should match beforeHash after global rollback"
);
// -- APPLY: re-apply from manifest globally ------------------------------
assert_run_ok(
cwd,
&["apply", "-g", "--global-prefix", nm_str],
"apply -g",
);
assert_eq!(
git_sha256_file(&index_js),
AFTER_HASH,
"index.js should match afterHash after global apply"
);
// -- REMOVE: rollback + remove from manifest globally --------------------
assert_run_ok(
cwd,
&["remove", NPM_UUID, "-g", "--global-prefix", nm_str],
"remove -g",
);
assert_eq!(
git_sha256_file(&index_js),
BEFORE_HASH,
"index.js should match beforeHash after global remove"
);
let manifest: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&manifest_path).unwrap()).unwrap();
assert!(
manifest["patches"].as_object().unwrap().is_empty(),
"manifest should be empty after global remove"
);
}
/// `get --save-only` should save the patch to the manifest without applying.
#[test]
#[ignore]
fn test_npm_save_only() {
if !has_command("npm") {
eprintln!("SKIP: npm not found on PATH");
return;
}
let dir = tempfile::tempdir().unwrap();
let cwd = dir.path();
write_package_json(cwd);
npm_run(cwd, &["install", "minimist@1.2.2"]);
let index_js = cwd.join("node_modules/minimist/index.js");
assert_eq!(git_sha256_file(&index_js), BEFORE_HASH);
// Download with --save-only (new name for --no-apply).
assert_run_ok(cwd, &["get", NPM_UUID, "--save-only"], "get --save-only");
// File should still be original.
assert_eq!(
git_sha256_file(&index_js),
BEFORE_HASH,
"file should not change after get --save-only"
);
// Manifest should exist with the patch.
let manifest_path = cwd.join(".socket/manifest.json");
assert!(manifest_path.exists(), "manifest should exist after get --save-only");
let manifest: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(&manifest_path).unwrap()).unwrap();
let patch = &manifest["patches"][NPM_PURL];
assert!(patch.is_object(), "manifest should contain {NPM_PURL}");
assert_eq!(patch["uuid"].as_str().unwrap(), NPM_UUID);
// Real apply should work.
assert_run_ok(cwd, &["apply"], "apply");
assert_eq!(
git_sha256_file(&index_js),
AFTER_HASH,
"file should match afterHash after apply"
);
}
/// `apply --force` should apply patches even when file hashes don't match.
#[test]
#[ignore]
fn test_npm_apply_force() {
if !has_command("npm") {
eprintln!("SKIP: npm not found on PATH");
return;
}
let dir = tempfile::tempdir().unwrap();
let cwd = dir.path();
write_package_json(cwd);
npm_run(cwd, &["install", "minimist@1.2.2"]);
let index_js = cwd.join("node_modules/minimist/index.js");
assert_eq!(git_sha256_file(&index_js), BEFORE_HASH);
// Save the patch without applying.
assert_run_ok(cwd, &["get", NPM_UUID, "--save-only"], "get --save-only");
// Corrupt the file to create a hash mismatch (keep same version so PURL matches).
std::fs::write(&index_js, b"// corrupted content\n").unwrap();
assert_ne!(
git_sha256_file(&index_js),
BEFORE_HASH,
"corrupted file should have a different hash"
);
// Normal apply should fail due to hash mismatch.
let (code, _stdout, _stderr) = run(cwd, &["apply"]);
assert_ne!(code, 0, "apply without --force should fail on hash mismatch");
// Apply with --force should succeed.
assert_run_ok(cwd, &["apply", "--force"], "apply --force");
assert_eq!(
git_sha256_file(&index_js),
AFTER_HASH,
"index.js should match afterHash after apply --force"
);
}
/// macOS auto-discovery: `scan -g --json` without `--global-prefix` uses real path probing.
#[cfg(target_os = "macos")]
#[test]
#[ignore]
fn test_npm_macos_global_auto_discovery() {
if !has_command("npm") {
eprintln!("SKIP: npm not found on PATH");
return;
}
let cwd_dir = tempfile::tempdir().unwrap();
let cwd = cwd_dir.path();
// Run scan -g without --global-prefix to exercise macOS auto-discovery
let (code, stdout, stderr) = run(cwd, &["scan", "-g", "--json"]);
// Should complete without error (exit 0)
assert_eq!(
code, 0,
"scan -g --json failed (exit {code}).\nstdout:\n{stdout}\nstderr:\n{stderr}"
);
// Output should be valid JSON with scannedPackages field
let scan: serde_json::Value = serde_json::from_str(&stdout)
.unwrap_or_else(|e| panic!("invalid JSON from scan -g: {e}\nstdout:\n{stdout}"));
assert!(
scan["scannedPackages"].is_u64(),
"scannedPackages should be a number, got: {}",
scan["scannedPackages"]
);
}
/// UUID shortcut: `socket-patch <UUID>` should behave like `socket-patch get <UUID>`.
#[test]
#[ignore]
fn test_npm_uuid_shortcut() {
if !has_command("npm") {
eprintln!("SKIP: npm not found on PATH");
return;
}
let dir = tempfile::tempdir().unwrap();
let cwd = dir.path();
write_package_json(cwd);
npm_run(cwd, &["install", "minimist@1.2.2"]);
let index_js = cwd.join("node_modules/minimist/index.js");
assert_eq!(git_sha256_file(&index_js), BEFORE_HASH);
// Run with bare UUID (no "get" subcommand).
assert_run_ok(cwd, &[NPM_UUID], "uuid shortcut");
assert_eq!(
git_sha256_file(&index_js),
AFTER_HASH,
"index.js should match afterHash after UUID shortcut"
);
let manifest_path = cwd.join(".socket/manifest.json");
assert!(manifest_path.exists(), "manifest should exist after UUID shortcut");
}