hardware-enclave 0.2.5

Hardware-backed key management — macOS Secure Enclave, Windows TPM 2.0, Linux TPM/keyring — plus in-process memory protection
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
#![allow(dead_code, unused_imports, unused_qualifications, unreachable_patterns)]
// Copyright 2026 Jay Gowdy
// SPDX-License-Identifier: MIT

//! Shell integration script generation.
//!
//! Generates shell-specific scripts that detect misuse of `export` for
//! sensitive environment variables and optionally provide helper functions.
//! Supports bash, zsh, fish, and PowerShell.

/// Configuration for shell integration script generation.
#[derive(Debug, Clone)]
pub struct ShellInitConfig {
    /// Command name (e.g., "awsenc", "sso-jwt").
    pub command: String,
    /// Environment variable patterns to detect in export statements.
    /// For bash/zsh these appear in a regex alternation.
    pub export_patterns: Vec<String>,
    /// Warning message lines when export is detected (each line printed to stderr).
    pub export_warning: Vec<String>,
    /// Whether to include PowerShell output support.
    pub include_powershell: bool,
    /// Optional: shell function name and body for a helper function
    /// (e.g., "awsenc-use" that sets env vars in the parent shell).
    /// If None, generates a command wrapper that intercepts the command itself.
    pub helper_function: Option<ShellHelperFunction>,
    /// If true, generates a command-wrapping function (like sso-jwt)
    /// that refuses to run when called inside an export statement.
    /// If false, generates a preexec/DEBUG hook that warns (like awsenc).
    pub command_wrapper: bool,
}

/// A helper shell function to include in the init script.
#[derive(Debug, Clone)]
pub struct ShellHelperFunction {
    /// Function name (e.g., "awsenc-use").
    pub name: String,
    /// Bash/zsh function body (the commands inside the function).
    pub bash_body: String,
    /// Fish function body.
    pub fish_body: String,
    /// PowerShell function body (if applicable).
    pub powershell_body: String,
}

/// Detect the user's current shell from the SHELL environment variable.
pub fn detect_shell(explicit: Option<&str>) -> Result<String, String> {
    if let Some(s) = explicit {
        return Ok(s.to_lowercase());
    }

    if let Ok(shell) = std::env::var("SHELL") {
        if let Some(name) = shell.rsplit('/').next() {
            match name {
                "zsh" => return Ok("zsh".into()),
                "bash" => return Ok("bash".into()),
                "fish" => return Ok("fish".into()),
                _ => {}
            }
        }
        if shell.contains("zsh") {
            return Ok("zsh".into());
        }
        if shell.contains("bash") {
            return Ok("bash".into());
        }
        if shell.contains("fish") {
            return Ok("fish".into());
        }
    }

    // Check PSModulePath for PowerShell
    if std::env::var("PSModulePath").is_ok() {
        return Ok("powershell".into());
    }

    Err("could not detect shell; specify one: bash, zsh, fish, powershell".into())
}

/// Generate a shell integration script for the given shell.
pub fn generate_shell_init(shell: &str, config: &ShellInitConfig) -> Result<String, String> {
    match shell {
        "bash" => Ok(generate_bash(config)),
        "zsh" => Ok(generate_zsh(config)),
        "fish" => Ok(generate_fish(config)),
        "powershell" | "pwsh" => {
            if config.include_powershell {
                Ok(generate_powershell(config))
            } else {
                Err(format!("PowerShell is not supported by {}", config.command))
            }
        }
        other => Err(format!("unsupported shell: {other}")),
    }
}

/// Build a regex alternation from export patterns for bash/zsh.
fn pattern_alternation(patterns: &[String]) -> String {
    patterns.join("|")
}

/// Build fish pattern match expression.
fn fish_pattern_match(patterns: &[String]) -> String {
    patterns.join("|")
}

/// Build the warning echo lines for bash/zsh.
fn bash_warning_lines(warning: &[String]) -> String {
    warning
        .iter()
        .map(|line| format!("    echo \"{}\" >&2", line.replace('"', "\\\"")))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Build the warning echo lines for fish.
fn fish_warning_lines(warning: &[String]) -> String {
    warning
        .iter()
        .map(|line| format!("        echo \"{}\" >&2", line.replace('"', "\\\"")))
        .collect::<Vec<_>>()
        .join("\n")
}

/// Build the warning lines for PowerShell.
fn powershell_warning_lines(warning: &[String]) -> String {
    warning
        .iter()
        .map(|line| {
            format!(
                "        Write-Host \"{}\" -ForegroundColor Yellow",
                line.replace('"', "`\"")
            )
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn generate_bash(config: &ShellInitConfig) -> String {
    let cmd = &config.command;
    let patterns = pattern_alternation(&config.export_patterns);
    let warnings = bash_warning_lines(&config.export_warning);
    // Sanitize command name for use as identifier prefix
    let prefix = cmd.replace('-', "_");

    if config.command_wrapper {
        // sso-jwt style: command wrapper that refuses to run inside export
        let mut script = format!(
            r#"# {cmd} shell integration for bash
# Add to your .bashrc: eval "$({cmd} shell-init bash)"

__{prefix}_debug() {{
    __{prefix}_CURRENT_CMD="$BASH_COMMAND"
}}

# Chain with existing DEBUG trap if present
__{prefix}_existing_trap=$(trap -p DEBUG 2>/dev/null | sed "s/^trap -- '//;s/' DEBUG$//")
if [[ -n "$__{prefix}_existing_trap" ]]; then
    eval "trap '${{__{prefix}_existing_trap}}; __{prefix}_debug' DEBUG"
else
    trap '__{prefix}_debug' DEBUG
fi
unset __{prefix}_existing_trap

{cmd}() {{
    if [[ "$__{prefix}_CURRENT_CMD" =~ ^[[:space:]]*(export|declare\ -x)[[:space:]] ]]; then
{warnings}
        return 1
    fi
    command {cmd} "$@"
}}
"#
        );

        if let Some(helper) = &config.helper_function {
            script.push('\n');
            script.push_str(&format!("{}() {{\n{}\n}}\n", helper.name, helper.bash_body));
        }

        script
    } else {
        // awsenc style: preexec hook that warns but doesn't block
        let mut script = format!(
            r#"# {cmd} shell integration (bash)
# Add to ~/.bashrc: eval "$({cmd} shell-init bash)"

_{cmd}_preexec() {{
  local cmd="$BASH_COMMAND"
  if [[ "$cmd" =~ ^[[:space:]]*(export|declare\ -x)[[:space:]]+({patterns})= ]]; then
{warnings}
  fi
}}

# Install the DEBUG trap, chaining with any existing trap
if [[ -z "${{_{cmd}_trap_installed:-}}" ]]; then
  _{cmd}_existing_trap=$(trap -p DEBUG | sed "s/^trap -- '//;s/' DEBUG$//")
  if [[ -n "$_{cmd}_existing_trap" ]]; then
    trap '_{cmd}_preexec; eval "$_{cmd}_existing_trap"' DEBUG
  else
    trap '_{cmd}_preexec' DEBUG
  fi
  _{cmd}_trap_installed=1
fi
"#
        );

        if let Some(helper) = &config.helper_function {
            script.push('\n');
            script.push_str(&format!("{}() {{\n{}\n}}\n", helper.name, helper.bash_body));
        }

        script
    }
}

fn generate_zsh(config: &ShellInitConfig) -> String {
    let cmd = &config.command;
    let patterns = pattern_alternation(&config.export_patterns);
    let warnings = bash_warning_lines(&config.export_warning);
    let prefix = cmd.replace('-', "_");

    if config.command_wrapper {
        // sso-jwt style: command wrapper
        let mut script = format!(
            r#"# {cmd} shell integration for zsh
# Add to your .zshrc: eval "$({cmd} shell-init zsh)"

__{prefix}_preexec() {{
    __{prefix}_CURRENT_CMD="$1"
}}
autoload -Uz add-zsh-hook
add-zsh-hook preexec __{prefix}_preexec

{cmd}() {{
    if [[ "$__{prefix}_CURRENT_CMD" =~ '^[[:space:]]*(export|declare[[:space:]]+-x|typeset[[:space:]]+-x)[[:space:]]' ]]; then
{warnings}
        __{prefix}_CURRENT_CMD=""
        return 1
    fi
    __{prefix}_CURRENT_CMD=""
    command {cmd} "$@"
}}
"#
        );

        if let Some(helper) = &config.helper_function {
            script.push('\n');
            script.push_str(&format!("{}() {{\n{}\n}}\n", helper.name, helper.bash_body));
        }

        script
    } else {
        // awsenc style: preexec warning
        let mut script = format!(
            r#"# {cmd} shell integration (zsh)
# Add to ~/.zshrc: eval "$({cmd} shell-init zsh)"

autoload -Uz add-zsh-hook

_{cmd}_preexec() {{
  local cmd="$1"
  if [[ "$cmd" =~ ^[[:space:]]*(export|declare\ -x)[[:space:]]+({patterns})= ]]; then
{warnings}
  fi
}}

add-zsh-hook preexec _{cmd}_preexec
"#
        );

        if let Some(helper) = &config.helper_function {
            script.push('\n');
            script.push_str(&format!("{}() {{\n{}\n}}\n", helper.name, helper.bash_body));
        }

        script
    }
}

fn generate_fish(config: &ShellInitConfig) -> String {
    let cmd = &config.command;
    let patterns = fish_pattern_match(&config.export_patterns);
    let warnings = fish_warning_lines(&config.export_warning);
    let prefix = cmd.replace('-', "_");

    if config.command_wrapper {
        // sso-jwt style: function wrapper
        format!(
            r#"# {cmd} shell integration for fish
# Add to your config.fish: {cmd} shell-init fish | source

function {cmd} --wraps='{cmd}' --description '{cmd} with export detection'
    set -l current_cmd (commandline)
    if string match -qr '^\s*(set -gx|set --global --export)' -- $current_cmd
{warnings}
        return 1
    end
    command {cmd} $argv
end
"#
        )
    } else {
        // awsenc style: preexec event function
        let mut script = format!(
            r#"# {cmd} shell integration (fish)
# Add to ~/.config/fish/config.fish: {cmd} shell-init fish | source

function __{prefix}_check_export --on-event fish_preexec
    set -l cmd $argv[1]
    if string match -rq '^\s*set\s+(-gx|-Ux)\s+({patterns})\s' -- "$cmd"
{warnings}
    end
end
"#
        );

        if let Some(helper) = &config.helper_function {
            script.push('\n');
            script.push_str(&format!(
                "function {}\n{}\nend\n",
                helper.name, helper.fish_body
            ));
        }

        script
    }
}

fn generate_powershell(config: &ShellInitConfig) -> String {
    let cmd = &config.command;
    let patterns = pattern_alternation(&config.export_patterns);
    let warnings = powershell_warning_lines(&config.export_warning);
    let prefix = cmd.replace('-', "");

    let mut script = format!(
        r#"# {cmd} shell integration (PowerShell)
# Add to $PROFILE: Invoke-Expression ({cmd} shell-init powershell)

$_{prefix}OriginalPrompt = $function:prompt

function prompt {{
    # Check recent history for credential exports
    $lastCmd = (Get-History -Count 1).CommandLine 2>$null
    if ($lastCmd -match '\$env:({patterns})\s*=') {{
{warnings}
    }}
    & $_{prefix}OriginalPrompt
}}
"#
    );

    if let Some(helper) = &config.helper_function {
        script.push('\n');
        script.push_str(&format!(
            "function {} {{\n{}\n}}\n",
            helper.name, helper.powershell_body
        ));
    }

    script
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::panic)]
mod tests {
    use super::*;

    fn awsenc_config() -> ShellInitConfig {
        ShellInitConfig {
            command: "awsenc".to_string(),
            export_patterns: vec![
                "AWS_ACCESS_KEY_ID".to_string(),
                "AWS_SECRET_ACCESS_KEY".to_string(),
                "AWS_SESSION_TOKEN".to_string(),
            ],
            export_warning: vec![
                "[awsenc] Warning: Exporting AWS credentials as environment variables defeats"
                    .to_string(),
                "hardware-backed protection. Use 'awsenc exec' or credential_process instead."
                    .to_string(),
            ],
            include_powershell: true,
            helper_function: Some(ShellHelperFunction {
                name: "awsenc-use".to_string(),
                bash_body: r#"  local profile
  profile=$(command awsenc use "$@" --print-profile) || return $?
  export AWSENC_PROFILE="$profile"
  export AWS_PROFILE="$profile"
  echo "Switched to profile: $profile" >&2"#
                    .to_string(),
                fish_body: r#"    set -l profile (command awsenc use $argv --print-profile)
    or return $status
    set -gx AWSENC_PROFILE $profile
    set -gx AWS_PROFILE $profile
    echo "Switched to profile: $profile" >&2"#
                    .to_string(),
                powershell_body: r#"    $profile = & awsenc use @args --print-profile
    if ($LASTEXITCODE -eq 0) {
        $env:AWSENC_PROFILE = $profile
        $env:AWS_PROFILE = $profile
        Write-Host "Switched to profile: $profile" -ForegroundColor Green
    }"#
                .to_string(),
            }),
            command_wrapper: false,
        }
    }

    fn ssojwt_config() -> ShellInitConfig {
        ShellInitConfig {
            command: "sso-jwt".to_string(),
            export_patterns: vec!["SSO_JWT".to_string(), "COMPANY_JWT".to_string()],
            export_warning: vec![
                "error: refusing to output JWT for 'export'. This would persist the token in your shell environment.".to_string(),
                "       Use: COMPANY_JWT=$(sso-jwt) your-command".to_string(),
                "       Or:  sso-jwt exec -- your-command".to_string(),
            ],
            include_powershell: true,
            helper_function: None,
            command_wrapper: true,
        }
    }

    #[test]
    fn bash_awsenc_contains_preexec() {
        let script = generate_shell_init("bash", &awsenc_config()).unwrap();
        assert!(script.contains("_awsenc_preexec"));
        assert!(script.contains("DEBUG"));
        assert!(script.contains("AWS_ACCESS_KEY_ID"));
    }

    #[test]
    fn bash_awsenc_contains_helper() {
        let script = generate_shell_init("bash", &awsenc_config()).unwrap();
        assert!(script.contains("awsenc-use()"));
        assert!(script.contains("AWSENC_PROFILE"));
    }

    #[test]
    fn zsh_awsenc_contains_hook() {
        let script = generate_shell_init("zsh", &awsenc_config()).unwrap();
        assert!(script.contains("add-zsh-hook preexec"));
        assert!(script.contains("awsenc-use()"));
    }

    #[test]
    fn fish_awsenc_contains_event() {
        let script = generate_shell_init("fish", &awsenc_config()).unwrap();
        assert!(script.contains("__awsenc_check_export"));
        assert!(script.contains("fish_preexec"));
        assert!(script.contains("function awsenc-use"));
    }

    #[test]
    fn powershell_awsenc_contains_prompt() {
        let script = generate_shell_init("powershell", &awsenc_config()).unwrap();
        assert!(script.contains("function prompt"));
        assert!(script.contains("function awsenc-use"));
    }

    #[test]
    fn bash_ssojwt_contains_wrapper() {
        let script = generate_shell_init("bash", &ssojwt_config()).unwrap();
        assert!(script.contains("sso-jwt()"));
        assert!(script.contains("command sso-jwt"));
        assert!(script.contains("refusing to output JWT"));
    }

    #[test]
    fn zsh_ssojwt_contains_wrapper() {
        let script = generate_shell_init("zsh", &ssojwt_config()).unwrap();
        assert!(script.contains("sso-jwt()"));
        assert!(script.contains("command sso-jwt"));
        assert!(script.contains("add-zsh-hook preexec"));
    }

    #[test]
    fn fish_ssojwt_contains_wrapper() {
        let script = generate_shell_init("fish", &ssojwt_config()).unwrap();
        assert!(script.contains("function sso-jwt"));
        assert!(script.contains("command sso-jwt"));
    }

    #[test]
    fn powershell_supported_for_ssojwt() {
        let result = generate_shell_init("powershell", &ssojwt_config());
        assert!(result.is_ok());
        let script = result.unwrap();
        assert!(script.contains("$PROFILE"));
        assert!(script.contains("sso-jwt shell-init powershell"));
    }

    #[test]
    fn unsupported_shell() {
        let result = generate_shell_init("tcsh", &awsenc_config());
        assert!(result.is_err());
        assert!(result.unwrap_err().contains("unsupported shell"));
    }

    // Mutex for tests that modify SHELL env var
    static SHELL_ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());

    #[test]
    fn detect_shell_explicit() {
        assert_eq!(detect_shell(Some("bash")).unwrap(), "bash");
        assert_eq!(detect_shell(Some("ZSH")).unwrap(), "zsh");
        assert_eq!(detect_shell(Some("fish")).unwrap(), "fish");
        assert_eq!(detect_shell(Some("PowerShell")).unwrap(), "powershell");
    }

    #[test]
    fn detect_shell_from_env_zsh() {
        let _lock = SHELL_ENV_LOCK.lock().expect("mutex poisoned");
        let prev = std::env::var("SHELL").ok();
        std::env::set_var("SHELL", "/bin/zsh");
        let result = detect_shell(None);
        match prev {
            Some(v) => std::env::set_var("SHELL", v),
            None => std::env::remove_var("SHELL"),
        }
        assert_eq!(result.unwrap(), "zsh");
    }

    #[test]
    fn detect_shell_from_env_bash() {
        let _lock = SHELL_ENV_LOCK.lock().expect("mutex poisoned");
        let prev = std::env::var("SHELL").ok();
        std::env::set_var("SHELL", "/bin/bash");
        let result = detect_shell(None);
        match prev {
            Some(v) => std::env::set_var("SHELL", v),
            None => std::env::remove_var("SHELL"),
        }
        assert_eq!(result.unwrap(), "bash");
    }

    #[test]
    fn detect_shell_from_env_fish() {
        let _lock = SHELL_ENV_LOCK.lock().expect("mutex poisoned");
        let prev = std::env::var("SHELL").ok();
        std::env::set_var("SHELL", "/usr/local/bin/fish");
        let result = detect_shell(None);
        match prev {
            Some(v) => std::env::set_var("SHELL", v),
            None => std::env::remove_var("SHELL"),
        }
        assert_eq!(result.unwrap(), "fish");
    }

    #[test]
    fn bash_wrapper_chains_existing_trap() {
        let script = generate_shell_init("bash", &ssojwt_config()).unwrap();
        assert!(script.contains("trap -p DEBUG"));
        assert!(script.contains("__sso_jwt_existing_trap"));
        assert!(script.contains("if [[ -n \"$__sso_jwt_existing_trap\" ]]; then"));
    }

    #[test]
    fn zsh_wrapper_uses_preexec() {
        let script = generate_shell_init("zsh", &ssojwt_config()).unwrap();
        assert!(script.contains("__sso_jwt_preexec"));
        assert!(script.contains("autoload -Uz add-zsh-hook"));
    }

    #[test]
    fn all_awsenc_shells_have_comment_header() {
        let config = awsenc_config();
        for shell in &["bash", "zsh", "fish", "powershell"] {
            let script = generate_shell_init(shell, &config).unwrap();
            assert!(
                script.starts_with("# awsenc"),
                "{shell} output should start with '# awsenc'"
            );
        }
    }

    #[test]
    fn all_ssojwt_shells_have_comment_header() {
        let config = ssojwt_config();
        for shell in &["bash", "zsh", "fish"] {
            let script = generate_shell_init(shell, &config).unwrap();
            assert!(
                script.starts_with("# sso-jwt"),
                "{shell} output should start with '# sso-jwt'"
            );
        }
    }

    #[test]
    fn all_ssojwt_shells_suggest_exec() {
        let config = ssojwt_config();
        for shell in &["bash", "zsh", "fish"] {
            let script = generate_shell_init(shell, &config).unwrap();
            assert!(
                script.contains("sso-jwt exec"),
                "{shell} output missing exec suggestion"
            );
        }
    }

    #[test]
    fn all_ssojwt_shells_use_command_prefix() {
        let config = ssojwt_config();
        for shell in &["bash", "zsh", "fish"] {
            let script = generate_shell_init(shell, &config).unwrap();
            assert!(
                script.contains("command sso-jwt"),
                "{shell} output missing 'command sso-jwt'"
            );
        }
    }

    #[test]
    fn bash_output_contains_trap_chaining() {
        let script = generate_shell_init("bash", &awsenc_config()).unwrap();
        // The bash awsenc-style output chains with existing DEBUG trap
        assert!(
            script.contains("trap"),
            "bash output should contain trap for DEBUG"
        );
        assert!(
            script.contains("existing_trap"),
            "bash output should chain with existing trap"
        );
    }

    #[test]
    fn zsh_output_contains_add_zsh_hook() {
        let script = generate_shell_init("zsh", &awsenc_config()).unwrap();
        assert!(
            script.contains("add-zsh-hook"),
            "zsh output should contain add-zsh-hook"
        );
    }

    #[test]
    fn fish_output_contains_commandline_check() {
        // For the command_wrapper style (sso-jwt), fish uses `commandline`
        let script = generate_shell_init("fish", &ssojwt_config()).unwrap();
        assert!(
            script.contains("commandline"),
            "fish command wrapper output should check commandline"
        );
    }

    #[test]
    fn powershell_output_when_enabled() {
        let script = generate_shell_init("powershell", &awsenc_config()).unwrap();
        assert!(script.contains("PowerShell"));
        assert!(script.contains("function prompt"));
        assert!(script.contains("Get-History"));
    }

    #[test]
    fn generate_unknown_shell_returns_error() {
        let result = generate_shell_init("csh", &awsenc_config());
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.contains("unsupported shell"));
    }

    #[test]
    fn export_patterns_appear_in_generated_output() {
        let config = awsenc_config();
        for shell in &["bash", "zsh"] {
            let script = generate_shell_init(shell, &config).unwrap();
            assert!(
                script.contains("AWS_ACCESS_KEY_ID"),
                "{shell} output should contain export pattern AWS_ACCESS_KEY_ID"
            );
            assert!(
                script.contains("AWS_SECRET_ACCESS_KEY"),
                "{shell} output should contain export pattern AWS_SECRET_ACCESS_KEY"
            );
            assert!(
                script.contains("AWS_SESSION_TOKEN"),
                "{shell} output should contain export pattern AWS_SESSION_TOKEN"
            );
        }
    }

    #[test]
    fn command_name_appears_in_generated_output() {
        let config = awsenc_config();
        for shell in &["bash", "zsh", "fish", "powershell"] {
            let script = generate_shell_init(shell, &config).unwrap();
            assert!(
                script.contains("awsenc"),
                "{shell} output should contain command name 'awsenc'"
            );
        }
    }

    #[test]
    fn helper_function_appears_in_bash_output() {
        let script = generate_shell_init("bash", &awsenc_config()).unwrap();
        assert!(
            script.contains("awsenc-use()"),
            "bash output should contain helper function 'awsenc-use()'"
        );
        assert!(
            script.contains("AWSENC_PROFILE"),
            "bash output should contain helper function body"
        );
    }

    #[test]
    fn pwsh_alias_works_for_powershell() {
        // "pwsh" should be treated the same as "powershell"
        let script = generate_shell_init("pwsh", &awsenc_config()).unwrap();
        assert!(script.contains("PowerShell"));
    }

    // Pure helper unit tests

    #[test]
    fn pattern_alternation_empty_produces_empty_string() {
        assert_eq!(pattern_alternation(&[]), "");
    }

    #[test]
    fn pattern_alternation_single_pattern() {
        let pats = vec!["AWS_ACCESS_KEY_ID".to_string()];
        assert_eq!(pattern_alternation(&pats), "AWS_ACCESS_KEY_ID");
    }

    #[test]
    fn pattern_alternation_multiple_patterns_joined_by_pipe() {
        let pats = vec![
            "AWS_ACCESS_KEY_ID".to_string(),
            "AWS_SECRET_ACCESS_KEY".to_string(),
            "AWS_SESSION_TOKEN".to_string(),
        ];
        assert_eq!(
            pattern_alternation(&pats),
            "AWS_ACCESS_KEY_ID|AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN"
        );
    }

    #[test]
    fn fish_pattern_match_empty_produces_empty_string() {
        assert_eq!(fish_pattern_match(&[]), "");
    }

    #[test]
    fn fish_pattern_match_multiple_patterns_joined_by_pipe() {
        let pats = vec!["SSO_JWT".to_string(), "COMPANY_JWT".to_string()];
        assert_eq!(fish_pattern_match(&pats), "SSO_JWT|COMPANY_JWT");
    }

    #[test]
    fn bash_warning_lines_empty_list_is_empty_string() {
        assert_eq!(bash_warning_lines(&[]), "");
    }

    #[test]
    fn bash_warning_lines_single_line_uses_4_space_indent() {
        let warning = vec!["danger!".to_string()];
        let result = bash_warning_lines(&warning);
        assert_eq!(result, "    echo \"danger!\" >&2");
    }

    #[test]
    fn bash_warning_lines_multiple_lines_joined_by_newline() {
        let warning = vec!["line one".to_string(), "line two".to_string()];
        let result = bash_warning_lines(&warning);
        assert!(result.contains("line one"));
        assert!(result.contains("line two"));
        assert!(result.contains('\n'));
        let parts: Vec<&str> = result.split('\n').collect();
        assert_eq!(parts.len(), 2);
    }

    #[test]
    fn bash_warning_lines_escapes_double_quotes() {
        let warning = vec!["say \"hello\"".to_string()];
        let result = bash_warning_lines(&warning);
        assert!(
            result.contains("\\\"hello\\\""),
            "double quotes must be escaped: {result}"
        );
    }

    #[test]
    fn fish_warning_lines_empty_list_is_empty_string() {
        assert_eq!(fish_warning_lines(&[]), "");
    }

    #[test]
    fn fish_warning_lines_single_line_uses_8_space_indent() {
        let warning = vec!["oops".to_string()];
        let result = fish_warning_lines(&warning);
        assert!(result.starts_with("        echo \"oops\""));
    }

    #[test]
    fn fish_warning_lines_escapes_double_quotes() {
        let warning = vec!["say \"hello\"".to_string()];
        let result = fish_warning_lines(&warning);
        assert!(
            result.contains("\\\"hello\\\""),
            "double quotes must be escaped: {result}"
        );
    }

    #[test]
    fn powershell_warning_lines_empty_list_is_empty_string() {
        assert_eq!(powershell_warning_lines(&[]), "");
    }

    #[test]
    fn powershell_warning_lines_single_line_contains_write_host() {
        let warning = vec!["danger".to_string()];
        let result = powershell_warning_lines(&warning);
        assert!(result.contains("Write-Host"));
        assert!(result.contains("ForegroundColor Yellow"));
        assert!(result.contains("danger"));
    }

    #[test]
    fn powershell_warning_lines_escapes_double_quotes_with_backtick() {
        let warning = vec!["say \"hello\"".to_string()];
        let result = powershell_warning_lines(&warning);
        assert!(
            result.contains("`\"hello`\""),
            "double quotes must use backtick escape: {result}"
        );
    }

    #[test]
    fn powershell_warning_lines_multiple_lines_joined_by_newline() {
        let warning = vec!["line one".to_string(), "line two".to_string()];
        let result = powershell_warning_lines(&warning);
        let parts: Vec<&str> = result.split('\n').collect();
        assert_eq!(parts.len(), 2);
        assert!(parts[0].contains("line one"));
        assert!(parts[1].contains("line two"));
    }
}