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
//! Detect network errors in sandboxed Bash output and provide actionable hints.
//!
//! When a Bash command runs inside a clash sandbox with `NetworkPolicy::Deny`
//! (the default), network calls fail at the OS level with cryptic errors.
//! This module detects those errors in PostToolUse responses and returns
//! advisory context so Claude can explain the cause and suggest fixes.

use tracing::{Level, info, instrument};

use crate::hooks::ToolUseHookInput;
use crate::policy::sandbox_types::{NetworkPolicy, ViolationAction};
use crate::settings::ClashSettings;

/// Network error patterns that indicate a sandboxed process tried to access the network.
///
/// These are substrings matched case-insensitively against the tool response text.
const NETWORK_ERROR_PATTERNS: &[&str] = &[
    // DNS resolution failures
    "could not resolve host",
    "name or service not known",
    "temporary failure in name resolution",
    "nodename nor servname provided",
    "failed to lookup address",
    "getaddrinfo",
    // Connection failures
    "network is unreachable",
    "network unreachable",
    // curl exit codes
    "curl: (6)",  // DNS
    "curl: (7)",  // connection
    "curl: (56)", // network recv failure
    // wget
    "unable to resolve host address",
    // cargo/rustup
    "failed to resolve address",
    "error trying to connect",
    // npm/yarn
    "getaddrinfo enotfound",
    "err_socket_not_connected",
    // pip
    "could not find a version that satisfies",
    "max retries exceeded with url",
    // go
    "dial tcp: lookup",
    // general socket errors
    "enetunreach",
    "socket: operation not permitted",
    "network access denied",
];

/// Check if a PostToolUse Bash response contains network errors likely caused
/// by sandbox network restrictions. Returns advisory context if so.
#[instrument(level = Level::TRACE, skip(input, settings))]
pub fn check_for_sandbox_network_hint(
    input: &ToolUseHookInput,
    settings: &ClashSettings,
) -> Option<String> {
    // Only check Bash tool responses
    if input.tool_name != "Bash" {
        return None;
    }

    // Extract text from tool_response
    let response_text = extract_response_text(input.tool_response.as_ref()?)?;

    // Check for network error patterns
    if !contains_network_error(&response_text) {
        return None;
    }

    // Re-evaluate the policy to check if this command would run under
    // a sandbox with NetworkPolicy::Deny
    let tree = settings.policy_tree()?;
    let decision = tree.evaluate(&input.tool_name, &input.tool_input);

    let network_policy = decision.sandbox.as_ref().map(|s| &s.network);

    let network_denied = matches!(network_policy, Some(NetworkPolicy::Deny));
    let network_domain_filtered = matches!(network_policy, Some(NetworkPolicy::AllowDomains(_)));

    if !network_denied && !network_domain_filtered {
        return None;
    }

    info!(
        tool = "Bash",
        domain_filtered = network_domain_filtered,
        "Detected network error in sandboxed command output"
    );

    let sandbox_name = decision
        .sandbox_name
        .map(|r| r.0)
        .unwrap_or_else(|| "unnamed".to_string());

    let action = tree.on_sandbox_violation;

    Some(build_network_hint(&sandbox_name, action))
}

/// Extract readable text from a tool_response JSON value.
///
/// Claude Code tool responses can be structured in various ways — this handles
/// common shapes (string, object with content/stdout/stderr fields, arrays).
pub(crate) fn extract_response_text(response: &serde_json::Value) -> Option<String> {
    match response {
        serde_json::Value::String(s) => Some(s.clone()),
        serde_json::Value::Object(obj) => {
            let mut parts = Vec::new();
            for key in ["content", "stdout", "stderr", "output", "error", "result"] {
                if let Some(serde_json::Value::String(s)) = obj.get(key) {
                    parts.push(s.as_str());
                }
            }
            if parts.is_empty() {
                // Fall back to the full JSON stringified
                Some(serde_json::to_string(response).ok()?)
            } else {
                Some(parts.join("\n"))
            }
        }
        serde_json::Value::Array(arr) => {
            let texts: Vec<String> = arr.iter().filter_map(extract_response_text).collect();
            if texts.is_empty() {
                None
            } else {
                Some(texts.join("\n"))
            }
        }
        _ => None,
    }
}

/// Check if text contains any network error patterns (case-insensitive).
fn contains_network_error(text: &str) -> bool {
    let lower = text.to_lowercase();
    NETWORK_ERROR_PATTERNS
        .iter()
        .any(|pattern| lower.contains(pattern))
}

/// Build advisory context for Claude when a sandbox blocks network access.
fn build_network_hint(sandbox_name: &str, action: ViolationAction) -> String {
    let directive = crate::sandbox_hints::formatter::directive_text(action);
    [
        &format!(
            "SANDBOX VIOLATION: sandbox \"{sandbox_name}\" blocked network access (policy: deny)."
        ),
        "",
        "To fix:",
        &format!("  clash sandbox add-rule --name {sandbox_name} --net allow"),
        "",
        directive,
    ]
    .join("\n")
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::policy::sandbox_types::ViolationAction;
    use serde_json::json;

    #[test]
    fn test_contains_network_error_dns() {
        assert!(contains_network_error(
            "curl: (6) Could not resolve host: example.com"
        ));
    }

    #[test]
    fn test_contains_network_error_unreachable() {
        assert!(contains_network_error("Network is unreachable"));
    }

    #[test]
    fn test_contains_network_error_case_insensitive() {
        assert!(contains_network_error("COULD NOT RESOLVE HOST: foo.com"));
    }

    #[test]
    fn test_contains_network_error_no_match() {
        assert!(!contains_network_error("file not found: /tmp/test.txt"));
    }

    #[test]
    fn test_contains_network_error_cargo() {
        assert!(contains_network_error(
            "error: failed to resolve address for github.com: Name or service not known"
        ));
    }

    #[test]
    fn test_contains_network_error_npm() {
        assert!(contains_network_error(
            "npm ERR! getaddrinfo ENOTFOUND registry.npmjs.org"
        ));
    }

    #[test]
    fn test_extract_response_text_string() {
        let val = json!("some output text");
        assert_eq!(extract_response_text(&val), Some("some output text".into()));
    }

    #[test]
    fn test_extract_response_text_object_with_content() {
        let val = json!({"content": "error: network unreachable"});
        let text = extract_response_text(&val).unwrap();
        assert!(text.contains("error: network unreachable"));
    }

    #[test]
    fn test_extract_response_text_object_with_stderr() {
        let val = json!({"stdout": "", "stderr": "curl: (6) Could not resolve host"});
        let text = extract_response_text(&val).unwrap();
        assert!(text.contains("Could not resolve host"));
    }

    #[test]
    fn test_extract_response_text_null() {
        assert_eq!(extract_response_text(&json!(null)), None);
    }

    #[test]
    fn test_extract_response_text_array() {
        let val = json!(["line 1", "Could not resolve host"]);
        let text = extract_response_text(&val).unwrap();
        assert!(text.contains("Could not resolve host"));
    }

    #[test]
    fn test_build_network_hint_contains_key_info() {
        let hint = build_network_hint("restricted", ViolationAction::Stop);
        assert!(hint.contains("SANDBOX VIOLATION"));
        assert!(hint.contains("\"restricted\""));
        assert!(hint.contains("net allow"));
        assert!(hint.contains("Do NOT retry"));
    }

    #[test]
    fn test_build_network_hint_workaround() {
        let hint = build_network_hint("mybox", ViolationAction::Workaround);
        assert!(hint.contains("\"mybox\""));
        assert!(hint.contains("Try an alternative approach"));
    }

    #[test]
    fn test_build_network_hint_smart() {
        let hint = build_network_hint("mybox", ViolationAction::Smart);
        assert!(hint.contains("Assess"));
    }

    #[test]
    fn test_check_returns_none_for_non_bash() {
        let input = ToolUseHookInput {
            tool_name: "Read".into(),
            tool_response: Some(json!("Could not resolve host")),
            ..Default::default()
        };
        let settings = ClashSettings::default();
        assert!(check_for_sandbox_network_hint(&input, &settings).is_none());
    }

    #[test]
    fn test_check_returns_none_without_response() {
        let input = ToolUseHookInput {
            tool_name: "Bash".into(),
            tool_response: None,
            ..Default::default()
        };
        let settings = ClashSettings::default();
        assert!(check_for_sandbox_network_hint(&input, &settings).is_none());
    }

    #[test]
    fn test_check_returns_none_for_non_network_error() {
        let input = ToolUseHookInput {
            tool_name: "Bash".into(),
            tool_response: Some(json!("file not found")),
            ..Default::default()
        };
        let settings = ClashSettings::default();
        assert!(check_for_sandbox_network_hint(&input, &settings).is_none());
    }

    #[test]
    fn test_check_returns_none_without_policy() {
        // No compiled policy → no decision tree → returns None
        let settings = ClashSettings::default();
        assert!(settings.decision_tree().is_none());
        let input = ToolUseHookInput {
            tool_name: "Bash".into(),
            tool_input: json!({"command": "curl example.com"}),
            tool_response: Some(json!("Could not resolve host")),
            ..Default::default()
        };
        assert!(check_for_sandbox_network_hint(&input, &settings).is_none());
    }

    #[test]
    fn test_check_returns_hint_with_implicit_sandbox() {
        // V5: allow Bash with a sandbox that denies network
        let mut settings = ClashSettings::default();
        settings.set_policy_source(
            r#"{"schema_version":5,"default_effect":"deny",
  "sandboxes":{"restricted":{"default":["read","execute"],"rules":[],"network":"deny"}},
  "tree":[
    {"condition":{"observe":"tool_name","pattern":{"literal":{"literal":"Bash"}},"children":[
      {"decision":{"allow":"restricted"}}
    ]}}
  ]}"#,
        );
        let input = ToolUseHookInput {
            tool_name: "Bash".into(),
            tool_input: json!({"command": "curl example.com"}),
            tool_response: Some(json!("curl: (6) Could not resolve host: example.com")),
            cwd: "/tmp".into(),
            ..Default::default()
        };
        let result = check_for_sandbox_network_hint(&input, &settings);
        assert!(
            result.is_some(),
            "should return hint for sandboxed network error"
        );
        let hint = result.unwrap();
        assert!(hint.contains("SANDBOX VIOLATION"));
    }

    #[test]
    fn test_check_returns_hint_with_explicit_sandbox_network_deny() {
        // Explicit sandbox with network=deny
        let mut settings = ClashSettings::default();
        settings.set_policy_source(
            r#"{"schema_version":5,"default_effect":"deny",
  "sandboxes":{"restricted":{"default":["read","execute"],"rules":[],"network":"deny"}},
  "tree":[
    {"condition":{"observe":"tool_name","pattern":{"literal":{"literal":"Bash"}},"children":[
      {"condition":{"observe":{"positional_arg":0},"pattern":{"literal":{"literal":"curl"}},"children":[
        {"decision":{"allow":"restricted"}}
      ]}}
    ]}}
  ]}"#,
        );
        let input = ToolUseHookInput {
            tool_name: "Bash".into(),
            tool_input: json!({"command": "curl example.com"}),
            tool_response: Some(json!("curl: (6) Could not resolve host: example.com")),
            cwd: "/tmp".into(),
            ..Default::default()
        };
        let result = check_for_sandbox_network_hint(&input, &settings);
        assert!(
            result.is_some(),
            "should return hint for sandboxed network error"
        );
        let hint = result.unwrap();
        assert!(hint.contains("SANDBOX VIOLATION"));
    }

    #[test]
    fn test_check_returns_none_with_sandbox_network_allow() {
        // Sandbox with network=allow → network errors aren't from sandbox
        let mut settings = ClashSettings::default();
        settings.set_policy_source(
            r#"{"schema_version":5,"default_effect":"deny",
  "sandboxes":{"with-net":{"default":["read","execute"],"rules":[],"network":"allow"}},
  "tree":[
    {"condition":{"observe":"tool_name","pattern":{"literal":{"literal":"Bash"}},"children":[
      {"condition":{"observe":{"positional_arg":0},"pattern":{"literal":{"literal":"curl"}},"children":[
        {"decision":{"allow":"with-net"}}
      ]}}
    ]}}
  ]}"#,
        );
        let input = ToolUseHookInput {
            tool_name: "Bash".into(),
            tool_input: json!({"command": "curl example.com"}),
            tool_response: Some(json!("Could not resolve host")),
            cwd: "/tmp".into(),
            ..Default::default()
        };
        assert!(check_for_sandbox_network_hint(&input, &settings).is_none());
    }

    #[test]
    fn test_check_returns_hint_with_domain_specific_net_rule() {
        // Domain-specific net allow → NetworkPolicy::AllowDomains → hint fires
        let mut settings = ClashSettings::default();
        settings.set_policy_source(
            r#"{"schema_version":5,"default_effect":"deny",
  "sandboxes":{"with-net":{"default":["read","execute"],"rules":[],"network":{"allow_domains":["example.com"]}}},
  "tree":[
    {"condition":{"observe":"tool_name","pattern":{"literal":{"literal":"Bash"}},"children":[
      {"condition":{"observe":{"positional_arg":0},"pattern":{"literal":{"literal":"curl"}},"children":[
        {"decision":{"allow":"with-net"}}
      ]}}
    ]}}
  ]}"#,
        );
        let input = ToolUseHookInput {
            tool_name: "Bash".into(),
            tool_input: json!({"command": "curl example.com"}),
            tool_response: Some(json!("Could not resolve host")),
            cwd: "/tmp".into(),
            ..Default::default()
        };
        assert!(check_for_sandbox_network_hint(&input, &settings).is_some());
    }
}