pacsea 0.8.2

A fast, friendly TUI for browsing and installing Arch and AUR packages with built-in news and security scanning
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
//! Privilege password validation utilities.
//!
//! Delegates to [`crate::logic::privilege`] for tool-aware checks.

use crate::logic::privilege::AuthMode;

/// What: Resolve the effective authentication mode from settings.
///
/// Inputs:
/// - `settings`: Reference to the application settings.
///
/// Output:
/// - The resolved [`AuthMode`] to use for privilege escalation.
///
/// Details:
/// - If `auth_mode` is explicitly set to something other than the default (`Prompt`),
///   it takes precedence.
/// - If `auth_mode` is `Prompt` (the default) and the legacy `use_passwordless_sudo`
///   is `true`, maps to `PasswordlessOnly` for backward compatibility and logs a
///   deprecation warning.
/// - When both `auth_mode != Prompt` and `use_passwordless_sudo = true` are set,
///   `auth_mode` wins and a deprecation warning is logged.
#[must_use]
pub fn resolve_auth_mode(settings: &crate::theme::Settings) -> AuthMode {
    static WARNED_LEGACY_PASSWORDLESS_MAPPING: std::sync::Once = std::sync::Once::new();
    static WARNED_LEGACY_PASSWORDLESS_CONFLICT: std::sync::Once = std::sync::Once::new();

    if crate::logic::privilege::is_integration_test() {
        if let Ok(val) = std::env::var("PACSEA_TEST_AUTH_MODE") {
            tracing::debug!(val = %val, "Using test override for resolve_auth_mode");
            if let Some(mode) = AuthMode::from_config_key(&val) {
                return coerce_prompt_mode_for_tool_capabilities(mode);
            }
        }
        if std::env::var("PACSEA_TEST_SUDO_PASSWORDLESS")
            .ok()
            .as_deref()
            == Some("1")
        {
            tracing::debug!("Legacy test env PACSEA_TEST_SUDO_PASSWORDLESS=1 → PasswordlessOnly");
            return coerce_prompt_mode_for_tool_capabilities(AuthMode::PasswordlessOnly);
        }
    }

    let explicit_auth_mode = settings.auth_mode;
    let legacy_passwordless = settings.use_passwordless_sudo;

    let resolved = match (explicit_auth_mode, legacy_passwordless) {
        (AuthMode::Prompt, true) => {
            WARNED_LEGACY_PASSWORDLESS_MAPPING.call_once(|| {
                tracing::warn!(
                    "Deprecated: 'use_passwordless_sudo = true' is active. \
                     Mapping to auth_mode = passwordless_only. \
                     Please migrate to 'auth_mode = passwordless_only' in settings.conf."
                );
            });
            AuthMode::PasswordlessOnly
        }
        (mode, true) if mode != AuthMode::Prompt => {
            WARNED_LEGACY_PASSWORDLESS_CONFLICT.call_once(|| {
                tracing::warn!(
                    auth_mode = %mode,
                    "Deprecated: 'use_passwordless_sudo' is set alongside 'auth_mode'. \
                     'auth_mode = {mode}' takes precedence. \
                     Please remove 'use_passwordless_sudo' from settings.conf."
                );
            });
            mode
        }
        (mode, _) => mode,
    };

    coerce_prompt_mode_for_tool_capabilities(resolved)
}

/// What: Ensure auth mode is compatible with the active privilege tool.
///
/// Inputs:
/// - `mode`: Resolved auth mode from settings and legacy compatibility logic.
///
/// Output:
/// - Compatible auth mode for the active privilege tool.
///
/// Details:
/// - If `mode` is `Prompt` and the active tool cannot read passwords from stdin
///   (e.g. doas), this coerces to `Interactive`.
/// - This avoids entering in-app password validation paths that can never succeed.
/// - If the active tool cannot be resolved, returns the original mode so regular
///   tool-resolution errors can be surfaced by callers later.
fn coerce_prompt_mode_for_tool_capabilities(mode: AuthMode) -> AuthMode {
    if mode != AuthMode::Prompt {
        return mode;
    }

    let tool = match crate::logic::privilege::active_tool() {
        Ok(tool) => tool,
        Err(err) => {
            tracing::debug!(
                error = %err,
                "Could not resolve active privilege tool while resolving auth mode; leaving mode unchanged"
            );
            return mode;
        }
    };

    if tool.capabilities().supports_stdin_password {
        return mode;
    }

    tracing::warn!(
        tool = %tool,
        configured_mode = %mode,
        forced_mode = %AuthMode::Interactive,
        "Auth mode 'prompt' is incompatible with the active privilege tool; forcing interactive auth"
    );
    AuthMode::Interactive
}

/// What: Determine whether Pacsea should perform interactive auth handoff.
///
/// Inputs:
/// - `settings`: Reference to the application settings.
///
/// Output:
/// - `true` when resolved auth mode is `Interactive`, otherwise `false`.
///
/// Details:
/// - Uses [`resolve_auth_mode`] so capability-based coercions are respected.
/// - Covers both explicit `auth_mode = interactive` and compatibility fallbacks
///   (for example, `doas + prompt` coercion).
#[must_use]
pub fn should_use_interactive_auth_handoff(settings: &crate::theme::Settings) -> bool {
    resolve_auth_mode(settings) == AuthMode::Interactive
}

/// What: Determine whether interactive handoff is being forced by compatibility fallback.
///
/// Inputs:
/// - `settings`: Reference to the application settings.
///
/// Output:
/// - `true` when resolved mode is `Interactive` but configured mode is not explicitly interactive.
///
/// Details:
/// - Useful for diagnostics/UX messaging that differentiates explicit user intent
///   from forced compatibility behavior.
#[must_use]
pub fn should_force_interactive_auth_handoff(settings: &crate::theme::Settings) -> bool {
    resolve_auth_mode(settings) == AuthMode::Interactive
        && settings.auth_mode != AuthMode::Interactive
}

/// What: Determine whether the Pacsea password modal should be skipped.
///
/// Inputs:
/// - `settings`: Reference to the application settings.
///
/// Output:
/// - `true` if the password modal should be skipped, `false` if it should be shown.
///
/// Details:
/// - Resolves the effective [`AuthMode`] via [`resolve_auth_mode`].
/// - `Interactive` always skips the modal.
/// - `PasswordlessOnly` skips only when `{tool} -n true` succeeds on the system.
/// - `Prompt` never skips the modal.
/// - Tool-agnostic: works identically for sudo and doas.
#[must_use]
pub fn should_skip_password_modal(settings: &crate::theme::Settings) -> bool {
    let mode = resolve_auth_mode(settings);
    match mode {
        AuthMode::Interactive => {
            tracing::info!("Auth mode is 'interactive'; skipping Pacsea password modal");
            true
        }
        AuthMode::PasswordlessOnly => should_use_passwordless_sudo(settings),
        AuthMode::Prompt => false,
    }
}

/// What: Check if passwordless privilege escalation is available for the current user.
///
/// Inputs:
/// - None (uses the active privilege tool from settings).
///
/// Output:
/// - `Ok(true)` if passwordless execution is available, `Ok(false)` if not, or `Err(String)` on error.
///
/// # Errors
///
/// - Returns `Err` if the check cannot be executed (e.g., tool not installed).
///
/// Details:
/// - Delegates to [`crate::logic::privilege::PrivilegeTool::check_passwordless`].
/// - Uses the resolved privilege tool (sudo or doas) based on settings.
/// - Both sudo and doas support `-n true` for non-interactive checking.
pub fn check_passwordless_sudo_available() -> Result<bool, String> {
    let tool = crate::logic::privilege::active_tool()?;
    tool.check_passwordless()
}

/// What: Check if passwordless privilege escalation should be used based on settings and system availability.
///
/// Inputs:
/// - `settings`: Reference to the application settings.
///
/// Output:
/// - `true` if passwordless execution should be used, `false` otherwise.
///
/// Details:
/// - This function is strictly about passwordless availability (`{tool} -n true`).
/// - For non-`PasswordlessOnly` modes, checks if `use_passwordless_sudo` is enabled
///   in settings (legacy safety barrier).
/// - If legacy toggle is required but disabled, returns `false` immediately.
/// - If enabled, checks if passwordless execution is actually available on the system.
/// - Returns `true` only if both conditions are met.
/// - Tool capability constraints (for example: doas lacking stdin password support) are
///   handled separately via [`should_use_interactive_auth_handoff`].
/// - Test overrides flow through [`check_passwordless_sudo_available`] via privilege module.
#[must_use]
pub fn should_use_passwordless_sudo(settings: &crate::theme::Settings) -> bool {
    // In integration test context, honor the test override directly.
    // This bypasses the settings check so tests can simulate passwordless without
    // modifying the persisted Settings struct.
    if crate::logic::privilege::is_integration_test()
        && let Ok(val) = std::env::var("PACSEA_TEST_SUDO_PASSWORDLESS")
    {
        tracing::debug!(
            val = %val,
            "Using test override for should_use_passwordless_sudo"
        );
        return val == "1";
    }

    let auth_mode = resolve_auth_mode(settings);
    let require_legacy_toggle = auth_mode != AuthMode::PasswordlessOnly;
    if require_legacy_toggle && !settings.use_passwordless_sudo {
        tracing::debug!("Passwordless privilege disabled in settings, requiring password prompt");
        return false;
    }

    match check_passwordless_sudo_available() {
        Ok(true) => {
            tracing::info!("Passwordless privilege enabled in settings and available on system");
            true
        }
        Ok(false) => {
            tracing::debug!(
                "Passwordless privilege enabled in settings but not available on system, requiring password prompt"
            );
            false
        }
        Err(e) => {
            tracing::debug!(
                "Passwordless privilege check failed ({}), requiring password prompt",
                e
            );
            false
        }
    }
}

/// What: Validate a privilege tool password without executing any command.
///
/// Inputs:
/// - `password`: Password to validate.
///
/// Output:
/// - `Ok(true)` if password is valid, `Ok(false)` if invalid, or `Err(String)` on error.
///
/// # Errors
///
/// - Returns `Err` if the validation command cannot be executed (e.g., tool not available).
/// - Returns `Err` if the active tool does not support password validation (e.g., doas).
///
/// Details:
/// - Delegates to [`crate::logic::privilege::validate_password`].
/// - Only works for tools that support stdin password piping (currently sudo).
/// - For doas, returns an error since doas cannot validate passwords via stdin.
pub fn validate_sudo_password(password: &str) -> Result<bool, String> {
    let tool = crate::logic::privilege::active_tool()?;
    crate::logic::privilege::validate_password(tool, password)
}

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

    /// What: Check if passwordless sudo is configured (test helper).
    ///
    /// Inputs:
    /// - None.
    ///
    /// Output:
    /// - `true` if passwordless sudo is available, `false` otherwise.
    ///
    /// Details:
    /// - Uses the public `check_passwordless_sudo_available()` function.
    /// - Returns `false` if sudo is not available or requires a password.
    fn is_passwordless_sudo() -> bool {
        check_passwordless_sudo_available().unwrap_or(false)
    }

    #[test]
    /// What: Test passwordless sudo check returns a valid result.
    ///
    /// Inputs:
    /// - None.
    ///
    /// Output:
    /// - Returns `Ok(bool)` without panicking.
    ///
    /// Details:
    /// - Verifies the function returns a valid result (either true or false).
    /// - Does not assert on the actual value since it depends on system configuration.
    fn test_check_passwordless_sudo_available() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "sudo");
            std::env::set_var("PACSEA_TEST_SUDO_PASSWORDLESS", "1");
        }

        let result = check_passwordless_sudo_available();

        unsafe {
            std::env::remove_var("PACSEA_TEST_SUDO_PASSWORDLESS");
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }

        assert_eq!(result, Ok(true));
    }

    #[test]
    /// What: Ensure doas no longer implies passwordless execution by capability alone.
    ///
    /// Inputs:
    /// - Integration test env forcing only doas availability.
    /// - Passwordless override set to disabled.
    /// - Explicit `auth_mode = passwordless_only`.
    ///
    /// Output:
    /// - Returns `false` from `should_use_passwordless_sudo`.
    ///
    /// Details:
    /// - Ensures `PasswordlessOnly` strictly follows `{tool} -n true` availability.
    /// - Prevents capability-based auto-pass for doas.
    fn test_should_use_passwordless_sudo_false_for_doas_when_passwordless_unavailable() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "doas");
            std::env::set_var("PACSEA_TEST_AUTH_MODE", "passwordless_only");
            std::env::set_var("PACSEA_TEST_SUDO_PASSWORDLESS", "0");
        }

        let settings = crate::theme::Settings::default();
        let should_skip_prompt = should_use_passwordless_sudo(&settings);

        unsafe {
            std::env::remove_var("PACSEA_TEST_SUDO_PASSWORDLESS");
            std::env::remove_var("PACSEA_TEST_AUTH_MODE");
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }

        assert!(
            !should_skip_prompt,
            "doas should not be treated as passwordless when -n check fails"
        );
    }

    #[test]
    /// What: Prompt mode with doas forces interactive auth handoff.
    ///
    /// Inputs:
    /// - Integration test env forcing doas availability.
    /// - Default settings (`auth_mode = prompt`).
    ///
    /// Output:
    /// - Returns `true` from `should_use_interactive_auth_handoff`.
    ///
    /// Details:
    /// - doas cannot support in-app stdin password validation.
    fn test_should_use_interactive_auth_handoff_true_for_prompt_doas() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "doas");
            std::env::remove_var("PACSEA_TEST_AUTH_MODE");
        }

        let settings = crate::theme::Settings::default();
        let result = should_use_interactive_auth_handoff(&settings);

        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }

        assert!(
            result,
            "doas + prompt should force interactive auth handoff"
        );
    }

    // -- resolve_auth_mode ---------------------------------------------------

    #[test]
    /// What: Default settings resolve to `Prompt` auth mode.
    ///
    /// Inputs: Default settings (`auth_mode` = Prompt, `use_passwordless_sudo` = false).
    ///
    /// Output: `AuthMode::Prompt`.
    ///
    /// Details: Ensures no accidental legacy mapping fires for default config.
    fn test_resolve_auth_mode_default_is_prompt() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "sudo");
            std::env::remove_var("PACSEA_TEST_AUTH_MODE");
        }

        let settings = crate::theme::Settings::default();
        let mode = resolve_auth_mode(&settings);

        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }

        assert_eq!(mode, AuthMode::Prompt);
    }

    #[test]
    /// What: Prompt mode is coerced to interactive for doas.
    ///
    /// Inputs:
    /// - Integration test env forcing doas as the only available tool.
    /// - Default settings (`auth_mode = Prompt`).
    ///
    /// Output: `AuthMode::Interactive`.
    ///
    /// Details:
    /// - doas does not support stdin password validation.
    /// - This ensures prompt-mode password modal flow cannot be reached with doas.
    fn test_resolve_auth_mode_prompt_for_doas_forces_interactive() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "doas");
            std::env::remove_var("PACSEA_TEST_AUTH_MODE");
        }

        let settings = crate::theme::Settings::default();
        let mode = resolve_auth_mode(&settings);

        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }

        assert_eq!(mode, AuthMode::Interactive);
    }

    #[test]
    /// What: Explicit `auth_mode = interactive` takes effect.
    ///
    /// Inputs: Settings with `auth_mode = Interactive`.
    ///
    /// Output: `AuthMode::Interactive`.
    ///
    /// Details: Verifies direct setting without legacy fallback.
    fn test_resolve_auth_mode_explicit_interactive() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "sudo");
            std::env::remove_var("PACSEA_TEST_AUTH_MODE");
        }

        let settings = crate::theme::Settings {
            auth_mode: AuthMode::Interactive,
            ..crate::theme::Settings::default()
        };
        let mode = resolve_auth_mode(&settings);

        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }

        assert_eq!(mode, AuthMode::Interactive);
    }

    #[test]
    /// What: Legacy `use_passwordless_sudo = true` maps to `PasswordlessOnly`.
    ///
    /// Inputs: Settings with `auth_mode = Prompt` (default) and `use_passwordless_sudo = true`.
    ///
    /// Output: `AuthMode::PasswordlessOnly`.
    ///
    /// Details: Backward compatibility mapping fires when `auth_mode` is still default.
    fn test_resolve_auth_mode_legacy_passwordless_maps() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "sudo");
            std::env::remove_var("PACSEA_TEST_AUTH_MODE");
        }

        let settings = crate::theme::Settings {
            use_passwordless_sudo: true,
            ..crate::theme::Settings::default()
        };
        let mode = resolve_auth_mode(&settings);

        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }

        assert_eq!(mode, AuthMode::PasswordlessOnly);
    }

    #[test]
    /// What: Explicit `auth_mode = interactive` wins over legacy `use_passwordless_sudo`.
    ///
    /// Inputs: `auth_mode = Interactive` and `use_passwordless_sudo = true`.
    ///
    /// Output: `AuthMode::Interactive` (explicit `auth_mode` wins).
    ///
    /// Details: When both keys are set, `auth_mode` takes precedence over legacy.
    fn test_resolve_auth_mode_explicit_wins_over_legacy() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "sudo");
            std::env::remove_var("PACSEA_TEST_AUTH_MODE");
        }

        let settings = crate::theme::Settings {
            auth_mode: AuthMode::Interactive,
            use_passwordless_sudo: true,
            ..crate::theme::Settings::default()
        };
        let mode = resolve_auth_mode(&settings);

        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }

        assert_eq!(mode, AuthMode::Interactive);
    }

    #[test]
    /// What: Test override env var controls resolved auth mode.
    ///
    /// Inputs: `PACSEA_TEST_AUTH_MODE=interactive` with default settings.
    ///
    /// Output: `AuthMode::Interactive`.
    ///
    /// Details: Integration test override should bypass settings entirely.
    fn test_resolve_auth_mode_env_override() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "sudo");
            std::env::set_var("PACSEA_TEST_AUTH_MODE", "interactive");
        }

        let settings = crate::theme::Settings::default();
        let mode = resolve_auth_mode(&settings);

        unsafe {
            std::env::remove_var("PACSEA_TEST_AUTH_MODE");
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }

        assert_eq!(mode, AuthMode::Interactive);
    }

    // -- should_skip_password_modal ------------------------------------------

    #[test]
    /// What: `should_skip_password_modal` returns true for interactive mode.
    ///
    /// Inputs: Settings with `auth_mode = Interactive`.
    ///
    /// Output: `true`.
    ///
    /// Details: Interactive always skips the modal, regardless of tool availability.
    fn test_should_skip_password_modal_interactive() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "sudo");
            std::env::remove_var("PACSEA_TEST_AUTH_MODE");
        }

        let settings = crate::theme::Settings {
            auth_mode: AuthMode::Interactive,
            ..crate::theme::Settings::default()
        };
        let skip = should_skip_password_modal(&settings);

        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }

        assert!(skip, "Interactive mode should always skip password modal");
    }

    #[test]
    /// What: `should_skip_password_modal` returns true for interactive mode with doas.
    ///
    /// Inputs: Settings with `auth_mode = Interactive` and only doas available.
    ///
    /// Output: `true`.
    ///
    /// Details: Interactive mode is tool-agnostic — must skip for doas too.
    fn test_should_skip_password_modal_interactive_doas() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "doas");
            std::env::remove_var("PACSEA_TEST_AUTH_MODE");
        }

        let settings = crate::theme::Settings {
            auth_mode: AuthMode::Interactive,
            ..crate::theme::Settings::default()
        };
        let skip = should_skip_password_modal(&settings);

        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }

        assert!(
            skip,
            "Interactive mode should skip password modal for doas too"
        );
    }

    #[test]
    /// What: `should_skip_password_modal` returns false for default prompt mode.
    ///
    /// Inputs: Default settings.
    ///
    /// Output: `false`.
    ///
    /// Details: Prompt mode always shows the modal.
    fn test_should_skip_password_modal_prompt() {
        let _guard = crate::global_test_mutex_lock();
        unsafe {
            std::env::set_var("PACSEA_INTEGRATION_TEST", "1");
            std::env::set_var("PACSEA_TEST_PRIVILEGE_AVAILABLE", "sudo");
            std::env::remove_var("PACSEA_TEST_AUTH_MODE");
        }

        let settings = crate::theme::Settings::default();
        let skip = should_skip_password_modal(&settings);

        unsafe {
            std::env::remove_var("PACSEA_TEST_PRIVILEGE_AVAILABLE");
            std::env::remove_var("PACSEA_INTEGRATION_TEST");
        }

        assert!(!skip, "Prompt mode should always show password modal");
    }

    #[test]
    #[ignore = "Uses sudo with wrong password - may lock user out. Run with --ignored"]
    /// What: Test password validation handles invalid passwords.
    ///
    /// Inputs:
    /// - Invalid password string.
    ///
    /// Output:
    /// - Returns `Ok(false)` for invalid password.
    ///
    /// Details:
    /// - Verifies the function correctly identifies invalid passwords.
    /// - Skips assertion if passwordless sudo is configured (common in CI).
    /// - Marked as ignored to prevent user lockout from failed sudo attempts.
    fn test_validate_sudo_password_invalid() {
        // Skip test if passwordless sudo is configured (common in CI environments)
        if is_passwordless_sudo() {
            return;
        }

        // This test uses an obviously wrong password
        // It should return Ok(false) without panicking
        let result = validate_sudo_password("definitely_wrong_password_12345");
        // Result may be Ok(false) or Err depending on system configuration
        if let Ok(valid) = result {
            // Should be false for invalid password
            assert!(!valid);
        } else {
            // Error is acceptable (e.g., sudo not available)
        }
    }

    #[test]
    #[ignore = "Uses sudo with wrong password - may lock user out. Run with --ignored"]
    /// What: Test password validation handles empty passwords.
    ///
    /// Inputs:
    /// - Empty password string.
    ///
    /// Output:
    /// - Returns `Ok(false)` for empty password.
    ///
    /// Details:
    /// - Verifies the function correctly handles empty passwords.
    /// - Skips assertion if passwordless sudo is configured (common in CI).
    /// - Marked as ignored to prevent user lockout from failed sudo attempts.
    fn test_validate_sudo_password_empty() {
        // Skip test if passwordless sudo is configured (common in CI environments)
        if is_passwordless_sudo() {
            return;
        }

        let result = validate_sudo_password("");
        // Empty password should be invalid
        if let Ok(valid) = result {
            assert!(!valid);
        } else {
            // Error is acceptable
        }
    }

    #[test]
    #[ignore = "Uses sudo with wrong password - may lock user out. Run with --ignored"]
    /// What: Test password validation handles special characters.
    ///
    /// Inputs:
    /// - Password with special characters that need escaping.
    ///
    /// Output:
    /// - Handles special characters without panicking.
    ///
    /// Details:
    /// - Verifies the function correctly escapes special characters in passwords.
    /// - Marked as ignored to prevent user lockout from failed sudo attempts.
    fn test_validate_sudo_password_special_chars() {
        // Test with password containing special shell characters
        let passwords = vec![
            "pass'word",
            "pass\"word",
            "pass$word",
            "pass`word",
            "pass\\word",
        ];
        for pass in passwords {
            let result = validate_sudo_password(pass);
            // Just verify it doesn't panic
            let _ = result;
        }
    }

    #[test]
    #[ignore = "Uses sudo with wrong password - may lock user out. Run with --ignored"]
    /// What: Test password validation function signature.
    ///
    /// Inputs:
    /// - Various password strings.
    ///
    /// Output:
    /// - Returns Result<bool, String> as expected.
    ///
    /// Details:
    /// - Verifies the function returns the correct type.
    /// - Marked as ignored to prevent user lockout from failed sudo attempts.
    fn test_validate_sudo_password_signature() {
        let result: Result<bool, String> = validate_sudo_password("test");
        // Verify it returns the correct type
        let _ = result;
    }
}