envseal 0.3.11

Write-only secret vault with process-level access control — post-agent secret management
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
//! Cross-platform GUI dialog orchestration — the user-facing
//! security boundary.
//!
//! Five public entry points fan out to per-platform implementations:
//!
//! - `request_passphrase` — vault unlock / change.
//! - `request_secret_value` — capture a new secret value.
//! - `request_approval` — per-secret release authorization (this is
//!   where the [`crate::guard`] signal/policy taxonomy is consumed:
//!   every detector runs, the policy decides, the approval pipeline
//!   acts).
//! - `request_totp_code` — second-factor entry.
//! - `preexec_capture_prompt` — bash/zsh/fish hook key-migration
//!   confirmation.
//!
//! Every entry point is gated by `has_display`; headless
//! environments produce [`crate::error::Error::NoDisplay`] rather
//! than silently falling through to a non-interactive code path.

pub mod linux;
pub mod macos;
pub mod relay;
pub mod windows;

#[cfg(feature = "mock-gui")]
pub mod mock;

use crate::audit;
use crate::error::Error;
use crate::guard;
use crate::security_config::SecurityConfig;
use std::process::Command;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use zeroize::Zeroizing;

#[cfg(target_os = "linux")]
use linux::{
    linux_fido2_pin_entry, linux_passphrase, linux_popup, linux_preexec_prompt, linux_secret_value,
    linux_totp_entry, resolve_linux_dialog, DialogKind,
};
#[cfg(target_os = "macos")]
use macos::{
    macos_fido2_pin_entry, macos_passphrase, macos_popup, macos_preexec_prompt, macos_secret_value,
    macos_totp_entry,
};
#[cfg(target_os = "windows")]
use windows::{
    windows_fido2_pin_entry, windows_passphrase, windows_popup, windows_preexec_prompt,
    windows_secret_value, windows_totp_entry,
};

/// Type of approval granted by the user.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Approval {
    /// Allow this single secret release. The next release of the
    /// same secret will prompt again.
    AllowOnce,
    /// Allow this secret release and persist a policy rule so
    /// subsequent releases of the same `(binary, secret, argv)`
    /// triple proceed without a prompt.
    AllowAlways,
    /// Refuse this release. The caller surfaces `Error::UserDenied`.
    Deny,
}

/// User's response to the `__preexec` migration prompt.
///
/// Used by the bash/zsh/fish hook to react when an API key is
/// detected in a typed shell command.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PreexecChoice {
    /// Store the value in the vault and emit a `.envseal` suggestion.
    Store,
    /// Skip this one occurrence; ask again next time.
    Skip,
    /// Record this (`env_var`, value) pair so we never re-prompt for it.
    DontAskAgain,
}

/// Pop a 3-button GUI dialog asking whether to migrate a freshly
/// detected API key into the vault. Returns [`PreexecChoice::Skip`]
/// on any platform/dialog failure rather than propagating an error
/// — the hook is best-effort and must never break the user's shell.
pub fn preexec_capture_prompt(message: &str) -> Result<PreexecChoice, Error> {
    #[cfg(feature = "mock-gui")]
    if let Some(choice) = mock::get_mock_preexec() {
        return Ok(choice);
    }

    if !has_display() {
        return Ok(PreexecChoice::Skip);
    }
    #[cfg(target_os = "linux")]
    {
        linux_preexec_prompt(message)
    }
    #[cfg(target_os = "macos")]
    {
        macos_preexec_prompt(message)
    }
    #[cfg(target_os = "windows")]
    {
        windows_preexec_prompt(message)
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        let _ = message;
        Ok(PreexecChoice::Skip)
    }
}

static RATE_LIMITER: Mutex<RateLimiterState> = Mutex::new(RateLimiterState {
    recent_requests: Vec::new(),
    last_request: None,
});

struct RateLimiterState {
    recent_requests: Vec<Instant>,
    last_request: Option<Instant>,
}

/// Request human approval to release a secret to a process.
///
/// This is the load-bearing security boundary. The flow is:
///
/// 1. Rate-limit gate (anti-fatigue / anti-spam).
/// 2. Relay path if `relay_required` — fail closed on relay error.
/// 3. Display gate — return `Error::NoDisplay` if headless.
/// 4. Run every detector via [`guard::assess_all_signals`], evaluate
///    against the default [`guard::Policy`] at the active tier, and
///    block / friction-gate / warn per the policy table. Every
///    signal is audit-logged.
/// 5. Optional challenge gate (config-requested or signal-demanded).
/// 6. Optional approval delay (anti-click-through).
/// 7. Render the platform popup with the accumulated warnings.
///
/// # Errors
/// `Error::UserDenied`, `Error::NoDisplay`,
/// `Error::EnvironmentCompromised` (signal blocked the operation),
/// `Error::RelayRequiredButUnavailable`, plus relay/audit IO errors.
pub fn request_approval(
    binary_path: &str,
    command: &[String],
    secret_name: &str,
    env_var: &str,
    config: &SecurityConfig,
) -> Result<Approval, Error> {
    #[cfg(feature = "mock-gui")]
    if let Some(response) = mock::get_mock_approval() {
        return response;
    }

    let cmd_str = command.join(" ");

    enforce_rate_limit(config)?;

    // If relay is configured as REQUIRED, the relay path must be tried
    // first and any error must be terminal — no fallback to local GUI.
    // The local-display check happens *after* this gate so that a
    // headless host with a paired phone can still authorize.
    if config.relay_required {
        match relay::request_relay_approval(config, binary_path, secret_name, env_var) {
            Ok(relay::RelayDecision::Allow) => return Ok(Approval::AllowOnce),
            Ok(relay::RelayDecision::Deny | relay::RelayDecision::Timeout) => {
                return Err(Error::UserDenied);
            }
            Err(e) => {
                return Err(Error::RelayRequiredButUnavailable(e.to_string()));
            }
        }
    }

    if !has_display() {
        return Err(Error::NoDisplay);
    }

    // Run every detector under the unified taxonomy and let the
    // policy decide. This is the single load-bearing consumer of
    // the signal model; doctor-rendering is a passive surface.
    //
    // The policy comes from `SecurityConfig::build_policy()` so
    // user-authored `signal_overrides` and `tier_overrides` from
    // `security.toml` are honored without any approval-pipeline
    // edits — exactly the "scales to 1000s of detectors without
    // touching this function" promise.
    // Build a per-operation context so detectors that care about the
    // target binary or stdin classification can fire. Ambient
    // detectors ignore the context fields they don't read.
    let ctx = guard::DetectorContext::builder()
        .binary_path(binary_path)
        .stdin_kind(guard::detect_stdin_kind())
        .build();
    let signals = guard::assess_all_signals(&ctx);
    let policy = config.build_policy();
    let decision = guard::evaluate(&signals, &policy, config.tier);

    // Audit-log every signal regardless of action — forensics need
    // the full picture, not just the blocking ones.
    for sig in &decision.log_entries {
        audit::log(&audit::AuditEvent::SignalRecorded {
            tier: format!("{:?}", config.tier),
            classification: format!("{} [{}] {}", sig.severity.as_str(), sig.id, sig.label),
        })
        .map_err(|e| Error::AuditLogFailed(e.to_string()))?;
    }

    if let Some(blocking) = decision.blocking_signal.as_ref() {
        return Err(Error::EnvironmentCompromised(format!(
            "{label} ({id}): {detail}{mitigation}",
            label = blocking.label,
            id = blocking.id,
            detail = blocking.detail,
            mitigation = blocking.mitigation,
        )));
    }

    // Challenge gate fires when EITHER the static config requests
    // it OR a signal demanded friction at this tier. Once cleared
    // within a process, we don't re-prompt — `envseal run` with
    // three unauthorized secrets shouldn't make the user solve the
    // numeric challenge three times for what is, from their
    // perspective, a single intent ("run this command with these
    // secrets"). The flag is process-scoped so a second `envseal`
    // invocation rightly re-prompts.
    if (config.challenge_required || decision.needs_friction)
        && !challenge_already_passed_in_process()
    {
        challenge_gate()?;
        mark_challenge_passed_in_process();
    }

    if config.approval_delay_secs > 0 {
        std::thread::sleep(Duration::from_secs(config.approval_delay_secs.into()));
    }

    // Single source of warnings: every detector that fired, rendered
    // through the unified `evaluate(...) -> Decision` pipeline. The
    // ad-hoc `shell_warning` / `check_untrusted_binary` strings that
    // used to be concatenated here are now signals emitted by
    // `guard::assess_target_binary_signals` and surface through the
    // same path as every other detector.
    let mut warnings = String::new();
    for warning in &decision.warnings {
        warnings.push_str(warning);
        warnings.push('\n');
    }

    #[cfg(target_os = "linux")]
    {
        linux_popup(binary_path, &cmd_str, secret_name, env_var, &warnings)
    }
    #[cfg(target_os = "macos")]
    {
        macos_popup(binary_path, &cmd_str, secret_name, env_var, &warnings)
    }
    #[cfg(target_os = "windows")]
    {
        windows_popup(binary_path, &cmd_str, secret_name, env_var, &warnings)
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        Err(Error::NoDisplay)
    }
}

/// Prompt the user for the vault passphrase. `is_new = true` shows
/// the create-and-confirm flow; `is_new = false` is a single-field
/// unlock prompt. Returns `Error::NoDisplay` in headless sessions.
///
/// Equivalent to [`request_passphrase_with_hint`] with no previous
/// error — kept for SDK back-compat.
pub fn request_passphrase(
    is_new: bool,
    config: &SecurityConfig,
) -> Result<Zeroizing<String>, Error> {
    request_passphrase_with_hint(is_new, None, config)
}

/// Same as [`request_passphrase`] but renders `prev_error` at the top
/// of the dialog when present — used by the unlock-retry loop so the
/// operator sees "Incorrect passphrase, try again." in the SAME
/// dialog instead of having the CLI exit with a cryptic error after
/// a single typo.
pub fn request_passphrase_with_hint(
    is_new: bool,
    prev_error: Option<&str>,
    _config: &SecurityConfig,
) -> Result<Zeroizing<String>, Error> {
    #[cfg(feature = "mock-gui")]
    if let Some(response) = mock::get_mock_passphrase() {
        return Ok(response);
    }

    if !has_display() {
        return Err(Error::NoDisplay);
    }
    #[cfg(target_os = "linux")]
    {
        linux_passphrase(is_new, prev_error)
    }
    #[cfg(target_os = "macos")]
    {
        macos_passphrase(is_new, prev_error)
    }
    #[cfg(target_os = "windows")]
    {
        windows_passphrase(is_new, prev_error)
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        let _ = prev_error;
        Err(Error::NoDisplay)
    }
}

/// Prompt the user to paste a new secret value (`store --gui` and
/// agent-initiated `request-key` flows). Returns `Error::NoDisplay`
/// in headless sessions.
pub fn request_secret_value(
    key_name: &str,
    description: &str,
    _config: &SecurityConfig,
) -> Result<Zeroizing<String>, Error> {
    #[cfg(feature = "mock-gui")]
    if let Some(response) = mock::get_mock_secret_value() {
        return Ok(response);
    }

    if !has_display() {
        return Err(Error::NoDisplay);
    }
    // Sanitize agent-provided descriptions to prevent phishing:
    // strip control characters and cap length so the dialog cannot
    // be used to spoof system warnings or inject formatting.
    let safe_desc: String = description
        .chars()
        .filter(|c| !c.is_control())
        .take(256)
        .collect();
    #[cfg(target_os = "linux")]
    {
        linux_secret_value(key_name, &safe_desc)
    }
    #[cfg(target_os = "macos")]
    {
        macos_secret_value(key_name, &safe_desc)
    }
    #[cfg(target_os = "windows")]
    {
        windows_secret_value(key_name, &safe_desc)
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        Err(Error::NoDisplay)
    }
}

/// Prompt the user for the PIN of their FIDO2 authenticator.
///
/// `retries_left` is the device's remaining PIN-attempt counter (per
/// CTAP2 `clientPin/getRetries`), surfaced in the dialog so the user
/// can see how close they are to a permanent lockout before typing.
/// `attempt` is the per-session attempt counter (1-based) so a retry
/// after a wrong PIN is explicit in the dialog title.
///
/// The returned PIN is wrapped in [`Zeroizing`] so it is scrubbed on
/// drop; callers should pass it directly into `ctap-hid-fido2`'s
/// `pin(..)` builder method and never copy it into a non-zeroizing
/// container.
///
/// # Errors
/// - [`Error::NoDisplay`] when no GUI is reachable
/// - [`Error::UserDenied`] when the user dismisses the dialog
pub fn request_fido2_pin(
    retries_left: u32,
    attempt: u32,
) -> Result<zeroize::Zeroizing<String>, Error> {
    #[cfg(feature = "mock-gui")]
    if let Some(response) = mock::get_mock_fido2_pin() {
        return Ok(response);
    }

    if !has_display() {
        return Err(Error::NoDisplay);
    }
    #[cfg(target_os = "linux")]
    {
        linux_fido2_pin_entry(retries_left, attempt)
    }
    #[cfg(target_os = "macos")]
    {
        macos_fido2_pin_entry(retries_left, attempt)
    }
    #[cfg(target_os = "windows")]
    {
        windows_fido2_pin_entry(retries_left, attempt)
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        let _ = (retries_left, attempt);
        Err(Error::NoDisplay)
    }
}

/// Prompt the user for a 6-digit TOTP code on tiers that require a
/// second factor. `attempt` is the 1-based attempt counter shown in
/// the prompt to make retries explicit.
pub fn request_totp_code(attempt: u32) -> Result<String, Error> {
    #[cfg(feature = "mock-gui")]
    if let Some(response) = mock::get_mock_totp() {
        return Ok(response);
    }

    if !has_display() {
        return Err(Error::NoDisplay);
    }
    #[cfg(target_os = "linux")]
    {
        linux_totp_entry(attempt)
    }
    #[cfg(target_os = "macos")]
    {
        macos_totp_entry(attempt)
    }
    #[cfg(target_os = "windows")]
    {
        windows_totp_entry(attempt)
    }
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        Err(Error::NoDisplay)
    }
}

/// Back-compat shim. The canonical home for interpreter / script-
/// runner detection is [`crate::guard::target_binary::is_interpreter`];
/// this re-export is kept so external callers that imported from
/// `crate::gui::is_interpreter` keep working.
#[must_use]
pub fn is_interpreter(binary_path: &str) -> bool {
    crate::guard::is_interpreter(binary_path)
}

/// Show an approval popup and return the user's decision.
///
/// The popup displays the binary path, secret name, and env var name,
/// with buttons for each approval tier.
///
/// Behavior is driven by the granular fields in `SecurityConfig`:
/// - `approval_delay_secs`: delay before popup appears (0 = immediate)
/// - `challenge_required`: if true, shows a 4-digit code gate first
/// - `signal_overrides` / `tier_overrides`: detection→policy overrides
///   (see [`crate::guard::signal`])
/// - `audit_logging`: whether to record events
///
/// For the average AI developer on Standard: popup appears instantly,
/// click Allow, done. Zero friction.
/// Process-scoped flag: has the challenge gate been cleared once in
/// this `envseal` invocation? Used to suppress re-prompting within a
/// single `inject` / `run` / `pipe` batch when multiple secrets each
/// trigger `request_approval`. Each new process starts at `false`.
static CHALLENGE_PASSED_THIS_PROCESS: std::sync::atomic::AtomicBool =
    std::sync::atomic::AtomicBool::new(false);

fn challenge_already_passed_in_process() -> bool {
    CHALLENGE_PASSED_THIS_PROCESS.load(std::sync::atomic::Ordering::Acquire)
}

fn mark_challenge_passed_in_process() {
    CHALLENGE_PASSED_THIS_PROCESS.store(true, std::sync::atomic::Ordering::Release);
}

fn challenge_gate() -> Result<(), Error> {
    let (challenge_text, expected) = guard::generate_gui_challenge();

    #[cfg(target_os = "linux")]
    {
        let (dialog_path, kind) = resolve_linux_dialog()?;

        let result = match kind {
            DialogKind::Zenity => Command::new(&dialog_path)
                .args([
                    "--entry",
                    "--title=envseal — Security Challenge",
                    &format!("--text=LOCKDOWN MODE\n\n{challenge_text}\n\nThis code confirms you are physically present."),
                    "--width=400",
                ])
                .output(),
            DialogKind::Kdialog => Command::new(&dialog_path)
                .args([
                    "--inputbox",
                    &format!("LOCKDOWN: {challenge_text}"),
                    "--title",
                    "envseal — Security Challenge",
                ])
                .output(),
        };

        match result {
            Ok(output) if output.status.success() => {
                let answer = String::from_utf8_lossy(&output.stdout).trim().to_string();
                if guard::verify_gui_challenge(&expected, &answer) {
                    Ok(())
                } else {
                    Err(Error::UserDenied)
                }
            }
            _ => Err(Error::UserDenied),
        }
    }

    #[cfg(target_os = "macos")]
    {
        let script = format!(
            r#"display dialog "LOCKDOWN: {challenge_text}" with title "envseal — Security Challenge" default answer "" buttons {{"Cancel", "OK"}} default button "OK""#
        );
        let binary = guard::verify_gui_binary("osascript")
            .unwrap_or_else(|_| std::path::PathBuf::from("/usr/bin/osascript"));
        let result = Command::new(&binary).args(["-e", &script]).output();
        match result {
            Ok(output) if output.status.success() => {
                let out = String::from_utf8_lossy(&output.stdout);
                if let Some(answer) = out.strip_prefix("text returned:") {
                    if guard::verify_gui_challenge(&expected, answer.trim()) {
                        return Ok(());
                    }
                }
                Err(Error::UserDenied)
            }
            _ => Err(Error::UserDenied),
        }
    }

    #[cfg(target_os = "windows")]
    {
        let script = format!(
            r#"$input = [Microsoft.VisualBasic.Interaction]::InputBox("LOCKDOWN: {challenge_text}", "envseal — Security Challenge"); Write-Output $input"#
        );
        let result = Command::new("powershell")
            .args([
                "-Command",
                &format!("Add-Type -AssemblyName Microsoft.VisualBasic; {script}"),
            ])
            .output();
        match result {
            Ok(output) if output.status.success() => {
                let answer = String::from_utf8_lossy(&output.stdout).trim().to_string();
                if guard::verify_gui_challenge(&expected, &answer) {
                    Ok(())
                } else {
                    Err(Error::UserDenied)
                }
            }
            _ => Err(Error::UserDenied),
        }
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        Err(Error::NoDisplay)
    }
}

/// Whether a graphical session capable of running the approval dialog
/// is available.
///
/// Returns `false` when:
/// - `ENVSEAL_DISABLE` or `ENVSEAL_NO_GUI` is set (any non-empty value),
/// - on Linux: neither `DISPLAY` nor `WAYLAND_DISPLAY` is exported,
/// - on Windows: the process has no interactive `SESSIONNAME` (Windows
///   service, ssh-without-rdp, scheduled task running as system),
///
/// Without the Windows session check, an SSH'd-in user on Windows
/// hangs forever trying to spawn a `PowerShell.Forms` dialog that has
/// no desktop to render onto. The user reported this exact symptom in
/// 0.3.9 — `envseal store` / `peek` over SSH on Windows blocked
/// indefinitely.
fn has_display() -> bool {
    if std::env::var("ENVSEAL_DISABLE").is_ok_and(|v| !v.is_empty())
        || std::env::var("ENVSEAL_NO_GUI").is_ok_and(|v| !v.is_empty())
    {
        return false;
    }

    #[cfg(target_os = "linux")]
    {
        std::env::var("DISPLAY").is_ok() || std::env::var("WAYLAND_DISPLAY").is_ok()
    }

    #[cfg(target_os = "macos")]
    {
        true // macOS always has a display if running as a desktop user
    }

    #[cfg(target_os = "windows")]
    {
        // SESSIONNAME is set on every interactive Windows session
        // ("Console" for local, "RDP-Tcp#0" for RDP, etc) and is
        // empty/unset for non-interactive contexts: Windows services,
        // SSH-only sessions, scheduled tasks running as SYSTEM, and
        // anything launched via PsExec without `-i`. If we can't see
        // it, there's no desktop to pop a dialog onto.
        std::env::var("SESSIONNAME")
            .map(|s| !s.trim().is_empty())
            .unwrap_or(false)
    }

    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    {
        false
    }
}

/// Enforce configurable rate limits on approval popups.
///
/// Two independent limits:
/// - `approval_cooldown_secs`: minimum time between popups
/// - `max_approvals_per_minute`: cap on popup frequency
///
/// When exceeded, requests are auto-denied and logged. This prevents
/// agents from spamming the user with 100 popups hoping they click
/// "Allow" reflexively (approval fatigue attack).
fn enforce_rate_limit(config: &crate::security_config::SecurityConfig) -> Result<(), Error> {
    let mut guard = RATE_LIMITER.lock().map_err(|_| {
        Error::CryptoFailure("rate limiter state corrupted — retry after cooldown".to_string())
    })?;
    let state = &mut *guard;

    let now = Instant::now();

    // Cooldown check
    if config.approval_cooldown_secs > 0 {
        if let Some(last) = state.last_request {
            let elapsed = now.duration_since(last);
            if elapsed.as_secs() < u64::from(config.approval_cooldown_secs) {
                let remaining = u64::from(config.approval_cooldown_secs) - elapsed.as_secs();
                crate::audit::log_required(&crate::audit::AuditEvent::RateLimited {
                    reason: format!("cooldown: {remaining}s remaining"),
                })?;
                return Err(Error::CryptoFailure(format!(
                    "rate limited: approval cooldown ({remaining}s remaining). \
                     this prevents approval fatigue attacks."
                )));
            }
        }
    }

    // Per-minute cap
    if config.max_approvals_per_minute > 0 {
        // Prune requests older than 60 seconds
        let one_minute_ago = now
            .checked_sub(std::time::Duration::from_secs(60))
            .unwrap_or(now);
        state.recent_requests.retain(|&t| t > one_minute_ago);

        if state.recent_requests.len() >= config.max_approvals_per_minute as usize {
            crate::audit::log_required(&crate::audit::AuditEvent::RateLimited {
                reason: format!(
                    "per-minute cap: {} requests in last 60s (max={})",
                    state.recent_requests.len(),
                    config.max_approvals_per_minute
                ),
            })?;
            return Err(Error::CryptoFailure(format!(
                "rate limited: {} approval requests in the last minute (max={}). \
                 this prevents approval fatigue attacks.",
                state.recent_requests.len(),
                config.max_approvals_per_minute
            )));
        }
    }

    // Record this request
    state.last_request = Some(now);
    state.recent_requests.push(now);

    Ok(())
}

// `check_untrusted_binary` and `shell_warning` previously emitted ad-hoc
// warning strings concatenated onto the approval popup body. Both are
// now Signals emitted by `crate::guard::target_binary` (interpreter +
// untrusted-path) and `crate::guard::context::assess_io_context_signals`
// (real-pipe stdin), flowing through the unified
// `evaluate(...) -> Decision` pipeline like every other detector.