socket-patch-cli 3.3.0

CLI binary for socket-patch: apply, rollback, get, scan security patches
Documentation
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
//! Compose tests: every global flag must be accepted on every subcommand.
//!
//! `GlobalArgs` is `#[command(flatten)]`-ed into each subcommand's `Args`
//! struct, so each subcommand should accept the full set of global flags.
//! This file catches regressions if a new subcommand is added and someone
//! forgets the flatten, or if a flag is accidentally dropped from
//! `GlobalArgs`.
//!
//! For commands that have a required positional (e.g. `get` and `remove`
//! take an identifier), we supply a dummy value alongside the flag under
//! test so clap's parser can complete.

use clap::Parser;
use socket_patch_cli::Cli;

/// Subcommands under test. `rollback` is omitted because its only positional
/// is optional — covered by the no-positional variant. Setup is exercised
/// even though most globals are no-ops there; the point is to lock in that
/// every subcommand parses every global flag.
const SUBCOMMANDS_NO_POSITIONAL: &[&str] = &[
    "apply", "list", "scan", "setup", "repair", "rollback",
];

/// Subcommands that require a positional identifier.
const SUBCOMMANDS_WITH_IDENTIFIER: &[&str] = &["get", "remove"];

const DUMMY_IDENTIFIER: &str = "80630680-4da6-45f9-bba8-b888e0ffd58c";

/// (flag, value-or-None) pairs covering every flag on `GlobalArgs`.
fn global_flag_cases() -> Vec<(&'static str, Option<&'static str>)> {
    vec![
        ("--cwd", Some("/tmp")),
        ("--manifest-path", Some("custom.json")),
        ("--api-url", Some("https://example.com")),
        ("--api-token", Some("tok123")),
        ("--org", Some("acme")),
        ("--proxy-url", Some("https://proxy.example.com")),
        ("--ecosystems", Some("npm,pypi")),
        ("--download-mode", Some("diff")),
        ("--offline", None),
        ("--global", None),
        ("--global-prefix", Some("/opt/global")),
        ("--json", None),
        ("--verbose", None),
        ("--silent", None),
        ("--dry-run", None),
        ("--yes", None),
        ("--debug", None),
        ("--no-telemetry", None),
        ("--break-lock", None),
        ("--lock-timeout", Some("30")),
    ]
}

fn try_parse(subcommand: &str, extra: &[&str]) -> Result<Cli, clap::Error> {
    let mut argv: Vec<String> = vec!["socket-patch".into(), subcommand.into()];
    if SUBCOMMANDS_WITH_IDENTIFIER.contains(&subcommand) {
        argv.push(DUMMY_IDENTIFIER.into());
    }
    for &arg in extra {
        argv.push(arg.into());
    }
    Cli::try_parse_from(&argv)
}

#[test]
fn every_global_flag_parses_on_every_subcommand() {
    let cases = global_flag_cases();
    let all_subcommands: Vec<&str> = SUBCOMMANDS_NO_POSITIONAL
        .iter()
        .chain(SUBCOMMANDS_WITH_IDENTIFIER.iter())
        .copied()
        .collect();

    for &subcommand in &all_subcommands {
        for &(flag, value) in &cases {
            let extra: Vec<&str> = if let Some(v) = value {
                vec![flag, v]
            } else {
                vec![flag]
            };
            let result = try_parse(subcommand, &extra);
            assert!(
                result.is_ok(),
                "subcommand `{}` failed to parse global flag `{}`: {}",
                subcommand,
                flag,
                result.err().map(|e| e.to_string()).unwrap_or_default(),
            );
        }
    }
}

/// Short forms (`-s`, `-y`, etc.) are part of the contract too. `-d`
/// and `-m` were dropped after v3.0 (they were reserved as aliases for
/// `--dry-run` and `--manifest-path` but we want those letters free
/// for future flags); the corresponding rejection check lives in
/// `reserved_short_forms_are_not_assigned` below.
#[test]
fn every_global_short_form_parses_on_every_subcommand() {
    // (short, requires_value) — only flags that actually have a short.
    let shorts: &[(&str, bool)] = &[
        ("-o", true),  // --org
        ("-e", true),  // --ecosystems
        ("-g", false), // --global
        ("-j", false), // --json
        ("-v", false), // --verbose
        ("-s", false), // --silent
        ("-y", false), // --yes
    ];
    let all_subcommands: Vec<&str> = SUBCOMMANDS_NO_POSITIONAL
        .iter()
        .chain(SUBCOMMANDS_WITH_IDENTIFIER.iter())
        .copied()
        .collect();

    for &subcommand in &all_subcommands {
        for &(short, needs_value) in shorts {
            // `apply` has its own `-f` for --force; we don't test that here
            // because it's local. The shorts we test are all GlobalArgs shorts.
            // `get` has `-p` for --package (local); also not tested here.
            let extra: Vec<&str> = if needs_value {
                vec![short, "value"]
            } else {
                vec![short]
            };
            let result = try_parse(subcommand, &extra);
            assert!(
                result.is_ok(),
                "subcommand `{}` failed to parse short flag `{}`: {}",
                subcommand,
                short,
                result.err().map(|e| e.to_string()).unwrap_or_default(),
            );
        }
    }
}

/// `-d` and `-m` were intentionally dropped (formerly aliases for
/// `--dry-run` and `--manifest-path`) so those letters stay free for
/// future flags. Lock that in: clap must reject the bare shorts on
/// every subcommand. The long forms still work and are exercised by
/// `every_global_flag_parses_on_every_subcommand` above.
#[test]
fn reserved_short_forms_are_not_assigned() {
    let all_subcommands: Vec<&str> = SUBCOMMANDS_NO_POSITIONAL
        .iter()
        .chain(SUBCOMMANDS_WITH_IDENTIFIER.iter())
        .copied()
        .collect();
    for &subcommand in &all_subcommands {
        for short in ["-d", "-m"] {
            let result = try_parse(subcommand, &[short]);
            assert!(
                result.is_err(),
                "`{}` should NOT accept the reserved short `{}` — \
                 if you bound it intentionally, update this test and \
                 the corresponding `--help` docs.",
                subcommand,
                short,
            );
            let err = result.err().unwrap();
            assert_eq!(
                err.kind(),
                clap::error::ErrorKind::UnknownArgument,
                "expected UnknownArgument when `{}` is passed to `{}`; got {:?}",
                short,
                subcommand,
                err.kind(),
            );
        }
    }
}

/// Locks the env-var bindings: setting a SOCKET_* env var must populate
/// the corresponding GlobalArgs field on parse.
///
/// Combined into one test to avoid env-var races between parallel tests.
#[test]
#[serial_test::serial]
fn env_vars_populate_global_args() {
    // Save then clear any env vars we set, then verify clap picks them up.
    let pairs = [
        ("SOCKET_CWD", "/env/cwd"),
        ("SOCKET_MANIFEST_PATH", "env-manifest.json"),
        ("SOCKET_API_URL", "https://env-api.example.com"),
        ("SOCKET_API_TOKEN", "env-token"),
        ("SOCKET_ORG_SLUG", "env-org"),
        ("SOCKET_PROXY_URL", "https://env-proxy.example.com"),
        ("SOCKET_ECOSYSTEMS", "npm,maven"),
        ("SOCKET_DOWNLOAD_MODE", "package"),
        ("SOCKET_OFFLINE", "true"),
        ("SOCKET_GLOBAL", "true"),
        ("SOCKET_GLOBAL_PREFIX", "/env/global"),
        ("SOCKET_JSON", "true"),
        ("SOCKET_VERBOSE", "true"),
        ("SOCKET_SILENT", "true"),
        ("SOCKET_DRY_RUN", "true"),
        ("SOCKET_YES", "true"),
        ("SOCKET_LOCK_TIMEOUT", "30"),
        ("SOCKET_BREAK_LOCK", "true"),
        ("SOCKET_DEBUG", "true"),
        ("SOCKET_TELEMETRY_DISABLED", "true"),
    ];

    // Save originals.
    let saved: Vec<(String, Option<String>)> = pairs
        .iter()
        .map(|(k, _)| (k.to_string(), std::env::var(k).ok()))
        .collect();

    // Set test values.
    for (k, v) in &pairs {
        std::env::set_var(k, v);
    }

    let cli = Cli::try_parse_from(["socket-patch", "list"]).expect("parse");
    if let socket_patch_cli::Commands::List(args) = cli.command {
        assert_eq!(args.common.cwd, std::path::PathBuf::from("/env/cwd"));
        assert_eq!(args.common.manifest_path, "env-manifest.json");
        assert_eq!(args.common.api_url, "https://env-api.example.com");
        assert_eq!(args.common.api_token.as_deref(), Some("env-token"));
        assert_eq!(args.common.org.as_deref(), Some("env-org"));
        assert_eq!(args.common.proxy_url, "https://env-proxy.example.com");
        assert_eq!(
            args.common.ecosystems.as_deref(),
            Some(&["npm".to_string(), "maven".to_string()][..])
        );
        assert_eq!(args.common.download_mode, "package");
        assert!(args.common.offline);
        assert!(args.common.global);
        assert_eq!(
            args.common.global_prefix,
            Some(std::path::PathBuf::from("/env/global"))
        );
        assert!(args.common.json);
        assert!(args.common.verbose);
        assert!(args.common.silent);
        assert!(args.common.dry_run);
        assert!(args.common.yes);
        assert_eq!(args.common.lock_timeout, Some(30));
        assert!(args.common.break_lock);
        assert!(args.common.debug);
        assert!(args.common.no_telemetry);
    } else {
        panic!("expected List");
    }

    // Restore originals.
    for (k, orig) in saved {
        match orig {
            Some(v) => std::env::set_var(&k, v),
            None => std::env::remove_var(&k),
        }
    }
}

/// Regression: bool env vars accept "1"/"yes" (the conventional truthy
/// strings), not just clap's strict "true"/"false". Before
/// BoolishValueParser was wired onto every bool with env, setting
/// SOCKET_OFFLINE=1 (or SOCKET_DEBUG=1) crashed clap with
/// `error: invalid value '1' for '--offline'`, taking down every
/// downstream CLI run that follows the conventional shell idiom.
///
/// `#[serial]` because env-var state is process-global; without it
/// these tests race each other (and the existing
/// `env_vars_populate_global_args`) when cargo runs them in
/// parallel.
#[test]
#[serial_test::serial]
fn bool_env_vars_accept_one_and_yes() {
    // (env var name, value to set)
    let cases: &[(&str, &str)] = &[
        ("SOCKET_OFFLINE", "1"),
        ("SOCKET_GLOBAL", "yes"),
        ("SOCKET_JSON", "on"),
        ("SOCKET_VERBOSE", "1"),
        ("SOCKET_SILENT", "y"),
        ("SOCKET_DRY_RUN", "1"),
        ("SOCKET_YES", "yes"),
        ("SOCKET_BREAK_LOCK", "1"),
        ("SOCKET_DEBUG", "1"),
        ("SOCKET_TELEMETRY_DISABLED", "1"),
    ];

    let saved: Vec<(String, Option<String>)> = cases
        .iter()
        .map(|(k, _)| (k.to_string(), std::env::var(k).ok()))
        .collect();
    for (k, v) in cases {
        std::env::set_var(k, v);
    }

    let cli = Cli::try_parse_from(["socket-patch", "list"]).expect("parse");
    if let socket_patch_cli::Commands::List(args) = cli.command {
        assert!(args.common.offline, "SOCKET_OFFLINE=1 must parse as true");
        assert!(args.common.global, "SOCKET_GLOBAL=yes must parse as true");
        assert!(args.common.json, "SOCKET_JSON=on must parse as true");
        assert!(args.common.verbose, "SOCKET_VERBOSE=1 must parse as true");
        assert!(args.common.silent, "SOCKET_SILENT=y must parse as true");
        assert!(args.common.dry_run, "SOCKET_DRY_RUN=1 must parse as true");
        assert!(args.common.yes, "SOCKET_YES=yes must parse as true");
        assert!(args.common.break_lock, "SOCKET_BREAK_LOCK=1 must parse as true");
        assert!(args.common.debug, "SOCKET_DEBUG=1 must parse as true");
        assert!(
            args.common.no_telemetry,
            "SOCKET_TELEMETRY_DISABLED=1 must parse as true"
        );
    } else {
        panic!("expected List");
    }

    for (k, orig) in saved {
        match orig {
            Some(v) => std::env::set_var(&k, v),
            None => std::env::remove_var(&k),
        }
    }
}

/// Defensive: "0", "false", "no", "off", and empty string must NOT
/// engage a bool. Otherwise an operator unsetting via SOCKET_OFFLINE=0
/// would still get airgap mode (and various subtler shell idioms).
#[test]
#[serial_test::serial]
fn bool_env_vars_reject_zero_and_falsey() {
    let cases: &[(&str, &str)] = &[
        ("SOCKET_OFFLINE", "0"),
        ("SOCKET_DEBUG", "false"),
        ("SOCKET_TELEMETRY_DISABLED", "no"),
        ("SOCKET_JSON", "off"),
    ];

    let saved: Vec<(String, Option<String>)> = cases
        .iter()
        .map(|(k, _)| (k.to_string(), std::env::var(k).ok()))
        .collect();
    for (k, v) in cases {
        std::env::set_var(k, v);
    }

    let cli = Cli::try_parse_from(["socket-patch", "list"]).expect("parse");
    if let socket_patch_cli::Commands::List(args) = cli.command {
        assert!(!args.common.offline);
        assert!(!args.common.debug);
        assert!(!args.common.no_telemetry);
        assert!(!args.common.json);
    } else {
        panic!("expected List");
    }

    for (k, orig) in saved {
        match orig {
            Some(v) => std::env::set_var(&k, v),
            None => std::env::remove_var(&k),
        }
    }
}

/// Names of every `SOCKET_*` env var that `GlobalArgs` binds, so tests that
/// need a clean slate can save/clear/restore them in one place.
const GLOBAL_ENV_VARS: &[&str] = &[
    "SOCKET_CWD",
    "SOCKET_MANIFEST_PATH",
    "SOCKET_API_URL",
    "SOCKET_API_TOKEN",
    "SOCKET_ORG_SLUG",
    "SOCKET_PROXY_URL",
    "SOCKET_ECOSYSTEMS",
    "SOCKET_DOWNLOAD_MODE",
    "SOCKET_OFFLINE",
    "SOCKET_GLOBAL",
    "SOCKET_GLOBAL_PREFIX",
    "SOCKET_JSON",
    "SOCKET_VERBOSE",
    "SOCKET_SILENT",
    "SOCKET_DRY_RUN",
    "SOCKET_YES",
    "SOCKET_LOCK_TIMEOUT",
    "SOCKET_BREAK_LOCK",
    "SOCKET_DEBUG",
    "SOCKET_TELEMETRY_DISABLED",
];

fn save_and_clear_global_env() -> Vec<(&'static str, Option<String>)> {
    let saved: Vec<(&'static str, Option<String>)> = GLOBAL_ENV_VARS
        .iter()
        .map(|&k| (k, std::env::var(k).ok()))
        .collect();
    for &k in GLOBAL_ENV_VARS {
        std::env::remove_var(k);
    }
    saved
}

fn restore_global_env(saved: Vec<(&'static str, Option<String>)>) {
    for (k, orig) in saved {
        match orig {
            Some(v) => std::env::set_var(k, v),
            None => std::env::remove_var(k),
        }
    }
}

/// Regression for the documented precedence (`CLI arg > env var > default`,
/// see the module header in `args.rs`): when both a CLI flag and its env var
/// are set, the CLI value must win. Covers a string field (`--api-url`) and a
/// bool field set on the CLI while the env says falsey. Env-only resolution is
/// asserted too so we know the env var really was live.
#[test]
#[serial_test::serial]
fn cli_arg_overrides_env_var() {
    let saved = save_and_clear_global_env();

    // String field: env set, CLI overrides.
    std::env::set_var("SOCKET_API_URL", "https://env-api.example.com");
    let cli = Cli::try_parse_from([
        "socket-patch",
        "list",
        "--api-url",
        "https://cli-api.example.com",
    ])
    .expect("parse");
    let socket_patch_cli::Commands::List(args) = cli.command else {
        panic!("expected List");
    };
    assert_eq!(
        args.common.api_url, "https://cli-api.example.com",
        "CLI --api-url must override SOCKET_API_URL"
    );

    // Sanity: with the CLI flag absent, the env value resolves through.
    let cli = Cli::try_parse_from(["socket-patch", "list"]).expect("parse");
    let socket_patch_cli::Commands::List(args) = cli.command else {
        panic!("expected List");
    };
    assert_eq!(
        args.common.api_url, "https://env-api.example.com",
        "with no CLI flag the env var must resolve through"
    );

    // Bool field: CLI `--offline` wins over a falsey env value.
    std::env::set_var("SOCKET_OFFLINE", "0");
    let cli = Cli::try_parse_from(["socket-patch", "list", "--offline"]).expect("parse");
    let socket_patch_cli::Commands::List(args) = cli.command else {
        panic!("expected List");
    };
    assert!(
        args.common.offline,
        "CLI --offline must win over SOCKET_OFFLINE=0"
    );

    restore_global_env(saved);
}

/// Regression: with neither CLI flags nor env vars set, clap must populate the
/// documented production defaults (the `default_value = ".."` attributes). This
/// is the production path that `GlobalArgs::default()` deliberately does *not*
/// mirror for `api_url`/`proxy_url`, so it needs its own coverage — and
/// `api_client_overrides()` must therefore forward those concrete URLs.
#[test]
#[serial_test::serial]
fn production_defaults_populate_when_unset() {
    let saved = save_and_clear_global_env();

    let cli = Cli::try_parse_from(["socket-patch", "list"]).expect("parse");
    let socket_patch_cli::Commands::List(args) = cli.command else {
        panic!("expected List");
    };
    let c = &args.common;
    assert_eq!(c.cwd, std::path::PathBuf::from("."));
    assert_eq!(c.manifest_path, ".socket/manifest.json");
    assert_eq!(c.api_url, "https://api.socket.dev");
    assert_eq!(c.proxy_url, "https://patches-api.socket.dev");
    assert_eq!(c.download_mode, "diff");
    assert!(c.api_token.is_none());
    assert!(c.org.is_none());
    assert!(c.ecosystems.is_none());
    assert!(!c.offline && !c.global && !c.json && !c.verbose && !c.silent);
    assert!(!c.dry_run && !c.yes && !c.break_lock && !c.debug && !c.no_telemetry);
    assert!(c.lock_timeout.is_none());
    assert!(c.global_prefix.is_none());

    // On the production path (unlike GlobalArgs::default()) the URLs are
    // non-empty, so api_client_overrides must forward them.
    let o = c.api_client_overrides();
    assert_eq!(o.api_url.as_deref(), Some("https://api.socket.dev"));
    assert_eq!(o.proxy_url.as_deref(), Some("https://patches-api.socket.dev"));
    assert!(o.api_token.is_none());
    assert!(o.org_slug.is_none());

    restore_global_env(saved);
}