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
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
//! Whitelist policy data model and the binary-path resolver.
//!
//! [`Policy`] is the in-memory rule set. Canonical persistence is
//! [`Policy::save_sealed`] / [`Policy::load_sealed`] — AES-256-GCM
//! encrypted blob keyed off the master key with HKDF domain
//! separation (`b"policy.v1"`). The plaintext rules are NEVER
//! written to disk in 0.3.0+; the v0.2.x plaintext-with-HMAC layout
//! is read for back-compat (`policy.toml` + `# hmac = ...` comment)
//! and silently rewritten to `policy.sealed` on the next save.
//!
//! The legacy HMAC framing lives in [`super::hmac`] and is only
//! consulted on the back-compat read path.

use std::fs;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use super::hmac::{compute_hmac, split_hmac};
use super::predicates::{PolicyContext, Predicates};
use crate::error::Error;
use crate::vault::sealed_blob;

/// Domain string for [`sealed_blob::seal`] / [`unseal`]. Stable —
/// changing it is a format break across releases.
const POLICY_SEAL_DOMAIN: &[u8] = b"policy.v1";

/// The scope of a whitelist rule.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum RuleScope {
    /// Binary is authorized for a specific secret only.
    Key,
    /// Binary is authorized for all secrets.
    All,
}

/// A single whitelist rule.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Rule {
    /// Absolute path to the authorized binary.
    pub binary: String,
    /// Secret name, or `"*"` for all secrets.
    pub secret: String,
    /// Whether this grants access to one key or all keys.
    pub scope: RuleScope,
    /// SHA-256 hash of the binary at the time it was approved.
    /// Used to detect binary replacement / PATH poisoning.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub binary_hash: Option<String>,
    /// Optional argv-binding fingerprint (see
    /// [`crate::execution::command_fingerprint`]). When present,
    /// this rule authorizes only invocations whose argv produces the same
    /// fingerprint. When absent (legacy / unscoped rule), the rule
    /// authorizes only no-argument invocations — argumented invocations
    /// are denied so an attacker who got a no-args approval cannot reuse
    /// it to run the binary with arbitrary flags.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub args_fingerprint: Option<String>,
    /// Unix timestamp (seconds since epoch) at which this rule
    /// stops authorizing the binary. `None` = forever (the v0.2
    /// default). Set when the operator picks a finite duration in
    /// the approval popup, OR when the active `SecurityConfig`
    /// `default_rule_expiry_secs` is non-zero. Expired rules are
    /// filtered out by [`Policy::is_authorized_with_args`] and
    /// re-prompt on next access.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<u64>,
    /// Optional runtime predicates (cwd glob, parent process name,
    /// network state) that must hold *in addition* to the binary +
    /// secret + argv match for this rule to authorize a release.
    ///
    /// Defaults to an empty [`Predicates`] — semantically identical
    /// to a v0.3.x rule with no predicate field. Existing
    /// `policy.toml` / `policy.sealed` files load unchanged because
    /// every predicate sub-field is independently optional.
    #[serde(default, skip_serializing_if = "Predicates::is_empty")]
    pub predicates: Predicates,
}

impl Rule {
    /// `true` iff this rule has expired relative to `now_unix_secs`.
    /// Rules with no expiry never expire.
    #[must_use]
    pub fn is_expired(&self, now_unix_secs: u64) -> bool {
        self.expires_at.is_some_and(|t| now_unix_secs >= t)
    }
}

/// The complete policy file.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Policy {
    /// Whitelist rules.
    #[serde(default)]
    pub rules: Vec<Rule>,
    /// Monotonic generation counter incremented on every save.
    /// Detects rollback attacks where an attacker replaces the policy
    /// file with an older (revoked-rules) version.
    #[serde(default)]
    pub generation: u64,
}

impl Policy {
    /// Load policy from a file, or return an empty policy if the file
    /// doesn't exist.
    ///
    /// # Errors
    /// Returns [`Error::StorageIo`] / [`Error::PolicyParse`] on read or
    /// parse failure, [`Error::PolicyTampered`] if the path is a symlink.
    pub fn load(path: &Path) -> Result<Self, Error> {
        if !path.exists() {
            return Ok(Self::default());
        }
        crate::guard::verify_not_symlink(path)?;

        let content = fs::read_to_string(path)?;
        let (toml_content, stored_hmac) = split_hmac(&content);
        // SECURITY: If an HMAC is present, verify it. This prevents an
        // attacker from modifying a legacy policy.toml and having the
        // unsigned load path silently accept the tampered file.
        if stored_hmac.is_some() {
            // Load requires a master key for HMAC verification. Without
            // one we cannot verify, so we reject HMAC-signed files on
            // the unsigned load path to fail closed.
            return Err(Error::PolicyTampered(
                "legacy policy.toml contains an HMAC signature — use load_sealed instead"
                    .to_string(),
            ));
        }
        toml::from_str(toml_content).map_err(|e| Error::PolicyParse(e.to_string()))
    }

    /// Load policy from the sealed-blob file at `<dir>/policy.sealed`,
    /// falling back to a legacy plaintext-with-HMAC `<dir>/policy.toml`
    /// if no sealed file exists.
    ///
    /// `path` is the *legacy* path (`policy.toml`); this function
    /// derives the sealed-blob path as `path.with_extension("sealed")`
    /// so existing callers don't need to know about both names. Use
    /// [`sealed_path_for`] to compute the sealed path explicitly.
    ///
    /// # Errors
    /// `Error::PolicyTampered` for HMAC mismatch on the legacy path;
    /// `Error::CryptoFailure` for sealed-blob decrypt failure
    /// (wrong key / tampered ciphertext / version mismatch);
    /// `Error::PolicyParse` for malformed plaintext after a
    /// successful unseal / HMAC check.
    pub fn load_sealed(path: &Path, master_key: &[u8; 32]) -> Result<Self, Error> {
        let lock_path = path.with_extension("lock");
        crate::guard::verify_not_symlink(&lock_path)?;
        let _lock = advisory_lock::acquire(&lock_path, false)?;
        let sealed_path = sealed_path_for(path);
        if sealed_path.exists() {
            crate::guard::verify_not_symlink(&sealed_path)?;
            let blob = fs::read(&sealed_path)?;
            let plaintext = sealed_blob::unseal(&blob, master_key, POLICY_SEAL_DOMAIN)?;
            let s = std::str::from_utf8(&plaintext)
                .map_err(|e| Error::PolicyParse(format!("sealed policy not utf-8: {e}")))?;
            let policy: Policy =
                toml::from_str(s).map_err(|e| Error::PolicyParse(e.to_string()))?;
            return Ok(policy);
        }
        // Fall back to the v0.2.x plaintext + HMAC layout. On the
        // next save we'll rewrite as sealed and remove the legacy
        // file — see `save_sealed`.
        load_verified_legacy(path, master_key)
    }

    /// Back-compat alias for the v0.2.x name. Prefer
    /// [`Policy::load_sealed`] in new code.
    pub fn load_verified(path: &Path, master_key: &[u8; 32]) -> Result<Self, Error> {
        Self::load_sealed(path, master_key)
    }

    /// Save policy to a file (unsigned).
    ///
    /// # Errors
    /// Returns [`Error::PolicyParse`] / [`Error::StorageIo`] on serialization
    /// or write failure.
    pub fn save(&self, path: &Path) -> Result<(), Error> {
        let content =
            toml::to_string_pretty(self).map_err(|e| Error::PolicyParse(e.to_string()))?;
        fs::write(path, content)?;
        set_file_permissions(path)?;
        Ok(())
    }

    /// Save policy as an AES-256-GCM sealed blob at
    /// `path.with_extension("sealed")`. AEAD provides integrity AND
    /// confidentiality in one primitive — the file is opaque on disk,
    /// so an attacker who reads it learns nothing about which
    /// binaries / secrets are authorized.
    ///
    /// Migration: if a legacy `policy.toml` exists at `path`, this
    /// removes it AFTER the sealed write succeeds (atomic-ish — the
    /// new file is durable on disk before the old plaintext goes
    /// away). The next [`Policy::load_sealed`] call will find only
    /// the sealed file.
    ///
    /// # Errors
    /// [`Error::PolicyParse`] for serialization failure,
    /// [`Error::CryptoFailure`] for sealed-blob encrypt failure,
    /// [`Error::StorageIo`] for filesystem failure.
    pub fn save_sealed(&self, path: &Path, master_key: &[u8; 32]) -> Result<(), Error> {
        let lock_path = path.with_extension("lock");
        crate::guard::verify_not_symlink(&lock_path)?;
        let _lock = advisory_lock::acquire(&lock_path, true)?;
        let mut to_save = self.clone();
        // Drop expired rules before persisting — they don't authorize
        // anything (the auth check filters on read), and keeping them
        // in the file makes `envseal policy show` noisier than it
        // needs to be. Pruning at save time is the right place
        // because every save is a natural cleanup point.
        let _pruned = to_save.prune_expired();
        to_save.generation = to_save.generation.saturating_add(1);
        let raw =
            toml::to_string_pretty(&to_save).map_err(|e| Error::PolicyParse(e.to_string()))?;
        let blob = sealed_blob::seal(raw.as_bytes(), master_key, POLICY_SEAL_DOMAIN)?;
        let sealed_path = sealed_path_for(path);
        // Atomic write: temp file + rename so a crash or concurrent
        // writer never leaves a truncated policy on disk.
        let rnd = rand::random::<u64>();
        let tmp_path = sealed_path.with_extension(format!("sealed.{rnd:016x}.tmp"));
        #[cfg(unix)]
        {
            use std::io::Write;
            use std::os::unix::fs::OpenOptionsExt;
            let mut f = std::fs::OpenOptions::new()
                .create_new(true)
                .write(true)
                .mode(0o600)
                .open(&tmp_path)
                .map_err(Error::StorageIo)?;
            f.write_all(&blob).map_err(Error::StorageIo)?;
            f.sync_all().map_err(Error::StorageIo)?;
        }
        #[cfg(not(unix))]
        {
            fs::write(&tmp_path, &blob).map_err(Error::StorageIo)?;
            set_file_permissions(&tmp_path)?;
        }
        fs::rename(&tmp_path, &sealed_path)?;
        // Migration: delete legacy plaintext now that sealed is on
        // disk. Best-effort — a permissions error here doesn't lose
        // data because the sealed file is the canonical source from
        // here on.
        if path.exists() && path != sealed_path {
            let _ = fs::remove_file(path);
        }
        Ok(())
    }

    /// Back-compat alias for the v0.2.x name. Prefer
    /// [`Policy::save_sealed`] in new code.
    pub fn save_signed(&self, path: &Path, master_key: &[u8; 32]) -> Result<(), Error> {
        self.save_sealed(path, master_key)
    }

    /// Check whether a binary is authorized to access a specific secret,
    /// **without** considering argv binding.
    ///
    /// This is the legacy unscoped check. New code paths should prefer
    /// [`Policy::is_authorized_with_args`] so an approval for a specific
    /// command pattern (`wrangler deploy`) cannot be reused for a
    /// different one (`wrangler --shell evil.sh`).
    #[must_use]
    pub fn is_authorized(&self, binary_path: &str, secret_name: &str) -> bool {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_secs());
        self.rules
            .iter()
            .any(|rule| !rule.is_expired(now) && rule_matches(rule, binary_path, secret_name, None))
    }

    /// Argv-bound authorization check.
    ///
    /// `args_fingerprint = None` means "the caller is invoking the binary
    /// with no arguments" — semantically equivalent to
    /// [`crate::execution::command_fingerprint`] returning `""`.
    /// `args_fingerprint = Some(fp)` means "the caller is invoking with
    /// argv that fingerprints to `fp`."
    ///
    /// Authorization rules:
    ///
    /// - A rule with `args_fingerprint = Some(stored)` matches if and
    ///   only if `stored == fp`. (`None` callers never match scoped rules.)
    /// - A rule with `args_fingerprint = None` (legacy / unscoped) is
    ///   conservative: it authorizes **only** the no-argument case.
    ///   Argumented invocations against a legacy rule are denied so users
    ///   who approved `wrangler` once can't have that approval transparently
    ///   apply to `wrangler --some-flag`.
    ///
    /// Argv-bound authorization check with optional binary-hash binding.
    ///
    /// `current_hash` should be the SHA-256 of the binary on disk right
    /// now. When `Some(hash)` is provided, any rule that has a stored
    /// `binary_hash` must match `hash` or it is rejected. This closes
    /// the swap attack where an attacker replaces an approved binary.
    #[must_use]
    pub fn is_authorized_with_hash_and_args(
        &self,
        binary_path: &str,
        secret_name: &str,
        args_fingerprint: Option<&str>,
        current_hash: Option<&str>,
    ) -> bool {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_secs());
        self.rules.iter().any(|rule| {
            if rule.is_expired(now) {
                return false;
            }
            if !rule_matches(rule, binary_path, secret_name, current_hash) {
                return false;
            }
            match (rule.args_fingerprint.as_deref(), args_fingerprint) {
                (Some(stored), Some(fp)) => stored == fp,
                (None, None) => true,
                _ => false,
            }
        })
    }

    /// Convenience wrapper that authorizes without binary-hash binding.
    /// Production injection paths should prefer
    /// [`Self::is_authorized_with_hash_and_args`] so that tampered
    /// binaries are rejected.
    #[must_use]
    pub fn is_authorized_with_args(
        &self,
        binary_path: &str,
        secret_name: &str,
        args_fingerprint: Option<&str>,
    ) -> bool {
        self.is_authorized_with_hash_and_args(binary_path, secret_name, args_fingerprint, None)
    }

    /// Predicate-aware authorization check.
    ///
    /// Identical to [`Self::is_authorized_with_hash_and_args`] but
    /// additionally requires every present predicate on the matched
    /// rule to hold against `ctx`. Used by the inject / pipe /
    /// supervised paths once they capture the runtime context.
    ///
    /// A rule with empty predicates (the default for legacy rules)
    /// behaves exactly like the predicate-less check, so this can
    /// be called unconditionally — there is no behavior change for
    /// rules that don't opt into predicates.
    ///
    /// `ctx` is consumed by reference; callers typically build it
    /// once via [`PolicyContext::capture`] and pass it through
    /// every per-secret authorization call in a single approval
    /// batch.
    #[must_use]
    pub fn is_authorized_with_context(
        &self,
        binary_path: &str,
        secret_name: &str,
        args_fingerprint: Option<&str>,
        current_hash: Option<&str>,
        ctx: &PolicyContext,
    ) -> bool {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_secs());
        self.rules.iter().any(|rule| {
            if rule.is_expired(now) {
                return false;
            }
            if !rule_matches(rule, binary_path, secret_name, current_hash) {
                return false;
            }
            match (rule.args_fingerprint.as_deref(), args_fingerprint) {
                (Some(stored), Some(fp)) if stored == fp => {}
                (None, None) => {}
                _ => return false,
            }
            rule.predicates.matches(ctx)
        })
    }

    /// Drop every expired rule from the policy. Returns the number
    /// removed so callers can decide whether to surface the cleanup
    /// (audit log, doctor report, etc.). Idempotent.
    pub fn prune_expired(&mut self) -> usize {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_secs());
        let before = self.rules.len();
        self.rules.retain(|r| !r.is_expired(now));
        before - self.rules.len()
    }

    /// Get the stored hash for a binary, if any non-expired rule has one.
    #[must_use]
    pub fn binary_hash(&self, binary_path: &str) -> Option<String> {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.as_secs());
        self.rules
            .iter()
            .find(|r| r.binary == binary_path && r.binary_hash.is_some() && !r.is_expired(now))
            .and_then(|r| r.binary_hash.clone())
    }

    /// Add a rule granting a binary access to a specific secret.
    ///
    /// Deduplicates: if an identical or broader rule exists, this is a no-op.
    pub fn allow_key(&mut self, binary_path: &str, secret_name: &str) {
        self.allow_key_with_hash(binary_path, secret_name, "");
    }

    /// Add a key-scoped rule with a verified binary hash. The rule has no
    /// argv-binding fingerprint (legacy / unscoped behavior — see
    /// [`Self::allow_key_with_hash_and_args`] for the bound variant).
    pub fn allow_key_with_hash(&mut self, binary_path: &str, secret_name: &str, hash: &str) {
        self.allow_key_with_hash_and_args(binary_path, secret_name, hash, None);
    }

    /// Add a key-scoped rule with both a verified binary hash and an
    /// argv-binding fingerprint.
    ///
    /// `args_fingerprint = None` records the rule as legacy/unscoped (the
    /// behavior of [`Self::allow_key_with_hash`]); `Some(fp)` scopes the
    /// approval to the exact argv pattern that produced `fp`.
    pub fn allow_key_with_hash_and_args(
        &mut self,
        binary_path: &str,
        secret_name: &str,
        hash: &str,
        args_fingerprint: Option<String>,
    ) {
        // Already authorized for this exact (binary, secret, args) combination?
        if self.is_authorized_with_hash_and_args(
            binary_path,
            secret_name,
            args_fingerprint.as_deref(),
            Some(hash).filter(|h| !h.is_empty()),
        ) {
            return;
        }

        let binary_hash = if hash.is_empty() {
            None
        } else {
            Some(hash.to_string())
        };

        self.rules.push(Rule {
            binary: binary_path.to_string(),
            secret: secret_name.to_string(),
            scope: RuleScope::Key,
            binary_hash,
            args_fingerprint,
            expires_at: None,
            predicates: Predicates::default(),
        });
    }

    /// Same as [`Self::allow_key_with_hash_and_args`] but stamps the
    /// rule with an expiry timestamp. Used by the popup path when
    /// the operator picks a finite duration ("Allow for 24h" /
    /// "Allow for 30 days") or when the active config sets a
    /// non-zero `default_rule_expiry_secs`.
    pub fn allow_key_with_expiry(
        &mut self,
        binary_path: &str,
        secret_name: &str,
        hash: &str,
        args_fingerprint: Option<String>,
        expires_at_unix_secs: u64,
    ) {
        if self.is_authorized_with_hash_and_args(
            binary_path,
            secret_name,
            args_fingerprint.as_deref(),
            Some(hash).filter(|h| !h.is_empty()),
        ) {
            return;
        }
        let binary_hash = if hash.is_empty() {
            None
        } else {
            Some(hash.to_string())
        };
        self.rules.push(Rule {
            binary: binary_path.to_string(),
            secret: secret_name.to_string(),
            scope: RuleScope::Key,
            binary_hash,
            args_fingerprint,
            expires_at: Some(expires_at_unix_secs),
            predicates: Predicates::default(),
        });
    }

    /// Add a rule granting a binary access to ALL secrets.
    ///
    /// Removes any per-key rules for this binary (they're now redundant).
    pub fn allow_all(&mut self, binary_path: &str) {
        self.allow_all_with_hash(binary_path, "");
    }

    /// Add an all-scope rule with a verified binary hash.
    pub fn allow_all_with_hash(&mut self, binary_path: &str, hash: &str) {
        // Remove per-key rules for this binary (now subsumed).
        self.rules
            .retain(|r| !(r.binary == binary_path && r.scope == RuleScope::Key));

        let has_all = self
            .rules
            .iter()
            .any(|r| r.binary == binary_path && r.scope == RuleScope::All);

        if !has_all {
            let binary_hash = if hash.is_empty() {
                None
            } else {
                Some(hash.to_string())
            };

            self.rules.push(Rule {
                binary: binary_path.to_string(),
                secret: "*".to_string(),
                scope: RuleScope::All,
                binary_hash,
                args_fingerprint: None,
                expires_at: None,
                predicates: Predicates::default(),
            });
        }
    }

    /// Remove all rules for a specific binary.
    pub fn revoke_binary(&mut self, binary_path: &str) {
        self.rules.retain(|r| r.binary != binary_path);
    }

    /// Remove all rules mentioning a specific secret.
    pub fn revoke_secret(&mut self, secret_name: &str) {
        self.rules
            .retain(|r| !(r.scope == RuleScope::Key && r.secret == secret_name));
    }
}

/// Whether `rule` matches `(binary_path, secret_name)` ignoring argv binding.
fn rule_matches(
    rule: &Rule,
    binary_path: &str,
    secret_name: &str,
    current_hash: Option<&str>,
) -> bool {
    if rule.binary != binary_path {
        return false;
    }
    if rule.scope != RuleScope::All && rule.scope == RuleScope::Key && rule.secret != secret_name {
        return false;
    }
    // SECURITY: If the rule was created with a binary hash, the current
    // binary MUST match that hash. Without this check, an attacker who
    // replaces an approved binary on disk retains authorization.
    if let (Some(stored), Some(current)) = (rule.binary_hash.as_deref(), current_hash) {
        return stored == current;
    }
    if current_hash.is_some() {
        return false;
    }
    true
}

/// Resolve a command name to its absolute binary path.
///
/// Uses `which`-style PATH lookup with two anti-poisoning rules baked in:
///
/// 1. **Relative PATH entries are ignored.** A `PATH` of `.:bin` is treated
///    as `bin` only — an attacker dropping `evil-tool` into the cwd
///    cannot get it picked up just because someone has `.` on their PATH.
/// 2. **Non-executable candidates are skipped** even if they exist with
///    the right name, so `~/bin/fake-tool` with mode 0644 doesn't shadow a
///    real binary later in the search order.
///
/// On Windows, each PATH dir is also searched with every `PATHEXT`
/// suffix (`.EXE`, `.CMD`, `.BAT`, `.PS1`, …) appended unless the
/// caller already supplied an extension. Without this, `python`,
/// `node`, `npm`, and every other executable that lives as `*.exe`
/// or `*.cmd` would resolve to "binary not found in PATH" even
/// though the operator can run them at any shell prompt.
///
/// # Errors
/// Returns [`Error::BinaryResolution`] if the command can't be found or
/// can't be canonicalized, or if the only candidate found is not executable.
pub fn resolve_binary(cmd: &str) -> Result<String, Error> {
    // Absolute-path fast-path — accepts both Unix `/usr/bin/foo` and
    // Windows `C:\path\foo.exe` / UNC `\\server\share\foo.exe`.
    // `cmd.starts_with('/')` was Unix-only and silently dropped
    // Windows callers into the PATH-lookup branch, where the
    // already-absolute path was then "joined" with each PATH dir
    // (a no-op on Windows since absolute beats relative in
    // `Path::join`) and could match by accident — confusing to
    // debug. Just check is_absolute once, properly.
    if std::path::Path::new(cmd).is_absolute() {
        if std::path::Path::new(cmd).exists() {
            return Ok(cmd.to_string());
        }
        return Err(Error::BinaryResolution(format!(
            "binary does not exist: {cmd}"
        )));
    }

    let path_var = std::env::var("PATH").unwrap_or_default();
    let separator = if cfg!(target_os = "windows") {
        ';'
    } else {
        ':'
    };

    // Build the list of name suffixes to try in each PATH dir. On
    // Unix, only the bare name. On Windows, the bare name first
    // (catches `python` if a literal `python` file exists) and then
    // each PATHEXT entry — without this, `envseal inject ... -- python`
    // fails on every Windows install because Python is on disk as
    // `python.exe`, not `python`.
    let suffix_candidates: Vec<String> = if cfg!(target_os = "windows") {
        let mut v = vec![String::new()];
        let pathext =
            std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD;.PS1".to_string());
        // Skip extension append when the user already supplied one
        // (e.g. `python.exe`) so we don't search for `python.exe.exe`.
        let already_has_ext = std::path::Path::new(cmd).extension().is_some();
        if !already_has_ext {
            for ext in pathext.split(';') {
                let ext = ext.trim();
                if ext.is_empty() {
                    continue;
                }
                v.push(ext.to_string());
            }
        }
        v
    } else {
        vec![String::new()]
    };

    for dir in path_var.split(separator) {
        // Anti-poisoning: skip relative PATH entries. `.`, empty string, or
        // any non-absolute directory is ignored so cwd-based attacks fail.
        let dir_path = std::path::Path::new(dir);
        if dir.is_empty() || !dir_path.is_absolute() {
            continue;
        }
        for suffix in &suffix_candidates {
            let name = if suffix.is_empty() {
                cmd.to_string()
            } else {
                format!("{cmd}{suffix}")
            };
            let candidate = dir_path.join(&name);
            if candidate.exists() {
                if !is_executable(&candidate) {
                    // A non-executable hit early in PATH is suspicious
                    // (could be a name-collision attack), but it
                    // shouldn't lock out a legitimate later match.
                    // Skip and keep searching.
                    continue;
                }
                return candidate
                    .canonicalize()
                    .map(|p| p.to_string_lossy().to_string())
                    .map_err(|e| {
                        Error::BinaryResolution(format!("cannot canonicalize {cmd}: {e}"))
                    });
            }
        }
    }

    Err(Error::BinaryResolution(format!(
        "binary not found in PATH: {cmd}"
    )))
}

/// Whether `path` points at an executable file the current process can run.
///
/// On Unix this means the owner/group/other-execute bit applicable to the
/// running uid is set. On Windows it means the file extension is in the
/// `PATHEXT` set (`.exe`, `.bat`, `.cmd`, …) or `PATHEXT` is empty.
fn is_executable(path: &std::path::Path) -> bool {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        let Ok(meta) = std::fs::metadata(path) else {
            return false;
        };
        if !meta.is_file() {
            return false;
        }
        meta.permissions().mode() & 0o111 != 0
    }

    #[cfg(windows)]
    {
        let Some(ext) = path
            .extension()
            .and_then(|e| e.to_str())
            .map(str::to_ascii_uppercase)
        else {
            return false;
        };
        let pathext =
            std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD;.PS1".to_string());
        if pathext.trim().is_empty() {
            return std::fs::metadata(path).is_ok_and(|m| m.is_file());
        }
        let needle = format!(".{ext}");
        pathext
            .split(';')
            .any(|entry| entry.eq_ignore_ascii_case(&needle))
    }

    #[cfg(not(any(unix, windows)))]
    {
        std::fs::metadata(path).is_ok_and(|m| m.is_file())
    }
}

/// Set file permissions to "owner only" — the equivalent of 0o600 on Unix.
///
/// On Unix: `chmod 0o600`.
/// On Windows: replace the file's DACL with a single ACE granting full
/// access to the current user's primary token SID, with `PROTECTED_DACL`
/// to block ACL inheritance from the parent directory. This is the NTFS
/// equivalent of "no group, no world, owner only" — the assumptions a
/// 0o600 keyfile relies on.
/// Compute the canonical sealed-blob path for a legacy plaintext
/// policy path. `<dir>/policy.toml` → `<dir>/policy.sealed`.
#[must_use]
pub fn sealed_path_for(legacy_path: &Path) -> PathBuf {
    legacy_path.with_extension("sealed")
}

/// Read the v0.2.x plaintext-with-HMAC layout from `path` for
/// back-compat during the migration window. Used only by
/// [`Policy::load_sealed`] when no sealed file exists at the
/// canonical location.
fn load_verified_legacy(path: &Path, master_key: &[u8; 32]) -> Result<Policy, Error> {
    if !path.exists() {
        return Ok(Policy::default());
    }
    crate::guard::verify_not_symlink(path)?;
    let content = fs::read_to_string(path)?;
    let (toml_content, stored_hmac) = split_hmac(&content);
    let stored_hmac = stored_hmac.ok_or_else(|| {
        Error::PolicyTampered(
            "policy.toml has no HMAC signature — it may have been \
             created or modified outside envseal."
                .to_string(),
        )
    })?;
    let computed = compute_hmac(toml_content.as_bytes(), master_key)?;
    if !crate::guard::constant_time_eq(computed.as_bytes(), stored_hmac.as_bytes()) {
        return Err(Error::PolicyTampered(
            "policy.toml HMAC mismatch".to_string(),
        ));
    }
    toml::from_str(toml_content).map_err(|e| Error::PolicyParse(e.to_string()))
}

fn set_file_permissions(path: &Path) -> Result<(), Error> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
    }

    #[cfg(windows)]
    {
        crate::policy::windows_acl::set_owner_only_dacl(path)?;
    }

    Ok(())
}

/// Advisory file-locking helper — prevents lost-update races when
/// multiple envseal processes read-modify-write the policy file
/// concurrently. Uses `flock` on Unix and `LockFile` on Windows.
mod advisory_lock {
    use crate::error::Error;
    use std::fs::File;
    use std::path::Path;

    pub fn acquire(path: &Path, exclusive: bool) -> Result<LockGuard, Error> {
        let file = File::options()
            .create(true)
            .truncate(false)
            .read(true)
            .write(true)
            .open(path)
            .map_err(Error::StorageIo)?;

        #[cfg(unix)]
        {
            use std::os::unix::io::AsRawFd;
            let op = if exclusive {
                libc::LOCK_EX
            } else {
                libc::LOCK_SH
            };
            let rc = unsafe { libc::flock(file.as_raw_fd(), op) };
            if rc != 0 {
                return Err(Error::StorageIo(std::io::Error::last_os_error()));
            }
        }

        #[cfg(windows)]
        {
            use std::os::windows::io::AsRawHandle;
            use windows_sys::Win32::Storage::FileSystem::LockFile;
            unsafe {
                let handle = file.as_raw_handle();
                if LockFile(handle, 0, 0, 0xFFFF_FFFF, 0xFFFF_FFFF) == 0 {
                    return Err(Error::StorageIo(std::io::Error::last_os_error()));
                }
            }
            let _ = exclusive; // Windows LockFile is always exclusive for our range
        }

        #[cfg(not(any(unix, windows)))]
        {
            let _ = exclusive;
        }

        Ok(LockGuard(file))
    }

    pub struct LockGuard(File);

    impl Drop for LockGuard {
        fn drop(&mut self) {
            #[cfg(unix)]
            {
                use std::os::unix::io::AsRawFd;
                unsafe {
                    libc::flock(self.0.as_raw_fd(), libc::LOCK_UN);
                }
            }

            #[cfg(windows)]
            {
                use std::os::windows::io::AsRawHandle;
                use windows_sys::Win32::Storage::FileSystem::UnlockFile;
                unsafe {
                    let handle = self.0.as_raw_handle();
                    UnlockFile(handle, 0, 0, 0xFFFF_FFFF, 0xFFFF_FFFF);
                }
            }
        }
    }
}

#[cfg(test)]
mod predicate_integration_tests {
    use super::*;
    use crate::policy::predicates::{NetworkRequirement, PolicyContext, Predicates};

    fn rule_with(pred: Predicates) -> Rule {
        Rule {
            binary: "/usr/bin/wrangler".to_string(),
            secret: "cf-token".to_string(),
            scope: RuleScope::Key,
            binary_hash: None,
            args_fingerprint: None,
            expires_at: None,
            predicates: pred,
        }
    }

    fn policy_with(rule: Rule) -> Policy {
        Policy {
            rules: vec![rule],
            generation: 1,
        }
    }

    #[test]
    fn rule_without_predicates_authorizes_in_any_context() {
        let policy = policy_with(rule_with(Predicates::default()));
        let ctx = PolicyContext::empty();
        assert!(policy.is_authorized_with_context(
            "/usr/bin/wrangler",
            "cf-token",
            None,
            None,
            &ctx,
        ));
    }

    #[test]
    fn predicate_blocks_when_cwd_diverges() {
        let policy = policy_with(rule_with(Predicates {
            cwd_glob: Some("/work/**".to_string()),
            ..Predicates::default()
        }));

        let ctx_in = PolicyContext {
            cwd: Some(std::path::PathBuf::from("/work/proj")),
            ..PolicyContext::empty()
        };
        assert!(policy.is_authorized_with_context(
            "/usr/bin/wrangler",
            "cf-token",
            None,
            None,
            &ctx_in,
        ));

        let ctx_out = PolicyContext {
            cwd: Some(std::path::PathBuf::from("/elsewhere")),
            ..PolicyContext::empty()
        };
        assert!(!policy.is_authorized_with_context(
            "/usr/bin/wrangler",
            "cf-token",
            None,
            None,
            &ctx_out,
        ));
    }

    #[test]
    fn predicate_blocks_when_parent_process_not_in_allowlist() {
        let policy = policy_with(rule_with(Predicates {
            parent_process_names: Some(vec!["fish".to_string(), "bash".to_string()]),
            ..Predicates::default()
        }));

        let ctx_shell = PolicyContext {
            parent_process_name: Some("fish".to_string()),
            ..PolicyContext::empty()
        };
        assert!(policy.is_authorized_with_context(
            "/usr/bin/wrangler",
            "cf-token",
            None,
            None,
            &ctx_shell,
        ));

        let ctx_cron = PolicyContext {
            parent_process_name: Some("cron".to_string()),
            ..PolicyContext::empty()
        };
        assert!(!policy.is_authorized_with_context(
            "/usr/bin/wrangler",
            "cf-token",
            None,
            None,
            &ctx_cron,
        ));
    }

    #[test]
    fn predicate_blocks_when_network_state_mismatches() {
        let policy = policy_with(rule_with(Predicates {
            network_state: Some(NetworkRequirement::Offline),
            ..Predicates::default()
        }));

        let ctx_offline = PolicyContext {
            network_online: Some(false),
            ..PolicyContext::empty()
        };
        assert!(policy.is_authorized_with_context(
            "/usr/bin/wrangler",
            "cf-token",
            None,
            None,
            &ctx_offline,
        ));

        let ctx_online = PolicyContext {
            network_online: Some(true),
            ..PolicyContext::empty()
        };
        assert!(!policy.is_authorized_with_context(
            "/usr/bin/wrangler",
            "cf-token",
            None,
            None,
            &ctx_online,
        ));
    }

    #[test]
    fn rule_must_satisfy_all_predicates_simultaneously() {
        let policy = policy_with(rule_with(Predicates {
            cwd_glob: Some("/work/**".to_string()),
            parent_process_names: Some(vec!["fish".to_string()]),
            network_state: Some(NetworkRequirement::Offline),
        }));

        let ctx_full = PolicyContext {
            cwd: Some(std::path::PathBuf::from("/work/p")),
            parent_process_name: Some("fish".to_string()),
            network_online: Some(false),
        };
        assert!(policy.is_authorized_with_context(
            "/usr/bin/wrangler",
            "cf-token",
            None,
            None,
            &ctx_full,
        ));

        // Flip a single predicate input — the whole match must fail.
        let ctx_one_off = PolicyContext {
            cwd: Some(std::path::PathBuf::from("/work/p")),
            parent_process_name: Some("fish".to_string()),
            network_online: Some(true),
        };
        assert!(!policy.is_authorized_with_context(
            "/usr/bin/wrangler",
            "cf-token",
            None,
            None,
            &ctx_one_off,
        ));
    }

    #[test]
    fn predicate_load_save_round_trips_via_sealed() {
        // A round-trip through save_sealed / load_sealed (i.e. the
        // production path) must preserve every predicate field
        // exactly. This is the LAW 2 backwards-compat guarantee at
        // serde-level: emerging predicate fields written by a new
        // client must read back unchanged on the same client and
        // be silently ignored on an old one.
        use tempfile::tempdir;

        let dir = tempdir().unwrap();
        let path = dir.path().join("policy.sealed");
        let master_key = [0xABu8; 32];

        let original = Policy {
            rules: vec![Rule {
                binary: "/usr/bin/wrangler".into(),
                secret: "cf-token".into(),
                scope: RuleScope::Key,
                binary_hash: Some("abc".into()),
                args_fingerprint: None,
                expires_at: None,
                predicates: Predicates {
                    cwd_glob: Some("/work/**".into()),
                    parent_process_names: Some(vec!["fish".into()]),
                    network_state: Some(NetworkRequirement::Offline),
                },
            }],
            generation: 7,
        };
        original.save_sealed(&path, &master_key).unwrap();

        let loaded = Policy::load_sealed(&path, &master_key).unwrap();
        assert_eq!(loaded.rules.len(), 1);
        let rule = &loaded.rules[0];
        assert_eq!(rule.predicates.cwd_glob.as_deref(), Some("/work/**"));
        assert_eq!(
            rule.predicates.parent_process_names.as_ref().map(Vec::len),
            Some(1)
        );
        assert_eq!(
            rule.predicates.network_state,
            Some(NetworkRequirement::Offline)
        );
    }

    #[test]
    fn legacy_rule_without_predicate_field_loads_clean() {
        // A pre-DSL rule (predicates field absent in serialized
        // form) must deserialize with a default Predicates and
        // continue to authorize unconditionally — LAW 2.
        let toml_input = r#"
            generation = 1

            [[rules]]
            binary = "/usr/bin/wrangler"
            secret = "cf-token"
            scope = "key"
        "#;
        let policy: Policy = toml::from_str(toml_input).unwrap();
        assert_eq!(policy.rules.len(), 1);
        assert!(
            policy.rules[0].predicates.is_empty(),
            "legacy rules must default to empty predicates"
        );

        // And it must still authorize via the predicate-aware API.
        let ctx = PolicyContext::empty();
        assert!(policy.is_authorized_with_context(
            "/usr/bin/wrangler",
            "cf-token",
            None,
            None,
            &ctx,
        ));
    }
}