envseal 0.3.10

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
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
//! Conditional clauses on whitelist rules.
//!
//! Where the base [`super::rules::Rule`] answers "is this binary
//! allowed to access this secret?", predicates answer "...AND only
//! when *these* runtime conditions hold." The combination lets an
//! operator approve `wrangler` for `cf-token` *only when* the cwd is
//! the work project and the parent process is an interactive shell —
//! not when the same binary is invoked from cron, a build script, or
//! a stray `nohup`.
//!
//! # Predicates that ship in this module
//!
//! - [`Predicates::cwd_glob`] — child's working directory must match
//!   a glob pattern (`*`, `?`, `**` for recursive). Defends against
//!   "approved wrangler under ~/work" being reused from anywhere
//!   else on disk.
//! - [`Predicates::parent_process_names`] — the immediate parent
//!   process name must appear in an allow-list. Defends against an
//!   approval being replayed from a non-interactive context (cron,
//!   ssh-via-rsh, headless agent, runaway subshell).
//! - [`Predicates::network_state`] — machine must be online or
//!   offline as specified. Defends against secrets leaking when the
//!   threat surface changes (for example: dev keys only when on the
//!   corp VPN; CI keys only when online).
//!
//! Each predicate is independently optional. A rule with no
//! predicates behaves exactly like a v0.3.x rule (LAW 2 backwards
//! compatibility), so existing policy files load and evaluate
//! unchanged.
//!
//! # Time-window predicates (future work)
//!
//! Ground-floor implementations exist in commit prep but are not
//! shipped here because cross-platform local-time formatting
//! without adding a `chrono` dependency requires a fork in
//! conditional compilation that this module avoids. Tracked in the
//! roadmap; will land in a follow-up commit alongside the
//! `time-of-day` field.

use std::path::Path;

use serde::{Deserialize, Serialize};

/// Runtime context evaluated against [`Predicates`] when deciding
/// whether a rule authorizes a release.
///
/// Captured once per authorization check by [`PolicyContext::capture`]
/// at the call site that already has the relevant info (the
/// inject/run path knows the child's cwd and the current process's
/// parent). Tests can construct [`PolicyContext`] directly so they
/// don't have to spawn real subprocesses.
#[derive(Debug, Clone, Default)]
pub struct PolicyContext {
    /// Working directory the secret is being released into. For
    /// `envseal inject` this is the cwd that will be inherited by
    /// the child. For `envseal pipe` and `envseal supervised` it
    /// is the same. `None` when the caller could not determine cwd
    /// (extremely rare; leaves cwd-glob predicates failing closed).
    pub cwd: Option<std::path::PathBuf>,
    /// Name of the immediate parent process — typically the shell
    /// that invoked envseal (`fish`, `bash`, `zsh`, `pwsh`, etc.).
    /// `None` when the platform-specific lookup fails (extremely
    /// rare on supported OSes; leaves parent-name predicates
    /// failing closed).
    pub parent_process_name: Option<String>,
    /// `Some(true)` when the machine has working egress, `Some(false)`
    /// when offline, `None` when the probe was disabled or
    /// inconclusive (treated as "unknown" → predicate fails closed
    /// rather than guessing).
    pub network_online: Option<bool>,
}

impl PolicyContext {
    /// Probe the live process for cwd, parent process name, and
    /// network state.
    ///
    /// Returns a populated context. Each probe is best-effort: any
    /// failure populates the corresponding field with `None` rather
    /// than failing the whole capture. The predicates handle `None`
    /// fields by failing closed (returning `false`), so a probe
    /// failure can never *grant* access that wasn't otherwise
    /// authorized.
    #[must_use]
    pub fn capture() -> Self {
        Self {
            cwd: std::env::current_dir().ok(),
            parent_process_name: parent_process_name(),
            network_online: probe_network_state(),
        }
    }

    /// Construct an empty context. Test-only. Returned context has
    /// every field set to `None`.
    #[must_use]
    pub fn empty() -> Self {
        Self::default()
    }
}

/// Allowed values for a network-state predicate. Stable wire enum
/// — adding variants in a future release is non-breaking, but
/// removing or renaming them is.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum NetworkRequirement {
    /// Predicate matches only when the machine has working egress.
    Online,
    /// Predicate matches only when the machine is confirmed offline.
    /// Intended for "local-only dev" workflows where a secret being
    /// pulled while online is itself suspicious.
    Offline,
}

/// Optional runtime predicates layered on top of a base
/// [`super::rules::Rule`].
///
/// Stored on the rule and serialized to the policy file as a flat
/// set of optional fields. All fields default to `None`; a rule
/// with all `None` predicates behaves like a v0.3.x rule.
///
/// Evaluation is short-circuit AND — every present predicate must
/// match for [`Predicates::matches`] to return `true`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Predicates {
    /// Glob pattern the child's cwd must satisfy. Supports `*` (any
    /// chars except `/`), `?` (single char), `**` (any chars
    /// including `/`). Matched against the absolute, normalized cwd.
    /// Path separators are normalized to `/` before matching so a
    /// single pattern works on Windows and Unix.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cwd_glob: Option<String>,
    /// List of allowed parent process names. Match is case-sensitive
    /// on Unix, case-insensitive on Windows (mirrors the OS file
    /// system semantics for executable names). Empty list means
    /// "any parent" — same as `None`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub parent_process_names: Option<Vec<String>>,
    /// Required network state. `None` means "don't care".
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub network_state: Option<NetworkRequirement>,
}

impl Predicates {
    /// `true` iff every present predicate matches the captured
    /// context. Absent predicates are always-true.
    ///
    /// Evaluation is short-circuit: the cheapest checks (in-memory
    /// string compares) run first; the network probe — which may
    /// have been disabled or failed — runs last so a `None`
    /// `network_online` only matters when a `network_state`
    /// predicate is actually present.
    #[must_use]
    pub fn matches(&self, ctx: &PolicyContext) -> bool {
        if let Some(glob) = &self.cwd_glob {
            let Some(cwd) = ctx.cwd.as_deref() else {
                return false;
            };
            if !glob_match(glob, &normalize_path(cwd)) {
                return false;
            }
        }

        if let Some(allowed) = &self.parent_process_names {
            if !allowed.is_empty() {
                let Some(parent) = ctx.parent_process_name.as_deref() else {
                    return false;
                };
                if !allowed.iter().any(|a| parent_name_eq(a, parent)) {
                    return false;
                }
            }
        }

        if let Some(req) = self.network_state {
            let Some(online) = ctx.network_online else {
                return false;
            };
            match req {
                NetworkRequirement::Online if !online => return false,
                NetworkRequirement::Offline if online => return false,
                _ => {}
            }
        }

        true
    }

    /// `true` iff this predicate set has no clauses set. A rule
    /// with empty predicates evaluates against any context as a
    /// match — same as not having the predicates field at all.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.cwd_glob.is_none()
            && self
                .parent_process_names
                .as_ref()
                .is_none_or(Vec::is_empty)
            && self.network_state.is_none()
    }
}

/// Compare a parent process name from the OS against an allow-list
/// entry. Windows strips a trailing `.exe` suffix from the captured
/// name and is case-insensitive; Unix is exact.
fn parent_name_eq(allow_entry: &str, captured: &str) -> bool {
    #[cfg(windows)]
    {
        if captured.eq_ignore_ascii_case(allow_entry) {
            return true;
        }
        // Case-insensitive .exe strip — `strip_suffix` is itself
        // case-sensitive, so we lowercase first when probing for
        // the suffix.
        let lower = captured.to_ascii_lowercase();
        if let Some(stem_lower) = lower.strip_suffix(".exe") {
            return stem_lower == allow_entry.to_ascii_lowercase();
        }
        false
    }
    #[cfg(not(windows))]
    {
        captured == allow_entry
    }
}

/// Normalize a filesystem path into the form predicates evaluate
/// against. Lowercases the drive letter on Windows (so a glob can
/// match either `C:/work/...` or `c:/work/...`) and converts every
/// separator to `/` so a single glob string works cross-platform.
fn normalize_path(p: &Path) -> String {
    let s = p.to_string_lossy();
    let s = s.replace('\\', "/");
    #[cfg(windows)]
    {
        // Lowercase drive letter only — the rest of the path is
        // case-sensitive on the predicate evaluation surface (we
        // intentionally don't fold the rest because users expect
        // their globs to be exact).
        if let Some((drive, rest)) = s.split_once(':') {
            if drive.len() == 1 {
                let mut out = String::with_capacity(s.len());
                out.push(drive.chars().next().unwrap_or('c').to_ascii_lowercase());
                out.push(':');
                out.push_str(rest);
                return out;
            }
        }
    }
    s
}

/// Tiny glob matcher.
///
/// Recognizes:
/// - `*`  — any run of non-`/` characters (zero or more)
/// - `**` — any run of any characters including `/` (zero or more)
/// - `?`  — exactly one non-`/` character
/// - everything else literal
///
/// The matcher is whole-string: a successful match consumes the
/// entire `path`. Trailing wildcards (`**` at the end) match the
/// remaining suffix.
///
/// This is enough expressiveness for the typical policy use cases
/// (`~/work/**`, `*.local/*`, `/srv/?/secrets`) without pulling in
/// `globset` or `regex`. If the test suite or operator feedback
/// finds the gap, swap in `globset` here — the call site at
/// `Predicates::matches` is the single seam.
#[must_use]
pub fn glob_match(pattern: &str, path: &str) -> bool {
    glob_match_inner(pattern.as_bytes(), path.as_bytes())
}

fn glob_match_inner(pat: &[u8], s: &[u8]) -> bool {
    let mut i = 0usize;
    let mut j = 0usize;
    let mut star_pat: Option<usize> = None;
    let mut star_match: usize = 0;
    let mut star_is_double = false;

    while j < s.len() {
        if i < pat.len() {
            match pat[i] {
                b'?' => {
                    if s[j] == b'/' {
                        // `?` is single non-slash char by spec — bail
                        // through the star-backtrack path.
                    } else {
                        i += 1;
                        j += 1;
                        continue;
                    }
                }
                b'*' => {
                    let is_double = i + 1 < pat.len() && pat[i + 1] == b'*';
                    star_pat = Some(if is_double { i + 2 } else { i + 1 });
                    star_match = j;
                    star_is_double = is_double;
                    i = star_pat.unwrap_or(i + 1);
                    continue;
                }
                c if c == s[j] => {
                    i += 1;
                    j += 1;
                    continue;
                }
                _ => {}
            }
        }
        // Backtrack through the most recent star if we have one.
        if let Some(sp) = star_pat {
            // `*` (single) cannot consume `/`. `**` can.
            if !star_is_double && s[star_match] == b'/' {
                return false;
            }
            i = sp;
            star_match += 1;
            j = star_match;
            continue;
        }
        return false;
    }

    // Consumed all of `s`. Pattern remainder must be all `*` / `**`
    // for the match to hold.
    while i < pat.len() {
        if pat[i] == b'*' {
            i += 1;
        } else {
            return false;
        }
    }
    true
}

/// Read the immediate parent process name. Best-effort; returns
/// `None` on lookup failure.
/// Linux: read `/proc/<ppid>/comm` for the parent's executable name.
#[cfg(target_os = "linux")]
#[must_use]
pub fn parent_process_name() -> Option<String> {
    let ppid = unsafe { libc::getppid() };
    if ppid <= 0 {
        return None;
    }
    let comm_path = format!("/proc/{ppid}/comm");
    let raw = std::fs::read_to_string(comm_path).ok()?;
    Some(raw.trim().to_string())
}

/// macOS: shell out to `ps` for the parent's `comm` field. macOS
/// ships `ps` in the base system, so this avoids pulling in
/// `mach-sys` or `sysctl` bindings just for one lookup.
#[cfg(target_os = "macos")]
#[must_use]
pub fn parent_process_name() -> Option<String> {
    use std::process::Command;
    let ppid = unsafe { libc::getppid() };
    if ppid <= 0 {
        return None;
    }
    // `ps -o comm=` on macOS prints the executable name (full path
    // on some systems; we strip to the basename).
    let out = Command::new("/bin/ps")
        .args(["-p", &ppid.to_string(), "-o", "comm="])
        .output()
        .ok()?;
    if !out.status.success() {
        return None;
    }
    let raw = String::from_utf8_lossy(&out.stdout).trim().to_string();
    let name = std::path::Path::new(&raw)
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or(&raw)
        .to_string();
    if name.is_empty() {
        None
    } else {
        Some(name)
    }
}

/// Windows: walk the `ToolHelp32Snapshot` process list to find the
/// parent of the current process and read its `szExeFile`.
#[cfg(target_os = "windows")]
#[must_use]
pub fn parent_process_name() -> Option<String> {
    // Use ToolHelp32Snapshot to walk the process list, find our
    // parent's pid, and read its `szExeFile` field. This is the
    // documented path that doesn't require pulling in a separate
    // `sysinfo` crate.
    use windows_sys::Win32::Foundation::{CloseHandle, INVALID_HANDLE_VALUE};
    use windows_sys::Win32::System::Diagnostics::ToolHelp::{
        CreateToolhelp32Snapshot, Process32FirstW, Process32NextW, PROCESSENTRY32W,
        TH32CS_SNAPPROCESS,
    };
    use windows_sys::Win32::System::Threading::GetCurrentProcessId;

    let our_pid = unsafe { GetCurrentProcessId() };

    let snap = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
    if snap == INVALID_HANDLE_VALUE {
        return None;
    }

    let mut entry: PROCESSENTRY32W = unsafe { std::mem::zeroed() };
    entry.dwSize = std::mem::size_of::<PROCESSENTRY32W>() as u32;

    let mut parent_pid: Option<u32> = None;
    if unsafe { Process32FirstW(snap, &mut entry) } != 0 {
        loop {
            if entry.th32ProcessID == our_pid {
                parent_pid = Some(entry.th32ParentProcessID);
                break;
            }
            if unsafe { Process32NextW(snap, &mut entry) } == 0 {
                break;
            }
        }
    }

    let name: Option<String> = if let Some(ppid) = parent_pid {
        // Reset the entry and walk again to find ppid's exe name.
        // (We could keep state from the first walk but the list
        // could have shifted between iterations on a busy system;
        // a fresh snapshot is more robust.)
        unsafe { CloseHandle(snap) };
        let snap2 = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
        if snap2 == INVALID_HANDLE_VALUE {
            return None;
        }
        let mut e2: PROCESSENTRY32W = unsafe { std::mem::zeroed() };
        e2.dwSize = std::mem::size_of::<PROCESSENTRY32W>() as u32;
        let mut found: Option<String> = None;
        if unsafe { Process32FirstW(snap2, &mut e2) } != 0 {
            loop {
                if e2.th32ProcessID == ppid {
                    let len = e2.szExeFile.iter().take_while(|&&c| c != 0).count();
                    let s = String::from_utf16_lossy(&e2.szExeFile[..len]);
                    if !s.is_empty() {
                        found = Some(s);
                    }
                    break;
                }
                if unsafe { Process32NextW(snap2, &mut e2) } == 0 {
                    break;
                }
            }
        }
        unsafe { CloseHandle(snap2) };
        found
    } else {
        unsafe { CloseHandle(snap) };
        None
    };

    name
}

/// Unsupported platform fallback: report `None` so any predicate
/// that requires a parent-process check fails closed.
#[cfg(not(any(target_os = "linux", target_os = "macos", target_os = "windows")))]
#[must_use]
pub fn parent_process_name() -> Option<String> {
    None
}

/// Best-effort online/offline probe.
///
/// Resolves a well-known DNS name (`one.one.one.one`, Cloudflare's
/// 1.1.1.1) with a short timeout. Returns `Some(true)` on success,
/// `Some(false)` on a clean resolution failure, `None` when the
/// probe was disabled by `ENVSEAL_DISABLE_NETWORK_PROBE` or the
/// underlying syscall errored in a way we couldn't classify.
///
/// The probe is intentionally minimal — pinging a single host —
/// because envseal must not become a thing that opens additional
/// network attack surface or hangs indefinitely on a flaky
/// connection. Typical resolution either completes in <1 s or
/// fails fast.
#[must_use]
pub fn probe_network_state() -> Option<bool> {
    if std::env::var("ENVSEAL_DISABLE_NETWORK_PROBE")
        .is_ok_and(|v| !v.is_empty() && v != "0" && v != "false")
    {
        return None;
    }
    use std::net::ToSocketAddrs;
    let result = std::thread::spawn(|| ("one.one.one.one", 443u16).to_socket_addrs())
        .join()
        .ok()?;
    match result {
        Ok(mut iter) => Some(iter.next().is_some()),
        Err(_) => Some(false),
    }
}

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

    #[test]
    fn glob_basic_literal() {
        assert!(glob_match("foo", "foo"));
        assert!(!glob_match("foo", "bar"));
        assert!(!glob_match("foo", "foobar"));
    }

    #[test]
    fn glob_star_within_segment() {
        assert!(glob_match("foo*", "foobar"));
        assert!(glob_match("*bar", "foobar"));
        assert!(glob_match("f*r", "foobar"));
        assert!(!glob_match("foo*", "foo/bar"), "* must not cross /");
    }

    #[test]
    fn glob_double_star_recursive() {
        assert!(glob_match("/work/**", "/work/proj/sub/file"));
        assert!(glob_match("/work/**", "/work/"));
        assert!(glob_match("**", "/anything/here"));
        assert!(!glob_match("/work/**", "/elsewhere/proj"));
    }

    #[test]
    fn glob_question_single_char() {
        assert!(glob_match("/srv/?/x", "/srv/a/x"));
        assert!(!glob_match("/srv/?/x", "/srv/ab/x"));
        assert!(!glob_match("/srv/?/x", "/srv/x"));
    }

    #[test]
    fn empty_predicates_match_everything() {
        let p = Predicates::default();
        let ctx = PolicyContext::empty();
        assert!(p.matches(&ctx));

        let ctx2 = PolicyContext {
            cwd: Some(std::path::PathBuf::from("/anywhere")),
            parent_process_name: Some("anything".to_string()),
            network_online: Some(true),
        };
        assert!(p.matches(&ctx2));
    }

    #[test]
    fn cwd_glob_matches_when_path_satisfies() {
        let p = Predicates {
            cwd_glob: Some("/work/**".to_string()),
            ..Predicates::default()
        };
        let ctx = PolicyContext {
            cwd: Some(std::path::PathBuf::from("/work/proj/sub")),
            ..PolicyContext::empty()
        };
        assert!(p.matches(&ctx));
    }

    #[test]
    fn cwd_glob_fails_when_path_diverges() {
        let p = Predicates {
            cwd_glob: Some("/work/**".to_string()),
            ..Predicates::default()
        };
        let ctx = PolicyContext {
            cwd: Some(std::path::PathBuf::from("/etc/whatever")),
            ..PolicyContext::empty()
        };
        assert!(!p.matches(&ctx));
    }

    #[test]
    fn cwd_glob_fails_closed_when_cwd_unknown() {
        let p = Predicates {
            cwd_glob: Some("/work/**".to_string()),
            ..Predicates::default()
        };
        let ctx = PolicyContext::empty();
        assert!(
            !p.matches(&ctx),
            "missing cwd must not silently match a glob predicate"
        );
    }

    #[test]
    fn parent_name_match_basic() {
        let p = Predicates {
            parent_process_names: Some(vec!["fish".to_string(), "bash".to_string()]),
            ..Predicates::default()
        };
        let ctx = PolicyContext {
            parent_process_name: Some("fish".to_string()),
            ..PolicyContext::empty()
        };
        assert!(p.matches(&ctx));

        let ctx_bad = PolicyContext {
            parent_process_name: Some("cron".to_string()),
            ..PolicyContext::empty()
        };
        assert!(!p.matches(&ctx_bad));
    }

    #[test]
    fn parent_name_fails_closed_when_unknown() {
        let p = Predicates {
            parent_process_names: Some(vec!["fish".to_string()]),
            ..Predicates::default()
        };
        let ctx = PolicyContext::empty();
        assert!(!p.matches(&ctx));
    }

    #[test]
    fn parent_name_empty_list_means_any() {
        let p = Predicates {
            parent_process_names: Some(vec![]),
            ..Predicates::default()
        };
        let ctx = PolicyContext {
            parent_process_name: Some("anything".to_string()),
            ..PolicyContext::empty()
        };
        assert!(p.matches(&ctx));
    }

    #[cfg(windows)]
    #[test]
    fn parent_name_windows_strips_exe_and_folds_case() {
        let p = Predicates {
            parent_process_names: Some(vec!["Fish".to_string()]),
            ..Predicates::default()
        };
        let ctx = PolicyContext {
            parent_process_name: Some("FISH.EXE".to_string()),
            ..PolicyContext::empty()
        };
        assert!(p.matches(&ctx));
    }

    #[test]
    fn network_online_required_passes_when_online() {
        let p = Predicates {
            network_state: Some(NetworkRequirement::Online),
            ..Predicates::default()
        };
        let ctx = PolicyContext {
            network_online: Some(true),
            ..PolicyContext::empty()
        };
        assert!(p.matches(&ctx));
    }

    #[test]
    fn network_online_required_fails_when_offline() {
        let p = Predicates {
            network_state: Some(NetworkRequirement::Online),
            ..Predicates::default()
        };
        let ctx = PolicyContext {
            network_online: Some(false),
            ..PolicyContext::empty()
        };
        assert!(!p.matches(&ctx));
    }

    #[test]
    fn network_offline_required_passes_when_offline() {
        let p = Predicates {
            network_state: Some(NetworkRequirement::Offline),
            ..Predicates::default()
        };
        let ctx = PolicyContext {
            network_online: Some(false),
            ..PolicyContext::empty()
        };
        assert!(p.matches(&ctx));
    }

    #[test]
    fn network_unknown_fails_closed() {
        for req in [NetworkRequirement::Online, NetworkRequirement::Offline] {
            let p = Predicates {
                network_state: Some(req),
                ..Predicates::default()
            };
            let ctx = PolicyContext::empty();
            assert!(
                !p.matches(&ctx),
                "unknown network state must not silently satisfy a {req:?} predicate"
            );
        }
    }

    #[test]
    fn predicates_combine_with_and_semantics() {
        // Every present predicate must hold simultaneously.
        let p = Predicates {
            cwd_glob: Some("/work/**".to_string()),
            parent_process_names: Some(vec!["fish".to_string()]),
            network_state: Some(NetworkRequirement::Offline),
        };
        // All match → true.
        let ctx_pass = PolicyContext {
            cwd: Some(std::path::PathBuf::from("/work/proj")),
            parent_process_name: Some("fish".to_string()),
            network_online: Some(false),
        };
        assert!(p.matches(&ctx_pass));

        // Single predicate fails → whole rule fails.
        let ctx_fail_one = PolicyContext {
            cwd: Some(std::path::PathBuf::from("/work/proj")),
            parent_process_name: Some("cron".to_string()),
            network_online: Some(false),
        };
        assert!(!p.matches(&ctx_fail_one));
    }

    #[test]
    fn predicates_serde_round_trip() {
        let p = Predicates {
            cwd_glob: Some("/work/**".to_string()),
            parent_process_names: Some(vec!["fish".to_string(), "bash".to_string()]),
            network_state: Some(NetworkRequirement::Offline),
        };
        let toml_str = toml::to_string(&p).unwrap();
        let back: Predicates = toml::from_str(&toml_str).unwrap();
        assert_eq!(back.cwd_glob, p.cwd_glob);
        assert_eq!(back.parent_process_names, p.parent_process_names);
        assert_eq!(back.network_state, p.network_state);
    }

    #[test]
    fn predicates_serde_omits_none_fields() {
        // A default Predicates serializes to nothing (no keys), so
        // a v0.3.x policy.toml that lacks the `predicates` field
        // round-trips cleanly through old → new → old code paths.
        let p = Predicates::default();
        let toml_str = toml::to_string(&p).unwrap();
        assert!(
            toml_str.trim().is_empty() || !toml_str.contains("cwd_glob"),
            "default predicates must not emit fields, got:\n{toml_str}"
        );
    }

    #[test]
    fn is_empty_correct() {
        assert!(Predicates::default().is_empty());
        assert!(!Predicates {
            cwd_glob: Some("x".into()),
            ..Predicates::default()
        }
        .is_empty());
        assert!(!Predicates {
            parent_process_names: Some(vec!["x".into()]),
            ..Predicates::default()
        }
        .is_empty());
        assert!(!Predicates {
            network_state: Some(NetworkRequirement::Online),
            ..Predicates::default()
        }
        .is_empty());
        // Empty parent list is still "empty" for predicate purposes.
        assert!(Predicates {
            parent_process_names: Some(vec![]),
            ..Predicates::default()
        }
        .is_empty());
    }
}