clash 0.7.1

Command Line Agent Safety Harness — permission policies for coding agents
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
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 fall back to 'ask' 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 fall back to 'ask'. 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::ask(Some(reason), Some(context)));
        }
    };

    let decision = tree.evaluate_with_context(
        &input.tool_name,
        &input.tool_input,
        Some(&input.permission_mode),
        input.agent.as_ref().map(|a| a.to_string()).as_deref(),
    );
    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).
    let audit_hash = crate::audit::log_decision(
        &settings.audit,
        &input.session_id,
        &input.tool_name,
        &input.tool_input,
        decision.effect,
        decision.reason.as_deref(),
        &decision.trace,
        Some(&input.permission_mode),
    );

    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(&format!("clash policy allow {}", audit_hash))
        );
    }

    Ok(match decision.effect {
        Effect::Allow => {
            let mut output =
                HookOutput::allow(decision.reason.or(Some("policy: allowed".into())), None);
            // If the policy decision includes a per-command sandbox, rewrite the
            // command to run through `clash shell` (brush) which handles
            // per-command sandbox enforcement internally.
            if decision.sandbox.is_some()
                && let Some(updated) = wrap_bash_with_sandbox(
                    input,
                    decision.sandbox_name.as_ref().map(|s| s.0.as_str()),
                )
            {
                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,
                &audit_hash,
            );
            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.
///
/// Uses canonical names where possible so output is agent-agnostic.
/// Verbs align with the bare verb shortcuts in `clash allow <verb>`:
/// shell, edit, read, web.
fn tool_to_verb_str(tool_name: &str) -> String {
    match tool_name {
        "Bash" => "shell".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()
        }
        _ => crate::agents::display_name(tool_name).to_lowercase(),
    }
}

/// If the tool input is a Bash command and a sandbox policy exists,
/// rewrite the command to run through `clash shell`.
///
/// Returns the updated `tool_input` JSON if rewriting is applicable, or None.
#[instrument(level = Level::TRACE, skip(input))]
fn wrap_bash_with_sandbox(
    input: &ToolUseHookInput,
    sandbox_name: Option<&str>,
) -> 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()?;

    // Run the command through `clash shell` (brush) which handles per-command
    // sandbox enforcement internally via its external command hook. We do NOT
    // wrap in `clash sandbox exec` here — that would nest sandbox-exec inside
    // sandbox-exec, which macOS seatbelt does not support.
    //
    // The --sandbox flag tells clash shell which named sandbox profile from
    // the policy to apply. Without it, clash shell has no sandbox to enforce.
    let sandbox_flag = match sandbox_name {
        Some(name) => format!(" --sandbox {}", shell_escape(name)),
        None => String::new(),
    };

    let sandboxed_command = format!(
        "{} shell --cwd {}{} -c {}",
        shell_escape(&clash_bin.to_string_lossy()),
        shell_escape(&input.cwd),
        sandbox_flag,
        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('\'', "'\\''"))
}

/// 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.",
        "shell" => "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,
    audit_hash: &str,
) -> String {
    let is_explicit_deny = reason.is_some_and(|r| r.contains("denied") || r.contains("deny"));

    let mut lines = Vec::new();

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

    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 *
        // TODO: rewrite with serde_json::json!
        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::Ask);
        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)?;
        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 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 result = wrap_bash_with_sandbox(&input, Some("edit"));
        assert!(result.is_some());
        let wrapped = result.unwrap();
        let cmd = extract_wrapped_command(&wrapped);
        // Should use `clash shell` (brush) for per-command sandboxing,
        // NOT `clash sandbox exec` (which would nest sandbox-exec).
        assert!(
            !cmd.contains("sandbox exec"),
            "should not nest sandbox-exec: {cmd}"
        );
        assert!(cmd.contains("shell"));
        assert!(cmd.contains("--cwd"));
        assert!(
            cmd.contains("--sandbox 'edit'"),
            "missing --sandbox flag: {cmd}"
        );
        assert!(cmd.contains("-c 'ls -la'"));
    }

    #[test]
    fn test_wrap_bash_no_sandbox_name() {
        let input = bash_input_for_sandbox("ls -la", "/home/user/project");
        let result = wrap_bash_with_sandbox(&input, None).unwrap();
        let cmd = extract_wrapped_command(&result);
        assert!(
            !cmd.contains("--sandbox"),
            "should omit --sandbox when None: {cmd}"
        );
    }

    #[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 result = wrap_bash_with_sandbox(&input, Some("edit"));
        assert!(result.is_none());
    }

    #[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, "test123");
        assert!(ctx.contains("BLOCKED"));
        assert!(ctx.contains("clash policy allow test123"));
        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(())
    }
}