-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlib.rs
More file actions
435 lines (387 loc) · 16.9 KB
/
Copy pathlib.rs
File metadata and controls
435 lines (387 loc) · 16.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
//! socket-patch CLI library crate.
//!
//! Exposes the clap parser types so integration tests can verify the public
//! CLI contract without invoking the binary. The `main.rs` binary entry point
//! is a thin wrapper that delegates to [`parse_with_uuid_fallback`] and the
//! `run` function on each command's `Args`.
pub mod args;
pub mod commands;
pub(crate) mod ecosystem_dispatch;
pub mod json_envelope;
pub mod output;
use clap::{Parser, Subcommand};
// CLI contract surface — subcommand names, visible_alias values, flag names,
// defaults, JSON shapes, and exit codes are PUBLIC and SEMVER-SIGNIFICANT.
// Changes here require a MAJOR bump + `scripts/version-sync.sh`.
// See crates/socket-patch-cli/CLI_CONTRACT.md.
#[derive(Parser)]
#[command(
name = "socket-patch",
about = "CLI tool for applying security patches to dependencies",
version,
propagate_version = true
)]
pub struct Cli {
#[command(subcommand)]
pub command: Commands,
}
#[derive(Subcommand)]
pub enum Commands {
/// Apply security patches to dependencies
Apply(commands::apply::ApplyArgs),
/// Rollback patches to restore original files
Rollback(commands::rollback::RollbackArgs),
/// Get security patches from Socket API and apply them
#[command(visible_alias = "download")]
Get(commands::get::GetArgs),
/// Scan installed packages for available security patches
Scan(commands::scan::ScanArgs),
/// List all patches in the local manifest
List(commands::list::ListArgs),
/// Remove a patch from the manifest by PURL or UUID (rolls back files first)
Remove(commands::remove::RemoveArgs),
/// Configure package.json postinstall scripts to apply patches
Setup(commands::setup::SetupArgs),
/// Download missing blobs and clean up unused blobs.
///
/// `repair` (alias `gc`) is a first-class command for cleaning up
/// the `.socket/` directory without running a scan. For the
/// combined workflow (discover + apply + GC), use
/// `scan --sync --json --yes`. `repair`/`gc` remain useful on
/// their own when the user wants to clean up without an apply pass.
#[command(visible_alias = "gc")]
Repair(commands::repair::RepairArgs),
/// Inspect (and optionally release) the `<.socket>/apply.lock`
/// advisory file lock used by mutating subcommands. Exits 0
/// when free, 1 when held. Pass `--release` to also delete the
/// lock file when it is free.
Unlock(commands::unlock::UnlockArgs),
/// Eject patched dependencies into committable `.socket/vendor/`
/// and rewire lockfiles so fresh checkouts build with the patches
/// (no socket-patch or Socket API needed). `--revert` undoes it.
Vendor(commands::vendor::VendorArgs),
/// Generate an OpenVEX 0.2.0 attestation describing the
/// vulnerabilities mitigated by the applied patches.
Vex(commands::vex::VexArgs),
}
/// Check whether `s` looks like a UUID (8-4-4-4-12 hex pattern).
///
/// Used by [`parse_with_uuid_fallback`] to detect the convenience form
/// `socket-patch <UUID>` and rewrite it to `socket-patch get <UUID>`.
fn looks_like_uuid(s: &str) -> bool {
let parts: Vec<&str> = s.split('-').collect();
if parts.len() != 5 {
return false;
}
let expected = [8, 4, 4, 4, 12];
parts
.iter()
.zip(expected.iter())
.all(|(p, &len)| p.len() == len && p.chars().all(|c| c.is_ascii_hexdigit()))
}
/// Parse a full argv vector, falling back to `get <UUID>` when the user
/// invoked `socket-patch <UUID> [...]` directly. Returns the original clap
/// error if the fallback also fails or if the first arg isn't a UUID.
///
/// Pulled out of `main.rs` so the fallback path is unit-testable.
pub fn parse_with_uuid_fallback(argv: Vec<String>) -> Result<Cli, clap::Error> {
match Cli::try_parse_from(&argv) {
Ok(cli) => Ok(cli),
Err(err) => {
if argv.len() >= 2 && looks_like_uuid(&argv[1]) {
let mut new_args = vec![argv[0].clone(), "get".into()];
new_args.extend_from_slice(&argv[1..]);
match Cli::try_parse_from(&new_args) {
Ok(cli) => Ok(cli),
// clap models `--help`/`--version` as `Err`, but they are
// display requests, not parse failures. For those the
// rewritten `get` form is the correct thing to show, so
// surface the rewrite's error (which clap exits 0 on).
// Only genuine failures (those clap prints to stderr) fall
// back to the original un-rewritten error.
Err(rewrite_err) if !rewrite_err.use_stderr() => Err(rewrite_err),
Err(_) => Err(err),
}
} else {
Err(err)
}
}
}
}
#[cfg(test)]
mod tests {
//! Unit tests for the bare-UUID fallback. These tests lock in the
//! `socket-patch <UUID>` rewrite shortcut and the shape predicate it
//! uses — both of which are part of the CLI contract (see
//! `CLI_CONTRACT.md`).
use super::*;
// ---------- looks_like_uuid ----------
#[test]
fn looks_like_uuid_accepts_canonical_lowercase() {
assert!(looks_like_uuid("80630680-4da6-45f9-bba8-b888e0ffd58c"));
}
#[test]
fn looks_like_uuid_accepts_uppercase() {
// `is_ascii_hexdigit` accepts A-F as well as a-f, so all-uppercase
// UUIDs must still pass the shape check.
assert!(looks_like_uuid("80630680-4DA6-45F9-BBA8-B888E0FFD58C"));
}
#[test]
fn looks_like_uuid_accepts_mixed_case() {
assert!(looks_like_uuid("80630680-4Da6-45F9-bBa8-B888e0FfD58c"));
}
#[test]
fn looks_like_uuid_rejects_four_groups() {
// 8-4-4-4 — missing the final 12-char group.
assert!(!looks_like_uuid("80630680-4da6-45f9-bba8"));
}
#[test]
fn looks_like_uuid_rejects_six_groups() {
// One too many groups — the split count must be exactly 5.
assert!(!looks_like_uuid(
"80630680-4da6-45f9-bba8-b888e0ffd58c-extra"
));
}
#[test]
fn looks_like_uuid_rejects_8_4_4_4_13_group_lengths() {
// Final group has 13 chars instead of 12.
assert!(!looks_like_uuid("80630680-4da6-45f9-bba8-b888e0ffd58cc"));
}
#[test]
fn looks_like_uuid_rejects_7_4_4_4_12_group_lengths() {
// First group has 7 chars instead of 8.
assert!(!looks_like_uuid("8063068-4da6-45f9-bba8-b888e0ffd58c0"));
}
#[test]
fn looks_like_uuid_rejects_non_hex_chars() {
// `g` is not a hex digit — must fail even though the shape is right.
assert!(!looks_like_uuid("g0630680-4da6-45f9-bba8-b888e0ffd58c"));
assert!(!looks_like_uuid("80630680-4dz6-45f9-bba8-b888e0ffd58c"));
assert!(!looks_like_uuid("80630680-4da6-45f9-bba8-b888e0ffd58z"));
}
#[test]
fn looks_like_uuid_rejects_empty_string() {
assert!(!looks_like_uuid(""));
}
#[test]
fn looks_like_uuid_rejects_string_with_no_dashes() {
// 32 hex chars, no dashes — close to a UUID but not the right shape.
assert!(!looks_like_uuid("806306804da645f9bba8b888e0ffd58c"));
}
#[test]
fn looks_like_uuid_rejects_bare_dashes() {
// Five empty groups — split count is right, group lengths aren't.
assert!(!looks_like_uuid("----"));
}
#[test]
fn looks_like_uuid_accepts_nil_uuid() {
// The all-zeros nil UUID is correctly shaped and all-hex.
assert!(looks_like_uuid("00000000-0000-0000-0000-000000000000"));
}
#[test]
fn looks_like_uuid_rejects_surrounding_whitespace() {
// The predicate must not trim: a leading/trailing space makes the
// first/last group the wrong length (and the space is non-hex).
assert!(!looks_like_uuid(" 80630680-4da6-45f9-bba8-b888e0ffd58c"));
assert!(!looks_like_uuid("80630680-4da6-45f9-bba8-b888e0ffd58c "));
}
#[test]
fn looks_like_uuid_rejects_internal_space() {
// A space inside a group keeps the byte length right in one spot but
// fails the hex check — guards against byte-length-only acceptance.
assert!(!looks_like_uuid("8063068 -4da6-45f9-bba8-b888e0ffd58c"));
}
// ---------- parse_with_uuid_fallback ----------
const UUID: &str = "80630680-4da6-45f9-bba8-b888e0ffd58c";
fn argv(items: &[&str]) -> Vec<String> {
items.iter().map(|s| (*s).to_string()).collect()
}
#[test]
fn fallback_rewrites_bare_uuid_to_get() {
let cli = parse_with_uuid_fallback(argv(&["socket-patch", UUID])).unwrap();
match cli.command {
Commands::Get(args) => assert_eq!(args.identifier, UUID),
_ => panic!("expected Commands::Get"),
}
}
#[test]
fn fallback_preserves_trailing_flags() {
// Flags after the UUID must be forwarded to the synthesized `get`.
let cli = parse_with_uuid_fallback(argv(&["socket-patch", UUID, "--json"])).unwrap();
match cli.command {
Commands::Get(args) => {
assert_eq!(args.identifier, UUID);
assert!(args.common.json, "--json should be forwarded to get");
}
_ => panic!("expected Commands::Get"),
}
}
#[test]
fn fallback_returns_original_error_when_first_arg_is_not_uuid() {
// No rewrite should happen; the original clap error must surface.
// `Cli` doesn't derive `Debug`, so `unwrap_err()` doesn't compile —
// pull the error out via `match` instead.
let err = match parse_with_uuid_fallback(argv(&["socket-patch", "not-a-uuid"])) {
Ok(_) => panic!("expected parse to fail"),
Err(e) => e,
};
assert_eq!(err.kind(), clap::error::ErrorKind::InvalidSubcommand);
}
#[test]
fn fallback_is_skipped_when_normal_parse_succeeds() {
// `list` parses normally — fallback should not engage.
let cli = parse_with_uuid_fallback(argv(&["socket-patch", "list"])).unwrap();
assert!(matches!(cli.command, Commands::List(_)));
}
#[test]
fn fallback_does_not_double_rewrite_explicit_get() {
// `socket-patch get <UUID>` already parses; fallback never runs.
let cli = parse_with_uuid_fallback(argv(&["socket-patch", "get", UUID])).unwrap();
match cli.command {
Commands::Get(args) => assert_eq!(args.identifier, UUID),
_ => panic!("expected Commands::Get"),
}
}
#[test]
fn fallback_forwards_multiple_flags_in_order() {
// Every arg after the program name (UUID included) must be forwarded
// after the synthesized `get`, preserving order, so multiple flags
// all reach the rewritten command.
let cli =
parse_with_uuid_fallback(argv(&["socket-patch", UUID, "--id", "--json"])).unwrap();
match cli.command {
Commands::Get(args) => {
assert_eq!(args.identifier, UUID);
assert!(args.id, "--id should be forwarded to get");
assert!(args.common.json, "--json should be forwarded to get");
}
_ => panic!("expected Commands::Get"),
}
}
#[test]
fn fallback_forwards_value_bearing_flag_in_order() {
// The existing forwarding tests only use boolean flags, which don't
// consume the following token. A value-bearing flag (`--manifest-path
// <value>`) exercises the splice ordering differently: an off-by-one in
// `extend_from_slice(&argv[1..])` would either drop the flag's value or
// shift it onto the wrong token. Passing the flag explicitly wins over
// its `SOCKET_MANIFEST_PATH` env fallback, so this holds regardless of
// ambient env.
let cli = parse_with_uuid_fallback(argv(&[
"socket-patch",
UUID,
"--manifest-path",
"custom/forwarded.json",
]))
.unwrap();
match cli.command {
Commands::Get(args) => {
assert_eq!(args.identifier, UUID);
assert_eq!(
args.common.manifest_path, "custom/forwarded.json",
"the value-bearing flag and its argument must survive the rewrite in order"
);
}
_ => panic!("expected Commands::Get"),
}
}
#[test]
fn fallback_handles_no_args_without_panicking() {
// Only the program name is present (argv.len() == 1). The
// `argv.len() >= 2` guard must short-circuit before indexing argv[1],
// so this returns the original clap error rather than panicking.
let err = match parse_with_uuid_fallback(argv(&["socket-patch"])) {
Ok(_) => panic!("expected parse to fail without a subcommand"),
Err(e) => e,
};
assert_eq!(
err.kind(),
clap::error::ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand,
"bare invocation should surface clap's missing-subcommand help, not panic"
);
}
#[test]
fn fallback_rewrites_uppercase_uuid_end_to_end() {
// The shape check accepts uppercase; confirm the full fallback path
// (not just `looks_like_uuid`) rewrites an uppercase bare UUID to get.
const UPPER: &str = "80630680-4DA6-45F9-BBA8-B888E0FFD58C";
let cli = parse_with_uuid_fallback(argv(&["socket-patch", UPPER])).unwrap();
match cli.command {
Commands::Get(args) => assert_eq!(args.identifier, UPPER),
_ => panic!("expected Commands::Get"),
}
}
#[test]
fn fallback_surfaces_original_error_when_rewrite_also_fails() {
// UUID is valid-shaped so a rewrite is attempted, but `get` doesn't
// accept this flag — the rewrite parse fails and we must return the
// ORIGINAL error (the one from the un-rewritten parse), not the
// rewrite's error.
let err = match parse_with_uuid_fallback(argv(&[
"socket-patch",
UUID,
"--invalid-flag-that-get-does-not-accept",
])) {
Ok(_) => panic!("expected parse to fail"),
Err(e) => e,
};
// The original parse failed because `<UUID>` isn't a known
// subcommand, so the surfaced error must be InvalidSubcommand —
// NOT UnknownArgument (which is what the rewrite parse would have
// produced).
assert_eq!(err.kind(), clap::error::ErrorKind::InvalidSubcommand);
}
#[test]
fn fallback_forwards_help_to_rewritten_get() {
// `socket-patch <UUID> --help` must display the rewritten `get`
// command's help rather than swallowing it and surfacing the original
// "invalid subcommand" error. clap models `--help` as an `Err`, but it
// is a display request (exit 0), so the fallback must surface THAT
// error, not the original InvalidSubcommand (which would exit 2).
let err = match parse_with_uuid_fallback(argv(&["socket-patch", UUID, "--help"])) {
Ok(_) => panic!("clap surfaces --help as an Err"),
Err(e) => e,
};
assert_eq!(
err.kind(),
clap::error::ErrorKind::DisplayHelp,
"bare-UUID + --help should show get's help, not the original error"
);
// Display requests exit 0 and print to stdout, not stderr.
assert!(!err.use_stderr());
assert_eq!(err.exit_code(), 0);
// The rendered help is for the rewritten `get` command, proving the
// rewrite's error (not the original) was surfaced.
assert!(err.to_string().contains("socket-patch get"));
}
#[test]
fn fallback_forwards_version_to_rewritten_get() {
// `--version` is likewise a display request that propagates to
// subcommands (propagate_version = true); it must not be swallowed.
let err = match parse_with_uuid_fallback(argv(&["socket-patch", UUID, "--version"])) {
Ok(_) => panic!("clap surfaces --version as an Err"),
Err(e) => e,
};
assert_eq!(err.kind(), clap::error::ErrorKind::DisplayVersion);
assert!(!err.use_stderr());
assert_eq!(err.exit_code(), 0);
}
#[test]
fn fallback_genuine_rewrite_failure_still_uses_original_error() {
// Regression guard for the fix: a *real* rewrite failure (one clap
// prints to stderr) must still fall back to the original error, so the
// help/version carve-out doesn't accidentally swallow legitimate
// failures. An unknown flag makes the rewrite fail with UnknownArgument
// (use_stderr == true), so the original InvalidSubcommand wins.
let err = match parse_with_uuid_fallback(argv(&[
"socket-patch",
UUID,
"--definitely-not-a-real-flag",
])) {
Ok(_) => panic!("expected parse to fail"),
Err(e) => e,
};
assert_eq!(err.kind(), clap::error::ErrorKind::InvalidSubcommand);
assert!(err.use_stderr());
}
}