tsafe-cli 1.0.26

Secrets runtime for developers — inject credentials into processes via exec, never into shell history or .env files
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
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
pub mod cli;
pub mod explain;
pub mod manpages;
pub mod providers;
#[cfg(feature = "cloud-pull-aws")]
pub use providers::aws as tsafe_aws;
#[cfg(feature = "cloud-pull-gcp")]
pub use providers::gcp as tsafe_gcp;
#[cfg(feature = "cloud-pull-vault")]
pub use providers::hcp as tsafe_hcp;
#[cfg(feature = "cloud-pull-keepass")]
pub use providers::keepass as tsafe_keepass;
#[cfg(feature = "cloud-pull-1password")]
pub use providers::onepassword as tsafe_op;

// Re-export the 1Password field-label normalisation function so that
// integration tests can verify the mapping contract without shelling out
// to `op`.
#[cfg(any(feature = "cloud-pull-1password", feature = "cloud-pull-vault", test))]
pub use op_mapping::op_field_label_to_key;

// Always-compiled module that holds the pure mapping logic so it is
// available for `#[cfg(test)]` regardless of feature flags.
pub mod op_mapping {
    /// Normalise a 1Password field label to an env-style vault key.
    ///
    /// Rule: spaces and hyphens → underscores, then uppercase.
    /// The 1Password item name is **not** included in the output key.
    ///
    /// Examples:
    /// - `"My Secret"` → `"MY_SECRET"`
    /// - `"db-password"` → `"DB_PASSWORD"`
    /// - `"API_KEY"` → `"API_KEY"`
    pub fn op_field_label_to_key(label: &str) -> String {
        label.replace([' ', '-'], "_").to_uppercase()
    }
}

// ── Sub-command modules ───────────────────────────────────────────────────────
// Declared here (lib root) so both the binary's main.rs and the meta-crate
// shim can reach them through the library crate.

#[cfg(feature = "agent")]
mod cmd_agent;
mod cmd_alias;
mod cmd_audit_cmd;
#[cfg(feature = "cloud-pull-aws")]
mod cmd_aws_pull;
#[cfg(feature = "cloud-pull-aws")]
mod cmd_aws_push;
#[cfg(feature = "biometric")]
mod cmd_biometric;
#[cfg(feature = "cloud-pull-bitwarden")]
mod cmd_bitwarden_pull;
#[cfg(feature = "nativehost")]
mod cmd_browser_native_host;
#[cfg(feature = "browser")]
mod cmd_browser_profile;
#[cfg(feature = "collab")]
mod cmd_collab;
mod cmd_config_cmd;
#[cfg(feature = "git-helpers")]
mod cmd_credential_helper;
mod cmd_diff;
mod cmd_doctor;
mod cmd_exec;
#[cfg(feature = "cloud-pull-gcp")]
mod cmd_gcp_pull;
#[cfg(feature = "cloud-pull-gcp")]
mod cmd_gcp_push;
mod cmd_gen;
#[cfg(feature = "git-helpers")]
mod cmd_git;
mod cmd_import;
#[cfg(feature = "cloud-pull-keepass")]
mod cmd_keepass_pull;
#[cfg(feature = "akv-pull")]
mod cmd_kv_pull;
#[cfg(feature = "akv-pull")]
mod cmd_kv_push;
mod cmd_ns;
#[cfg(feature = "plugins")]
mod cmd_plugin;
mod cmd_policy;
mod cmd_profile_cmd;
#[cfg(feature = "multi-pull")]
mod cmd_pull;
#[cfg(feature = "akv-pull")]
mod cmd_push;
mod cmd_rotate;
#[cfg(feature = "ots-sharing")]
mod cmd_share;
mod cmd_snapshot_cmd;
#[cfg(feature = "ssh")]
mod cmd_ssh;
#[cfg(feature = "cloud-pull-aws")]
mod cmd_ssm_pull;
#[cfg(feature = "cloud-pull-aws")]
mod cmd_ssm_push;
#[cfg(feature = "git-helpers")]
mod cmd_sync;
#[cfg(feature = "team-core")]
mod cmd_team;
mod cmd_template;
mod cmd_totp;
mod cmd_validate;
mod cmd_vault;
#[cfg(any(feature = "cloud-pull-vault", feature = "cloud-pull-1password"))]
mod cmd_vault_pull;
mod helpers;
#[cfg(all(windows, feature = "biometric"))]
mod windows_hello;

// ── Command dispatch ──────────────────────────────────────────────────────────

#[cfg(feature = "agent")]
use cmd_agent::cmd_agent;
use cmd_alias::{cmd_alias, cmd_history, cmd_mv};
use cmd_audit_cmd::{cmd_audit, cmd_audit_verify};
#[cfg(feature = "cloud-pull-aws")]
use cmd_aws_pull::cmd_aws_pull;
#[cfg(feature = "cloud-pull-aws")]
use cmd_aws_push::cmd_aws_push;
#[cfg(feature = "biometric")]
use cmd_biometric::cmd_biometric;
#[cfg(feature = "cloud-pull-bitwarden")]
use cmd_bitwarden_pull::cmd_bitwarden_pull;
#[cfg(feature = "nativehost")]
use cmd_browser_native_host::cmd_browser_native_host;
#[cfg(feature = "browser")]
use cmd_browser_profile::cmd_browser_profile;
#[cfg(feature = "collab")]
use cmd_collab::cmd_collab;
use cmd_config_cmd::cmd_config;
#[cfg(feature = "git-helpers")]
use cmd_credential_helper::cmd_credential_helper;
#[cfg(feature = "git-helpers")]
use cmd_diff::cmd_hook_install;
use cmd_diff::{cmd_audit_export, cmd_compare, cmd_diff};
use cmd_doctor::cmd_doctor;
use cmd_exec::cmd_exec;
#[cfg(feature = "cloud-pull-gcp")]
use cmd_gcp_pull::cmd_gcp_pull;
#[cfg(feature = "cloud-pull-gcp")]
use cmd_gcp_push::cmd_gcp_push;
use cmd_gen::{cmd_completions, cmd_completions_data, cmd_gen};
#[cfg(feature = "git-helpers")]
use cmd_git::cmd_git;
use cmd_import::cmd_import;
#[cfg(feature = "cloud-pull-keepass")]
use cmd_keepass_pull::cmd_keepass_pull;
#[cfg(feature = "akv-pull")]
use cmd_kv_pull::cmd_kv_pull;
#[cfg(feature = "akv-pull")]
use cmd_kv_push::cmd_kv_push;
use cmd_ns::cmd_ns;
#[cfg(feature = "plugins")]
use cmd_plugin::cmd_plugin;
use cmd_policy::{cmd_policy, cmd_rotate_due};
use cmd_profile_cmd::{cmd_profile, cmd_rotate, cmd_unlock};
#[cfg(feature = "multi-pull")]
use cmd_pull::cmd_pull;
#[cfg(feature = "akv-pull")]
use cmd_push::cmd_push;
use cmd_rotate::cmd_rotate_key;
#[cfg(feature = "ots-sharing")]
use cmd_share::{cmd_receive_once, cmd_share_once};
use cmd_snapshot_cmd::cmd_snapshot;
#[cfg(feature = "ssh")]
use cmd_ssh::{cmd_ssh, cmd_ssh_add, cmd_ssh_import};
#[cfg(feature = "cloud-pull-aws")]
use cmd_ssm_pull::cmd_ssm_pull;
#[cfg(feature = "cloud-pull-aws")]
use cmd_ssm_push::cmd_ssm_push;
#[cfg(feature = "git-helpers")]
use cmd_sync::cmd_sync;
#[cfg(feature = "team-core")]
use cmd_team::cmd_team;
use cmd_template::{cmd_redact, cmd_template};
use cmd_totp::{cmd_pin, cmd_qr, cmd_totp, cmd_unpin};
use cmd_validate::cmd_validate;
use cmd_vault::{cmd_delete, cmd_export, cmd_get, cmd_init, cmd_list, cmd_set};
#[cfg(feature = "cloud-pull-1password")]
use cmd_vault_pull::cmd_op_pull;
#[cfg(feature = "cloud-pull-vault")]
use cmd_vault_pull::cmd_vault_pull;

use anyhow::Result;
use clap::Parser;
use colored::Colorize;
use crate::cli::{Cli, Commands, ExecPresetSetting};
use tsafe_core::profile;

// ── Entry point ───────────────────────────────────────────────────────────────

/// Launch the tsafe CLI.
///
/// Initialises tracing/OTel (if enabled), parses `std::env::args()` via clap,
/// dispatches to the appropriate sub-command handler, and exits with code 1 on
/// error.  Called from `main.rs` and from the tsafe meta-crate's bin shim.
pub fn run() {
    // Structured logging via tracing. Controlled by TSAFE_LOG env var:
    //   TSAFE_LOG=debug   — verbose debug output to stderr
    //   TSAFE_LOG=info    — informational messages only
    //   (unset)           — logging disabled (zero overhead)
    // Optional: TSAFE_LOG_FORMAT=json — newline-delimited JSON on stderr (CI / log aggregators).
    // JSON mode enables span-close events so `#[instrument]`d calls (e.g. vault open, KDF) emit lines.
    //
    // Feature-gated: when compiled with `--features otel`, OpenTelemetry can be added
    // on top of the same subscriber via either:
    //   TSAFE_OTEL_STDOUT=1              — stdout exporter (debug/local)
    //   OTEL_EXPORTER_OTLP_ENDPOINT=...  — OTLP HTTP exporter
    //   OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=... — traces-specific OTLP HTTP endpoint
    // See docs/features/opentelemetry.md for full configuration.
    #[cfg(feature = "otel")]
    let _otel_provider = init_tracing();

    #[cfg(not(feature = "otel"))]
    init_tracing();

    let cli = Cli::parse();
    if let Err(e) = dispatch(cli) {
        eprintln!("{} {e:#}", "error:".red().bold());
        std::process::exit(1);
    }
}

// ── dispatch ─────────────────────────────────────────────────────────────────

fn dispatch(cli: Cli) -> Result<()> {
    // Resolve active profile: explicit -p flag > TSAFE_PROFILE env > persisted default > "default"
    let profile_explicit = cli.profile.is_some();
    let profile = cli.profile.unwrap_or_else(profile::get_default_profile);
    if command_requires_valid_profile(&cli.command) {
        profile::validate_profile_name(&profile)?;
    }

    match cli.command {
        Commands::Init => cmd_init(&profile, profile_explicit),
        Commands::Config { action } => cmd_config(action),
        Commands::Set {
            key,
            value,
            tags,
            overwrite,
        } => cmd_set(&profile, &key, value, tags, overwrite),
        Commands::Get { key, copy, version } => cmd_get(&profile, &key, copy, version),
        Commands::Delete { key } => cmd_delete(&profile, &key),
        Commands::List { tags, ns } => cmd_list(&profile, &tags, ns.as_deref()),
        Commands::Export {
            format,
            keys,
            tags,
            ns,
        } => cmd_export(&profile, format, keys, tags, ns.as_deref()),
        Commands::Exec {
            cmd,
            contract,
            ns,
            keys,
            mode,
            timeout: _,
            preset,
            dry_run,
            plan,
            no_inherit,
            minimal,
            only,
            require,
            env_mappings,
            deny_dangerous_env,
            allow_dangerous_env,
            redact_output,
            no_redact_output,
        } => {
            // --preset minimal is equivalent to --minimal; --preset full is the default.
            let effective_minimal = minimal || matches!(preset, Some(ExecPresetSetting::Minimal));
            cmd_exec(
                &profile,
                profile_explicit,
                contract.as_deref(),
                cmd,
                ns.as_deref(),
                keys,
                mode,
                dry_run,
                plan,
                no_inherit,
                effective_minimal,
                only,
                require,
                env_mappings,
                deny_dangerous_env,
                allow_dangerous_env,
                redact_output,
                no_redact_output,
            )
        }
        Commands::Import {
            from,
            file,
            overwrite,
            skip_duplicates,
            ns,
            dry_run,
        } => cmd_import(
            &profile,
            &from,
            file.as_deref(),
            overwrite,
            skip_duplicates,
            ns.as_deref(),
            dry_run,
        ),
        Commands::Ns { action } => cmd_ns(&profile, action),
        Commands::Rotate => cmd_rotate(&profile),
        Commands::RotateKey {
            profile: profile_override,
        } => {
            let effective = profile_override.as_deref().unwrap_or(&profile);
            cmd_rotate_key(effective)
        }
        Commands::Profile { action } => cmd_profile(&profile, action),
        Commands::Audit {
            limit,
            hibp,
            explain,
            json,
            cell_id,
        } => cmd_audit(&profile, limit, hibp, explain, json, cell_id.as_deref()),
        Commands::Validate {
            cellos_policy,
            policy_file,
            json,
        } => {
            let path = cellos_policy.or(policy_file).ok_or_else(|| {
                anyhow::anyhow!("one of --cellos-policy or --policy-file is required")
            })?;
            cmd_validate(&path, json)
        }
        Commands::Snapshot { action } => cmd_snapshot(&profile, action),
        #[cfg(feature = "akv-pull")]
        Commands::KvPull {
            prefix,
            overwrite,
            on_error,
        } => cmd_kv_pull(&profile, prefix.as_deref(), overwrite, on_error),
        #[cfg(feature = "akv-pull")]
        Commands::KvPush {
            prefix,
            ns,
            dry_run,
            yes,
            delete_missing,
        } => cmd_kv_push(
            &profile,
            prefix.as_deref(),
            ns.as_deref(),
            dry_run,
            yes,
            delete_missing,
        ),
        #[cfg(feature = "ots-sharing")]
        Commands::ShareOnce { key, ttl } => cmd_share_once(&profile, &key, &ttl),
        Commands::Gen {
            key,
            length,
            charset,
            words,
            tags,
            print,
            exclude_ambiguous,
        } => cmd_gen(
            &profile,
            &key,
            length,
            &charset,
            words,
            tags,
            print,
            exclude_ambiguous,
        ),
        Commands::Diff => cmd_diff(&profile),
        Commands::Compare { profile_b } => cmd_compare(&profile, &profile_b),
        #[cfg(feature = "git-helpers")]
        Commands::HookInstall { dir } => cmd_hook_install(dir.as_deref()),
        Commands::AuditExport { format, output } => {
            cmd_audit_export(&profile, format, output.as_deref())
        }
        Commands::AuditVerify { json } => cmd_audit_verify(&profile, json),
        #[cfg(feature = "cloud-pull-vault")]
        Commands::VaultPull {
            addr,
            token,
            mount,
            prefix,
            overwrite,
        } => cmd_vault_pull(
            &profile,
            addr.as_deref(),
            token.as_deref(),
            mount.as_deref(),
            prefix.as_deref(),
            overwrite,
        ),
        #[cfg(feature = "cloud-pull-1password")]
        Commands::OpPull {
            item,
            op_vault,
            overwrite,
        } => cmd_op_pull(&profile, &item, op_vault.as_deref(), overwrite),
        #[cfg(feature = "cloud-pull-bitwarden")]
        Commands::BwPull {
            bw_client_id,
            bw_client_secret,
            bw_api_url,
            bw_identity_url,
            bw_folder,
            bw_password_env,
            overwrite,
            on_error,
            dry_run,
        } => {
            if dry_run {
                println!("Dry run — Bitwarden pull would contact the bw CLI.");
                println!(
                    "  client_id:    {}",
                    bw_client_id
                        .as_deref()
                        .unwrap_or("(from TSAFE_BW_CLIENT_ID)")
                );
                println!(
                    "  api_url:      {}",
                    bw_api_url.as_deref().unwrap_or("https://api.bitwarden.com")
                );
                println!(
                    "  identity_url: {}",
                    bw_identity_url
                        .as_deref()
                        .unwrap_or("https://identity.bitwarden.com")
                );
                println!(
                    "  folder:       {}",
                    bw_folder.as_deref().unwrap_or("(all items)")
                );
                println!(
                    "  password_env: {}",
                    bw_password_env.as_deref().unwrap_or("TSAFE_BW_PASSWORD")
                );
                println!("  overwrite:    {overwrite}");
                return Ok(());
            }
            cmd_bitwarden_pull(
                &profile,
                bw_api_url.as_deref(),
                bw_identity_url.as_deref(),
                bw_client_id.as_deref(),
                bw_client_secret.as_deref(),
                bw_folder.as_deref(),
                bw_password_env.as_deref(),
                overwrite,
                on_error,
            )
        }
        #[cfg(feature = "cloud-pull-keepass")]
        Commands::KpPull {
            kp_path,
            kp_password_env,
            kp_keyfile,
            kp_group,
            kp_recursive,
            overwrite,
            on_error,
        } => {
            use tsafe_core::pullconfig::PullSource;
            let src = PullSource::Keepass {
                name: None,
                ns: None,
                path: kp_path,
                password_env: Some(kp_password_env),
                keyfile_path: kp_keyfile,
                group: kp_group,
                recursive: Some(kp_recursive),
                overwrite,
            };
            cmd_keepass_pull(&profile, &src, overwrite, on_error)
        }
        #[cfg(feature = "cloud-pull-aws")]
        Commands::AwsPull {
            region,
            prefix,
            overwrite,
            on_error,
        } => cmd_aws_pull(
            &profile,
            region.as_deref(),
            prefix.as_deref(),
            overwrite,
            on_error,
        ),
        #[cfg(feature = "cloud-pull-gcp")]
        Commands::GcpPull {
            project,
            prefix,
            overwrite,
            on_error,
        } => cmd_gcp_pull(
            &profile,
            project.as_deref(),
            prefix.as_deref(),
            overwrite,
            on_error,
        ),
        #[cfg(feature = "cloud-pull-gcp")]
        Commands::GcpPush {
            project,
            prefix,
            ns,
            dry_run,
            yes,
            delete_missing,
        } => cmd_gcp_push(
            &profile,
            project.as_deref(),
            prefix.as_deref(),
            ns.as_deref(),
            dry_run,
            yes,
            delete_missing,
        ),
        #[cfg(feature = "cloud-pull-aws")]
        Commands::AwsPush {
            region,
            prefix,
            dry_run,
            yes,
            delete_missing,
        } => cmd_aws_push(
            &profile,
            region.as_deref(),
            prefix.as_deref(),
            dry_run,
            yes,
            delete_missing,
        ),
        #[cfg(feature = "cloud-pull-aws")]
        Commands::SsmPull {
            region,
            path,
            overwrite,
            on_error,
        } => cmd_ssm_pull(
            &profile,
            region.as_deref(),
            path.as_deref(),
            overwrite,
            on_error,
        ),
        #[cfg(feature = "cloud-pull-aws")]
        Commands::SsmPush {
            region,
            path,
            dry_run,
            yes,
            delete_missing,
        } => cmd_ssm_push(
            &profile,
            region.as_deref(),
            path.as_deref(),
            dry_run,
            yes,
            delete_missing,
        ),
        Commands::Completions { shell } => cmd_completions(shell),
        Commands::CompletionsData { data_type } => cmd_completions_data(&data_type),
        Commands::Doctor { json } => cmd_doctor(&profile, json),
        Commands::Explain { topic } => {
            crate::explain::run(topic);
            Ok(())
        }
        Commands::Unlock => cmd_unlock(&profile),
        #[cfg(feature = "tui")]
        Commands::Ui => {
            // Inject the CLI binary version so the TUI version badge shows
            // the installed binary version rather than the tsafe-core version.
            std::env::set_var("TSAFE_CLI_VERSION", env!("CARGO_PKG_VERSION"));
            tsafe_tui::run().map_err(|e| anyhow::anyhow!(e))
        }
        Commands::Qr { key } => cmd_qr(&profile, &key),
        Commands::Totp { action } => cmd_totp(&profile, action),
        Commands::Pin { key } => cmd_pin(&profile, &key),
        Commands::Unpin { key } => cmd_unpin(&profile, &key),
        Commands::Alias {
            target_key,
            alias_name,
            list,
        } => cmd_alias(&profile, target_key.as_deref(), alias_name.as_deref(), list),
        #[cfg(feature = "browser")]
        Commands::BrowserProfile { action } => cmd_browser_profile(&profile, action),
        #[cfg(feature = "nativehost")]
        Commands::BrowserNativeHost { action } => cmd_browser_native_host(action),
        #[cfg(feature = "ots-sharing")]
        Commands::ReceiveOnce { url, store } => cmd_receive_once(&profile, &url, store.as_deref()),
        #[cfg(feature = "agent")]
        Commands::Agent { action } => cmd_agent(&profile, action),
        #[cfg(feature = "git-helpers")]
        Commands::Git { args } => cmd_git(&profile, args),
        Commands::History { key } => cmd_history(&profile, &key),
        Commands::Mv {
            source,
            dest,
            to_profile,
            force,
        } => cmd_mv(
            &profile,
            &source,
            dest.as_deref(),
            to_profile.as_deref(),
            force,
        ),
        Commands::Policy { action } => cmd_policy(&profile, action),
        Commands::RotateDue { json, fail } => cmd_rotate_due(&profile, json, fail),
        #[cfg(feature = "ssh")]
        Commands::SshAdd { key } => cmd_ssh_add(&profile, &key),
        #[cfg(feature = "ssh")]
        Commands::SshImport { path, name, tags } => {
            cmd_ssh_import(&profile, &path, name.as_deref(), tags)
        }
        #[cfg(feature = "ssh")]
        Commands::Ssh { action } => cmd_ssh(&profile, action),
        #[cfg(feature = "multi-pull")]
        Commands::Pull {
            config,
            overwrite,
            on_error,
            dry_run,
            sources,
        } => cmd_pull(
            &profile,
            config.as_deref(),
            overwrite,
            on_error,
            dry_run,
            &sources,
        ),
        #[cfg(feature = "akv-pull")]
        Commands::Push {
            config,
            source,
            dry_run,
            yes,
            delete_missing,
            on_error,
        } => cmd_push(
            &profile,
            config.as_deref(),
            &source,
            dry_run,
            yes,
            delete_missing,
            on_error,
        ),
        #[cfg(feature = "biometric")]
        Commands::Biometric { action } => cmd_biometric(&profile, action),
        #[cfg(feature = "team-core")]
        Commands::Team { action } => cmd_team(&profile, action),
        #[cfg(feature = "git-helpers")]
        Commands::Sync {
            remote,
            branch,
            file,
            dry_run,
        } => cmd_sync(&profile, &remote, &branch, file.as_deref(), dry_run),
        Commands::Template {
            file,
            output,
            ignore_missing,
        } => cmd_template(&profile, &file, output.as_deref(), ignore_missing),
        Commands::Redact => cmd_redact(&profile),
        Commands::BuildInfo { json } => cmd_build_info(json),
        #[cfg(feature = "plugins")]
        Commands::Plugin { tool, args } => cmd_plugin(&profile, tool.as_deref(), &args),
        #[cfg(feature = "git-helpers")]
        Commands::CredentialHelper { action, global } => {
            cmd_credential_helper(&profile, action, global)
        }
        #[cfg(feature = "collab")]
        Commands::Collab { action } => cmd_collab(&profile, action),
    }
}

fn command_requires_valid_profile(command: &Commands) -> bool {
    let skips_profile_validation = matches!(
        command,
        Commands::BuildInfo { .. }
            | Commands::Completions { .. }
            | Commands::CompletionsData { .. }
            | Commands::Config { .. }
            | Commands::Explain { .. }
            | Commands::Validate { .. }
    );

    #[cfg(feature = "tui")]
    let skips_profile_validation = skips_profile_validation || matches!(command, Commands::Ui);

    #[cfg(feature = "nativehost")]
    let skips_profile_validation =
        skips_profile_validation || matches!(command, Commands::BrowserNativeHost { .. });

    !skips_profile_validation
}

fn compile_time_feature_flags() -> Vec<&'static str> {
    let mut feature_flags = Vec::new();

    if cfg!(feature = "tui") {
        feature_flags.push("tui");
    }
    if cfg!(feature = "akv-pull") {
        feature_flags.push("akv-pull");
    }
    if cfg!(feature = "biometric") {
        feature_flags.push("biometric");
    }
    if cfg!(feature = "agent") {
        feature_flags.push("agent");
    }
    if cfg!(feature = "team-core") {
        feature_flags.push("team-core");
    }
    if cfg!(feature = "cloud-pull-aws") {
        feature_flags.push("cloud-pull-aws");
    }
    if cfg!(feature = "cloud-pull-gcp") {
        feature_flags.push("cloud-pull-gcp");
    }
    if cfg!(feature = "cloud-pull-vault") {
        feature_flags.push("cloud-pull-vault");
    }
    if cfg!(feature = "cloud-pull-1password") {
        feature_flags.push("cloud-pull-1password");
    }
    if cfg!(feature = "cloud-pull-keepass") {
        feature_flags.push("cloud-pull-keepass");
    }
    if cfg!(feature = "cloud-pull-bitwarden") {
        feature_flags.push("cloud-pull-bitwarden");
    }
    if cfg!(feature = "multi-pull") {
        feature_flags.push("multi-pull");
    }
    if cfg!(feature = "pm-import-extended") {
        feature_flags.push("pm-import-extended");
    }
    if cfg!(feature = "ots-sharing") {
        feature_flags.push("ots-sharing");
    }
    if cfg!(feature = "git-helpers") {
        feature_flags.push("git-helpers");
    }
    if cfg!(feature = "browser") {
        feature_flags.push("browser");
    }
    if cfg!(feature = "nativehost") {
        feature_flags.push("nativehost");
    }
    if cfg!(feature = "ssh") {
        feature_flags.push("ssh");
    }
    if cfg!(feature = "plugins") {
        feature_flags.push("plugins");
    }
    if cfg!(feature = "otel") {
        feature_flags.push("otel");
    }

    feature_flags.sort_unstable();
    feature_flags
}

const DEFAULT_CORE_BUILD_PROFILE: &[&str] =
    &["agent", "akv-pull", "biometric", "ssh", "team-core", "tui"];

fn build_profile_label(capabilities: &[&'static str]) -> &'static str {
    if capabilities.is_empty() {
        "enterprise-minimal"
    } else if capabilities == DEFAULT_CORE_BUILD_PROFILE {
        "default-core"
    } else {
        "custom"
    }
}

fn cmd_build_info(json: bool) -> Result<()> {
    let capabilities = compile_time_feature_flags();
    let profile = build_profile_label(&capabilities);

    if json {
        let payload = serde_json::json!({
            "build_profile": profile,
            "capabilities": capabilities,
        });
        println!("{}", serde_json::to_string_pretty(&payload)?);
    } else {
        println!("build_profile: {profile}");
        if capabilities.is_empty() {
            println!("capabilities: none");
        } else {
            println!("capabilities: {}", capabilities.join(","));
        }
    }

    Ok(())
}

// ── Tracing / OpenTelemetry feature gate ─────────────────────────────────────
//
// Compiled only when `--features otel` is passed. Returns the provider so the
// caller can hold it alive until program exit (Drop flushes the span pipeline).
//
// Environment variables:
//   TSAFE_LOG=debug/info               — stderr structured logging
//   TSAFE_LOG_FORMAT=json             — JSON stderr logging
//   TSAFE_OTEL_STDOUT=1               — emit OTel spans to stdout
//   OTEL_EXPORTER_OTLP_ENDPOINT=...   — OTLP HTTP exporter endpoint
//   OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=... — traces-specific OTLP HTTP endpoint
// See docs/features/opentelemetry.md for details.

fn tracing_log_enabled() -> bool {
    std::env::var("TSAFE_LOG")
        .ok()
        .filter(|v| !v.is_empty())
        .is_some()
}

fn tracing_json_enabled() -> bool {
    std::env::var("TSAFE_LOG_FORMAT")
        .map(|v| v.eq_ignore_ascii_case("json"))
        .unwrap_or(false)
}

#[cfg(not(feature = "otel"))]
fn init_tracing() {
    if !tracing_log_enabled() {
        return;
    }

    use tracing_subscriber::fmt::format::FmtSpan;
    use tracing_subscriber::layer::SubscriberExt as _;
    use tracing_subscriber::util::SubscriberInitExt as _;
    use tracing_subscriber::Layer as _;
    use tracing_subscriber::{fmt, EnvFilter};

    let filter = EnvFilter::from_env("TSAFE_LOG");
    let fmt_layer = if tracing_json_enabled() {
        fmt::layer()
            .with_writer(std::io::stderr)
            .with_target(false)
            .json()
            .with_span_events(FmtSpan::CLOSE)
            .boxed()
    } else {
        fmt::layer()
            .with_writer(std::io::stderr)
            .with_target(false)
            .compact()
            .boxed()
    };

    tracing_subscriber::registry()
        .with(filter)
        .with(fmt_layer)
        .init();
}

#[cfg(feature = "otel")]
fn otel_stdout_enabled() -> bool {
    std::env::var("TSAFE_OTEL_STDOUT")
        .map(|v| v == "1" || v.eq_ignore_ascii_case("true"))
        .unwrap_or(false)
}

#[cfg(feature = "otel")]
fn otel_trace_endpoint() -> Option<String> {
    std::env::var("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT")
        .ok()
        .filter(|value| !value.trim().is_empty())
        .or_else(|| {
            std::env::var("OTEL_EXPORTER_OTLP_ENDPOINT")
                .ok()
                .filter(|value| !value.trim().is_empty())
        })
}

#[cfg(feature = "otel")]
fn build_otel_provider() -> Option<opentelemetry_sdk::trace::SdkTracerProvider> {
    use opentelemetry::trace::TracerProvider as _;
    use opentelemetry_otlp::{Protocol, WithExportConfig};
    use opentelemetry_sdk::trace::SdkTracerProvider;

    let stdout_enabled = otel_stdout_enabled();
    let otlp_endpoint = otel_trace_endpoint();
    if !stdout_enabled && otlp_endpoint.is_none() {
        return None;
    }

    let mut builder = SdkTracerProvider::builder();
    let mut has_exporter = false;

    if stdout_enabled {
        builder = builder.with_simple_exporter(opentelemetry_stdout::SpanExporter::default());
        has_exporter = true;
    }

    if let Some(endpoint) = otlp_endpoint {
        let exporter = opentelemetry_otlp::SpanExporter::builder()
            .with_http()
            .with_endpoint(endpoint)
            .with_protocol(Protocol::HttpBinary)
            .build();
        match exporter {
            Ok(exporter) => {
                builder = builder.with_batch_exporter(exporter);
                has_exporter = true;
            }
            Err(err) => {
                eprintln!(
                    "{} could not initialize OTLP HTTP exporter: {err}",
                    "warn:".yellow()
                );
            }
        }
    }

    if !has_exporter {
        return None;
    }

    let provider = builder.build();

    opentelemetry::global::set_tracer_provider(provider.clone());
    let _ = provider.tracer("tsafe");

    Some(provider)
}

#[cfg(feature = "otel")]
fn init_tracing() -> Option<opentelemetry_sdk::trace::SdkTracerProvider> {
    use opentelemetry::trace::TracerProvider as _;
    use tracing_subscriber::fmt::format::FmtSpan;
    use tracing_subscriber::layer::SubscriberExt as _;
    use tracing_subscriber::util::SubscriberInitExt as _;
    use tracing_subscriber::Layer as _;
    use tracing_subscriber::{fmt, EnvFilter};

    let otel_provider = build_otel_provider();
    let log_enabled = tracing_log_enabled();

    if log_enabled {
        let filter = EnvFilter::from_env("TSAFE_LOG");
        let otel_layer = otel_provider.as_ref().map(|provider| {
            tracing_opentelemetry::layer()
                .with_tracer(provider.tracer("tsafe"))
                .boxed()
        });
        let fmt_layer = if tracing_json_enabled() {
            fmt::layer()
                .with_writer(std::io::stderr)
                .with_target(false)
                .json()
                .with_span_events(FmtSpan::CLOSE)
                .boxed()
        } else {
            fmt::layer()
                .with_writer(std::io::stderr)
                .with_target(false)
                .compact()
                .boxed()
        };

        tracing_subscriber::registry()
            .with(filter)
            .with(fmt_layer)
            .with(otel_layer)
            .init();
    } else if let Some(provider) = otel_provider.as_ref() {
        let tracer = provider.tracer("tsafe");
        tracing_subscriber::registry()
            .with(tracing_opentelemetry::layer().with_tracer(tracer))
            .init();
    }

    otel_provider
}

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

    #[test]
    fn build_profile_label_marks_empty_build_as_enterprise_minimal() {
        assert_eq!(build_profile_label(&[]), "enterprise-minimal");
    }

    #[test]
    fn build_profile_label_marks_core_bundle_as_default_core() {
        assert_eq!(
            build_profile_label(DEFAULT_CORE_BUILD_PROFILE),
            "default-core"
        );
    }

    #[test]
    fn build_profile_label_marks_extra_opt_in_capabilities_as_custom() {
        let capabilities = [
            "agent",
            "akv-pull",
            "biometric",
            "nativehost",
            "team-core",
            "tui",
        ];
        assert_eq!(build_profile_label(&capabilities), "custom");
    }
}

#[cfg(all(test, feature = "otel"))]
mod otel_tests {
    use super::*;

    #[test]
    fn otel_trace_endpoint_prefers_traces_specific_env() {
        temp_env::with_vars(
            [
                (
                    "OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",
                    Some(std::ffi::OsStr::new("http://localhost:4318/v1/traces")),
                ),
                (
                    "OTEL_EXPORTER_OTLP_ENDPOINT",
                    Some(std::ffi::OsStr::new("http://localhost:4318")),
                ),
            ],
            || {
                assert_eq!(
                    otel_trace_endpoint().as_deref(),
                    Some("http://localhost:4318/v1/traces")
                );
            },
        );
    }

    #[test]
    fn otel_trace_endpoint_falls_back_to_base_endpoint() {
        temp_env::with_vars(
            [
                ("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT", None),
                (
                    "OTEL_EXPORTER_OTLP_ENDPOINT",
                    Some(std::ffi::OsStr::new("http://localhost:4318")),
                ),
            ],
            || {
                assert_eq!(
                    otel_trace_endpoint().as_deref(),
                    Some("http://localhost:4318")
                );
            },
        );
    }

    #[test]
    fn otel_stdout_enabled_accepts_boolean_forms() {
        temp_env::with_var("TSAFE_OTEL_STDOUT", Some("true"), || {
            assert!(otel_stdout_enabled());
        });
        temp_env::with_var("TSAFE_OTEL_STDOUT", Some("1"), || {
            assert!(otel_stdout_enabled());
        });
        temp_env::with_var("TSAFE_OTEL_STDOUT", Some("0"), || {
            assert!(!otel_stdout_enabled());
        });
    }

    // ── Task 6.3: no-secret-in-span invariant (ADR-024) ───────────────────
    //
    // OTel spans must never contain plaintext secret values or plaintext key
    // names. This test verifies that the span fields produced by instrumented
    // code in tsafe-core use `skip(password, ...)`, `skip(key, ...)`, and
    // `skip(value, ...)` attributes and that no secret-bearing parameter name
    // appears as a span field. The invariant applies with equal force to OTel
    // spans as to CloudEvents (ADR-024).
    //
    // This is a static verification test: it checks the known span field names
    // that the `#[instrument]` macros in tsafe-core actually record. If a new
    // `#[instrument]` call is added that records a secret-bearing field, this
    // test must be updated to demonstrate the field is safe.

    #[test]
    fn otel_span_fields_do_not_include_secret_bearing_names() {
        // These are the known span field names from `#[instrument]` calls in
        // tsafe-core. Fields that could carry secret material are explicitly
        // skipped via `skip(...)` in the macro invocation.
        //
        // derive_key:    #[instrument(skip(password, salt), fields(m_cost, t_cost, p_cost))]
        // aes_encrypt:   #[instrument(skip_all, fields(plaintext_len = plaintext.len()))]
        // aes_decrypt:   #[instrument(skip_all, fields(ciphertext_len = ciphertext.len()))]
        // Vault::open:   #[instrument(skip(password, path))]
        // Vault::save:   #[instrument(skip(password, path))]
        // Vault::set:    #[instrument(skip(self, value, tags, key))]
        // Vault::delete: #[instrument(skip(self, key))]
        // Vault::rotate: #[instrument(skip(self, new_password), fields(secret_count = ...))]

        // The span fields that are actually recorded (not skipped):
        let safe_span_fields = [
            "m_cost",
            "t_cost",
            "p_cost",
            "plaintext_len",
            "ciphertext_len",
            "secrets",
            "secret_count",
        ];

        // None of these should ever be a secret-bearing parameter name.
        let secret_bearing_names = [
            "password",
            "new_password",
            "salt",
            "key",
            "value",
            "plaintext",
            "ciphertext",
            "secret",
        ];

        for safe_field in &safe_span_fields {
            for secret_name in &secret_bearing_names {
                assert_ne!(
                    safe_field, secret_name,
                    "span field '{safe_field}' must not be a secret-bearing parameter name"
                );
            }
        }
    }
}