envseal 0.3.12

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
//! User-authored detection→policy overrides for [`SecurityConfig`].
//!
//! Lives in its own file so the data definition (`tiers.rs`) and the
//! HMAC persistence layer (`persistence.rs`) don't get intermixed
//! with vocabulary parsing and override mutators. Plus the test
//! module proving the bridge to [`crate::guard::Policy`] stays
//! adjacent to the code it covers.
//!
//! # Vocabulary
//!
//! Three concepts have stable lowercase string representations so
//! `security.toml` and the CLI override commands speak the same
//! language:
//!
//! | Concept   | Constant         | Values                                                   |
//! |-----------|------------------|----------------------------------------------------------|
//! | Action    | [`ACTION_NAMES`] | `ignore`, `log`, `warn`, `warn_with_challenge`, `block`  |
//! | Severity  | [`SEVERITY_NAMES`] | `info`, `warn`, `degraded`, `hostile`, `critical`      |
//! | Tier      | [`TIER_NAMES`]   | `standard`, `hardened`, `lockdown`                       |

use super::tiers::{SecurityConfig, SecurityTier};
use crate::error::Error;

/// Canonical action vocabulary. Used in `--help` text and the CLI override command.
pub const ACTION_NAMES: &[&str] = &["ignore", "log", "warn", "warn_with_challenge", "block"];
/// Canonical severity vocabulary.
pub const SEVERITY_NAMES: &[&str] = &["info", "warn", "degraded", "hostile", "critical"];
/// Canonical tier vocabulary.
pub const TIER_NAMES: &[&str] = &["standard", "hardened", "lockdown"];

impl SecurityConfig {
    /// Build a [`crate::guard::Policy`] from this config's
    /// `signal_overrides` and `tier_overrides`. Unknown action /
    /// severity / tier strings are silently ignored — the resulting
    /// policy falls back to the default table for those entries.
    /// This is the single bridge between user-authored config and
    /// the runtime detection→policy taxonomy.
    #[must_use]
    pub fn build_policy(&self) -> crate::guard::Policy {
        let mut policy = crate::guard::Policy::new();

        for (sig_id, action_str) in &self.signal_overrides {
            if let Some(action) = parse_action(action_str) {
                policy.override_signal(crate::guard::SignalId::from_runtime_string(sig_id), action);
            }
        }

        for (key, action_str) in &self.tier_overrides {
            let Some((sev, tier)) = key.split_once(':') else {
                continue;
            };
            let Some(severity) = parse_severity(sev) else {
                continue;
            };
            let Some(tier_v) = parse_tier(tier) else {
                continue;
            };
            let Some(action) = parse_action(action_str) else {
                continue;
            };
            policy.override_action(severity, tier_v, action);
        }

        policy
    }

    /// Set or replace a per-signal policy override.
    ///
    /// `signal_id` is the stable taxonomy identifier (e.g.
    /// `gui.input_injector.xdotool`, `env.preload.ld_preload`).
    /// `action` must be one of `ignore` / `log` / `warn` /
    /// `warn_with_challenge` / `block` (case-insensitive); the value
    /// is stored in lowercase so reads round-trip cleanly.
    ///
    /// # Errors
    /// `Error::CryptoFailure` when `signal_id` is empty or contains
    /// control characters, or when `action` is not a recognized
    /// vocabulary word. Validation up front prevents typos from
    /// being silently dropped at policy-build time.
    pub fn set_signal_override(&mut self, signal_id: &str, action: &str) -> Result<(), Error> {
        let id = validate_signal_id(signal_id)?;
        let canon = canonical_action(action)?;
        self.signal_overrides.insert(id, canon);
        Ok(())
    }

    /// Remove a per-signal override. Returns whether one was present.
    pub fn clear_signal_override(&mut self, signal_id: &str) -> bool {
        self.signal_overrides.remove(signal_id.trim()).is_some()
    }

    /// Set or replace a per-(severity, tier) policy override.
    ///
    /// # Errors
    /// `Error::CryptoFailure` when `severity`, `tier`, or `action`
    /// is not a recognized vocabulary word.
    pub fn set_tier_override(
        &mut self,
        severity: &str,
        tier: &str,
        action: &str,
    ) -> Result<(), Error> {
        let sev = canonical_severity(severity)?;
        let tier_canon = canonical_tier(tier)?;
        let action_canon = canonical_action(action)?;
        self.tier_overrides
            .insert(format!("{sev}:{tier_canon}"), action_canon);
        Ok(())
    }

    /// Remove a per-(severity, tier) override. Returns whether one was present.
    ///
    /// # Errors
    /// `Error::CryptoFailure` when `severity` or `tier` is not a
    /// recognized vocabulary word.
    pub fn clear_tier_override(&mut self, severity: &str, tier: &str) -> Result<bool, Error> {
        let sev = canonical_severity(severity)?;
        let tier_canon = canonical_tier(tier)?;
        Ok(self
            .tier_overrides
            .remove(&format!("{sev}:{tier_canon}"))
            .is_some())
    }
}

fn validate_signal_id(s: &str) -> Result<String, Error> {
    let trimmed = s.trim();
    if trimmed.is_empty() {
        return Err(Error::CryptoFailure(
            "signal id must be non-empty".to_string(),
        ));
    }
    if trimmed.chars().any(char::is_control) {
        return Err(Error::CryptoFailure(format!(
            "signal id contains control characters: {trimmed:?}"
        )));
    }
    Ok(trimmed.to_string())
}

fn canonical_action(s: &str) -> Result<String, Error> {
    let lc = s.trim().to_ascii_lowercase();
    if parse_action(&lc).is_some() {
        Ok(lc)
    } else {
        Err(Error::CryptoFailure(format!(
            "unknown action '{s}'. valid: {}",
            ACTION_NAMES.join(", ")
        )))
    }
}

fn canonical_severity(s: &str) -> Result<String, Error> {
    let lc = s.trim().to_ascii_lowercase();
    if parse_severity(&lc).is_some() {
        Ok(lc)
    } else {
        Err(Error::CryptoFailure(format!(
            "unknown severity '{s}'. valid: {}",
            SEVERITY_NAMES.join(", ")
        )))
    }
}

fn canonical_tier(s: &str) -> Result<String, Error> {
    let lc = s.trim().to_ascii_lowercase();
    if parse_tier(&lc).is_some() {
        Ok(lc)
    } else {
        Err(Error::CryptoFailure(format!(
            "unknown tier '{s}'. valid: {}",
            TIER_NAMES.join(", ")
        )))
    }
}

/// Parse a free-form action string into a [`crate::guard::Action`].
/// Accepts `ignore` / `log` / `warn` / `warn_with_challenge` /
/// `block` (case-insensitive). Returns `None` for anything else so
/// callers can fall back to the default table without crashing on
/// a typo in `security.toml`.
fn parse_action(s: &str) -> Option<crate::guard::Action> {
    match s.trim().to_ascii_lowercase().as_str() {
        "ignore" => Some(crate::guard::Action::Ignore),
        "log" => Some(crate::guard::Action::Log),
        "warn" => Some(crate::guard::Action::Warn { friction: false }),
        "warn_with_challenge" | "challenge" => Some(crate::guard::Action::Warn { friction: true }),
        "block" => Some(crate::guard::Action::Block),
        _ => None,
    }
}

fn parse_severity(s: &str) -> Option<crate::guard::Severity> {
    match s.trim().to_ascii_lowercase().as_str() {
        "info" => Some(crate::guard::Severity::Info),
        "warn" => Some(crate::guard::Severity::Warn),
        "degraded" => Some(crate::guard::Severity::Degraded),
        "hostile" => Some(crate::guard::Severity::Hostile),
        "critical" => Some(crate::guard::Severity::Critical),
        _ => None,
    }
}

fn parse_tier(s: &str) -> Option<SecurityTier> {
    match s.trim().to_ascii_lowercase().as_str() {
        "standard" => Some(SecurityTier::Standard),
        "hardened" => Some(SecurityTier::Hardened),
        "lockdown" => Some(SecurityTier::Lockdown),
        _ => None,
    }
}

#[cfg(test)]
mod policy_override_tests {
    use super::*;
    use crate::guard::{Action, Severity};

    #[test]
    fn empty_overrides_yield_default_policy() {
        let config = SecurityConfig::default();
        let policy = config.build_policy();
        let id = crate::guard::SignalId::from_runtime_string("any.signal");
        let sig = crate::guard::Signal::new(
            id,
            crate::guard::Category::Other,
            Severity::Hostile,
            "x",
            "",
            "",
        );
        assert_eq!(policy.decide(&sig, SecurityTier::Lockdown), Action::Block);
    }

    #[test]
    fn signal_override_loaded_from_config_takes_effect() {
        let mut config = SecurityConfig::default();
        config.signal_overrides.insert(
            "gui.input_injector.xdotool".to_string(),
            "ignore".to_string(),
        );
        let policy = config.build_policy();
        let xdotool = crate::guard::Signal::new(
            crate::guard::SignalId::from_runtime_string("gui.input_injector.xdotool"),
            crate::guard::Category::InputInjection,
            Severity::Hostile,
            "xdotool",
            "running",
            "",
        );
        assert_eq!(
            policy.decide(&xdotool, SecurityTier::Lockdown),
            Action::Ignore
        );

        let ydotool = crate::guard::Signal::new(
            crate::guard::SignalId::from_runtime_string("gui.input_injector.ydotool"),
            crate::guard::Category::InputInjection,
            Severity::Hostile,
            "ydotool",
            "running",
            "",
        );
        assert_eq!(
            policy.decide(&ydotool, SecurityTier::Lockdown),
            Action::Block
        );
    }

    #[test]
    fn tier_override_loaded_from_config_takes_effect() {
        let mut config = SecurityConfig::default();
        config
            .tier_overrides
            .insert("warn:hardened".to_string(), "block".to_string());
        let policy = config.build_policy();

        let warn_sig = crate::guard::Signal::new(
            crate::guard::SignalId::from_runtime_string("test.warn.x"),
            crate::guard::Category::Other,
            Severity::Warn,
            "x",
            "",
            "",
        );
        assert_eq!(
            policy.decide(&warn_sig, SecurityTier::Hardened),
            Action::Block
        );
        assert_eq!(
            policy.decide(&warn_sig, SecurityTier::Standard),
            Action::Warn { friction: false }
        );
    }

    #[test]
    fn typo_in_action_string_is_silently_ignored_not_panic() {
        let mut config = SecurityConfig::default();
        config.signal_overrides.insert(
            "gui.input_injector.xdotool".to_string(),
            "BLOK_PLZ".to_string(),
        );
        let policy = config.build_policy();
        let sig = crate::guard::Signal::new(
            crate::guard::SignalId::from_runtime_string("gui.input_injector.xdotool"),
            crate::guard::Category::InputInjection,
            Severity::Hostile,
            "xdotool",
            "",
            "",
        );
        assert_eq!(
            policy.decide(&sig, SecurityTier::Lockdown),
            Action::Block,
            "garbage action string falls back to default, which blocks Hostile under Lockdown"
        );
    }

    #[test]
    fn config_roundtrips_through_toml_with_overrides() {
        let mut config = SecurityConfig::default();
        config.signal_overrides.insert(
            "env.suspicious_loader_var.ld_library_path".to_string(),
            "warn".to_string(),
        );
        config
            .tier_overrides
            .insert("warn:lockdown".to_string(), "block".to_string());

        let serialized = toml::to_string(&config).expect("serialize");
        let parsed: SecurityConfig = toml::from_str(&serialized).expect("deserialize");
        assert_eq!(
            parsed
                .signal_overrides
                .get("env.suspicious_loader_var.ld_library_path"),
            Some(&"warn".to_string())
        );
        assert_eq!(
            parsed.tier_overrides.get("warn:lockdown"),
            Some(&"block".to_string())
        );
    }

    #[test]
    fn apply_preset_preserves_user_authored_overrides() {
        let mut config = SecurityConfig::default();
        config
            .signal_overrides
            .insert("gui.screen_recorder.obs".to_string(), "ignore".to_string());
        config.apply_preset(SecurityTier::Lockdown);
        assert_eq!(
            config.signal_overrides.get("gui.screen_recorder.obs"),
            Some(&"ignore".to_string()),
            "tier preset must not wipe user-authored signal overrides"
        );
    }

    #[test]
    fn set_signal_override_canonicalizes_action() {
        let mut config = SecurityConfig::default();
        config
            .set_signal_override("gui.input_injector.xdotool", "BLOCK")
            .expect("valid action");
        assert_eq!(
            config.signal_overrides.get("gui.input_injector.xdotool"),
            Some(&"block".to_string()),
            "action must be normalized to lowercase on write"
        );
    }

    #[test]
    fn set_signal_override_rejects_unknown_action() {
        let mut config = SecurityConfig::default();
        let err = config
            .set_signal_override("gui.x", "deny")
            .expect_err("must reject");
        assert!(
            err.to_string().contains("unknown action"),
            "error message: {err}"
        );
    }

    #[test]
    fn set_signal_override_rejects_empty_id() {
        let mut config = SecurityConfig::default();
        let err = config
            .set_signal_override("   ", "block")
            .expect_err("must reject");
        assert!(err.to_string().contains("non-empty"));
    }

    #[test]
    fn clear_signal_override_returns_presence() {
        let mut config = SecurityConfig::default();
        config.set_signal_override("a.b.c", "ignore").unwrap();
        assert!(config.clear_signal_override("a.b.c"));
        assert!(!config.clear_signal_override("a.b.c"));
    }

    #[test]
    fn set_tier_override_validates_all_three_fields() {
        let mut config = SecurityConfig::default();
        config
            .set_tier_override("warn", "hardened", "block")
            .expect("valid");
        assert_eq!(
            config.tier_overrides.get("warn:hardened"),
            Some(&"block".to_string())
        );

        assert!(config
            .set_tier_override("scary", "hardened", "block")
            .is_err());
        assert!(config
            .set_tier_override("warn", "paranoid", "block")
            .is_err());
        assert!(config
            .set_tier_override("warn", "hardened", "deny")
            .is_err());
    }

    #[test]
    fn clear_tier_override_validates_inputs() {
        let mut config = SecurityConfig::default();
        config
            .set_tier_override("warn", "hardened", "block")
            .unwrap();
        assert!(config.clear_tier_override("warn", "hardened").unwrap());
        assert!(!config.clear_tier_override("warn", "hardened").unwrap());
        assert!(config.clear_tier_override("scary", "hardened").is_err());
    }

    #[test]
    fn override_then_build_policy_applies_canonical_value() {
        let mut config = SecurityConfig::default();
        config
            .set_signal_override("env.preload.ld_preload", "ignore")
            .unwrap();
        let policy = config.build_policy();
        let sig = crate::guard::Signal::new(
            crate::guard::SignalId::from_runtime_string("env.preload.ld_preload"),
            crate::guard::Category::EnvironmentInjection,
            Severity::Hostile,
            "ld_preload",
            "",
            "",
        );
        assert_eq!(
            policy.decide(&sig, SecurityTier::Lockdown),
            Action::Ignore,
            "API-set override must round-trip through build_policy"
        );
    }
}