tsafe-cli 1.0.21

tsafe CLI — local secret and credential manager (replaces .env files)
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
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
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
//! Shell plugin command handler — `tsafe plugin <tool> [args...]`
//!
//! Provides tool-aware secret injection: instead of remembering which vault
//! keys each tool needs, `tsafe plugin gh` automatically maps vault keys to
//! the environment variable names expected by the `gh` CLI.
//!
//! Each plugin entry is a static mapping of vault-key → env-var-name.
//! Keys that are missing from the vault are reported as warnings (not errors)
//! unless marked as required, in which case the plugin aborts.
//!
//! Registry entries (loaded from an operator-maintained TOML file when
//! `TSAFE_PLUGIN_REGISTRY` is set) are command launchers only: they invoke
//! the specified binary with no vault interaction. See ADR-031.
//!
//! # Trust model (ADR-025, ADR-031)
//!
//! Five invariants are enforced by construction in this module:
//!
//! **D1 — Static-only extension for built-ins:** built-in plugin entries live
//! in the compile-time `PLUGINS` constant. The registry-file path (ADR-031)
//! extends the preset list without dynamic loading: the operator writes the
//! file, the file IS the trust list.
//!
//! **D2 — Authority ceiling:** only keys declared in `plugin.keys` are ever
//! read from the vault. Registry entries carry no key declarations and
//! therefore inject no vault secrets.
//!
//! **D3 — Vault-drop-before-spawn:** `drop(vault)` is called after key
//! collection and before subprocess spawn. See the marked `// TRUST: D3` site.
//!
//! **D4 — Ambient env-var strip:** `command_with_secrets_and_extra_strips`
//! removes all declared plugin env-var names from the inherited parent
//! environment before applying vault-sourced overrides. Does not apply to
//! registry entries (no declared env-var names).
//!
//! **D6 — Audit scope:** the audit entry records the tool name only, not the
//! injected key names.
//!
//! # Failure semantics (ADR-026)
//!
//! Pre-spawn failures exit 1 with a clear stderr message. Post-spawn failures
//! propagate the subprocess exit code verbatim. See the ADR for the full table.

use std::collections::HashMap;

use anyhow::{bail, Result};
use colored::Colorize;
use tsafe_core::{audit::AuditEntry, env as tsenv};

use crate::helpers::*;

/// One vault key → environment variable mapping within a built-in plugin.
struct KeyMap {
    /// Key name as stored in the vault (may include a namespace prefix).
    vault_key: &'static str,
    /// Environment variable name the tool expects.
    env_var: &'static str,
    /// Whether to abort if this key is absent from the vault.
    required: bool,
}

/// Built-in plugin definition: the tool's binary name and the list of key mappings.
struct Plugin {
    /// Human-readable tool name (same as the CLI subcommand, e.g. "gh").
    name: &'static str,
    /// Binary to invoke (usually the same as `name`).
    binary: &'static str,
    /// Vault key → env var mappings.
    keys: &'static [KeyMap],
    /// Short description shown in the plugin list.
    description: &'static str,
}

const PLUGINS: &[Plugin] = &[
    Plugin {
        name: "gh",
        binary: "gh",
        description: "GitHub CLI — injects GH_TOKEN",
        keys: &[
            KeyMap {
                vault_key: "GH_TOKEN",
                env_var: "GH_TOKEN",
                required: false,
            },
            KeyMap {
                vault_key: "GITHUB_TOKEN",
                env_var: "GITHUB_TOKEN",
                required: false,
            },
        ],
    },
    Plugin {
        name: "aws",
        binary: "aws",
        description: "AWS CLI — injects AWS_ACCESS_KEY_ID / SECRET / REGION",
        keys: &[
            KeyMap {
                vault_key: "AWS_ACCESS_KEY_ID",
                env_var: "AWS_ACCESS_KEY_ID",
                required: true,
            },
            KeyMap {
                vault_key: "AWS_SECRET_ACCESS_KEY",
                env_var: "AWS_SECRET_ACCESS_KEY",
                required: true,
            },
            KeyMap {
                vault_key: "AWS_DEFAULT_REGION",
                env_var: "AWS_DEFAULT_REGION",
                required: false,
            },
            KeyMap {
                vault_key: "AWS_SESSION_TOKEN",
                env_var: "AWS_SESSION_TOKEN",
                required: false,
            },
        ],
    },
    Plugin {
        name: "az",
        binary: "az",
        description: "Azure CLI — injects AZURE_CLIENT_ID / SECRET / TENANT",
        keys: &[
            KeyMap {
                vault_key: "AZURE_CLIENT_ID",
                env_var: "AZURE_CLIENT_ID",
                required: false,
            },
            KeyMap {
                vault_key: "AZURE_CLIENT_SECRET",
                env_var: "AZURE_CLIENT_SECRET",
                required: false,
            },
            KeyMap {
                vault_key: "AZURE_TENANT_ID",
                env_var: "AZURE_TENANT_ID",
                required: false,
            },
            KeyMap {
                vault_key: "AZURE_SUBSCRIPTION_ID",
                env_var: "AZURE_SUBSCRIPTION_ID",
                required: false,
            },
        ],
    },
    Plugin {
        name: "docker",
        binary: "docker",
        description: "Docker CLI — injects DOCKER_USERNAME / DOCKER_PASSWORD",
        keys: &[
            KeyMap {
                vault_key: "DOCKER_USERNAME",
                env_var: "DOCKER_USERNAME",
                required: false,
            },
            KeyMap {
                vault_key: "DOCKER_PASSWORD",
                env_var: "DOCKER_PASSWORD",
                required: false,
            },
            KeyMap {
                vault_key: "DOCKER_TOKEN",
                env_var: "DOCKER_TOKEN",
                required: false,
            },
        ],
    },
    Plugin {
        name: "npm",
        binary: "npm",
        description: "npm / pnpm / yarn — injects NPM_TOKEN",
        keys: &[KeyMap {
            vault_key: "NPM_TOKEN",
            env_var: "NPM_TOKEN",
            required: false,
        }],
    },
    Plugin {
        name: "pypi",
        binary: "twine",
        description: "PyPI publish (twine) — injects TWINE_USERNAME / TWINE_PASSWORD",
        keys: &[
            KeyMap {
                vault_key: "PYPI_TOKEN",
                env_var: "TWINE_PASSWORD",
                required: false,
            },
            KeyMap {
                vault_key: "TWINE_USERNAME",
                env_var: "TWINE_USERNAME",
                required: false,
            },
        ],
    },
    Plugin {
        name: "terraform",
        binary: "terraform",
        description: "Terraform — injects TF_TOKEN_* and cloud provider vars",
        keys: &[
            KeyMap {
                vault_key: "TF_TOKEN_app_terraform_io",
                env_var: "TF_TOKEN_app_terraform_io",
                required: false,
            },
            KeyMap {
                vault_key: "ARM_CLIENT_ID",
                env_var: "ARM_CLIENT_ID",
                required: false,
            },
            KeyMap {
                vault_key: "ARM_CLIENT_SECRET",
                env_var: "ARM_CLIENT_SECRET",
                required: false,
            },
            KeyMap {
                vault_key: "ARM_TENANT_ID",
                env_var: "ARM_TENANT_ID",
                required: false,
            },
            KeyMap {
                vault_key: "ARM_SUBSCRIPTION_ID",
                env_var: "ARM_SUBSCRIPTION_ID",
                required: false,
            },
        ],
    },
];

// ── Registry file support (ADR-031) ────────────────────────────────────────

/// A registry entry loaded from the operator-maintained TOML registry file.
///
/// Registry entries are command launchers only: they invoke the named binary
/// with no vault interaction. This is a deliberate authority scope reduction
/// relative to the static built-in entries, which carry vault key mappings.
#[derive(Debug, Clone)]
pub(crate) struct RegistryEntry {
    /// Subcommand name (`tsafe plugin <name>`).
    pub(crate) name: String,
    /// Binary path or name. Not executed at load time — stored verbatim.
    pub(crate) command: String,
    /// Optional short description shown in `tsafe plugin list`.
    pub(crate) description: Option<String>,
    /// Optional arguments prepended to any user-supplied args.
    pub(crate) args: Vec<String>,
    /// Optional informational URL shown in `tsafe plugin list`.
    pub(crate) url: Option<String>,
}

/// Deserializable raw TOML shape for a single registry entry.
///
/// Uses `serde` to parse the TOML; fields that fail validation are caught in
/// `load_registry_plugins` before a `RegistryEntry` is constructed.
#[cfg(feature = "plugins")]
#[derive(serde::Deserialize)]
struct RawRegistryEntry {
    name: Option<String>,
    command: Option<String>,
    description: Option<String>,
    args: Option<Vec<String>>,
    url: Option<String>,
}

/// Top-level TOML document shape: `[[plugins]]` array.
#[cfg(feature = "plugins")]
#[derive(serde::Deserialize)]
struct RegistryFile {
    #[serde(default)]
    plugins: Vec<RawRegistryEntry>,
}

/// Load registry entries from the file at `TSAFE_PLUGIN_REGISTRY`.
///
/// Returns `Ok(vec![])` when the env var is not set (opt-in only).
/// Returns `Err(...)` when the env var is set but the file cannot be read or
/// is not valid TOML — callers must propagate this as a non-zero exit.
///
/// Individual entries that are missing required fields are skipped with a
/// warning; the rest of the file continues to load.
///
/// # Trust invariants (ADR-031)
/// - No network fetch at any point.
/// - The `command` field is stored as a string; the binary is not executed here.
/// - No dynamic library loading occurs.
#[cfg(feature = "plugins")]
pub(crate) fn load_registry_plugins() -> Result<Vec<RegistryEntry>> {
    let path = match std::env::var("TSAFE_PLUGIN_REGISTRY") {
        Ok(p) if !p.is_empty() => p,
        _ => return Ok(Vec::new()),
    };

    let raw = std::fs::read_to_string(&path)
        .map_err(|e| anyhow::anyhow!("tsafe: plugin registry: cannot read '{path}': {e}"))?;

    let doc: RegistryFile = toml::from_str(&raw).map_err(|e| {
        anyhow::anyhow!("tsafe: plugin registry: TOML parse error in '{path}': {e}")
    })?;

    let mut entries = Vec::with_capacity(doc.plugins.len());
    for raw_entry in doc.plugins {
        let name = match raw_entry.name {
            Some(n) if !n.is_empty() => n,
            _ => {
                eprintln!("tsafe: plugin registry: skipping entry with missing 'name' field");
                continue;
            }
        };
        let command = match raw_entry.command {
            Some(c) if !c.is_empty() => c,
            _ => {
                eprintln!(
                    "tsafe: plugin registry: skipping entry '{name}' with missing 'command' field"
                );
                continue;
            }
        };
        entries.push(RegistryEntry {
            name,
            command,
            description: raw_entry.description,
            args: raw_entry.args.unwrap_or_default(),
            url: raw_entry.url,
        });
    }

    Ok(entries)
}

// ── Plugin resolution ───────────────────────────────────────────────────────

fn find_builtin(name: &str) -> Option<&'static Plugin> {
    PLUGINS.iter().find(|p| p.name == name)
}

/// The resolved kind of a plugin lookup.
enum ResolvedPlugin<'a> {
    BuiltIn(&'a Plugin),
    #[cfg(feature = "plugins")]
    Registry(RegistryEntry),
}

// ── List formatting ─────────────────────────────────────────────────────────

/// Build the plugin list header that is common to both the plain and registry
/// variants. Returns the opening body and appends the usage footer when
/// `include_footer` is true.
fn builtin_list_lines() -> String {
    let mut out = String::from("This build includes these plugin launchers:\n\n");
    for p in PLUGINS {
        out.push_str(&format!("  {:<12} {} [built-in]\n", p.name, p.description));
    }
    out
}

fn append_list_footer(out: &mut String) {
    out.push_str("\nUsage:\n");
    out.push_str("  tsafe plugin list\n");
    out.push_str("  tsafe plugin <name> [tool args...]\n");
    out.push_str("  tsafe plugin <name> --help\n");
}

// Used by `print_plugin_list()` when the `plugins` feature is off, and by
// unit tests in both configurations.
#[cfg_attr(feature = "plugins", allow(dead_code))]
fn plugin_list_text_builtin_only() -> String {
    let mut out = builtin_list_lines();
    append_list_footer(&mut out);
    out
}

#[cfg(feature = "plugins")]
fn plugin_list_text_with_registry(registry: &[RegistryEntry]) -> String {
    let mut out = builtin_list_lines();
    for r in registry {
        let desc = r.description.as_deref().unwrap_or("");
        out.push_str(&format!("  {:<12} {} [registry]\n", r.name, desc));
        if let Some(ref u) = r.url {
            out.push_str(&format!("  {:<12}   {}\n", "", u));
        }
    }
    append_list_footer(&mut out);
    out
}

/// List available plugins to stdout.
#[cfg(not(feature = "plugins"))]
fn print_plugin_list() {
    print!("{}", plugin_list_text_builtin_only().cyan());
}

#[cfg(feature = "plugins")]
fn print_plugin_list(registry: &[RegistryEntry]) {
    print!("{}", plugin_list_text_with_registry(registry).cyan());
}

// ── Command entry point ─────────────────────────────────────────────────────

#[cfg(not(feature = "plugins"))]
pub(crate) fn cmd_plugin(profile: &str, tool: Option<&str>, args: &[String]) -> Result<()> {
    let tool_name = match tool {
        None => {
            print_plugin_list();
            return Ok(());
        }
        Some(t) if t == "--list" || t == "list" => {
            print_plugin_list();
            return Ok(());
        }
        Some(t) => t,
    };

    let plugin = match find_builtin(tool_name) {
        Some(p) => p,
        None => {
            bail!("unknown plugin '{tool_name}'. Run `tsafe plugin` to list available plugins.");
        }
    };

    run_builtin_plugin(profile, plugin, args)
}

#[cfg(feature = "plugins")]
pub(crate) fn cmd_plugin(profile: &str, tool: Option<&str>, args: &[String]) -> Result<()> {
    // Load registry entries first so the list command can include them.
    let raw_registry = match load_registry_plugins() {
        Ok(entries) => entries,
        Err(e) => {
            eprintln!("{} {e}", "error:".red());
            // Static plugins still list even on registry error — but if the
            // operator set TSAFE_PLUGIN_REGISTRY and the file is broken, we
            // exit non-zero to surface the misconfiguration clearly.
            std::process::exit(1);
        }
    };

    // Filter out registry entries whose name conflicts with a built-in.
    // Static entries win; emit a warning for each conflict (ADR-031 invariant 5).
    let registry: Vec<RegistryEntry> = raw_registry
        .into_iter()
        .filter(|entry| {
            if find_builtin(&entry.name).is_some() {
                eprintln!(
                    "{} registry entry '{}' conflicts with a built-in static entry; \
                     built-in wins (ADR-031)",
                    "warn:".yellow(),
                    entry.name,
                );
                false
            } else {
                true
            }
        })
        .collect();

    let tool_name = match tool {
        None => {
            print_plugin_list(&registry);
            return Ok(());
        }
        Some(t) if t == "--list" || t == "list" => {
            print_plugin_list(&registry);
            return Ok(());
        }
        Some(t) => t,
    };

    // Resolve the requested tool name. Static entries win (already enforced by
    // the filter above, which removed conflicting registry entries).
    let resolved = if let Some(p) = find_builtin(tool_name) {
        ResolvedPlugin::BuiltIn(p)
    } else if let Some(r) = registry.into_iter().find(|e| e.name == tool_name) {
        ResolvedPlugin::Registry(r)
    } else {
        bail!("unknown plugin '{tool_name}'. Run `tsafe plugin` to list available plugins.");
    };

    match resolved {
        ResolvedPlugin::BuiltIn(p) => run_builtin_plugin(profile, p, args),
        ResolvedPlugin::Registry(r) => run_registry_plugin(profile, &r, args),
    }
}

// ── Built-in plugin execution ───────────────────────────────────────────────

/// Execute a built-in plugin with vault key injection per ADR-025/ADR-026.
fn run_builtin_plugin(profile: &str, plugin: &Plugin, args: &[String]) -> Result<()> {
    // Open vault and collect mapped env vars.
    //
    // TRUST: D2 — authority ceiling (ADR-025 §D2).
    // Only keys declared in `plugin.keys` are iterated here. The vault is never
    // queried for keys outside this static declaration. This ensures the plugin
    // cannot inject more vault content than its build-time declaration allows.
    let vault = open_vault(profile)?;
    let mut env_overrides: Vec<(String, String)> = Vec::new();
    let mut missing_required: Vec<&str> = Vec::new();

    for km in plugin.keys {
        match vault.get(km.vault_key) {
            Ok(val) => {
                env_overrides.push((km.env_var.to_string(), val.to_string()));
            }
            Err(_) => {
                if km.required {
                    missing_required.push(km.vault_key);
                }
                // Optional missing keys are silently skipped.
            }
        }
    }

    if !missing_required.is_empty() {
        bail!(
            "plugin '{}' requires vault keys that are missing: {}\n\
             Hint: tsafe set {} <value>",
            plugin.name,
            missing_required.join(", "),
            missing_required[0],
        );
    }

    if env_overrides.is_empty() {
        eprintln!(
            "{} no matching vault keys found for plugin '{}'; running {} without extra env vars",
            "warn:".yellow(),
            plugin.name,
            plugin.binary,
        );
    }

    // TRUST: D3 — vault-drop-before-spawn guarantee (ADR-025 §D3).
    // Drop the vault handle (and any in-memory decrypted values) before the
    // subprocess is spawned. This releases the advisory lock and limits how
    // long decrypted key material lives in the tsafe process after use.
    drop(vault);

    // TRUST RESIDUAL: D5 — PATH-lookup binary verification (ADR-025 §D5).
    // We resolve the binary via PATH scan but do not verify its signature or
    // integrity. An attacker who controls PATH before tsafe runs could substitute
    // a malicious binary. This residual is accepted for v1; operators who need
    // PATH-integrity guarantees should use container entrypoints or absolute
    // binary paths via process wrappers.
    let binary = which_binary(plugin.binary).unwrap_or_else(|| plugin.binary.to_string());
    let plugin_env_names: Vec<String> = plugin
        .keys
        .iter()
        .map(|mapping| mapping.env_var.to_string())
        .collect();
    let mut command = build_plugin_command(&binary, args, &plugin_env_names, &env_overrides)?;

    let status = command
        .status()
        .map_err(|e| anyhow::anyhow!("failed to run '{binary}': {e}"))?;

    let exit_code = status.code().unwrap_or(1);
    // TRUST: D6 — audit scope (ADR-025 §D6, ADR-026).
    // The audit entry records the tool name only. Injected key names are not
    // recorded so that audit-log exfiltration does not reveal the shape of
    // the operator's vault. The static PLUGINS table maps tool names to their
    // declared keys for any reviewer who needs that mapping.
    if exit_code == 0 {
        audit(profile)
            .append(&AuditEntry::success(profile, "plugin", Some(plugin.name)))
            .ok();
    } else {
        audit(profile)
            .append(&AuditEntry::failure(
                profile,
                "plugin",
                Some(plugin.name),
                &format!("exited with code {exit_code}"),
            ))
            .ok();
    }

    std::process::exit(exit_code);
}

// ── Registry plugin execution ───────────────────────────────────────────────

/// Execute a registry entry as a bare command launcher (no vault interaction).
///
/// Registry entries carry no vault key mappings (ADR-031 §authority-scope).
/// The binary is invoked directly with the declared args prepended to any
/// user-supplied args. No vault is opened; no env vars are stripped or injected.
#[cfg(feature = "plugins")]
fn run_registry_plugin(profile: &str, entry: &RegistryEntry, user_args: &[String]) -> Result<()> {
    // Prepend declared args then append user args.
    let all_args: Vec<String> = entry
        .args
        .iter()
        .cloned()
        .chain(user_args.iter().cloned())
        .collect();

    let binary = which_binary(&entry.command).unwrap_or_else(|| entry.command.clone());

    let mut cmd = std::process::Command::new(&binary);
    cmd.args(&all_args);

    let status = cmd
        .status()
        .map_err(|e| anyhow::anyhow!("failed to run '{}': {e}", entry.command))?;

    let exit_code = status.code().unwrap_or(1);

    if exit_code == 0 {
        audit(profile)
            .append(&AuditEntry::success(profile, "plugin", Some(&entry.name)))
            .ok();
    } else {
        audit(profile)
            .append(&AuditEntry::failure(
                profile,
                "plugin",
                Some(&entry.name),
                &format!("exited with code {exit_code}"),
            ))
            .ok();
    }

    std::process::exit(exit_code);
}

// ── Command builder ─────────────────────────────────────────────────────────

fn build_plugin_command(
    binary: &str,
    args: &[String],
    plugin_env_names: &[String],
    env_overrides: &[(String, String)],
) -> Result<std::process::Command> {
    let cmd_parts: Vec<String> = std::iter::once(binary.to_string())
        .chain(args.iter().cloned())
        .collect();
    let secrets: HashMap<String, String> = env_overrides.iter().cloned().collect();
    tsenv::command_with_secrets_and_extra_strips(&secrets, plugin_env_names, &cmd_parts)
        .map_err(|e| anyhow::anyhow!("{e}"))
}

/// Find the full path to a binary on PATH, falling back to the name itself.
fn which_binary(name: &str) -> Option<String> {
    std::env::var_os("PATH").and_then(|path| {
        std::env::split_paths(&path).find_map(|dir| {
            let candidate = dir.join(name);
            if candidate.is_file() {
                candidate.to_str().map(|s| s.to_string())
            } else {
                None
            }
        })
    })
}

// ── Unit tests ──────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn plugin_list_text_is_build_local_and_command_local() {
        let help = plugin_list_text_builtin_only();

        assert!(help.contains("This build includes these plugin launchers:"));
        assert!(help.contains("tsafe plugin list"));
        assert!(help.contains("tsafe plugin <name> --help"));
        assert!(!help.contains("tsafe plugin gh repo list"));
        assert!(!help.contains("tsafe plugin aws s3 ls --bucket my-bucket"));
    }

    #[test]
    fn builtin_entries_tagged_in_list() {
        let help = plugin_list_text_builtin_only();
        assert!(help.contains("[built-in]"));
    }

    #[test]
    fn build_plugin_command_strips_sensitive_parent_env_and_applies_overrides() {
        temp_env::with_vars(
            [
                (
                    "GITHUB_TOKEN",
                    Some(std::ffi::OsStr::new("ambient-gh-token")),
                ),
                (
                    "AZURE_CLIENT_SECRET",
                    Some(std::ffi::OsStr::new("ambient-azure-secret")),
                ),
            ],
            || {
                let env_overrides = vec![
                    ("GH_TOKEN".to_string(), "vault-gh-token".to_string()),
                    ("AWS_DEFAULT_REGION".to_string(), "eu-west-2".to_string()),
                ];
                let plugin_env_names = vec![
                    "GH_TOKEN".to_string(),
                    "GITHUB_TOKEN".to_string(),
                    "DOCKER_PASSWORD".to_string(),
                ];
                let command = build_plugin_command(
                    "echo",
                    &["hello".to_string()],
                    &plugin_env_names,
                    &env_overrides,
                )
                .unwrap();

                let envs: HashMap<String, Option<String>> = command
                    .get_envs()
                    .map(|(key, value)| {
                        (
                            key.to_string_lossy().into_owned(),
                            value.map(|item| item.to_string_lossy().into_owned()),
                        )
                    })
                    .collect();

                assert_eq!(envs.get("GH_TOKEN"), Some(&Some("vault-gh-token".into())));
                assert_eq!(
                    envs.get("AWS_DEFAULT_REGION"),
                    Some(&Some("eu-west-2".into()))
                );
                assert_eq!(envs.get("GITHUB_TOKEN"), Some(&None));
                assert_eq!(envs.get("AZURE_CLIENT_SECRET"), Some(&None));
                assert_eq!(envs.get("DOCKER_PASSWORD"), Some(&None));
            },
        );
    }

    // ── Registry loading unit tests (ADR-031 adversarial proof) ────────────

    #[cfg(feature = "plugins")]
    mod registry_tests {
        use super::*;
        use std::io::Write;

        fn write_registry(content: &str) -> tempfile::NamedTempFile {
            let mut f = tempfile::NamedTempFile::new().unwrap();
            f.write_all(content.as_bytes()).unwrap();
            f
        }

        /// ADR-031 adversarial proof E5.3-1: a "forged" registry entry that
        /// attempts a shell injection in its `command` field. The entry must be
        /// stored verbatim in memory without being executed at parse/load time.
        ///
        /// The test confirms:
        ///  - load succeeds (no panic, no process spawn)
        ///  - `entry.command` contains the literal malicious string
        ///  - no side effects occurred (which would be observable if the
        ///    command ran — there is no process-launch call in `load_registry_plugins`)
        #[test]
        fn registry_file_forgery_attempt_command_stored_not_executed() {
            let malicious_command = "/bin/sh -c 'rm -rf /'";
            let toml = format!("[[plugins]]\nname = \"evil\"\ncommand = {malicious_command:?}\n");
            let f = write_registry(&toml);

            temp_env::with_var(
                "TSAFE_PLUGIN_REGISTRY",
                Some(f.path().to_str().unwrap()),
                || {
                    let entries = load_registry_plugins().expect("load must succeed");
                    assert_eq!(entries.len(), 1, "one entry must be loaded");
                    let entry = &entries[0];
                    // The command is stored literally — no execution, no side effects.
                    assert_eq!(entry.command, malicious_command);
                    // Name is preserved.
                    assert_eq!(entry.name, "evil");
                    // If we reached here without side effects, no code was executed.
                },
            );
        }

        /// ADR-031 proof E5.3-2: an entry missing the `command` field is
        /// skipped with a warning; other valid entries in the same file load.
        #[test]
        fn missing_required_field_command_skips_entry_others_load() {
            let toml = r#"
[[plugins]]
name = "bad-entry"
# command is intentionally missing

[[plugins]]
name = "good-entry"
command = "/usr/local/bin/good"
"#;
            let f = write_registry(toml);

            temp_env::with_var(
                "TSAFE_PLUGIN_REGISTRY",
                Some(f.path().to_str().unwrap()),
                || {
                    let entries = load_registry_plugins().expect("load must succeed");
                    // The bad entry is skipped; the good entry loads.
                    assert_eq!(entries.len(), 1, "only one valid entry should load");
                    assert_eq!(entries[0].name, "good-entry");
                },
            );
        }

        /// ADR-031 proof E5.3-2 variant: entry missing the `name` field is skipped.
        #[test]
        fn missing_required_field_name_skips_entry() {
            let toml = r#"
[[plugins]]
command = "/usr/local/bin/nameless"
# name is intentionally missing

[[plugins]]
name = "ok-entry"
command = "/usr/local/bin/ok"
"#;
            let f = write_registry(toml);

            temp_env::with_var(
                "TSAFE_PLUGIN_REGISTRY",
                Some(f.path().to_str().unwrap()),
                || {
                    let entries = load_registry_plugins().expect("load must succeed");
                    assert_eq!(entries.len(), 1);
                    assert_eq!(entries[0].name, "ok-entry");
                },
            );
        }

        /// ADR-031 proof E5.3-3: when `TSAFE_PLUGIN_REGISTRY` points to a
        /// non-existent file, `load_registry_plugins` returns an `Err`.
        /// The caller exits non-zero; static plugins still list (tested via
        /// integration test).
        #[test]
        fn missing_registry_file_returns_error() {
            temp_env::with_var(
                "TSAFE_PLUGIN_REGISTRY",
                Some("/nonexistent/path/plugins.toml"),
                || {
                    let result = load_registry_plugins();
                    assert!(result.is_err(), "missing file must return Err");
                    let msg = result.unwrap_err().to_string();
                    assert!(
                        msg.contains("plugin registry"),
                        "error must mention 'plugin registry'; got: {msg}"
                    );
                },
            );
        }

        /// ADR-031 proof E5.3-4: when a registry entry has the same `name` as
        /// a built-in static entry, the static entry wins. This is enforced in
        /// `cmd_plugin` by checking `find_builtin` first, but we can prove the
        /// registry still loads the entry (it is present in the list; the
        /// conflict resolution happens at lookup time in cmd_plugin).
        ///
        /// The registry loader itself stores the entry; the caller (cmd_plugin)
        /// performs deduplication so static entries win.
        #[test]
        fn name_conflict_registry_entry_loads_but_static_wins_at_lookup() {
            // "gh" is a static built-in.
            let toml = r#"
[[plugins]]
name = "gh"
command = "/attacker/fake-gh"
"#;
            let f = write_registry(toml);

            temp_env::with_var(
                "TSAFE_PLUGIN_REGISTRY",
                Some(f.path().to_str().unwrap()),
                || {
                    let entries = load_registry_plugins().expect("load must succeed");
                    // The registry entry loads (it is in the list).
                    assert_eq!(entries.len(), 1);
                    assert_eq!(entries[0].name, "gh");

                    // But find_builtin("gh") returns the static entry first —
                    // cmd_plugin calls find_builtin before scanning registry.
                    let builtin = find_builtin("gh");
                    assert!(builtin.is_some(), "static 'gh' must still be found");
                    // The static entry's binary is "gh", not "/attacker/fake-gh".
                    assert_eq!(builtin.unwrap().binary, "gh");
                },
            );
        }

        /// Optional fields load correctly when present.
        #[test]
        fn optional_fields_are_loaded() {
            let toml = r#"
[[plugins]]
name = "full-entry"
command = "/usr/local/bin/full"
description = "A fully specified entry"
args = ["--mode", "safe"]
url = "https://example.com/full"
"#;
            let f = write_registry(toml);

            temp_env::with_var(
                "TSAFE_PLUGIN_REGISTRY",
                Some(f.path().to_str().unwrap()),
                || {
                    let entries = load_registry_plugins().expect("load must succeed");
                    assert_eq!(entries.len(), 1);
                    let e = &entries[0];
                    assert_eq!(e.description.as_deref(), Some("A fully specified entry"));
                    assert_eq!(e.args, vec!["--mode", "safe"]);
                    assert_eq!(e.url.as_deref(), Some("https://example.com/full"));
                },
            );
        }

        /// When `TSAFE_PLUGIN_REGISTRY` is unset, loading returns an empty vec
        /// without error (opt-in only; no implicit path).
        #[test]
        fn no_registry_env_var_returns_empty() {
            temp_env::with_var("TSAFE_PLUGIN_REGISTRY", None::<&str>, || {
                let entries = load_registry_plugins().expect("must succeed when var is unset");
                assert!(
                    entries.is_empty(),
                    "no implicit registry path should be searched"
                );
            });
        }

        /// `[registry]` tag appears in plugin list when registry entries are present.
        #[test]
        fn registry_entries_tagged_in_list() {
            let registry = vec![RegistryEntry {
                name: "my-tool".to_string(),
                command: "/usr/local/bin/my-tool".to_string(),
                description: Some("Test tool".to_string()),
                args: vec![],
                url: None,
            }];
            let text = plugin_list_text_with_registry(&registry);
            assert!(text.contains("[registry]"));
            assert!(text.contains("[built-in]"));
            assert!(text.contains("my-tool"));
        }
    }
}