leviath-core 0.1.0

Core types and traits for Leviath: context regions, memory layouts, blueprints, and lifecycle policies
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
//! Policy rules for taint tracking allowlists.
//!
//! Users configure allowlist rules in `~/.config/leviath/policy.toml` to relax
//! taint gating restrictions. Rules can be static (TOML pattern matching) or
//! scripted (Rhai).

use crate::taint::TaintLevel;
use serde::{Deserialize, Serialize};

/// A static allowlist rule from the policy file.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AllowlistRule {
    /// Tool name this rule applies to.
    pub tool: String,
    /// Target patterns (e.g., email addresses, Slack channels).
    /// If empty, matches any target.
    #[serde(default)]
    pub to: Vec<String>,
    /// Channel patterns (for tools like Slack).
    #[serde(default)]
    pub channel: Vec<String>,
    /// Maximum sensitivity level allowed by this rule.
    pub max_sensitivity: TaintLevel,
}

impl AllowlistRule {
    /// Check if this rule matches a given tool invocation.
    pub fn matches(&self, tool_name: &str, target: Option<&str>, taint: TaintLevel) -> bool {
        if self.tool != tool_name {
            return false;
        }

        if taint > self.max_sensitivity {
            return false;
        }

        // If no patterns specified, match any target
        if self.to.is_empty() && self.channel.is_empty() {
            return true;
        }

        // Check target against 'to' patterns
        if let Some(target_str) = target {
            if self.to.iter().any(|p| pattern_matches(p, target_str)) {
                return true;
            }
            if self.channel.iter().any(|p| pattern_matches(p, target_str)) {
                return true;
            }
        }

        // If patterns are specified but no target provided, no match
        if target.is_none() && (!self.to.is_empty() || !self.channel.is_empty()) {
            return false;
        }

        false
    }
}

/// Simple glob-like pattern matching: supports `*` as wildcard prefix/suffix.
fn pattern_matches(pattern: &str, value: &str) -> bool {
    if pattern == "*" {
        return true;
    }
    if let Some(suffix) = pattern.strip_prefix('*') {
        return value.ends_with(suffix);
    }
    if let Some(prefix) = pattern.strip_suffix('*') {
        return value.starts_with(prefix);
    }
    pattern == value
}

/// MCP tool classification override.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct McpToolOverride {
    /// Tool sensitivity level.
    #[serde(default)]
    pub sensitivity: Option<TaintLevel>,
    /// Tool direction.
    #[serde(default)]
    pub direction: Option<String>,
    /// Tool clearance level.
    #[serde(default)]
    pub clearance: Option<TaintLevel>,
}

/// Complete policy configuration loaded from policy.toml.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct PolicyConfig {
    /// Static allowlist rules.
    #[serde(default)]
    pub allowlist: Vec<AllowlistRule>,
    /// MCP tool overrides keyed by "server_name.tool_name".
    #[serde(default)]
    pub mcp_overrides: std::collections::HashMap<String, McpToolOverride>,
}

impl PolicyConfig {
    /// Parse a policy config from TOML string.
    pub fn from_toml(content: &str) -> Result<Self, String> {
        // Parse the raw TOML
        let parsed: toml::Value =
            toml::from_str(content).map_err(|e| format!("Failed to parse policy.toml: {}", e))?;

        let mut config = PolicyConfig::default();

        // Parse [[allowlist]] array
        if let Some(allowlist_arr) = parsed.get("allowlist").and_then(|v| v.as_array()) {
            for rule_val in allowlist_arr {
                let tool = rule_val
                    .get("tool")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();

                let to: Vec<String> = rule_val
                    .get("to")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|v| v.as_str().map(|s| s.to_string()))
                            .collect()
                    })
                    .unwrap_or_default();

                let channel: Vec<String> = rule_val
                    .get("channel")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|v| v.as_str().map(|s| s.to_string()))
                            .collect()
                    })
                    .unwrap_or_default();

                let max_sensitivity = rule_val
                    .get("max_sensitivity")
                    .and_then(|v| v.as_str())
                    .and_then(TaintLevel::from_str_loose)
                    .unwrap_or(TaintLevel::Public);

                config.allowlist.push(AllowlistRule {
                    tool,
                    to,
                    channel,
                    max_sensitivity,
                });
            }
        }

        // Parse [mcp_overrides] section
        if let Some(overrides_table) = parsed.get("mcp_overrides").and_then(|v| v.as_table()) {
            for (server_name, server_val) in overrides_table {
                if let Some(tools_table) = server_val.get("tools").and_then(|v| v.as_table()) {
                    for (tool_name, tool_val) in tools_table {
                        let key = format!("{}.{}", server_name, tool_name);
                        let sensitivity = tool_val
                            .get("sensitivity")
                            .and_then(|v| v.as_str())
                            .and_then(TaintLevel::from_str_loose);
                        let direction = tool_val
                            .get("direction")
                            .and_then(|v| v.as_str())
                            .map(|s| s.to_string());
                        let clearance = tool_val
                            .get("clearance")
                            .and_then(|v| v.as_str())
                            .and_then(TaintLevel::from_str_loose);

                        config.mcp_overrides.insert(
                            key,
                            McpToolOverride {
                                sensitivity,
                                direction,
                                clearance,
                            },
                        );
                    }
                }
            }
        }

        Ok(config)
    }

    /// Check whether any allowlist rule matches the given invocation.
    /// Returns the index of the matching rule, if any.
    pub fn check_allowlist(
        &self,
        tool_name: &str,
        target: Option<&str>,
        taint: TaintLevel,
    ) -> Option<usize> {
        self.allowlist
            .iter()
            .position(|rule| rule.matches(tool_name, target, taint))
    }
}

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

    // ─── pattern_matches ────────────────────────────────────────────────────

    #[test]
    fn pattern_matches_exact() {
        assert!(pattern_matches("hello", "hello"));
        assert!(!pattern_matches("hello", "world"));
    }

    #[test]
    fn pattern_matches_wildcard_all() {
        assert!(pattern_matches("*", "anything"));
        assert!(pattern_matches("*", ""));
    }

    #[test]
    fn pattern_matches_wildcard_prefix() {
        assert!(pattern_matches("*@example.com", "user@example.com"));
        assert!(!pattern_matches("*@example.com", "user@other.com"));
    }

    #[test]
    fn pattern_matches_wildcard_suffix() {
        assert!(pattern_matches("megan@*", "megan@anywhere.com"));
        assert!(!pattern_matches("megan@*", "bob@anywhere.com"));
    }

    // ─── AllowlistRule::matches ──────────────────────────────────────────────

    #[test]
    fn rule_matches_tool_and_sensitivity() {
        let rule = AllowlistRule {
            tool: "send_email".into(),
            to: vec![],
            channel: vec![],
            max_sensitivity: TaintLevel::Private,
        };
        assert!(rule.matches("send_email", None, TaintLevel::Private));
        assert!(rule.matches("send_email", None, TaintLevel::Public));
        assert!(!rule.matches("other_tool", None, TaintLevel::Private));
    }

    #[test]
    fn rule_blocks_above_max_sensitivity() {
        let rule = AllowlistRule {
            tool: "send_email".into(),
            to: vec![],
            channel: vec![],
            max_sensitivity: TaintLevel::Internal,
        };
        assert!(!rule.matches("send_email", None, TaintLevel::Private));
    }

    #[test]
    fn rule_matches_target_pattern() {
        let rule = AllowlistRule {
            tool: "send_email".into(),
            to: vec!["megan@*".into(), "+17576306267".into()],
            channel: vec![],
            max_sensitivity: TaintLevel::Private,
        };
        assert!(rule.matches("send_email", Some("megan@work.com"), TaintLevel::Internal));
        assert!(rule.matches("send_email", Some("+17576306267"), TaintLevel::Internal));
        assert!(!rule.matches("send_email", Some("bob@work.com"), TaintLevel::Internal));
    }

    #[test]
    fn rule_matches_channel_pattern() {
        let rule = AllowlistRule {
            tool: "post_to_slack".into(),
            to: vec![],
            channel: vec!["#team-standup".into()],
            max_sensitivity: TaintLevel::Internal,
        };
        assert!(rule.matches("post_to_slack", Some("#team-standup"), TaintLevel::Internal));
        assert!(!rule.matches("post_to_slack", Some("#general"), TaintLevel::Internal));
    }

    #[test]
    fn rule_no_match_when_patterns_but_no_target() {
        let rule = AllowlistRule {
            tool: "send_email".into(),
            to: vec!["megan@*".into()],
            channel: vec![],
            max_sensitivity: TaintLevel::Private,
        };
        assert!(!rule.matches("send_email", None, TaintLevel::Internal));
    }

    // ─── PolicyConfig::from_toml ────────────────────────────────────────────

    #[test]
    fn parse_policy_with_allowlist() {
        let toml = r##"
[[allowlist]]
tool = "send_email"
to = ["megan@*", "+17576306267"]
max_sensitivity = "private"

[[allowlist]]
tool = "post_to_slack"
channel = ["#team-standup"]
max_sensitivity = "internal"
"##;
        let config = PolicyConfig::from_toml(toml).unwrap();
        assert_eq!(config.allowlist.len(), 2);
        assert_eq!(config.allowlist[0].tool, "send_email");
        assert_eq!(config.allowlist[0].to.len(), 2);
        assert_eq!(config.allowlist[0].max_sensitivity, TaintLevel::Private);
        assert_eq!(config.allowlist[1].tool, "post_to_slack");
        assert_eq!(config.allowlist[1].channel, vec!["#team-standup"]);
    }

    #[test]
    fn parse_policy_with_mcp_overrides() {
        let toml = r#"
[mcp_overrides."my-server".tools]
read_customer_data = { sensitivity = "private" }
search_public_docs = { sensitivity = "public" }
"#;
        let config = PolicyConfig::from_toml(toml).unwrap();
        assert_eq!(config.mcp_overrides.len(), 2);
        let cust = config
            .mcp_overrides
            .get("my-server.read_customer_data")
            .unwrap();
        assert_eq!(cust.sensitivity, Some(TaintLevel::Private));
        let docs = config
            .mcp_overrides
            .get("my-server.search_public_docs")
            .unwrap();
        assert_eq!(docs.sensitivity, Some(TaintLevel::Public));
    }

    #[test]
    fn parse_policy_mcp_override_with_direction_and_clearance() {
        // Exercises the direction/clearance branches of `[mcp_overrides]`
        // parsing, which a sensitivity-only override never reaches.
        let toml = r#"
[mcp_overrides."srv".tools]
send_email = { sensitivity = "private", direction = "egress", clearance = "public" }
"#;
        let config = PolicyConfig::from_toml(toml).unwrap();
        let ov = config.mcp_overrides.get("srv.send_email").unwrap();
        assert_eq!(ov.sensitivity, Some(TaintLevel::Private));
        assert_eq!(ov.direction.as_deref(), Some("egress"));
        assert_eq!(ov.clearance, Some(TaintLevel::Public));
    }

    #[test]
    fn parse_policy_empty() {
        let config = PolicyConfig::from_toml("").unwrap();
        assert!(config.allowlist.is_empty());
        assert!(config.mcp_overrides.is_empty());
    }

    #[test]
    fn parse_policy_invalid_toml() {
        let result = PolicyConfig::from_toml("{{invalid}}");
        assert!(result.is_err());
    }

    #[test]
    fn check_allowlist_returns_matching_index() {
        let config = PolicyConfig {
            allowlist: vec![
                AllowlistRule {
                    tool: "send_email".into(),
                    to: vec!["megan@*".into()],
                    channel: vec![],
                    max_sensitivity: TaintLevel::Private,
                },
                AllowlistRule {
                    tool: "post_to_slack".into(),
                    to: vec![],
                    channel: vec![],
                    max_sensitivity: TaintLevel::Internal,
                },
            ],
            mcp_overrides: Default::default(),
        };

        assert_eq!(
            config.check_allowlist("send_email", Some("megan@work.com"), TaintLevel::Internal),
            Some(0)
        );
        assert_eq!(
            config.check_allowlist("post_to_slack", None, TaintLevel::Internal),
            Some(1)
        );
        assert_eq!(
            config.check_allowlist("unknown", None, TaintLevel::Public),
            None
        );
    }

    // ─── Serde roundtrips ───────────────────────────────────────────────────

    #[test]
    fn allowlist_rule_serde_roundtrip() {
        let rule = AllowlistRule {
            tool: "send_email".into(),
            to: vec!["test@*".into()],
            channel: vec![],
            max_sensitivity: TaintLevel::Private,
        };
        let json = serde_json::to_string(&rule).unwrap();
        let back: AllowlistRule = serde_json::from_str(&json).unwrap();
        assert_eq!(rule, back);
    }

    #[test]
    fn mcp_override_serde_roundtrip() {
        let o = McpToolOverride {
            sensitivity: Some(TaintLevel::Private),
            direction: Some("outbound".into()),
            clearance: Some(TaintLevel::Internal),
        };
        let json = serde_json::to_string(&o).unwrap();
        let back: McpToolOverride = serde_json::from_str(&json).unwrap();
        assert_eq!(o, back);
    }

    #[test]
    fn test_matches_false_when_only_channel_pattern_set_but_no_target() {
        let rule = AllowlistRule {
            tool: "post_message".to_string(),
            to: vec![],
            channel: vec!["#general".to_string()],
            max_sensitivity: TaintLevel::Private,
        };
        // `to` is empty (first operand false), which forces evaluation of the
        // `channel` operand in the "patterns set but no target" guard; with no
        // target the rule must not match.
        assert!(!rule.matches("post_message", None, TaintLevel::Public));
    }

    #[test]
    fn test_from_toml_mcp_override_server_without_tools_table() {
        // A server entry that has no `tools` sub-table exercises the
        // `if let Some(tools_table)` None branch - nothing is inserted.
        let toml = r#"
[mcp_overrides.emptyserver]
note = "no tools declared here"
"#;
        let config = PolicyConfig::from_toml(toml).unwrap();
        assert!(config.mcp_overrides.is_empty());
    }
}