clash 0.5.3

Command Line Agent Safety Harness — permission policies for coding agents
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
//! Shared test fixtures and helpers for the clash crate.
//!
//! Provides reusable builders for policies, hook events, and tool inputs
//! so that test files do not need to reinvent boilerplate.

use crate::hooks::{HookOutput, HookSpecificOutput, ToolUseHookInput};
use crate::policy::Effect;
use crate::settings::ClashSettings;

// ---------------------------------------------------------------------------
// Tool input builders
// ---------------------------------------------------------------------------

/// Build a `serde_json::Value` representing a Bash tool input.
pub fn bash_command(command: &str) -> serde_json::Value {
    serde_json::json!({"command": command})
}

/// Build a `serde_json::Value` representing a Read tool input.
pub fn read_file(path: &str) -> serde_json::Value {
    serde_json::json!({"file_path": path})
}

/// Build a `serde_json::Value` representing a Write tool input.
pub fn write_file(path: &str) -> serde_json::Value {
    serde_json::json!({"file_path": path, "content": ""})
}

/// Build a `serde_json::Value` representing an Edit tool input.
pub fn edit_file(path: &str) -> serde_json::Value {
    serde_json::json!({"file_path": path, "old_string": "", "new_string": ""})
}

/// Build a `serde_json::Value` representing a Glob tool input.
pub fn glob_pattern(pattern: &str) -> serde_json::Value {
    serde_json::json!({"pattern": pattern})
}

/// Build a `serde_json::Value` representing a Grep tool input.
pub fn grep_pattern(pattern: &str) -> serde_json::Value {
    serde_json::json!({"pattern": pattern})
}

// ---------------------------------------------------------------------------
// Hook event builders
// ---------------------------------------------------------------------------

/// Build a [`ToolUseHookInput`] for a PreToolUse event.
pub fn pre_tool_use(tool_name: &str, tool_input: serde_json::Value) -> ToolUseHookInput {
    ToolUseHookInput {
        session_id: "test-session".into(),
        transcript_path: "/tmp/transcript.jsonl".into(),
        cwd: "/tmp".into(),
        permission_mode: "default".into(),
        hook_event_name: "PreToolUse".into(),
        tool_name: tool_name.into(),
        tool_input,
        tool_use_id: Some("toolu_test".into()),
        tool_response: None,
    }
}

/// Build a [`ToolUseHookInput`] for a PostToolUse event.
pub fn post_tool_use(
    tool_name: &str,
    tool_input: serde_json::Value,
    tool_response: serde_json::Value,
) -> ToolUseHookInput {
    ToolUseHookInput {
        hook_event_name: "PostToolUse".into(),
        tool_response: Some(tool_response),
        ..pre_tool_use(tool_name, tool_input)
    }
}

// ---------------------------------------------------------------------------
// TestPolicy builder
// ---------------------------------------------------------------------------

/// Builder for constructing [`ClashSettings`] with an inline JSON policy.
///
/// # Example
///
/// ```ignore
/// let settings = TestPolicy::deny_all()
///     .allow_exec("git")
///     .build();
/// ```
pub struct TestPolicy {
    default_effect: &'static str,
    tree: Vec<String>,
}

impl TestPolicy {
    /// Start with a policy that denies everything by default.
    pub fn deny_all() -> Self {
        Self {
            default_effect: "deny",
            tree: Vec::new(),
        }
    }

    /// Start with a policy that asks for everything by default.
    pub fn ask_all() -> Self {
        Self {
            default_effect: "ask",
            tree: Vec::new(),
        }
    }

    /// Start with a policy that allows everything by default.
    pub fn allow_all() -> Self {
        Self {
            default_effect: "allow",
            tree: Vec::new(),
        }
    }

    /// Add a rule that allows executing a specific binary.
    pub fn allow_exec(mut self, bin: &str) -> Self {
        self.tree.push(format!(
            r#"{{"condition":{{"observe":"tool_name","pattern":{{"literal":{{"literal":"Bash"}}}},"children":[
                {{"condition":{{"observe":{{"positional_arg":0}},"pattern":{{"literal":{{"literal":"{bin}"}}}},"children":[
                    {{"decision":{{"allow":null}}}}
                ]}}}}
            ]}}}}"#
        ));
        self
    }

    /// Add a rule that denies executing a specific binary.
    pub fn deny_exec(mut self, bin: &str) -> Self {
        self.tree.push(format!(
            r#"{{"condition":{{"observe":"tool_name","pattern":{{"literal":{{"literal":"Bash"}}}},"children":[
                {{"condition":{{"observe":{{"positional_arg":0}},"pattern":{{"literal":{{"literal":"{bin}"}}}},"children":[
                    {{"decision":"deny"}}
                ]}}}}
            ]}}}}"#
        ));
        self
    }

    /// Add a rule that allows reading files under a path prefix.
    pub fn allow_read(mut self, path_prefix: &str) -> Self {
        self.tree.push(format!(
            r#"{{"condition":{{"observe":"fs_op","pattern":{{"literal":{{"literal":"read"}}}},"children":[
                {{"condition":{{"observe":"fs_path","pattern":{{"prefix":{{"literal":"{path_prefix}"}}}},"children":[
                    {{"decision":{{"allow":null}}}}
                ]}}}}
            ]}}}}"#
        ));
        self
    }

    /// Add a rule that allows writing files under a path prefix.
    pub fn allow_write(mut self, path_prefix: &str) -> Self {
        self.tree.push(format!(
            r#"{{"condition":{{"observe":"fs_op","pattern":{{"literal":{{"literal":"write"}}}},"children":[
                {{"condition":{{"observe":"fs_path","pattern":{{"prefix":{{"literal":"{path_prefix}"}}}},"children":[
                    {{"decision":{{"allow":null}}}}
                ]}}}}
            ]}}}}"#
        ));
        self
    }

    /// Add a rule that allows all tools (wildcard on tool_name).
    pub fn allow_all_tools(mut self) -> Self {
        self.tree.push(
            r#"{"condition":{"observe":"tool_name","pattern":"wildcard","children":[
                {"decision":{"allow":null}}
            ]}}"#
                .into(),
        );
        self
    }

    /// Add a raw JSON tree node string.
    pub fn raw_node(mut self, json: &str) -> Self {
        self.tree.push(json.to_string());
        self
    }

    /// Build the policy into a [`ClashSettings`] ready for permission checks.
    pub fn build(&self) -> ClashSettings {
        let tree_json = self.tree.join(",");
        let source = format!(
            r#"{{"schema_version":5,"default_effect":"{}","sandboxes":{{}},"tree":[{}]}}"#,
            self.default_effect, tree_json
        );
        let mut settings = ClashSettings::default();
        settings.set_policy_source(&source);
        settings
    }
}

// ---------------------------------------------------------------------------
// TestEnvironment
// ---------------------------------------------------------------------------

/// A temporary environment with a directory for policy files.
///
/// Useful for tests that need to write policy files to disk.
pub struct TestEnvironment {
    pub dir: tempfile::TempDir,
}

impl Default for TestEnvironment {
    fn default() -> Self {
        Self::new()
    }
}

impl TestEnvironment {
    /// Create a new test environment with a temporary directory.
    pub fn new() -> Self {
        Self {
            dir: tempfile::tempdir().expect("failed to create temp dir"),
        }
    }

    /// Write a policy JSON string to a file in the temp directory and return its path.
    pub fn write_policy(&self, filename: &str, content: &str) -> std::path::PathBuf {
        let path = self.dir.path().join(filename);
        std::fs::write(&path, content).expect("failed to write policy file");
        path
    }

    /// Return the path of the temp directory.
    pub fn path(&self) -> &std::path::Path {
        self.dir.path()
    }
}

// ---------------------------------------------------------------------------
// Decision extraction helpers
// ---------------------------------------------------------------------------

/// Extract the permission decision [`Effect`] from a [`HookOutput`].
pub fn get_effect(output: &HookOutput) -> Option<Effect> {
    match &output.hook_specific_output {
        Some(HookSpecificOutput::PreToolUse(pre)) => {
            pre.permission_decision
                .as_ref()
                .and_then(|rule| match rule {
                    claude_settings::PermissionRule::Allow => Some(Effect::Allow),
                    claude_settings::PermissionRule::Deny => Some(Effect::Deny),
                    claude_settings::PermissionRule::Ask => Some(Effect::Ask),
                    _ => None,
                })
        }
        _ => None,
    }
}

/// Extract the additional_context from a PreToolUse [`HookOutput`].
pub fn get_context(output: &HookOutput) -> Option<String> {
    match &output.hook_specific_output {
        Some(HookSpecificOutput::PreToolUse(pre)) => pre.additional_context.clone(),
        _ => None,
    }
}

/// Extract the permission_decision_reason from a PreToolUse [`HookOutput`].
pub fn get_reason(output: &HookOutput) -> Option<String> {
    match &output.hook_specific_output {
        Some(HookSpecificOutput::PreToolUse(pre)) => pre.permission_decision_reason.clone(),
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// assert_decision! macro
// ---------------------------------------------------------------------------

/// Assert that evaluating a policy against a hook event produces the expected effect.
///
/// # Usage
///
/// ```ignore
/// let settings = TestPolicy::deny_all().allow_exec("git").build();
/// let input = pre_tool_use("Bash", bash_command("git status"));
/// assert_decision!(settings, input, Effect::Allow);
/// ```
///
/// With optional reason substring check:
///
/// ```ignore
/// assert_decision!(settings, input, Effect::Allow, reason_contains: "allow");
/// ```
#[macro_export]
macro_rules! assert_decision {
    ($settings:expr, $input:expr, $expected_effect:expr) => {{
        let result =
            $crate::permissions::check_permission(&$input, &$settings).expect("check_permission");
        let effect = $crate::test_utils::get_effect(&result);
        assert_eq!(
            effect,
            Some($expected_effect),
            "expected {:?}, got {:?}",
            $expected_effect,
            effect
        );
        result
    }};
    ($settings:expr, $input:expr, $expected_effect:expr, reason_contains: $substr:expr) => {{
        let result = $crate::assert_decision!($settings, $input, $expected_effect);
        let reason = $crate::test_utils::get_reason(&result);
        let reason_str = reason.as_deref().unwrap_or("");
        assert!(
            reason_str.contains($substr),
            "expected reason to contain {:?}, got {:?}",
            $substr,
            reason_str
        );
        result
    }};
}

// ---------------------------------------------------------------------------
// Tests for test_utils
// ---------------------------------------------------------------------------

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

    #[test]
    fn test_policy_builder_deny_all() {
        let settings = TestPolicy::deny_all().build();
        let input = pre_tool_use("Bash", bash_command("ls"));
        let result =
            crate::permissions::check_permission(&input, &settings).expect("check_permission");
        assert_eq!(get_effect(&result), Some(Effect::Deny));
    }

    #[test]
    fn test_policy_builder_allow_exec() {
        let settings = TestPolicy::deny_all().allow_exec("git").build();
        let input = pre_tool_use("Bash", bash_command("git status"));
        assert_decision!(settings, input, Effect::Allow);
    }

    #[test]
    fn test_policy_builder_deny_exec() {
        let settings = TestPolicy::deny_all()
            .deny_exec("rm")
            .allow_all_tools()
            .build();
        let input = pre_tool_use("Bash", bash_command("rm -rf /"));
        assert_decision!(settings, input, Effect::Deny);
    }

    #[test]
    fn test_policy_builder_allow_read() {
        let settings = TestPolicy::deny_all()
            .allow_read("/home/user/project")
            .build();
        let input = pre_tool_use("Read", read_file("/home/user/project/src/main.rs"));
        assert_decision!(settings, input, Effect::Allow);
    }

    #[test]
    fn test_policy_builder_deny_read_outside_prefix() {
        let settings = TestPolicy::deny_all()
            .allow_read("/home/user/project")
            .build();
        let input = pre_tool_use("Read", read_file("/etc/passwd"));
        assert_decision!(settings, input, Effect::Deny);
    }

    #[test]
    fn test_policy_builder_allow_write() {
        let settings = TestPolicy::deny_all().allow_write("/tmp").build();
        let input = pre_tool_use("Write", write_file("/tmp/test.txt"));
        assert_decision!(settings, input, Effect::Allow);
    }

    #[test]
    fn test_policy_builder_ask_all() {
        let settings = TestPolicy::ask_all().build();
        let input = pre_tool_use("Bash", bash_command("ls"));
        assert_decision!(settings, input, Effect::Ask);
    }

    #[test]
    fn test_assert_decision_macro_with_reason() {
        let settings = TestPolicy::deny_all().allow_exec("git").build();
        let input = pre_tool_use("Bash", bash_command("git status"));
        assert_decision!(settings, input, Effect::Allow, reason_contains: "allow");
    }

    #[test]
    fn test_pre_tool_use_builder() {
        let input = pre_tool_use("Bash", bash_command("ls"));
        assert_eq!(input.tool_name, "Bash");
        assert_eq!(input.hook_event_name, "PreToolUse");
        assert_eq!(input.tool_input["command"], "ls");
    }

    #[test]
    fn test_post_tool_use_builder() {
        let response = serde_json::json!({"output": "file contents"});
        let input = post_tool_use("Read", read_file("/tmp/foo"), response.clone());
        assert_eq!(input.hook_event_name, "PostToolUse");
        assert_eq!(input.tool_response, Some(response));
    }

    #[test]
    fn test_environment_write_policy() {
        let env = TestEnvironment::new();
        let path = env.write_policy("test.json", r#"{"hello": "world"}"#);
        assert!(path.exists());
        let content = std::fs::read_to_string(&path).unwrap();
        assert_eq!(content, r#"{"hello": "world"}"#);
    }

    #[test]
    fn test_tool_input_builders() {
        assert_eq!(bash_command("ls")["command"], "ls");
        assert_eq!(read_file("/tmp/foo")["file_path"], "/tmp/foo");
        assert_eq!(write_file("/tmp/bar")["file_path"], "/tmp/bar");
        assert_eq!(edit_file("/tmp/baz")["file_path"], "/tmp/baz");
        assert_eq!(glob_pattern("**/*.rs")["pattern"], "**/*.rs");
        assert_eq!(grep_pattern("fn main")["pattern"], "fn main");
    }
}