clash 0.5.4

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
429
430
431
//! `clash shell` — bash-compatible shell with per-command sandbox enforcement.
//!
//! Uses brush (a bash-compatible shell implementation in Rust) with an external
//! command hook that evaluates the clash policy for every external command,
//! exactly as if Claude had issued it via the Bash tool. If the policy includes
//! a sandbox, the command is wrapped through `clash sandbox exec --policy <json>`.
//!
//! Three modes:
//! - `clash shell` — interactive REPL (brush-interactive with basic backend)
//! - `clash shell -c "cmd"` — execute a command string
//! - `clash shell script.sh` — execute a script file

use std::sync::Arc;

use anyhow::{Context, Result};
use tracing::info;

use crate::policy::CompiledPolicy;
use crate::policy::sandbox_types::SandboxPolicy;
use crate::settings::ClashSettings;

/// Build the external command hook that evaluates the policy for each command
/// and wraps it with the appropriate sandbox (same as Claude's Bash tool).
/// Shell builtins that should never be wrapped — they must run in-process.
const SHELL_BUILTINS: &[&str] = &[
    ".",
    ":",
    "[",
    "alias",
    "bg",
    "bind",
    "break",
    "builtin",
    "caller",
    "cd",
    "command",
    "compgen",
    "complete",
    "compopt",
    "continue",
    "declare",
    "dirs",
    "disown",
    "echo",
    "enable",
    "eval",
    "exec",
    "exit",
    "export",
    "false",
    "fc",
    "fg",
    "getopts",
    "hash",
    "help",
    "history",
    "jobs",
    "kill",
    "let",
    "local",
    "logout",
    "mapfile",
    "popd",
    "printf",
    "pushd",
    "pwd",
    "read",
    "readarray",
    "readonly",
    "return",
    "set",
    "shift",
    "shopt",
    "source",
    "suspend",
    "test",
    "times",
    "trap",
    "true",
    "type",
    "typeset",
    "ulimit",
    "umask",
    "unalias",
    "unset",
    "wait",
];

fn make_sandbox_hook(
    clash_bin: String,
    policy: Arc<CompiledPolicy>,
    default_sandbox: Option<SandboxPolicy>,
    debug: bool,
) -> clash_brush_core::ExternalCommandHook {
    Arc::new(move |executable_path: &str, args: &[String]| {
        // Don't wrap shell builtins — they must run in the shell process.
        let basename = executable_path
            .rsplit('/')
            .next()
            .unwrap_or(executable_path);
        if SHELL_BUILTINS.contains(&basename) {
            return None;
        }

        // Reconstruct the command string as it would appear in a Bash tool call.
        // Use the basename — brush resolves to full paths (e.g. /bin/cat) but
        // policies match against bare names (e.g. exe("cat")).
        let mut cmd_parts = vec![basename.to_string()];
        cmd_parts.extend(args.iter().cloned());
        let command_str = cmd_parts.join(" ");

        // Build a tool_input that matches what Claude's Bash tool produces.
        let tool_input = serde_json::json!({
            "command": command_str,
        });

        // Evaluate the policy exactly as check_permission would.
        let decision = policy.evaluate("Bash", &tool_input);

        // Use the policy's sandbox if present, otherwise fall back to the
        // user-specified default sandbox for the shell session.
        let effective_sandbox;
        let sandbox = match decision.sandbox {
            Some(ref sbx) => sbx,
            None => match default_sandbox {
                Some(ref fallback) => {
                    effective_sandbox = fallback.clone();
                    &effective_sandbox
                }
                None => {
                    if debug {
                        eprintln!("[clash-shell] {}: no sandbox", command_str);
                    }
                    return None;
                }
            },
        };

        // Resolve env vars in sandbox paths before serializing.
        // $HOME and $TMPDIR are process-global; $PWD is resolved by sandbox
        // exec via its process cwd (which brush sets correctly).
        let mut resolved = sandbox.clone();
        let resolver = crate::policy::path::PathResolver::from_env();
        for rule in &mut resolved.rules {
            rule.path = rule
                .path
                .replace("$HOME", resolver.home())
                .replace("$TMPDIR", resolver.tmpdir());
        }

        if debug {
            eprintln!(
                "[clash-shell] {}: effect={:?}",
                command_str, decision.effect
            );
            if let Ok(json) = serde_json::to_string_pretty(&resolved) {
                eprintln!("[clash-shell] sandbox: {}", json);
            }
        }

        let policy_json = match serde_json::to_string(&resolved) {
            Ok(j) => j,
            Err(_) => return None,
        };

        // Don't pass --cwd explicitly; brush sets current_dir on the child
        // process to the shell's working directory, and sandbox exec defaults
        // --cwd to "." which resolves via the process cwd.
        let mut new_args = vec![
            "sandbox".to_string(),
            "exec".to_string(),
            "--sandbox".to_string(),
            policy_json,
            "--".to_string(),
            executable_path.to_string(),
        ];
        new_args.extend(args.iter().cloned());
        Some((clash_bin.clone(), new_args))
    })
}

/// Run a bash-compatible shell with per-command sandbox enforcement.
pub fn run_shell(
    command: Option<String>,
    script_args: Vec<String>,
    cwd: String,
    sandbox_name: Option<String>,
    debug: bool,
) -> Result<()> {
    let cwd = crate::sandbox_cmd::resolve_cwd(&cwd)?;
    let clash_bin = std::env::current_exe()
        .context("failed to determine clash executable path")?
        .to_string_lossy()
        .to_string();

    // Load the policy so we can evaluate it per-command.
    let settings = ClashSettings::load_or_create().context("failed to load clash settings")?;
    let policy = settings
        .policy_tree()
        .context("no compiled policy available — run `clash init` first")?
        .clone();

    // Resolve the default sandbox: CLI --sandbox flag overrides policy's default_sandbox.
    let effective_name = sandbox_name
        .as_deref()
        .or(policy.default_sandbox.as_deref());

    let default_sandbox = match effective_name {
        Some(name) => {
            let sbx = policy.sandboxes.get(name).cloned().ok_or_else(|| {
                anyhow::anyhow!(
                    "no sandbox named '{}' in policy (available: {:?})",
                    name,
                    policy.sandboxes.keys().collect::<Vec<_>>()
                )
            })?;
            Some(sbx)
        }
        None => None,
    };

    let hook = make_sandbox_hook(clash_bin, Arc::new(policy), default_sandbox, debug);

    // Build a tokio runtime for brush's async API.
    let rt = tokio::runtime::Runtime::new().context("failed to create tokio runtime")?;

    rt.block_on(async {
        if let Some(ref cmd) = command {
            run_command_string(cmd, &cwd, hook).await
        } else if !script_args.is_empty() {
            run_script(&script_args, &cwd, hook).await
        } else {
            run_interactive(&cwd, hook).await
        }
    })
}

/// Register the standard set of bash builtins (cd, export, source, etc.)
/// into a shell instance. brush-core doesn't include builtins by default;
/// they live in the separate brush-builtins crate.
fn register_builtins(shell: &mut clash_brush_core::Shell) {
    for (name, registration) in
        clash_brush_builtins::default_builtins(clash_brush_builtins::BuiltinSet::BashMode)
    {
        shell.register_builtin(&name, registration);
    }
}

/// Execute a command string (`clash shell -c "..."`).
async fn run_command_string(
    command: &str,
    cwd: &str,
    hook: clash_brush_core::ExternalCommandHook,
) -> Result<()> {
    info!(command = %command, "executing command string with sandbox hook");

    let mut shell = clash_brush_core::Shell::builder()
        .command_string_mode(true)
        .working_dir(std::path::PathBuf::from(cwd))
        .external_command_hook(hook)
        .profile(clash_brush_core::ProfileLoadBehavior::Skip)
        .rc(clash_brush_core::RcLoadBehavior::Skip)
        .build()
        .await
        .map_err(|e| anyhow::anyhow!("failed to create shell: {e}"))?;

    register_builtins(&mut shell);

    let params = shell.default_exec_params();
    let source_info = clash_brush_core::SourceInfo::from("clash-shell");

    let result = shell
        .run_string(command, &source_info, &params)
        .await
        .map_err(|e| anyhow::anyhow!("execution error: {e}"))?;

    if !result.is_success() {
        std::process::exit(1);
    }
    Ok(())
}

/// Execute a script file (`clash shell script.sh arg1 arg2`).
async fn run_script(
    script_args: &[String],
    cwd: &str,
    hook: clash_brush_core::ExternalCommandHook,
) -> Result<()> {
    let script_path = &script_args[0];
    info!(script = %script_path, "executing script with sandbox hook");

    let args: Vec<String> = if script_args.len() > 1 {
        script_args[1..].to_vec()
    } else {
        vec![]
    };

    let mut shell = clash_brush_core::Shell::builder()
        .working_dir(std::path::PathBuf::from(cwd))
        .external_command_hook(hook)
        .profile(clash_brush_core::ProfileLoadBehavior::Skip)
        .rc(clash_brush_core::RcLoadBehavior::Skip)
        .build()
        .await
        .map_err(|e| anyhow::anyhow!("failed to create shell: {e}"))?;

    register_builtins(&mut shell);

    let result = shell
        .run_script(script_path, args.into_iter())
        .await
        .map_err(|e| anyhow::anyhow!("script execution error: {e}"))?;

    if !result.is_success() {
        std::process::exit(1);
    }
    Ok(())
}

/// Run an interactive shell REPL (`clash shell`).
async fn run_interactive(cwd: &str, hook: clash_brush_core::ExternalCommandHook) -> Result<()> {
    info!("starting interactive shell with sandbox hook");

    let mut shell = clash_brush_core::Shell::builder()
        .interactive(true)
        .working_dir(std::path::PathBuf::from(cwd))
        .external_command_hook(hook)
        .shell_name("clash-shell".to_string())
        .profile(clash_brush_core::ProfileLoadBehavior::Skip)
        .rc(clash_brush_core::RcLoadBehavior::Skip)
        .build()
        .await
        .map_err(|e| anyhow::anyhow!("failed to create shell: {e}"))?;

    register_builtins(&mut shell);

    let shell_ref = std::sync::Arc::new(tokio::sync::Mutex::new(shell));

    let mut input = clash_brush_interactive::BasicInputBackend;

    let options = clash_brush_interactive::InteractiveOptions::default();

    let mut interactive =
        clash_brush_interactive::InteractiveShell::new(&shell_ref, &mut input, &options)
            .map_err(|e| anyhow::anyhow!("failed to create interactive shell: {e}"))?;

    interactive
        .run_interactively()
        .await
        .map_err(|e| anyhow::anyhow!("interactive shell error: {e}"))?;

    Ok(())
}

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

    /// Compile a Starlark policy string into a CompiledPolicy.
    fn compile_star(source: &str) -> CompiledPolicy {
        let output =
            clash_starlark::evaluate(source, "test.star", std::path::Path::new(".")).unwrap();
        let mut settings = ClashSettings::default();
        settings.set_policy_source(&output.json);
        settings.policy_tree().unwrap().clone()
    }

    /// Build a test policy that allows Bash with a sandbox.
    fn test_policy() -> Arc<CompiledPolicy> {
        Arc::new(compile_star(
            r#"load("@clash//std.star", "policy", "sandbox", "cwd", "match", "allow", "deny")
def main():
    return policy(default = deny(), rules = [
        match({"Bash": allow(sandbox=sandbox(name="test", default=deny(), fs=[cwd().allow(read=True)]))}),
    ])
"#,
        ))
    }

    fn test_hook() -> clash_brush_core::ExternalCommandHook {
        make_sandbox_hook("/usr/bin/clash".to_string(), test_policy(), None, false)
    }

    #[test]
    fn hook_wraps_with_policy_json() {
        let hook = test_hook();
        // Brush resolves to full paths; hook should still match policy.
        let result = hook("/usr/bin/git", &["push".to_string()]);
        let (exe, args) = result.unwrap();
        assert_eq!(exe, "/usr/bin/clash");
        assert_eq!(args[0], "sandbox");
        assert_eq!(args[1], "exec");
        assert_eq!(args[2], "--sandbox");
        // args[3] should be the sandbox policy JSON
        let _: serde_json::Value =
            serde_json::from_str(&args[3]).expect("--sandbox arg should be valid JSON");
        assert_eq!(args[4], "--");
        // The actual exec still uses the full path from brush.
        assert_eq!(args[5], "/usr/bin/git");
        assert_eq!(args[6], "push");
    }

    #[test]
    fn hook_preserves_args_order() {
        let hook = test_hook();
        let result = hook(
            "/bin/cat",
            &["file1.txt".to_string(), "file2.txt".to_string()],
        );
        let (_, args) = result.unwrap();
        let dash_pos = args.iter().position(|a| a == "--").unwrap();
        assert_eq!(args[dash_pos + 1], "/bin/cat");
        assert_eq!(args[dash_pos + 2], "file1.txt");
        assert_eq!(args[dash_pos + 3], "file2.txt");
    }

    #[test]
    fn hook_returns_none_without_sandbox() {
        let policy = Arc::new(compile_star(
            r#"load("@clash//std.star", "allow", "policy")
def main():
    return policy(default = allow(), rules = [])
"#,
        ));
        let hook = make_sandbox_hook("/usr/bin/clash".to_string(), policy, None, false);
        // No sandbox → command runs unchanged.
        let result = hook("/usr/bin/git", &["push".to_string()]);
        assert!(result.is_none());
    }
}