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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
use crate::policy::Effect;
use tracing::{Level, info, instrument, warn};

use crate::hooks::{HookOutput, ToolInput, ToolUseHookInput};
use crate::settings::ClashSettings;

/// Check if a tool invocation should be allowed, denied, or require user confirmation.
#[instrument(level = Level::TRACE, ret)]
pub fn check_permission(
    input: &ToolUseHookInput,
    settings: &ClashSettings,
) -> anyhow::Result<HookOutput> {
    let tree = match settings.policy_tree() {
        Some(t) => t,
        None => {
            let (reason, context) = match settings.policy_error() {
                Some(err) => {
                    let reason = format!(
                        "Policy failed to compile: {}. All actions are blocked until the policy is fixed.",
                        err
                    );
                    let context = "POLICY ERROR: clash cannot enforce permissions because the policy failed to compile.\n\
                         The user's policy file has a syntax or compilation error.\n\n\
                         Agent instructions:\n\
                         - Tell the user their clash policy has an error and all actions are blocked\n\
                         - Suggest running: clash policy validate\n\
                         - Do NOT retry the tool call — it will be blocked until the policy is fixed\n\
                         - Do NOT attempt workarounds".to_string();
                    (reason, context)
                }
                None => {
                    let reason = "No policy configured. All actions are blocked. Run `clash init` to create a policy.".to_string();
                    let context = "POLICY ERROR: clash has no compiled policy available.\n\
                         All actions are blocked because there is no valid policy to evaluate.\n\n\
                         Agent instructions:\n\
                         - Tell the user clash has no policy configured\n\
                         - Suggest running: clash init\n\
                         - Do NOT retry the tool call"
                        .to_string();
                    (reason, context)
                }
            };

            // Print distinctive error to stderr
            eprintln!(
                "{} {}",
                crate::style::err_red_bold("clash policy error:"),
                &reason
            );
            eprintln!(
                "  {} {}",
                crate::style::err_dim("To diagnose:"),
                crate::style::err_yellow("clash policy validate")
            );

            warn!("{}", reason);
            return Ok(HookOutput::deny(reason, Some(context)));
        }
    };

    let decision = tree.evaluate(&input.tool_name, &input.tool_input);
    let noun = extract_noun(&input.tool_name, &input.tool_input);

    info!(
        tool = %input.tool_name,
        noun = %noun,
        effect = %decision.effect,
        reason = ?decision.reason,
        trace = ?decision.trace,
        "Policy decision"
    );

    // Write audit log entry (global + session).
    crate::audit::log_decision(
        &settings.audit,
        &input.session_id,
        &input.tool_name,
        &input.tool_input,
        decision.effect,
        decision.reason.as_deref(),
        &decision.trace,
    );

    let explanation = decision.human_explanation();
    let additional_context = if explanation.is_empty() {
        None
    } else {
        Some(explanation.join("\n"))
    };

    // Print a concise denial message to stderr so the user sees it in the terminal.
    if decision.effect == Effect::Deny {
        let verb_str = tool_to_verb_str(&input.tool_name);
        let noun_summary = truncate_noun(&noun, 60);

        eprintln!(
            "{} blocked {} on {}",
            crate::style::err_red_bold("clash:"),
            verb_str,
            noun_summary
        );

        let is_explicit_deny = decision
            .reason
            .as_deref()
            .is_some_and(|r| r.contains("denied") || r.contains("deny"));

        if is_explicit_deny {
            eprintln!(
                "  {}",
                crate::style::err_dim("This action is explicitly denied by your policy.")
            );
        } else {
            eprintln!("  {}", crate::style::err_dim(denial_explanation(&verb_str)));
        }

        eprintln!(
            "  {} {}",
            crate::style::err_dim("To allow this:"),
            crate::style::err_yellow(&suggest_allow_command(&verb_str))
        );
        eprintln!(
            "  {}",
            crate::style::err_dim("(run \"clash allow --help\" for more options)")
        );
    }

    Ok(match decision.effect {
        Effect::Allow => {
            let mut output = HookOutput::allow(
                decision.reason.or(Some("policy: allowed".into())),
                additional_context,
            );
            // If the policy decision includes a per-command sandbox, rewrite the
            // command to run through `clash sandbox exec`.
            if let Some(ref sandbox_policy) = decision.sandbox
                && let Some(updated) = wrap_bash_with_sandbox(input, sandbox_policy)
            {
                output.set_updated_input(updated);
                info!("Rewrote Bash command to run under sandbox");
            }
            output
        }
        Effect::Deny => {
            let deny_context = build_deny_context(
                &input.tool_name,
                decision.reason.as_deref(),
                &input.tool_input,
            );
            HookOutput::deny(
                decision.reason.unwrap_or_else(|| "policy: denied".into()),
                Some(deny_context),
            )
        }
        Effect::Ask => HookOutput::ask(
            decision.reason.or(Some("policy: ask".into())),
            additional_context,
        ),
    })
}

/// Map a tool name to a short verb string for user-facing messages.
///
/// Verbs align with the bare verb shortcuts in `clash allow <verb>`:
/// bash, edit, read, web.
fn tool_to_verb_str(tool_name: &str) -> String {
    match tool_name {
        "Bash" => "bash".into(),
        "Read" | "Glob" | "Grep" => "read".into(),
        "Write" | "Edit" => "edit".into(),
        "WebFetch" | "WebSearch" => "web".into(),
        "Skill" | "Task" | "TaskCreate" | "TaskUpdate" | "TaskList" | "TaskGet" | "TaskStop"
        | "TaskOutput" | "AskUserQuestion" | "EnterPlanMode" | "ExitPlanMode" | "NotebookEdit" => {
            "tool".into()
        }
        _ => tool_name.to_lowercase(),
    }
}

/// If the tool input is a Bash command and a sandbox policy exists,
/// rewrite the command to run through `clash sandbox exec`.
///
/// Returns the updated `tool_input` JSON if rewriting is applicable, or None.
#[instrument(level = Level::TRACE, skip(input, sandbox_policy))]
fn wrap_bash_with_sandbox(
    input: &ToolUseHookInput,
    sandbox_policy: &crate::policy::sandbox_types::SandboxPolicy,
) -> Option<serde_json::Value> {
    let bash_input = match input.typed_tool_input() {
        ToolInput::Bash(b) => b,
        _ => return None,
    };

    let clash_bin = std::env::current_exe().ok()?;
    let policy_json = serde_json::to_string(sandbox_policy).ok()?;

    // Pass session and tool_use_id so `clash sandbox exec` can log violations
    // to the audit trail after the sandboxed process exits.
    let mut extra_args = String::new();
    if !input.session_id.is_empty() {
        extra_args += &format!(" --session-id {}", shell_escape(&input.session_id));
        if let Some(ref tuid) = input.tool_use_id {
            extra_args += &format!(" --tool-use-id {}", shell_escape(tuid));
        }
    }

    let sandboxed_command = format!(
        "{} sandbox exec --sandbox {} --cwd {}{} -- bash -c {}",
        shell_escape(&clash_bin.to_string_lossy()),
        shell_escape(&policy_json),
        shell_escape(&input.cwd),
        extra_args,
        shell_escape(&bash_input.command),
    );

    let mut updated = input.tool_input.clone();
    if let Some(obj) = updated.as_object_mut() {
        obj.insert(
            "command".into(),
            serde_json::Value::String(sandboxed_command),
        );
    }

    Some(updated)
}

/// Simple shell escaping: wrap in single quotes, escaping embedded single quotes.
#[instrument(level = Level::TRACE)]
fn shell_escape(s: &str) -> String {
    format!("'{}'", s.replace('\'', "'\\''"))
}

/// Suggest the most specific `clash policy allow` command for a denied tool use.
///
/// Prefers precise commands (e.g., `clash policy allow "git status"`) over broad
/// ones (e.g., `clash policy allow --tool Bash`).
fn suggest_allow_command_specific(tool_name: &str, tool_input: &serde_json::Value) -> String {
    match tool_name {
        "Bash" => {
            // Extract the command and suggest allowing the specific binary (+ first arg if present).
            if let Some(cmd) = tool_input.get("command").and_then(|v| v.as_str()) {
                let parts: Vec<&str> = cmd.split_whitespace().collect();
                match parts.len() {
                    0 => "clash policy allow --tool Bash".into(),
                    1 => format!("clash policy allow \"{}\"", parts[0]),
                    _ => {
                        // Include binary + first arg for specificity
                        format!("clash policy allow \"{} {}\"", parts[0], parts[1])
                    }
                }
            } else {
                "clash policy allow --tool Bash".into()
            }
        }
        "Read" | "Glob" | "Grep" => format!("clash policy allow --tool {tool_name}"),
        "Write" | "Edit" => format!("clash policy allow --tool {tool_name}"),
        "WebFetch" | "WebSearch" => format!("clash policy allow --tool {tool_name}"),
        _ => format!("clash policy allow --tool {tool_name}"),
    }
}

/// Suggest a broad `clash policy allow` command for a denied verb (used in stderr).
fn suggest_allow_command(verb_str: &str) -> String {
    match verb_str {
        "edit" | "bash" | "read" | "web" | "tool" => {
            format!("clash policy allow --tool {}", verb_str_to_tool(verb_str))
        }
        _ => format!("clash policy allow '{verb_str}'"),
    }
}

/// Map verb strings back to canonical tool names.
fn verb_str_to_tool(verb_str: &str) -> &'static str {
    match verb_str {
        "bash" => "Bash",
        "edit" => "Edit",
        "read" => "Read",
        "web" => "WebFetch",
        "tool" => "Skill",
        _ => "Bash",
    }
}

/// Return a plain-English explanation for why a verb was denied.
fn denial_explanation(verb_str: &str) -> &'static str {
    match verb_str {
        "edit" => "File editing is not allowed by your current policy.",
        "bash" => "Command execution is not allowed by your current policy.",
        "web" => "Web access is not allowed by your current policy.",
        "read" => "File reading outside the project is not allowed by your current policy.",
        _ => "This action is not allowed by your current policy.",
    }
}

/// Truncate a noun string to approximately `max_len` characters, appending "..." if truncated.
fn truncate_noun(noun: &str, max_len: usize) -> String {
    if noun.len() <= max_len {
        noun.to_string()
    } else {
        format!("{}...", &noun[..max_len])
    }
}

/// Build structured agent context for a Deny decision.
fn build_deny_context(
    tool_name: &str,
    reason: Option<&str>,
    tool_input: &serde_json::Value,
) -> String {
    let is_explicit_deny = reason.is_some_and(|r| r.contains("denied") || r.contains("deny"));

    let suggested = suggest_allow_command_specific(tool_name, tool_input);

    let mut lines = Vec::new();

    if is_explicit_deny {
        lines.push(format!(
            "BLOCKED by explicit deny rule. To allow: {suggested}"
        ));
    } else {
        lines.push(format!("BLOCKED by default deny. To allow: {suggested}"));
    }

    lines.push("Do NOT retry this tool call — it will be blocked again.".into());

    lines.join("\n")
}

/// Extract the noun (resource identifier) from tool input JSON.
pub fn extract_noun(tool_name: &str, tool_input: &serde_json::Value) -> String {
    let fields = [
        "command",   // Bash
        "file_path", // Read, Write, Edit, NotebookEdit
        "pattern",   // Glob, Grep
        "query",     // WebSearch
        "url",       // WebFetch
        "path",      // Glob, Grep (secondary field)
        "prompt",    // Task
        "skill",     // Skill
    ];
    for field in &fields {
        if let Some(val) = tool_input.get(*field).and_then(|v| v.as_str()) {
            return val.to_string();
        }
    }
    tool_name.to_lowercase()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::assert_decision;
    use crate::hooks::ToolUseHookInput;
    use crate::test_utils::{TestPolicy, bash_command, get_context, pre_tool_use, read_file};
    use anyhow::Result;
    use serde_json::json;

    fn bash_input(command: &str) -> ToolUseHookInput {
        pre_tool_use("Bash", bash_command(command))
    }

    fn settings_with_policy(source: &str) -> ClashSettings {
        let mut settings = ClashSettings::default();
        settings.set_policy_source(source);
        settings
    }

    // --- policy engine tests ---

    #[test]
    fn test_policy_allow_git_status() -> Result<()> {
        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");
        Ok(())
    }

    #[test]
    fn test_policy_deny_git_push() -> Result<()> {
        // deny git push, allow git *
        let source = r#"{"schema_version":5,"default_effect":"deny","sandboxes":{},"tree":[
            {"condition":{"observe":"tool_name","pattern":{"literal":{"literal":"Bash"}},"children":[
                {"condition":{"observe":{"positional_arg":0},"pattern":{"literal":{"literal":"git"}},"children":[
                    {"condition":{"observe":{"positional_arg":1},"pattern":{"literal":{"literal":"push"}},"children":[
                        {"decision":"deny"}
                    ]}},
                    {"decision":{"allow":null}}
                ]}}
            ]}}
        ]}"#;
        let settings = settings_with_policy(source);
        assert_decision!(settings, bash_input("git push origin main"), Effect::Deny);
        Ok(())
    }

    #[test]
    fn test_policy_default_deny() -> Result<()> {
        let settings = TestPolicy::deny_all().allow_exec("git").build();
        assert_decision!(settings, bash_input("ls"), Effect::Deny);
        Ok(())
    }

    #[test]
    fn test_policy_read_under_cwd() -> Result<()> {
        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, reason_contains: "allow");
        Ok(())
    }

    #[test]
    fn test_policy_read_outside_cwd_denied() -> Result<()> {
        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);
        Ok(())
    }

    #[test]
    fn test_no_compiled_policy_denies() -> Result<()> {
        let settings = ClashSettings::default();
        assert_decision!(settings, bash_input("ls"), Effect::Deny);
        Ok(())
    }

    // --- Explanation tests ---

    #[test]
    fn test_explanation_contains_matched_rule() -> Result<()> {
        let settings = TestPolicy::deny_all().allow_exec("git").build();
        let input = pre_tool_use("Bash", bash_command("git status"));
        let result = check_permission(&input, &settings)?;
        let ctx = get_context(&result).expect("should have additional_context");
        assert!(
            ctx.contains("matched"),
            "explanation should contain 'matched' but got: {ctx}"
        );
        Ok(())
    }

    #[test]
    fn test_explanation_no_rules_matched() -> Result<()> {
        let settings = TestPolicy::ask_all().allow_exec("git").build();
        let result = check_permission(&bash_input("ls"), &settings)?;
        let ctx = get_context(&result).expect("should have additional_context");
        assert!(
            ctx.contains("No rules matched"),
            "explanation should say 'No rules matched' but got: {ctx}"
        );
        Ok(())
    }

    // --- interactive tool (AskUserQuestion) policy tests ---

    #[test]
    fn test_ask_user_question_allowed_by_blanket_tool_rule() -> Result<()> {
        let settings = TestPolicy::deny_all().allow_all_tools().build();
        let input = pre_tool_use(
            "AskUserQuestion",
            json!({"questions": [{"question": "Which approach?", "options": []}]}),
        );
        assert_decision!(settings, input, Effect::Allow, reason_contains: "allow");
        Ok(())
    }

    #[test]
    fn test_ask_user_question_denied_by_explicit_deny() -> Result<()> {
        // Deny AskUserQuestion, allow everything else
        let source = r#"{"schema_version":5,"default_effect":"deny","sandboxes":{},"tree":[
            {"condition":{"observe":"tool_name","pattern":{"literal":{"literal":"AskUserQuestion"}},"children":[
                {"decision":"deny"}
            ]}},
            {"condition":{"observe":"tool_name","pattern":"wildcard","children":[
                {"decision":{"allow":null}}
            ]}}
        ]}"#;
        let settings = settings_with_policy(source);
        let input = pre_tool_use("AskUserQuestion", json!({"questions": []}));
        assert_decision!(settings, input, Effect::Deny);
        Ok(())
    }

    // --- shell_escape tests ---

    #[test]
    fn test_shell_escape_simple_string() {
        assert_eq!(shell_escape("hello"), "'hello'");
    }

    #[test]
    fn test_shell_escape_string_with_spaces() {
        assert_eq!(shell_escape("hello world"), "'hello world'");
    }

    #[test]
    fn test_shell_escape_empty_string() {
        assert_eq!(shell_escape(""), "''");
    }

    #[test]
    fn test_shell_escape_embedded_single_quotes() {
        assert_eq!(shell_escape("it's"), "'it'\\''s'");
    }

    #[test]
    fn test_shell_escape_multiple_single_quotes() {
        assert_eq!(shell_escape("a'b'c"), "'a'\\''b'\\''c'");
    }

    #[test]
    fn test_shell_escape_special_characters() {
        assert_eq!(shell_escape("$HOME"), "'$HOME'");
        assert_eq!(shell_escape("`whoami`"), "'`whoami`'");
        assert_eq!(shell_escape("a\\b"), "'a\\b'");
    }

    #[test]
    fn test_shell_escape_double_quotes() {
        assert_eq!(shell_escape("say \"hi\""), "'say \"hi\"'");
    }

    // --- wrap_bash_with_sandbox tests ---

    fn test_sandbox_policy() -> crate::policy::sandbox_types::SandboxPolicy {
        use crate::policy::sandbox_types::{Cap, NetworkPolicy};
        crate::policy::sandbox_types::SandboxPolicy {
            default: Cap::READ | Cap::EXECUTE,
            rules: vec![],
            network: NetworkPolicy::Deny,
            doc: None,
        }
    }

    fn bash_input_for_sandbox(command: &str, cwd: &str) -> ToolUseHookInput {
        ToolUseHookInput {
            tool_name: "Bash".into(),
            tool_input: json!({"command": command}),
            cwd: cwd.into(),
            ..Default::default()
        }
    }

    fn extract_wrapped_command(result: &serde_json::Value) -> &str {
        result
            .get("command")
            .and_then(|v| v.as_str())
            .expect("wrapped result should have a 'command' string field")
    }

    #[test]
    fn test_wrap_bash_basic_command() {
        let input = bash_input_for_sandbox("ls -la", "/home/user/project");
        let policy = test_sandbox_policy();
        let result = wrap_bash_with_sandbox(&input, &policy);
        assert!(result.is_some());
        let wrapped = result.unwrap();
        let cmd = extract_wrapped_command(&wrapped);
        assert!(cmd.contains("sandbox exec"));
        assert!(cmd.contains("--sandbox"));
        assert!(cmd.contains("--cwd"));
        assert!(cmd.contains("-- bash -c 'ls -la'"));
    }

    #[test]
    fn test_wrap_bash_returns_none_for_read_tool() {
        let input = ToolUseHookInput {
            tool_name: "Read".into(),
            tool_input: json!({"file_path": "/tmp/test.txt"}),
            ..Default::default()
        };
        let policy = test_sandbox_policy();
        let result = wrap_bash_with_sandbox(&input, &policy);
        assert!(result.is_none());
    }

    // --- suggest/deny tests ---

    #[test]
    fn test_suggest_allow_specific_bash_command() {
        let input = json!({"command": "git status"});
        assert_eq!(
            suggest_allow_command_specific("Bash", &input),
            "clash policy allow \"git status\""
        );
    }

    #[test]
    fn test_suggest_allow_specific_bash_single_binary() {
        let input = json!({"command": "ls"});
        assert_eq!(
            suggest_allow_command_specific("Bash", &input),
            "clash policy allow \"ls\""
        );
    }

    #[test]
    fn test_suggest_allow_specific_tool() {
        let input = json!({"file_path": "/tmp/test.txt"});
        assert_eq!(
            suggest_allow_command_specific("Read", &input),
            "clash policy allow --tool Read"
        );
    }

    #[test]
    fn test_truncate_noun_short() {
        assert_eq!(truncate_noun("hello", 60), "hello");
    }

    #[test]
    fn test_truncate_noun_long() {
        let s = "a".repeat(100);
        let result = truncate_noun(&s, 60);
        assert_eq!(result.len(), 63);
        assert!(result.ends_with("..."));
    }

    #[test]
    fn test_build_deny_context_contains_allow_command() {
        let input = json!({"command": "ls -la"});
        let ctx = build_deny_context("Bash", None, &input);
        assert!(ctx.contains("BLOCKED"));
        assert!(ctx.contains("clash policy allow \"ls -la\""));
        assert!(ctx.contains("Do NOT retry"));
    }

    #[test]
    fn test_deny_decision_includes_agent_context() -> Result<()> {
        let settings = TestPolicy::deny_all()
            .raw_node(r#"{"condition":{"observe":"tool_name","pattern":{"literal":{"literal":"Bash"}},"children":[
                {"decision":"deny"}
            ]}}"#)
            .build();
        let result = assert_decision!(settings, bash_input("ls -la"), Effect::Deny);
        let ctx = get_context(&result).expect("deny should have additional_context");
        assert!(ctx.contains("BLOCKED"), "got: {ctx}");
        Ok(())
    }
}