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
//! Secret-aware process supervisor — runtime dataflow monitoring.
//!
//! Uses a fork+exec+monitor model to watch the child process's I/O for
//! secret leakage. This is the most aggressive defense tier: every write
//! to stdout/stderr is inspected in real-time and any chunk containing the
//! secret is redacted before forwarding.
//!
//! # Architecture
//!
//! ```text
//! envseal supervisor (parent)
//!//!   ├── fork child
//!   │     ├── apply sandbox (namespaces — Linux only today)
//!   │     ├── apply hardening (RLIMIT_CORE, PR_SET_DUMPABLE, NO_NEW_PRIVS)
//!   │     └── exec <command>
//!//!   ├── capture stdout/stderr via pipes
//!   │     ├── scan each write for secret bytes
//!   │     ├── if found: log BLOCKED event, write `[ENVSEAL:REDACTED]`
//!   │     └── if clean: pass through to real stdout/stderr
//!//!   └── wait for child exit
//! ```
//!
//! # Difference from `inject::execute`
//!
//! - [`crate::execution::inject::execute`]: replaces process; fast, no overhead.
//! - [`supervised_execute`]: fork+exec+monitor. Adds pipe overhead but
//!   catches leaks. Use for Lockdown tier or when runtime detection is
//!   needed.

use std::io::{Read, Write};
use std::process::{Command, Stdio};

#[cfg(unix)]
use std::os::unix::process::CommandExt;

use zeroize::{Zeroize, Zeroizing};

use crate::error::Error;
use crate::sandbox::SandboxTier;

use super::context::{prepare_execution, PreparedExecution};

/// Result of a supervised execution — includes dataflow events.
pub struct SupervisedResult {
    /// Child exit code.
    pub exit_code: i32,
    /// Number of times the secret was found in stdout/stderr.
    pub leak_events: usize,
    /// Dataflow events recorded during execution.
    pub events: Vec<DataflowEvent>,
}

/// A single dataflow event observed during supervised execution.
#[derive(Debug, Clone)]
pub struct DataflowEvent {
    /// What happened.
    pub kind: DataflowEventKind,
    /// Timestamp (monotonic millis since execution start).
    pub timestamp_ms: u64,
    /// Additional detail.
    pub detail: String,
}

/// Types of dataflow events.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DataflowEventKind {
    /// Secret injected into the child process.
    SecretInjected,
    /// Secret detected in stdout — output redacted.
    LeakedStdout,
    /// Secret detected in stderr — output redacted.
    LeakedStderr,
    /// Child process exited.
    ProcessExited,
}

/// Execute a command under full supervision with secret leak detection.
///
/// Uses [`prepare_execution`] for all security checks, then wraps the child
/// in a pipe monitor that scans for secret leakage.
///
/// # Errors
///
/// Refuses non-`None` tiers on platforms where the `pre_exec` sandbox path
/// is not available (returns [`Error::CryptoFailure`]). Also bubbles up any
/// error from [`prepare_execution`] or the child spawn.
#[allow(clippy::too_many_lines)]
pub fn supervised_execute(
    vault: &crate::vault::Vault,
    secret_name: &str,
    env_var: &str,
    command: &[String],
    tier: SandboxTier,
) -> Result<SupervisedResult, Error> {
    // The overlap-buffer approach in `monitor_stream` can only reliably
    // detect secrets that fit within two consecutive 8192-byte reads
    // (16383 bytes max). Beyond that, a split across three+ chunks
    // could evade detection.
    const MAX_SUPERVISABLE_SECRET_LEN: usize = 16383;

    // GUARD: Refuse to proceed when the *current* envseal process
    // has an LD_PRELOAD / DYLD_INSERT_LIBRARIES / library-injection
    // pattern set. Same rationale as `inject` / `pipe`: foreign code
    // in our address space can siphon the decrypted secret before it
    // reaches the supervised child. (audit C3)
    crate::guard::check_self_preload()?;
    crate::guard::harden_process();

    // PLATFORM GUARD: sandbox tiers other than `None` are applied via
    // platform-specific paths (Linux/macOS in `pre_exec`, Windows via
    // post-spawn Job Object assignment). If we ever land on a platform
    // without any backend, refuse rather than silently spawn unsandboxed.
    #[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
    if tier.any_isolation() {
        return Err(Error::CryptoFailure(format!(
            "supervised mode with sandbox tier '{}' is not supported on this platform",
            tier.as_str()
        )));
    }

    let mappings = [(secret_name, env_var)];
    let prepared = prepare_execution(vault, &mappings, command)?;

    // SECURITY: an empty secret value makes `contains_secret` return false
    // for every chunk, silently disabling all leak detection. Refuse to
    // supervise rather than give the caller a false sense of security.
    //
    // Additionally, the overlap-buffer approach in `monitor_stream` can only
    // reliably detect secrets that fit within two consecutive 8192-byte reads
    // (16383 bytes max). For longer secrets, a split across three+ chunks
    // would evade detection.
    if let Some((_, ref val)) = prepared.env_pairs.first() {
        if val.len() > MAX_SUPERVISABLE_SECRET_LEN {
            return Err(Error::CryptoFailure(format!(
                "secret '{secret_name}' is {len} bytes — supervised mode cannot reliably \
                 detect leaks for secrets longer than {max} bytes. Use inject mode, split \
                 the secret, or store a shorter value.",
                len = val.len(),
                max = MAX_SUPERVISABLE_SECRET_LEN
            )));
        }
        if val.is_empty() {
            return Err(Error::CryptoFailure(format!(
                "secret '{secret_name}' has an empty value — supervised mode cannot detect \
                 leaks of an empty string. Store a non-empty secret or use inject mode."
            )));
        }
    }

    let start_time = std::time::Instant::now();
    let mut events: Vec<DataflowEvent> = Vec::new();

    events.push(DataflowEvent {
        kind: DataflowEventKind::SecretInjected,
        timestamp_ms: 0,
        detail: format!(
            "secret '{secret_name}' injected as ${env_var} into {}",
            command[0]
        ),
    });

    let mut cmd = build_supervised_command(&prepared, tier);

    // Windows: spawn the child suspended, assign it to the job, then
    // resume — eliminates the post-spawn race window where a brand-new
    // child could `CreateProcessW` a grandchild that escapes the job.
    // Other platforms apply sandbox limits in `pre_exec`, so the
    // ordinary `spawn()` already places the child inside the namespace
    // / SBPL profile before `execve`.
    #[cfg(windows)]
    let (mut child, job_handle) = crate::sandbox::windows::spawn_in_job(&mut cmd, tier)
        .map_err(|e| Error::CryptoFailure(format!("windows sandbox spawn failed: {e}")))?;
    #[cfg(not(windows))]
    let mut child = cmd.spawn().map_err(Error::ExecFailed)?;

    let child_stdout = child.stdout.take();
    let child_stderr = child.stderr.take();

    // Audit L14: hold the secret bytes in Zeroizing so a panic / early
    // return scrubs them on stack unwind. Both monitor streams take a
    // ref so the buffer is shared rather than copied per stream.
    let secret_bytes: Zeroizing<Vec<u8>> = Zeroizing::new(
        prepared
            .env_pairs
            .first()
            .map_or_else(Vec::new, |(_, val)| val.as_bytes().to_vec()),
    );

    let secret_for_stdout = Zeroizing::new(secret_bytes.to_vec());
    let stdout_start = start_time;
    let stdout_handle = std::thread::spawn(move || -> (usize, Vec<DataflowEvent>) {
        monitor_stream(
            child_stdout,
            &secret_for_stdout,
            &DataflowEventKind::LeakedStdout,
            true,
            stdout_start,
        )
    });

    let secret_for_stderr = Zeroizing::new(secret_bytes.to_vec());
    let stderr_start = start_time;
    let stderr_handle = std::thread::spawn(move || -> (usize, Vec<DataflowEvent>) {
        monitor_stream(
            child_stderr,
            &secret_for_stderr,
            &DataflowEventKind::LeakedStderr,
            false,
            stderr_start,
        )
    });

    // Wait for the *direct* child to exit. Grandchildren that
    // inherited stdout/stderr and forked into the background may
    // still hold the pipe write-ends open — those would otherwise
    // leave our reader threads blocked on EOF forever (audit C4).
    let status = child.wait().map_err(Error::ExecFailed)?;
    let exit_code = status.code().unwrap_or(-1);

    // After the direct child exits, take down any grandchildren that
    // could still be writing to the pipes. On Windows we have the
    // job-object handle (`job_handle` above); dropping it via
    // `TerminateJobObject` kills every descendant. On Unix we sent
    // the child to its own session via `setsid()` in pre_exec, so
    // killing the negative pgid signals the whole tree.
    #[cfg(windows)]
    {
        // Exit code 137 mirrors `kill -9` on Unix for clarity in
        // logs. The job handle drops at the end of scope anyway,
        // but we proactively terminate so the grandchildren do
        // not outlive our drain window.
        if let Some(ref job) = job_handle {
            job.kill_now(137);
        }
    }
    #[cfg(unix)]
    {
        // Best-effort: signal the child's process group. -pgid means
        // "send to every process in the pgid". If the child created
        // its own session via setsid, the grandchildren live in the
        // same group and all receive SIGKILL. ESRCH (no such pgid)
        // is fine — it means the tree is already gone.
        unsafe {
            let pgid = libc::getpgid(status.code().unwrap_or(0).max(0) as libc::pid_t);
            if pgid > 0 {
                let _ = libc::kill(-pgid, libc::SIGKILL);
            }
        }
    }

    // Drain the monitor threads with a hard deadline. If the writes
    // never land (grandchild died holding the pipe but never wrote
    // EOF for some reason), close the handles after the deadline so
    // we exit instead of hanging forever. 2 s is generous — once the
    // job is terminated, EOF should arrive in microseconds.
    let drain_deadline = std::time::Duration::from_secs(2);
    let (stdout_leaks, mut stdout_events) =
        join_with_deadline(stdout_handle, drain_deadline).unwrap_or((0, Vec::new()));
    let (stderr_leaks, mut stderr_events) =
        join_with_deadline(stderr_handle, drain_deadline).unwrap_or((0, Vec::new()));

    let leak_count = stdout_leaks + stderr_leaks;
    events.append(&mut stdout_events);
    events.append(&mut stderr_events);

    events.push(DataflowEvent {
        kind: DataflowEventKind::ProcessExited,
        timestamp_ms: u64::try_from(start_time.elapsed().as_millis()).unwrap_or(u64::MAX),
        detail: format!("child exited with code {exit_code}"),
    });

    if leak_count > 0 {
        log_leak_alerts(&events, leak_count, secret_name, &prepared.binary_path)?;
    }

    Ok(SupervisedResult {
        exit_code,
        leak_events: leak_count,
        events,
    })
}

/// Build a `Command` with piped I/O and sandbox pre-exec hooks.
///
/// For [`SandboxTier::Lockdown`] on Linux this spawns the envseal binary in
/// `__sandbox_helper` mode instead of the target directly: the helper finishes
/// the namespace setup (private `tmpfs` over `/tmp`, `MS_PRIVATE` propagation)
/// — operations that aren't async-signal-safe and can't run in `pre_exec` —
/// then `execve`s the target via the inherited fd so TOCTOU pinning is preserved.
fn build_supervised_command(prepared: &PreparedExecution, tier: SandboxTier) -> Command {
    #[cfg(target_os = "linux")]
    {
        if matches!(tier, SandboxTier::Lockdown) {
            return build_lockdown_helper_command(prepared, tier);
        }
    }

    let mut cmd = Command::new(&prepared.exec_path);
    #[cfg(target_os = "linux")]
    cmd.arg0(&prepared.binary_path);
    cmd.args(&prepared.args);
    cmd.env_clear();
    for (k, v) in &prepared.clean_env {
        cmd.env(k, v);
    }
    for (var, val) in &prepared.env_pairs {
        cmd.env(var, val.as_str());
    }

    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());

    #[cfg(unix)]
    {
        let tier_for_child = tier;
        unsafe {
            cmd.pre_exec(move || {
                // Audit L15: block all signals for the duration of
                // the sandbox-setup window. A signal arriving during
                // namespace / seccomp / mount-NS construction could
                // interrupt syscalls partway through, leaving the
                // child in a half-sandboxed state — or kill it
                // outright before execve. Save the previous mask so
                // execve inherits a clean state. SIGKILL and SIGSTOP
                // cannot be blocked (kernel ignores any attempt) so
                // the parent retains its emergency-kill ability.
                //
                // SAFETY: sigprocmask is async-signal-safe; we hold
                // a stack-resident sigset_t for the lifetime of the
                // call.
                let prev_mask: libc::sigset_t = unsafe {
                    let mut full: libc::sigset_t = std::mem::zeroed();
                    libc::sigfillset(&mut full);
                    let mut prev: libc::sigset_t = std::mem::zeroed();
                    libc::sigprocmask(libc::SIG_BLOCK, &full, &mut prev);
                    prev
                };

                super::context::harden_child_process_inner()?;
                // Audit M16: arrange for the child to be SIGKILLed
                // when the parent (envseal supervisor) dies. Without
                // this, an OOM-killed / SIGKILLed supervisor would
                // leave the child re-parented to init and still
                // running with the secret in its environment. Linux
                // only — no equivalent on macOS.
                #[cfg(target_os = "linux")]
                {
                    // SAFETY: prctl(PR_SET_PDEATHSIG, SIGKILL) is
                    // async-signal-safe and well-documented to be
                    // valid in pre_exec. Failure (rare) doesn't
                    // prevent execve — we only lose the kill-on-
                    // parent-death property.
                    let rc = unsafe { libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) };
                    if rc != 0 {
                        // Log to stderr but do not abort — the rest
                        // of the sandboxing matters more than this
                        // belt-and-suspenders signal.
                        let _ = std::io::Write::write_all(
                            &mut std::io::stderr(),
                            b"envseal: pre_exec: prctl(PR_SET_PDEATHSIG) failed; child may outlive supervisor\n",
                        );
                    }
                }
                crate::sandbox::apply_sandbox(tier_for_child)?;
                // Restore the inherited signal mask just before
                // execve. The child's new image gets a normal
                // signal handler set rather than the oddly-narrow
                // mask we used for setup.
                unsafe {
                    libc::sigprocmask(libc::SIG_SETMASK, &prev_mask, std::ptr::null_mut());
                }
                Ok(())
            });
        }
    }
    #[cfg(not(unix))]
    let _ = tier;

    cmd
}

/// Build the Lockdown helper-mode Command (Linux-only).
///
/// The helper runs `envseal __sandbox_helper`, inheriting:
///
/// - The target binary's pinned fd (via `clear_cloexec` on `prepared._pinned_file`'s
///   raw fd in `pre_exec`).
/// - The decrypted secret env-vars and sanitized environment.
/// - Stdout/stderr pipes from the supervisor.
///
/// The helper performs the not-async-signal-safe mount setup, then `execve`s
/// the target via `/proc/self/fd/<N>`.
#[cfg(target_os = "linux")]
fn build_lockdown_helper_command(prepared: &PreparedExecution, tier: SandboxTier) -> Command {
    let envseal_self =
        std::env::current_exe().unwrap_or_else(|_| std::path::PathBuf::from("/proc/self/exe"));

    // The pinned-file fd is exposed as a typed accessor so the
    // Lockdown helper can inherit the binary across `execve`. The
    // `PreparedExecution` keeps the file alive until after spawn —
    // see [`crate::execution::context::PreparedExecution`].
    let target_fd: std::os::fd::RawFd = prepared.pinned_target_fd();

    let mut cmd = Command::new(&envseal_self);
    cmd.arg("__sandbox_helper");
    cmd.arg("--target-fd");
    cmd.arg(target_fd.to_string());
    cmd.arg("--arg0");
    cmd.arg(&prepared.binary_path);
    cmd.arg("--");
    cmd.args(&prepared.args);

    cmd.env_clear();
    for (k, v) in &prepared.clean_env {
        cmd.env(k, v);
    }
    for (var, val) in &prepared.env_pairs {
        cmd.env(var, val.as_str());
    }

    cmd.stdout(Stdio::piped());
    cmd.stderr(Stdio::piped());

    let tier_for_child = tier;
    unsafe {
        cmd.pre_exec(move || {
            super::context::harden_child_process_inner()?;
            crate::sandbox::apply_sandbox(tier_for_child)?;
            // Clear FD_CLOEXEC on the target fd so it survives the upcoming
            // execve into the helper. Without this the helper would see a
            // closed fd and have no way to reach the target binary.
            if target_fd >= 0 {
                let prev = libc::fcntl(target_fd, libc::F_GETFD);
                if prev < 0 {
                    return Err(std::io::Error::last_os_error());
                }
                if libc::fcntl(target_fd, libc::F_SETFD, prev & !libc::FD_CLOEXEC) < 0 {
                    return Err(std::io::Error::last_os_error());
                }
            }
            Ok(())
        });
    }

    cmd
}

/// Monitor a piped stream for secret leakage, forwarding clean output.
///
/// Uses an overlap buffer of `secret.len() - 1` bytes from the previous
/// chunk to catch secrets that straddle read boundaries. Without this,
/// a secret split across two 8192-byte reads would evade detection.
/// Join a thread but give up after `deadline`. Returns `Some(value)`
/// if the thread finished in time, `None` if it had to be abandoned.
///
/// Audit C4: a grandchild process that inherited the supervised
/// child's stdout/stderr can keep the pipe write-end open after the
/// direct child exits, causing `JoinHandle::join()` to block on EOF
/// that never arrives. Even though we kill the entire process group
/// / job object before draining, defense-in-depth says: never let an
/// I/O thread we don't trust to terminate keep us hostage. The
/// caller treats `None` as "no leaks observed in the drained
/// fragment, no events recorded" — preferable to a hang.
fn join_with_deadline<T: Send + 'static>(
    handle: std::thread::JoinHandle<T>,
    deadline: std::time::Duration,
) -> Option<T> {
    use std::sync::mpsc;
    let (tx, rx) = mpsc::channel();
    std::thread::spawn(move || {
        let _ = tx.send(handle.join());
    });
    match rx.recv_timeout(deadline) {
        Ok(Ok(value)) => Some(value),
        Ok(Err(_panic)) => None,
        Err(_timeout) => None,
    }
}

fn monitor_stream(
    stream: Option<impl Read>,
    secret: &[u8],
    leak_kind: &DataflowEventKind,
    is_stdout: bool,
    start_time: std::time::Instant,
) -> (usize, Vec<DataflowEvent>) {
    let mut leaks = 0;
    let mut events = Vec::new();

    if let Some(mut reader) = stream {
        let mut buf = [0u8; 8192];
        let overlap_len = if secret.len() > 1 {
            secret.len() - 1
        } else {
            0
        };
        let mut overlap = Zeroizing::new(Vec::<u8>::new());

        loop {
            match reader.read(&mut buf) {
                Ok(0) | Err(_) => break,
                Ok(n) => {
                    let chunk = &buf[..n];

                    let has_leak = if overlap.is_empty() {
                        contains_secret(chunk, secret)
                    } else {
                        let mut combined = Zeroizing::new(overlap.clone());
                        combined.extend_from_slice(chunk);
                        contains_secret(combined.as_ref(), secret)
                    };

                    if has_leak {
                        let redacted = redact_bytes(chunk, secret);
                        if is_stdout {
                            let _ = std::io::stdout().write_all(&redacted);
                        } else {
                            let _ = std::io::stderr().write_all(&redacted);
                        }
                        leaks += 1;
                        events.push(DataflowEvent {
                            kind: leak_kind.clone(),
                            timestamp_ms: u64::try_from(start_time.elapsed().as_millis())
                                .unwrap_or(u64::MAX),
                            detail: format!(
                                "secret detected in {} output ({n} bytes) — redacted",
                                if is_stdout { "stdout" } else { "stderr" }
                            ),
                        });
                    } else if is_stdout {
                        let _ = std::io::stdout().write_all(chunk);
                    } else {
                        let _ = std::io::stderr().write_all(chunk);
                    }

                    if overlap_len > 0 && n >= overlap_len {
                        overlap = Zeroizing::new(chunk[n - overlap_len..].to_vec());
                    } else if overlap_len > 0 {
                        overlap = Zeroizing::new(chunk.to_vec());
                    }
                }
            }
        }
        buf.fill(0);
        overlap.zeroize();
    }

    (leaks, events)
}

/// Log leak alerts to stderr and the audit log.
fn log_leak_alerts(
    events: &[DataflowEvent],
    leak_count: usize,
    secret_name: &str,
    binary_path: &str,
) -> Result<(), Error> {
    // Build a single multi-line detail string for the Signal so the
    // unified renderer surfaces every leak under one warning rather
    // than fragmenting it into N stderr lines that drift in format.
    let mut detail = format!(
        "{leak_count} secret leak(s) detected and REDACTED — the secret was NOT \
         exposed to the calling process"
    );
    for event in events {
        if event.kind == DataflowEventKind::LeakedStdout
            || event.kind == DataflowEventKind::LeakedStderr
        {
            detail.push_str("\n    └─ ");
            detail.push_str(&event.detail);
        }
    }

    let _ = crate::guard::emit_signal_inline(
        crate::guard::Signal::new(
            crate::guard::SignalId::scoped("execution.supervisor.leak", secret_name),
            crate::guard::Category::SupervisorLeak,
            crate::guard::Severity::Hostile,
            "supervised child leaked secret",
            detail,
            "review the child binary; tighten the rule set to require Lockdown sandbox tier",
        ),
        &crate::security_config::load_system_defaults(),
    );

    // Keep the structured audit event alongside the Signal-flavored log
    // entry — it carries typed fields useful for forensic analytics
    // beyond what the SignalId alone captures.
    crate::audit::log_required(&crate::audit::AuditEvent::SupervisorLeakDetected {
        secret: secret_name.to_string(),
        binary: binary_path.to_string(),
        leak_count,
    })?;
    Ok(())
}

/// Check if a byte buffer contains the secret value.
fn contains_secret(haystack: &[u8], needle: &[u8]) -> bool {
    if needle.is_empty() || haystack.len() < needle.len() {
        return false;
    }
    haystack.windows(needle.len()).any(|w| w == needle)
}

/// Replace all occurrences of the secret in a byte buffer with a redaction marker.
fn redact_bytes(data: &[u8], secret: &[u8]) -> Zeroizing<Vec<u8>> {
    if secret.is_empty() {
        return Zeroizing::new(data.to_vec());
    }

    let marker = b"[ENVSEAL:REDACTED]";
    let mut result = Zeroizing::new(Vec::with_capacity(data.len()));
    let mut i = 0;

    while i < data.len() {
        if i + secret.len() <= data.len() && &data[i..i + secret.len()] == secret {
            result.extend_from_slice(marker);
            i += secret.len();
        } else {
            result.push(data[i]);
            i += 1;
        }
    }

    result
}

/// Print a dataflow report to stderr.
pub fn print_dataflow_report(result: &SupervisedResult, secret_name: &str) {
    eprintln!();
    eprintln!("╔═══════════════════════════════════════════════╗");
    eprintln!("║          envseal dataflow report              ║");
    eprintln!("╚═══════════════════════════════════════════════╝");
    eprintln!();

    for event in &result.events {
        let icon = match event.kind {
            DataflowEventKind::SecretInjected => "🔑",
            DataflowEventKind::LeakedStdout | DataflowEventKind::LeakedStderr => "🚨",
            DataflowEventKind::ProcessExited => "",
        };
        eprintln!("  {icon} [{:>6}ms] {}", event.timestamp_ms, event.detail);
    }

    eprintln!();
    if result.leak_events > 0 {
        eprintln!(
            "  ⚠️  {} leak(s) detected and REDACTED for secret '{}'",
            result.leak_events, secret_name
        );
    } else {
        eprintln!("  ✅ no leaks detected for secret '{secret_name}'");
    }
    eprintln!("  exit code: {}", result.exit_code);
    eprintln!();
}