vallum 0.8.10

Security boundary between AI coding agents and your shell — redacts secrets, neutralizes prompt injection, sanitizes untrusted terminal output, audits every command.
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
//! Configuration: loading, defaults, and validation of `~/.vallum/config.toml`.

use regex::Regex;
use serde::{Deserialize, Serialize};
use std::env;
use std::fs;
use std::path::{Path, PathBuf};

const CONFIG_ENV_VAR: &str = "VALLUM_CONFIG";

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct AppConfig {
    pub audit: AuditConfig,
    pub pipeline: PipelineConfig,
    pub scrubber: ScrubberConfig,
    pub security: SecurityConfig,
    pub optimizer: OptimizerConfig,
    pub policy: PolicyConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct AuditConfig {
    pub log_dir: Option<PathBuf>,
    pub raw_enabled: bool,
    pub sanitized_enabled: bool,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PipelineConfig {
    pub head_lines: usize,
    pub tail_lines: usize,
    pub min_optimize_tokens: usize,
    pub max_output_bytes: usize,
    pub timeout_secs: u64,
    pub max_line_length: usize,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ScrubberConfig {
    pub extra_secret_patterns: Vec<RedactionRule>,
    /// Context-gated entropy redaction of credential-ish assignment values.
    /// Default on; bare tokens (git SHAs, UUIDs) are never candidates.
    pub entropy: bool,
    /// Input normalization (strip invisible/bidi chars + shadow-fold homoglyphs
    /// for injection matching). Default on; `false` reverts to legacy behavior.
    pub normalize: bool,
}

impl Default for ScrubberConfig {
    fn default() -> Self {
        Self {
            extra_secret_patterns: Vec::new(),
            entropy: true,
            normalize: true,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SecurityConfig {
    /// Block the entire output when an injection is detected.
    pub strict: bool,
    /// Enable the pre-exec guardrail/policy layer. Default on; all built-in
    /// rules default to `ask`, so ordinary commands are unaffected.
    pub guardrail: bool,
    /// Auto-approve direct-mode `ask` verdicts (for scripts/CI). Also honored
    /// via the `VALLUM_ASSUME_YES=1` environment variable.
    pub assume_yes: bool,
    /// Blast-radius circuit breaker: when `breaker_threshold` Ask/Deny
    /// verdicts land within `breaker_window_secs`, ALL commands are denied
    /// for `breaker_cooldown_secs` (or until `vallum unlock`). Default on.
    pub circuit_breaker: bool,
    /// Ask/Deny events within the window that trip the breaker (≥ 1).
    pub breaker_threshold: u32,
    /// Sliding-window length in seconds (≥ 1).
    pub breaker_window_secs: u64,
    /// Lock duration in seconds once tripped (≥ 1).
    pub breaker_cooldown_secs: u64,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            strict: false,
            guardrail: true,
            assume_yes: false,
            circuit_breaker: true,
            breaker_threshold: 5,
            breaker_window_secs: 60,
            breaker_cooldown_secs: 300,
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct OptimizerConfig {
    /// Names of optimizers to disable. All optimizers are on by default.
    /// Valid names: git_status, git_diff, git_log, cargo, pytest, npm,
    /// docker, go_test, make, kubectl, terraform, grep, file_list.
    /// `vallum doctor` warns about names here that match no optimizer.
    pub disabled: Vec<String>,
}

#[derive(Debug, Clone, Serialize)]
pub struct RedactionRule {
    pub pattern: String,
    pub replacement: String,
}

// Hand-rolled so a bare string entry gets an error that shows the expected
// table form instead of serde's "invalid type: string, expected struct".
impl<'de> Deserialize<'de> for RedactionRule {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct RuleVisitor;

        impl<'de> serde::de::Visitor<'de> for RuleVisitor {
            type Value = RedactionRule;

            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                write!(f, "a table like {{ pattern = \"\", replacement = \"\" }}")
            }

            fn visit_str<E: serde::de::Error>(self, s: &str) -> Result<Self::Value, E> {
                Err(E::custom(format!(
                    "bare string \"{s}\" is not a valid secret pattern entry; use a table: \
                     extra_secret_patterns = [{{ pattern = \"{s}\", replacement = \"***\" }}]"
                )))
            }

            fn visit_map<M: serde::de::MapAccess<'de>>(
                self,
                mut map: M,
            ) -> Result<Self::Value, M::Error> {
                let mut pattern = None;
                let mut replacement = None;
                while let Some(key) = map.next_key::<String>()? {
                    match key.as_str() {
                        "pattern" => pattern = Some(map.next_value()?),
                        "replacement" => replacement = Some(map.next_value()?),
                        other => {
                            return Err(serde::de::Error::unknown_field(
                                other,
                                &["pattern", "replacement"],
                            ))
                        }
                    }
                }
                Ok(RedactionRule {
                    pattern: pattern.ok_or_else(|| serde::de::Error::missing_field("pattern"))?,
                    replacement: replacement
                        .ok_or_else(|| serde::de::Error::missing_field("replacement"))?,
                })
            }
        }

        deserializer.deserialize_any(RuleVisitor)
    }
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(default)]
pub struct PolicyConfig {
    /// Extra user rules, evaluated together with the built-ins.
    pub rules: Vec<PolicyRuleConfig>,
    /// Built-in rule names to disable. `vallum doctor` warns on unknown names.
    pub disabled: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PolicyRuleConfig {
    pub pattern: String,
    /// "ask" | "deny" ("allow" is rejected — use [policy] disabled to suppress a built-in).
    pub action: String,
    pub reason: String,
}

impl Default for AuditConfig {
    fn default() -> Self {
        Self {
            log_dir: None,
            raw_enabled: false,
            sanitized_enabled: true,
        }
    }
}

impl Default for PipelineConfig {
    fn default() -> Self {
        Self {
            head_lines: 50,
            tail_lines: 50,
            min_optimize_tokens: 50,
            max_output_bytes: 10 * 1024 * 1024,
            timeout_secs: 300,
            max_line_length: 2000,
        }
    }
}

impl AppConfig {
    pub fn load() -> Result<Self, String> {
        let path = config_path_from_env_or_default();
        Self::from_path(&path)
    }

    pub fn from_path(path: &Path) -> Result<Self, String> {
        if !path.exists() {
            return Ok(Self::default());
        }

        let raw = fs::read_to_string(path)
            .map_err(|e| format!("failed to read config {}: {}", path.display(), e))?;
        let config: Self = toml::from_str(&raw)
            .map_err(|e| format!("failed to parse config {}: {}", path.display(), e))?;
        config.validate()?;
        Ok(config)
    }

    fn validate(&self) -> Result<(), String> {
        for rule in &self.scrubber.extra_secret_patterns {
            Regex::new(&rule.pattern)
                .map_err(|e| format!("invalid scrubber regex '{}': {}", rule.pattern, e))?;
        }
        for rule in &self.policy.rules {
            match rule.action.as_str() {
                "ask" | "deny" => {}
                "allow" => {
                    return Err(format!(
                        "policy rule action \"allow\" is not allowed (pattern '{}'); \
                         user rules may only \"ask\" or \"deny\" — use [policy] disabled \
                         to suppress a built-in",
                        rule.pattern
                    ))
                }
                other => {
                    return Err(format!(
                        "invalid policy rule action \"{}\" (pattern '{}'); expected \"ask\" or \"deny\"",
                        other, rule.pattern
                    ))
                }
            }
            Regex::new(&rule.pattern)
                .map_err(|e| format!("invalid policy regex '{}': {}", rule.pattern, e))?;
        }
        if self.security.breaker_threshold == 0 {
            return Err("breaker_threshold must be at least 1".to_string());
        }
        if self.security.breaker_window_secs == 0 {
            return Err("breaker_window_secs must be at least 1".to_string());
        }
        if self.security.breaker_cooldown_secs == 0 {
            return Err("breaker_cooldown_secs must be at least 1".to_string());
        }
        Ok(())
    }
}

pub fn config_path_from_env_or_default() -> PathBuf {
    if let Ok(path) = env::var(CONFIG_ENV_VAR) {
        PathBuf::from(path)
    } else if let Some(home) = dirs::home_dir() {
        home.join(".vallum").join("config.toml")
    } else {
        PathBuf::from("vallum-config.toml")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{SystemTime, UNIX_EPOCH};

    #[test]
    fn missing_config_uses_defaults() {
        let path = unique_temp_path("missing");
        let config = AppConfig::from_path(&path).unwrap();

        assert!(!config.audit.raw_enabled);
        assert!(config.audit.sanitized_enabled);
        assert_eq!(config.pipeline.head_lines, 50);
        assert_eq!(config.pipeline.tail_lines, 50);
        assert_eq!(config.pipeline.min_optimize_tokens, 50);
        assert_eq!(config.pipeline.max_output_bytes, 10 * 1024 * 1024);
        assert_eq!(config.pipeline.timeout_secs, 300);
        assert_eq!(config.pipeline.max_line_length, 2000);
        assert!(config.scrubber.extra_secret_patterns.is_empty());
    }

    #[test]
    fn parses_config_file_and_validates_regex() {
        let dir = unique_temp_path("valid");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");
        fs::write(
            &path,
            format!(
                r#"
[audit]
log_dir = "{}"
raw_enabled = false
sanitized_enabled = true

[pipeline]
head_lines = 3
tail_lines = 2

[scrubber]
extra_secret_patterns = [{{ pattern = "token-[0-9]+", replacement = "token-***" }}]
"#,
                dir.join("logs").display()
            ),
        )
        .unwrap();

        let config = AppConfig::from_path(&path).unwrap();
        assert_eq!(config.audit.log_dir.as_ref().unwrap(), &dir.join("logs"));
        assert!(!config.audit.raw_enabled);
        assert!(config.audit.sanitized_enabled);
        assert_eq!(config.pipeline.head_lines, 3);
        assert_eq!(config.pipeline.tail_lines, 2);
        assert_eq!(config.scrubber.extra_secret_patterns.len(), 1);
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn rejects_invalid_regex_in_config() {
        let dir = unique_temp_path("invalid");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");
        fs::write(
            &path,
            r#"
[scrubber]
extra_secret_patterns = [ { pattern = "token-(", replacement = "token-***" } ]
"#,
        )
        .unwrap();

        let err = AppConfig::from_path(&path).unwrap_err();
        assert!(err.contains("invalid scrubber regex"));
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn bare_string_secret_pattern_error_shows_expected_form() {
        let dir = unique_temp_path("barestr");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");
        fs::write(
            &path,
            r#"
[scrubber]
extra_secret_patterns = ["token-[0-9]+"]
"#,
        )
        .unwrap();

        let err = AppConfig::from_path(&path).unwrap_err();
        assert!(
            err.contains("pattern =") && err.contains("replacement ="),
            "error must show the expected table form, got: {err}"
        );
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn table_secret_pattern_missing_field_still_clear() {
        let dir = unique_temp_path("missingfield");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");
        fs::write(
            &path,
            r#"
[scrubber]
extra_secret_patterns = [ { pattern = "token-[0-9]+" } ]
"#,
        )
        .unwrap();

        let err = AppConfig::from_path(&path).unwrap_err();
        assert!(
            err.contains("replacement"),
            "error must name the missing field, got: {err}"
        );
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn security_strict_defaults_false_and_parses() {
        let def = AppConfig::default();
        assert!(!def.security.strict);

        let dir = unique_temp_path("security");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");
        fs::write(&path, "[security]\nstrict = true\n").unwrap();
        let config = AppConfig::from_path(&path).unwrap();
        assert!(config.security.strict);
        let _ = fs::remove_dir_all(&dir);
    }

    #[test]
    fn scrubber_entropy_defaults_true_and_parses_false() {
        assert!(AppConfig::default().scrubber.entropy);
        let parsed: AppConfig =
            toml::from_str("[scrubber]\nentropy = false\n").expect("valid toml");
        assert!(!parsed.scrubber.entropy);
    }

    #[test]
    fn scrubber_normalize_defaults_true_and_parses_false() {
        assert!(AppConfig::default().scrubber.normalize);
        let parsed: AppConfig =
            toml::from_str("[scrubber]\nnormalize = false\n").expect("valid toml");
        assert!(!parsed.scrubber.normalize);
    }

    #[test]
    fn optimizer_disabled_defaults_empty_and_parses() {
        assert!(AppConfig::default().optimizer.disabled.is_empty());

        let dir = unique_temp_path("optimizer");
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        let path = dir.join("config.toml");
        fs::write(&path, "[optimizer]\ndisabled = [\"npm\", \"docker\"]\n").unwrap();
        let config = AppConfig::from_path(&path).unwrap();
        assert_eq!(
            config.optimizer.disabled,
            vec!["npm".to_string(), "docker".to_string()]
        );
        let _ = fs::remove_dir_all(&dir);
    }

    fn unique_temp_path(name: &str) -> PathBuf {
        let suffix = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        std::env::temp_dir().join(format!("vallum_config_test_{}_{}", name, suffix))
    }

    fn write_tmp(name: &str, body: &str) -> std::path::PathBuf {
        let dir = std::env::temp_dir().join(format!(
            "vallum_cfg_{}_{}",
            name,
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        let p = dir.join("config.toml");
        std::fs::write(&p, body).unwrap();
        p
    }

    #[test]
    fn guardrail_defaults_on_assume_yes_off() {
        let cfg = AppConfig::default();
        assert!(cfg.security.guardrail);
        assert!(!cfg.security.assume_yes);
        assert!(cfg.policy.rules.is_empty());
        assert!(cfg.policy.disabled.is_empty());
    }

    #[test]
    fn breaker_defaults_on_with_conservative_thresholds() {
        let c = SecurityConfig::default();
        assert!(c.circuit_breaker);
        assert_eq!(c.breaker_threshold, 5);
        assert_eq!(c.breaker_window_secs, 60);
        assert_eq!(c.breaker_cooldown_secs, 300);
    }

    #[test]
    fn breaker_zero_threshold_is_config_error() {
        let mut config = AppConfig::default();
        config.security.breaker_threshold = 0;
        let err = config.validate().unwrap_err();
        assert!(err.contains("breaker_threshold"), "{err}");
        config.security.breaker_threshold = 5;
        config.security.breaker_window_secs = 0;
        let err = config.validate().unwrap_err();
        assert!(err.contains("breaker_window_secs"), "{err}");
        config.security.breaker_window_secs = 60;
        config.security.breaker_cooldown_secs = 0;
        let err = config.validate().unwrap_err();
        assert!(err.contains("breaker_cooldown_secs"), "{err}");
    }

    #[test]
    fn policy_rule_parses_and_validates() {
        let p = write_tmp(
            "ok",
            "[[policy.rules]]\npattern = 'terraform\\s+destroy'\naction = \"deny\"\nreason = \"blocked\"\n",
        );
        let cfg = AppConfig::from_path(&p).unwrap();
        assert_eq!(cfg.policy.rules.len(), 1);
        assert_eq!(cfg.policy.rules[0].action, "deny");
    }

    #[test]
    fn policy_rule_allow_action_is_error() {
        let p = write_tmp(
            "allow",
            "[[policy.rules]]\npattern = 'x'\naction = \"allow\"\nreason = \"r\"\n",
        );
        let err = AppConfig::from_path(&p).unwrap_err();
        assert!(err.contains("allow"), "got: {err}");
    }

    #[test]
    fn policy_rule_bad_regex_is_error() {
        let p = write_tmp(
            "badre",
            "[[policy.rules]]\npattern = '('\naction = \"ask\"\nreason = \"r\"\n",
        );
        assert!(AppConfig::from_path(&p).is_err());
    }

    #[test]
    fn policy_rule_unknown_action_is_error() {
        let p = write_tmp(
            "unk",
            "[[policy.rules]]\npattern = 'x'\naction = \"warn\"\nreason = \"r\"\n",
        );
        let err = AppConfig::from_path(&p).unwrap_err();
        assert!(err.contains("warn") || err.contains("action"), "got: {err}");
    }
}