kovra-wrapper 0.9.1

kovra subprocess wrapper — injects resolved secrets into a child process's environment without leaking plaintext (I6/I7).
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
//! Integration tests for KOV-6 (L5) — the Wrapper end-to-end over a `tempfile`
//! registry with mock core dependencies. Covers the spec §17 L5 exit criteria
//! and the applicable invariants: I7 (no disk writes; injected via child env),
//! I15 (non-allowlisted command refused high/prod injection), I3/I16 (high/prod
//! blocks pending an attended confirmation whose prompt shows the exact argv).
//! No real secrets, no real provider, no network.

use std::path::Path;
use std::str::FromStr;
use std::sync::Mutex;
use std::time::Duration;

use kovra_core::{
    AuditAction, CliApproveConfirmer, ConfirmOutcome, ConfirmRequest, Confirmer, Coordinate,
    EnvRefs, KEY_LEN, MockAuditSink, MockClock, MockConfirmer, MockEnvSource, MockKeyring,
    MockProvider, Origin, Registry, SecretRecord, SecretValue, Sensitivity, seal, store,
};
use kovra_wrapper::{Allowlist, MockRunner, Output, ProcessRunner, Wrapper, WrapperError};
// Only the real-spawn (`SystemRunner`) e2e tests use it, and those are `cfg(unix)`
// (they launch a `/bin/sh` child); the Windows inject e2e is validated live (row 5).
#[cfg(unix)]
use kovra_wrapper::SystemRunner;

const MASTER: [u8; KEY_LEN] = [0x5a; KEY_LEN];

fn lit(value: &str, sensitivity: Sensitivity, env: &str, comp: &str, key: &str) -> SecretRecord {
    SecretRecord::Literal {
        value: SecretValue::from(value),
        sensitivity,
        revealable: false,
        environment: env.to_string(),
        component: comp.to_string(),
        key: key.to_string(),
        description: None,
        created: "2026-05-30T00:00:00Z".to_string(),
        updated: "2026-05-30T00:00:00Z".to_string(),
    }
}

/// Owns the long-lived mock dependencies so the `Wrapper`'s borrows outlive it.
struct Fixture {
    _tmp: tempfile::TempDir,
    reg: Registry,
    keyring: MockKeyring,
    env_source: MockEnvSource,
    provider: MockProvider,
    audit: MockAuditSink,
    clock: MockClock,
    requesting_process: Option<String>,
}

impl Fixture {
    fn new() -> Self {
        let tmp = tempfile::tempdir().unwrap();
        let reg = Registry::open(tmp.path()).unwrap();
        Self {
            _tmp: tmp,
            reg,
            keyring: MockKeyring::with_key(MASTER),
            env_source: MockEnvSource::new(),
            provider: MockProvider::new(),
            audit: MockAuditSink::new(),
            clock: MockClock::default(),
            requesting_process: None,
        }
    }

    /// Set the trusted, observed requesting-process identity (I16, §8.3).
    fn with_requesting_process(mut self, s: &str) -> Self {
        self.requesting_process = Some(s.to_string());
        self
    }

    fn seed_global(&self, coord: &str, record: SecretRecord) {
        let c = Coordinate::from_str(coord).unwrap();
        store::write_record(&self.reg.global_dir(), &c, &seal(&record, &MASTER).unwrap()).unwrap();
    }

    fn wrapper<'a>(
        &'a self,
        confirmer: &'a dyn Confirmer,
        allowlist: &'a Allowlist,
        runner: &'a dyn ProcessRunner,
        confirm_timeout: Duration,
        sanitize_output: bool,
    ) -> Wrapper<'a> {
        Wrapper {
            registry: &self.reg,
            keyring: &self.keyring,
            env_source: &self.env_source,
            provider: &self.provider,
            confirmer,
            audit: &self.audit,
            clock: &self.clock,
            allowlist,
            runner,
            confirm_timeout,
            sanitize_output,
            stdio_passthrough: false,
            requesting_process: self.requesting_process.clone(),
        }
    }
}

/// A confirmer that records the request it saw and returns a fixed outcome — for
/// asserting the authoritative prompt contract (I16).
struct RecordingConfirmer {
    outcome: ConfirmOutcome,
    seen: Mutex<Option<ConfirmRequest>>,
}

impl RecordingConfirmer {
    fn new(outcome: ConfirmOutcome) -> Self {
        Self {
            outcome,
            seen: Mutex::new(None),
        }
    }
    fn request(&self) -> Option<ConfirmRequest> {
        self.seen.lock().unwrap().clone()
    }
}

impl Confirmer for RecordingConfirmer {
    fn confirm(&self, req: &ConfirmRequest, _timeout: Duration) -> ConfirmOutcome {
        *self.seen.lock().unwrap() = Some(req.clone());
        self.outcome
    }
}

/// A reviewed, allowlisted executable (must exist for path canonicalization).
fn reviewed_exe(dir: &Path) -> std::path::PathBuf {
    let p = dir.join("deploy.sh");
    std::fs::write(&p, b"#!/bin/sh\n").unwrap();
    p
}

// I7 — a low/medium non-prod value injects into the child's environment (proven
// by the child echoing it) and the Wrapper writes nothing to a scratch dir. Also
// proves the allowlist/broker are NOT consulted for non-gated values (the
// confirmer is always-deny yet the run succeeds).
// Unix-only: spawns a real `/bin/sh -c printf` child. The Windows inject e2e
// (env injection + no-disk-write) is validated live on the HP i7 (tracker row 5);
// the inject logic itself is platform-agnostic and covered on Unix here.
#[test]
#[cfg(unix)]
fn injects_value_via_child_env_and_writes_nothing_to_disk() {
    let fx = Fixture::new();
    fx.seed_global(
        "secret:dev/app/token",
        lit("s3cr3t-dev", Sensitivity::Medium, "dev", "app", "token"),
    );

    let scratch = tempfile::tempdir().unwrap();
    let allow = Allowlist::empty();
    let runner = SystemRunner;
    let deny = MockConfirmer::always(ConfirmOutcome::Denied);
    let w = fx.wrapper(&deny, &allow, &runner, Duration::from_secs(1), false);

    let refs = EnvRefs::parse("TOKEN=secret:dev/app/token").unwrap();
    let out = w
        .run(
            &refs,
            "dev",
            None,
            Path::new("/bin/sh"),
            &["-c".to_string(), "printf %s \"$TOKEN\"".to_string()],
            Origin::Human,
        )
        .unwrap();

    assert_eq!(out.status, Some(0));
    assert_eq!(String::from_utf8_lossy(&out.stdout), "s3cr3t-dev");
    assert_eq!(
        std::fs::read_dir(scratch.path()).unwrap().count(),
        0,
        "the Wrapper must not write any file to disk (I7)"
    );
}

// KOV-65 — stdio passthrough threads `inherit_stdio` to the runner and skips the
// output mask: an inherited stream is not captured, so there is nothing to mask;
// the secret stays in the child env only (I6/I7). Deterministic via MockRunner.
#[test]
fn stdio_passthrough_threads_inherit_stdio_and_skips_masking() {
    let fx = Fixture::new();
    fx.seed_global(
        "secret:dev/app/token",
        lit("supersecret", Sensitivity::Low, "dev", "app", "token"),
    );
    let refs = EnvRefs::parse("TOKEN=secret:dev/app/token").unwrap();
    let deny = MockConfirmer::always(ConfirmOutcome::Denied); // `low` never gates
    let allow = Allowlist::empty();

    // Passthrough ON: inherit_stdio is threaded and masking is skipped — the raw
    // (mock) child output passes through unchanged.
    let runner = MockRunner::new(Output {
        status: Some(0),
        stdout: b"child echoed supersecret".to_vec(),
        stderr: Vec::new(),
    });
    let mut w = fx.wrapper(&deny, &allow, &runner, Duration::from_secs(1), true);
    w.stdio_passthrough = true;
    let out = w
        .run(
            &refs,
            "dev",
            None,
            Path::new("/bin/true"),
            &[],
            Origin::Human,
        )
        .unwrap();
    let runs = runner.invocations();
    assert_eq!(runs.len(), 1);
    assert!(
        runs[0].inherit_stdio,
        "passthrough must thread inherit_stdio"
    );
    assert_eq!(
        out.stdout, b"child echoed supersecret",
        "masking is skipped"
    );

    // Contrast: passthrough OFF (default) with sanitize ON masks the vault value.
    let runner2 = MockRunner::new(Output {
        status: Some(0),
        stdout: b"child echoed supersecret".to_vec(),
        stderr: Vec::new(),
    });
    let w2 = fx.wrapper(&deny, &allow, &runner2, Duration::from_secs(1), true);
    let out2 = w2
        .run(
            &refs,
            "dev",
            None,
            Path::new("/bin/true"),
            &[],
            Origin::Human,
        )
        .unwrap();
    assert!(!runner2.invocations()[0].inherit_stdio);
    assert!(
        !String::from_utf8_lossy(&out2.stdout).contains("supersecret"),
        "non-passthrough run masks the vault-backed secret"
    );
}

// KOV-65 — in passthrough mode the child's stdout is INHERITED, not captured, so
// kovra returns no captured output (the child streams straight through). Proves
// the inherit branch is taken with a real spawn. Real stdin piping into a wrapped
// stdio server (the MCP use case) is validated `[host]`.
#[test]
#[cfg(unix)]
fn stdio_passthrough_inherits_output_instead_of_capturing() {
    let fx = Fixture::new();
    fx.seed_global(
        "secret:dev/app/token",
        lit("s3cr3t", Sensitivity::Low, "dev", "app", "token"),
    );
    let runner = SystemRunner;
    let deny = MockConfirmer::always(ConfirmOutcome::Denied);
    let allow = Allowlist::empty();
    let mut w = fx.wrapper(&deny, &allow, &runner, Duration::from_secs(5), true);
    w.stdio_passthrough = true;
    let refs = EnvRefs::parse("TOKEN=secret:dev/app/token").unwrap();
    let out = w
        .run(
            &refs,
            "dev",
            None,
            Path::new("/bin/sh"),
            &["-c".to_string(), "true".to_string()],
            Origin::Human,
        )
        .unwrap();
    assert_eq!(out.status, Some(0));
    assert!(
        out.stdout.is_empty(),
        "passthrough inherits stdout; nothing is captured by kovra"
    );
}

// I15 — a `high` secret injected into a command NOT on the executor allowlist is
// refused, before any confirmation or launch. The confirmer is always-approve to
// prove the allowlist gate fires first.
#[test]
fn high_injection_into_non_allowlisted_command_is_refused() {
    let fx = Fixture::new();
    fx.seed_global(
        "secret:dev/app/key",
        lit("hunter2", Sensitivity::High, "dev", "app", "key"),
    );

    let allow = Allowlist::empty(); // nothing reviewed
    let runner = MockRunner::ok();
    let approve = MockConfirmer::always(ConfirmOutcome::Approved);
    let w = fx.wrapper(&approve, &allow, &runner, Duration::from_secs(1), false);

    let refs = EnvRefs::parse("KEY=secret:dev/app/key").unwrap();
    let err = w
        .run(
            &refs,
            "dev",
            None,
            Path::new("/bin/sh"),
            &["-c".to_string(), "true".to_string()],
            Origin::Agent,
        )
        .unwrap_err();

    assert!(matches!(err, WrapperError::NotAllowlisted { .. }));
    assert!(!runner.was_invoked(), "the child must never launch (I15)");
    assert!(
        fx.audit
            .events()
            .iter()
            .any(|e| e.result == "denied:not-allowlisted"),
        "the refusal is audited"
    );
}

// I3/I16 — a prod (born-high) injection into an allowlisted command blocks on the
// broker; a denial refuses injection and the child never launches. The
// authoritative prompt carries the exact resolved argv (I16) and no requester
// text.
#[test]
fn prod_high_denied_blocks_injection_and_prompt_shows_argv() {
    let fx = Fixture::new();
    fx.seed_global(
        "secret:prod/db/password",
        lit("prod-pw", Sensitivity::High, "prod", "db", "password"),
    );

    let bin = tempfile::tempdir().unwrap();
    let deploy = reviewed_exe(bin.path());
    let allow = Allowlist::from_paths([&deploy]);

    let runner = MockRunner::ok();
    let confirmer = RecordingConfirmer::new(ConfirmOutcome::Denied);
    let w = fx.wrapper(&confirmer, &allow, &runner, Duration::from_secs(1), false);

    let refs = EnvRefs::parse("DB=secret:prod/db/password").unwrap();
    let err = w
        .run(
            &refs,
            "prod",
            None,
            &deploy,
            &["--now".to_string()],
            Origin::Human,
        )
        .unwrap_err();

    assert!(matches!(err, WrapperError::ConfirmationDenied));
    assert!(!runner.was_invoked(), "denied ⇒ child never launches");

    let req = confirmer.request().expect("the broker was consulted");
    let expected = format!("{} --now", deploy.display());
    assert_eq!(
        req.resolved_command.as_deref(),
        Some(expected.as_str()),
        "the prompt shows the exact resolved argv (I16)"
    );
    assert_eq!(req.coordinate, "prod/db/password");
    assert_eq!(req.environment, "prod");
    assert_eq!(req.sensitivity, Sensitivity::High);
    assert!(
        req.requester_description.is_none(),
        "authoritative prompt carries no requester free-text"
    );
    assert!(fx.audit.events().iter().any(|e| e.result == "denied"));
}

// I16/§8.3 — the trusted, observed requesting-process identity threads onto the
// authoritative prompt as its own field, never via the untrusted description.
#[test]
fn prompt_carries_observed_requesting_process() {
    let fx = Fixture::new().with_requesting_process("node (pid 4242)");
    fx.seed_global(
        "secret:prod/db/password",
        lit("prod-pw", Sensitivity::High, "prod", "db", "password"),
    );

    let bin = tempfile::tempdir().unwrap();
    let deploy = reviewed_exe(bin.path());
    let allow = Allowlist::from_paths([&deploy]);

    let runner = MockRunner::ok();
    let confirmer = RecordingConfirmer::new(ConfirmOutcome::Denied);
    let w = fx.wrapper(&confirmer, &allow, &runner, Duration::from_secs(1), false);

    let refs = EnvRefs::parse("DB=secret:prod/db/password").unwrap();
    let _ = w.run(&refs, "prod", None, &deploy, &[], Origin::Agent);

    let req = confirmer.request().expect("the broker was consulted");
    assert_eq!(
        req.requesting_process.as_deref(),
        Some("node (pid 4242)"),
        "the observed requesting process threads onto the prompt (I16/§8.3)"
    );
    // It is a trusted field, distinct from the untrusted requester description.
    assert!(req.requester_description.is_none());
}

// The approved path: prod/high into an allowlisted command launches, injects the
// value, and audits Approve + Inject.
#[test]
fn prod_high_approved_injects_and_audits() {
    let fx = Fixture::new();
    fx.seed_global(
        "secret:prod/db/password",
        lit("prod-pw", Sensitivity::High, "prod", "db", "password"),
    );

    let bin = tempfile::tempdir().unwrap();
    let deploy = reviewed_exe(bin.path());
    let allow = Allowlist::from_paths([&deploy]);

    let runner = MockRunner::ok();
    let approve = MockConfirmer::always(ConfirmOutcome::Approved);
    let w = fx.wrapper(&approve, &allow, &runner, Duration::from_secs(1), false);

    let refs = EnvRefs::parse("DB=secret:prod/db/password").unwrap();
    let out = w
        .run(&refs, "prod", None, &deploy, &[], Origin::Human)
        .unwrap();

    assert_eq!(
        out,
        Output {
            status: Some(0),
            stdout: Vec::new(),
            stderr: Vec::new()
        }
    );
    let runs = runner.invocations();
    assert_eq!(runs.len(), 1);
    assert_eq!(
        runs[0].env_value("DB"),
        Some("prod-pw"),
        "value injected into child env"
    );

    let actions: Vec<_> = fx.audit.events().iter().map(|e| e.action).collect();
    assert!(actions.contains(&AuditAction::Approve));
    assert!(actions.contains(&AuditAction::Inject));
}

// KOV-25 — a deliberately-downgraded `prod` secret (now `low`) injects into an
// allowlisted command WITHOUT a biometric prompt (I3: confirmation is
// sensitivity-only, orthogonal to environment); the executor allowlist (I15)
// still applies.
#[test]
fn downgraded_prod_low_injects_without_prompt_but_still_needs_allowlist() {
    let fx = Fixture::new();
    fx.seed_global(
        "secret:prod/db/password",
        lit("prod-pw", Sensitivity::Low, "prod", "db", "password"),
    );

    let bin = tempfile::tempdir().unwrap();
    let deploy = reviewed_exe(bin.path());
    let allow = Allowlist::from_paths([&deploy]);

    let runner = MockRunner::ok();
    // Always-deny broker: were it consulted, the run would fail. It must NOT be.
    let confirmer = RecordingConfirmer::new(ConfirmOutcome::Denied);
    let w = fx.wrapper(&confirmer, &allow, &runner, Duration::from_secs(1), false);

    let refs = EnvRefs::parse("DB=secret:prod/db/password").unwrap();
    let out = w
        .run(&refs, "prod", None, &deploy, &[], Origin::Human)
        .unwrap();
    assert_eq!(
        out.status,
        Some(0),
        "downgraded prod injects without a prompt"
    );
    assert!(
        confirmer.request().is_none(),
        "the broker is NOT consulted for a `low` secret (I3 — sensitivity-only)"
    );
    assert!(runner.was_invoked(), "the child launches");

    // …but I15 still holds: the same injection into a non-allowlisted command is
    // refused (prod containment is environment-aware, independent of the prompt).
    let runner2 = MockRunner::ok();
    let empty = Allowlist::empty();
    let approve = MockConfirmer::always(ConfirmOutcome::Approved);
    let w2 = fx.wrapper(&approve, &empty, &runner2, Duration::from_secs(1), false);
    let err = w2
        .run(&refs, "prod", None, &deploy, &[], Origin::Human)
        .unwrap_err();
    assert!(
        matches!(err, WrapperError::NotAllowlisted { .. }),
        "a downgraded prod secret still requires an allowlisted executable (I15)"
    );
    assert!(!runner2.was_invoked());
}

// inject-only (non-prod) is its normal delivery: injected without a prompt and
// without consulting the allowlist (the confirmer is always-deny yet it runs).
#[test]
fn inject_only_non_prod_passes_without_confirmation() {
    let fx = Fixture::new();
    fx.seed_global(
        "secret:dev/app/secret",
        lit("io-value", Sensitivity::InjectOnly, "dev", "app", "secret"),
    );

    let allow = Allowlist::empty();
    let runner = MockRunner::ok();
    let deny = MockConfirmer::always(ConfirmOutcome::Denied);
    let w = fx.wrapper(&deny, &allow, &runner, Duration::from_secs(1), false);

    let refs = EnvRefs::parse("S=secret:dev/app/secret").unwrap();
    w.run(
        &refs,
        "dev",
        None,
        Path::new("/bin/sh"),
        &["-c".to_string(), "true".to_string()],
        Origin::Agent,
    )
    .unwrap();

    let runs = runner.invocations();
    assert_eq!(runs.len(), 1, "inject-only delivers by injection");
    assert_eq!(runs[0].env_value("S"), Some("io-value"));
}

// A confirmation timeout fails safe to denial (§8): injection refused, child
// never launches, timeout audited.
#[test]
fn confirmation_timeout_denies_injection() {
    let fx = Fixture::new();
    fx.seed_global(
        "secret:prod/db/password",
        lit("prod-pw", Sensitivity::High, "prod", "db", "password"),
    );

    let bin = tempfile::tempdir().unwrap();
    let deploy = reviewed_exe(bin.path());
    let allow = Allowlist::from_paths([&deploy]);

    let runner = MockRunner::ok();
    let confirmer = CliApproveConfirmer::new(); // no approver ⇒ times out
    let w = fx.wrapper(
        &confirmer,
        &allow,
        &runner,
        Duration::from_millis(20),
        false,
    );

    let refs = EnvRefs::parse("DB=secret:prod/db/password").unwrap();
    let err = w
        .run(&refs, "prod", None, &deploy, &[], Origin::Human)
        .unwrap_err();

    assert!(matches!(err, WrapperError::ConfirmationTimedOut));
    assert!(!runner.was_invoked());
    assert!(fx.audit.events().iter().any(|e| e.result == "timeout"));
}

// The §5.1 margin defense, end-to-end: with sanitization on, a naive echo of an
// injected value is masked in the child's stdout.
// Unix-only: spawns a real `/bin/sh` child. The Windows masking e2e is validated
// live on the HP i7 (tracker row 5: `cmd /c echo` → vault value shown as `***`).
#[test]
#[cfg(unix)]
fn sanitization_masks_injected_value_in_output() {
    let fx = Fixture::new();
    fx.seed_global(
        "secret:dev/app/token",
        lit("leak-me-123", Sensitivity::Medium, "dev", "app", "token"),
    );

    let allow = Allowlist::empty();
    let runner = SystemRunner;
    let deny = MockConfirmer::always(ConfirmOutcome::Denied);
    let w = fx.wrapper(&deny, &allow, &runner, Duration::from_secs(1), true);

    let refs = EnvRefs::parse("TOKEN=secret:dev/app/token").unwrap();
    let out = w
        .run(
            &refs,
            "dev",
            None,
            Path::new("/bin/sh"),
            &["-c".to_string(), "printf %s \"$TOKEN\"".to_string()],
            Origin::Human,
        )
        .unwrap();

    assert_eq!(String::from_utf8_lossy(&out.stdout), "***");
    assert!(!String::from_utf8_lossy(&out.stdout).contains("leak-me-123"));
}

// Sanitization masks vault-backed secret values but leaves plain literals and
// `${env:}` passthrough untouched (§5.1 — the net targets secrets, not config).
// Unix-only: spawns a real `/bin/sh` child. Windows masking validated live (row 5).
#[test]
#[cfg(unix)]
fn sanitization_masks_only_vault_backed_secrets() {
    let fx = Fixture::new();
    fx.seed_global(
        "secret:dev/app/token",
        lit("sekret9", Sensitivity::Medium, "dev", "app", "token"),
    );

    let allow = Allowlist::empty();
    let runner = SystemRunner;
    let deny = MockConfirmer::always(ConfirmOutcome::Denied);
    let w = fx.wrapper(&deny, &allow, &runner, Duration::from_secs(1), true);

    // PORT is a literal, TOKEN is a vault secret. The child echoes both.
    let refs = EnvRefs::parse("PORT=8080\nTOKEN=secret:dev/app/token").unwrap();
    let out = w
        .run(
            &refs,
            "dev",
            None,
            Path::new("/bin/sh"),
            &[
                "-c".to_string(),
                "printf 'PORT=%s TOKEN=%s' \"$PORT\" \"$TOKEN\"".to_string(),
            ],
            Origin::Human,
        )
        .unwrap();

    let stdout = String::from_utf8_lossy(&out.stdout);
    assert_eq!(
        stdout, "PORT=8080 TOKEN=***",
        "literal visible, secret masked"
    );
}

// I2/I7 — a launched child must NOT inherit kovra's own `KOVRA_*` environment.
// In passphrase mode `KOVRA_PASSPHRASE` is the master key; if it leaked into a
// child, any non-gated `low`/`medium` run could scrape the vault key from its
// own environment. The runner scrubs every inherited `KOVRA_*` before injecting,
// while still delivering the explicitly injected variables.
#[test]
#[cfg(unix)]
fn child_never_inherits_kovra_own_env() {
    use kovra_wrapper::Command as RunCommand;

    // SAFETY: edition-2024 marks env mutation unsafe (it is process-global and
    // races with concurrent readers). This test owns a uniquely-named var and
    // only asserts the *absence* of `KOVRA_*` in the child, which holds
    // regardless of races; we remove it again before returning.
    unsafe {
        std::env::set_var("KOVRA_PASSPHRASE", "leak-me-master-key");
        std::env::set_var("KOVRA_RECIPIENT_KEY", "leak-me-recipient");
    }

    let runner = SystemRunner;
    let cmd = RunCommand {
        program: Path::new("/bin/sh").to_path_buf(),
        args: vec!["-c".to_string(), "env".to_string()],
        env: vec![("TOKEN".to_string(), SecretValue::from("injected-ok"))],
        inherit_stdio: false,
    };
    let out = runner.run(&cmd).unwrap();

    unsafe {
        std::env::remove_var("KOVRA_PASSPHRASE");
        std::env::remove_var("KOVRA_RECIPIENT_KEY");
    }

    let dump = String::from_utf8_lossy(&out.stdout);
    assert!(
        !dump.contains("KOVRA_PASSPHRASE") && !dump.contains("leak-me-master-key"),
        "child must not inherit KOVRA_PASSPHRASE (I2/I7)"
    );
    assert!(
        !dump.contains("KOVRA_RECIPIENT_KEY") && !dump.contains("leak-me-recipient"),
        "child must not inherit KOVRA_RECIPIENT_KEY (I2/I7)"
    );
    assert!(
        !dump.lines().any(|l| l.starts_with("KOVRA_")),
        "no KOVRA_* variable may reach the child"
    );
    assert!(
        dump.contains("TOKEN=injected-ok"),
        "explicitly injected variables are still delivered"
    );
}

// I15 (TOCTOU) — an allowlist-gated run executes the *canonicalized* reviewed
// file, not the (possibly symlinked) path as-typed. The allowlist matches on the
// canonical path; if the spawn used the raw symlink, an attacker could repoint it
// to another file during the confirmation window and have it receive the
// high/prod value. Resolving once and spawning the resolved path binds the
// decision to the execution.
#[test]
#[cfg(unix)]
fn gated_run_executes_canonical_path_not_symlink() {
    let fx = Fixture::new();
    fx.seed_global(
        "secret:prod/db/password",
        lit("prod-pw", Sensitivity::High, "prod", "db", "password"),
    );

    let dir = tempfile::tempdir().unwrap();
    let real = dir.path().join("real-deploy.sh");
    std::fs::write(&real, b"#!/bin/sh\n").unwrap();
    let link = dir.path().join("deploy.sh");
    std::os::unix::fs::symlink(&real, &link).unwrap();

    // The allowlist is built from the symlink; it canonicalizes to `real`.
    let allow = Allowlist::from_paths([&link]);
    let runner = MockRunner::ok();
    let approve = MockConfirmer::always(ConfirmOutcome::Approved);
    let w = fx.wrapper(&approve, &allow, &runner, Duration::from_secs(1), false);

    let refs = EnvRefs::parse("DB=secret:prod/db/password").unwrap();
    // Invoke via the symlink path.
    w.run(&refs, "prod", None, &link, &[], Origin::Human)
        .unwrap();

    let runs = runner.invocations();
    assert_eq!(runs.len(), 1, "the allowlisted run launched");
    let canonical_real = std::fs::canonicalize(&real).unwrap();
    assert_eq!(
        runs[0].program, canonical_real,
        "gated run spawns the canonicalized reviewed file, not the symlink (I15 TOCTOU)"
    );
    assert_ne!(
        runs[0].program, link,
        "the raw symlink path is not the spawn target"
    );
}