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
//! Policy discovery, evaluation, and compilation.
//!
//! This module extracts the policy loading pipeline from [`crate::settings`]:
//!
//! 1. **Discovery** — finding `policy.json` / `policy.star` files at user/project/session levels
//! 2. **Validation** — checking file metadata (size, permissions, type)
//! 3. **Evaluation** — running Starlark `.star` files through `clash_starlark`,
//!    or parsing `.json` manifests (with optional `includes`)
//! 4. **Compilation** — compiling evaluated JSON sources into a [`CompiledPolicy`] tree

use std::path::Path;

use anyhow::{Context, Result};
use tracing::{error, warn};

#[cfg(test)]
use tracing::info;

use crate::policy::compile;
use crate::policy::match_tree::{CompiledPolicy, PolicyManifest};
use crate::settings::{LoadedPolicy, PolicyLevel};

/// Maximum policy file size (1 MiB).
pub const MAX_POLICY_SIZE: u64 = 1024 * 1024;

/// Outcome of attempting to load a single policy file.
///
/// On success, carries both the evaluated JSON source (needed for compilation)
/// and the [`LoadedPolicy`] metadata.
pub struct ValidatedPolicy {
    /// The evaluated JSON source text.
    pub json_source: String,
    /// The loaded policy metadata.
    pub loaded: LoadedPolicy,
    /// Leaf conflicts recorded by `merge()` during Starlark evaluation.
    pub shadows: Vec<clash_starlark::eval_context::ShadowedRule>,
}

/// Evaluate a `.star` policy file through the Starlark evaluator and return
/// the full [`clash_starlark::EvalOutput`] (JSON source + shadow data).
pub fn evaluate_star_policy(path: &Path) -> Result<clash_starlark::EvalOutput> {
    let source = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read {}", path.display()))?;

    let base_dir = path.parent().unwrap_or(Path::new("."));

    let output = clash_starlark::evaluate(&source, &path.display().to_string(), base_dir)?;

    Ok(output)
}

/// Construct the standard "legacy `policy.json` detected" error for any
/// non-migrate caller that encounters a `.json` policy file.
pub fn legacy_json_error(path: &Path) -> anyhow::Error {
    anyhow::anyhow!(
        "Legacy `policy.json` detected at `{}`. Run `clash policy migrate` to convert to `.star` (the only supported format).",
        path.display()
    )
}

/// Only call from cmd::policy::migrate. All other JSON loading paths have been removed.
#[allow(dead_code)]
pub(crate) fn migrate_load_json_policy(path: &Path) -> Result<String> {
    let raw = std::fs::read_to_string(path)
        .with_context(|| format!("failed to read {}", path.display()))?;

    let manifest: PolicyManifest = serde_json::from_str(&raw)
        .with_context(|| format!("failed to parse {}", path.display()))?;

    if manifest.includes.is_empty() {
        // No includes — the manifest JSON is the policy source directly.
        return Ok(raw);
    }

    // Merge: inline tree nodes come first (highest precedence), then includes in order.
    let base_dir = path.parent().unwrap_or(Path::new("."));
    merge_manifest_with_includes(&manifest, base_dir)
}

/// Merge a [`PolicyManifest`]'s inline policy with its `includes`.
///
/// Inline tree nodes come first (first-match wins), followed by included
/// policies in declaration order.
#[allow(dead_code)]
fn merge_manifest_with_includes(manifest: &PolicyManifest, base_dir: &Path) -> Result<String> {
    let mut merged = manifest.policy.clone();

    for include in &manifest.includes {
        let json_source = evaluate_include(&include.path, base_dir)?;
        let included: CompiledPolicy = serde_json::from_str(&json_source)
            .with_context(|| format!("failed to parse included policy {:?}", include.path))?;

        // Append included rules after inline rules (lower precedence).
        merged.tree.extend(included.tree);
        // Merge sandboxes (inline wins on conflict).
        for (k, v) in included.sandboxes {
            merged.sandboxes.entry(k).or_insert(v);
        }
    }

    serde_json::to_string(&merged).context("failed to serialize merged policy")
}

/// Evaluate an include entry and return the compiled JSON source.
///
/// For `.star` files (local or `@clash//` stdlib), evaluates through Starlark.
fn evaluate_include(include_path: &str, base_dir: &Path) -> Result<String> {
    if include_path.starts_with("@clash//") {
        // Stdlib includes are library modules — they export values, not policies.
        // Wrap in a minimal Starlark policy that loads the export and registers it.
        evaluate_stdlib_include(include_path)
    } else {
        // Local .star file — must call policy().
        let resolved = base_dir.join(include_path);
        evaluate_star_policy(&resolved).map(|o| o.json)
    }
}

/// Evaluate a `@clash//` stdlib module by wrapping it in a Starlark policy.
///
/// The wrapper loads the module, imports its `builtins` export (a list of rule
/// nodes), and registers them via `policy()` and `settings()`.
fn evaluate_stdlib_include(include_path: &str) -> Result<String> {
    use clash_starlark::codegen::ast::{Expr, Stmt};
    use clash_starlark::codegen::builder::*;

    let wrapper = clash_starlark::codegen::serialize(&[
        Stmt::load(include_path, &["builtins"]),
        Stmt::load("@clash//std.star", &["deny", "policy", "settings"]),
        Stmt::Blank,
        Stmt::Expr(settings(deny(), None)),
        Stmt::Expr(policy(
            "include",
            deny(),
            vec![Expr::ident("builtins")],
            None,
        )),
    ]);
    let eval_output = clash_starlark::evaluate(&wrapper, "<include>", Path::new("."))
        .with_context(|| format!("failed to evaluate stdlib include {include_path}"))?;
    Ok(eval_output.json)
}

/// Resolve includes and return the combined included policy plus any warnings.
///
/// Evaluates each include entry and merges their rules and sandboxes.
/// Returns the merged included content (without the inline policy) and a list
/// of warnings for includes that failed to evaluate or parse.
/// Rules/sandboxes from includes should be treated as read-only in the TUI.
pub fn resolve_includes(
    manifest: &PolicyManifest,
    base_dir: &Path,
) -> Result<(CompiledPolicy, Vec<String>)> {
    use std::collections::HashMap;

    let mut merged = CompiledPolicy {
        sandboxes: HashMap::new(),
        tree: vec![],
        default_effect: manifest.policy.default_effect,
        default_sandbox: None,
        on_sandbox_violation: Default::default(),
        harness_defaults: None,
    };

    let mut warnings = Vec::new();

    for include in &manifest.includes {
        match evaluate_include(&include.path, base_dir) {
            Ok(json_source) => match serde_json::from_str::<CompiledPolicy>(&json_source) {
                Ok(included) => {
                    for mut node in included.tree {
                        node.stamp_source(&include.path);
                        merged.tree.push(node);
                    }
                    for (k, v) in included.sandboxes {
                        merged.sandboxes.entry(k).or_insert(v);
                    }
                }
                Err(e) => {
                    warnings.push(format!("{}: parse error: {e}", include.path));
                }
            },
            Err(e) => {
                warnings.push(format!("{}: {e:#}", include.path));
            }
        }
    }

    if !warnings.is_empty() {
        tracing::warn!("include resolution warnings: {}", warnings.join("; "));
    }

    Ok((merged, warnings))
}

/// Validate a policy file's metadata (existence, type, size, permissions).
///
/// Returns `Some(metadata)` when the file is suitable for loading.
/// Returns `None` when the file is missing, is a directory, or exceeds the
/// size limit.
fn validate_policy_file(path: &Path, level: PolicyLevel) -> Option<std::fs::Metadata> {
    match validate_policy_file_with_diagnostics(path) {
        Ok(metadata) => {
            #[cfg(unix)]
            check_permissions_warning(path, level, &metadata);
            Some(metadata)
        }
        Err(ValidationError::NotFound) => None,
        Err(e) => {
            warn!(path = %path.display(), level = %level, "Policy file invalid: {e}");
            None
        }
    }
}

/// Validate a policy file with rich diagnostic messages suitable for user display.
///
/// Returns `Ok(metadata)` when the file is suitable for loading, or a
/// [`ValidationError`] describing exactly what is wrong.
fn validate_policy_file_with_diagnostics(
    path: &Path,
) -> Result<std::fs::Metadata, ValidationError> {
    let metadata = match std::fs::metadata(path) {
        Ok(m) => m,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
            return Err(ValidationError::NotFound);
        }
        Err(e) => {
            return Err(ValidationError::IoError(format!(
                "Cannot read policy file at {}: {}",
                path.display(),
                e
            )));
        }
    };

    if metadata.is_dir() {
        return Err(ValidationError::IsDirectory(format!(
            "{} is a directory, not a file. Remove it and run `clash init` to create a policy.",
            path.display()
        )));
    }

    if metadata.len() > MAX_POLICY_SIZE {
        return Err(ValidationError::TooLarge(format!(
            "policy file is too large ({} bytes, max {} bytes). Check that {} is the correct file.",
            metadata.len(),
            MAX_POLICY_SIZE,
            path.display()
        )));
    }

    Ok(metadata)
}

/// Emit a warning if the policy file is readable by other users.
#[cfg(unix)]
fn check_permissions_warning(path: &Path, level: PolicyLevel, metadata: &std::fs::Metadata) {
    use std::os::unix::fs::PermissionsExt;
    let mode = metadata.permissions().mode();
    if mode & 0o044 != 0 {
        warn!(
            path = %path.display(),
            level = %level,
            mode = format!("{:o}", mode),
            "policy file is readable by other users; consider `chmod 600`"
        );
    }
}

/// Reason a policy file failed metadata validation.
enum ValidationError {
    /// File does not exist (not an error — just absent).
    NotFound,
    /// I/O error reading metadata.
    IoError(String),
    /// Path is a directory, not a file.
    IsDirectory(String),
    /// File exceeds the size limit.
    TooLarge(String),
}

impl std::fmt::Display for ValidationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ValidationError::NotFound => write!(f, "file not found"),
            ValidationError::IoError(msg)
            | ValidationError::IsDirectory(msg)
            | ValidationError::TooLarge(msg) => write!(f, "{msg}"),
        }
    }
}

/// Try to load and validate a policy file, returning the evaluated JSON source
/// and a [`LoadedPolicy`] on success.
///
/// Returns `None` when the file is missing, is a directory, exceeds the size
/// limit, or fails Starlark evaluation. Writes diagnostics to `policy_error`
/// on evaluation failure.
pub fn try_load_policy(
    level: PolicyLevel,
    path: &Path,
    policy_error: &mut Option<String>,
) -> Option<ValidatedPolicy> {
    let _metadata = validate_policy_file(path, level)?;

    let is_json = path.extension().is_some_and(|ext| ext == "json");
    let (json_source, shadows) = if is_json {
        let e = legacy_json_error(path);
        error!(path = %path.display(), level = %level, error = %e, "Legacy policy.json rejected");
        *policy_error = Some(e.to_string());
        return None;
    } else {
        match evaluate_star_policy(path) {
            Ok(output) => (output.json, output.shadows),
            Err(e) => {
                error!(path = %path.display(), level = %level, error = %e, "Failed to evaluate starlark policy");
                *policy_error = Some(format!("Failed to evaluate {}: {}", path.display(), e));
                return None;
            }
        }
    };

    let loaded = LoadedPolicy {
        level,
        path: path.to_path_buf(),
        source: json_source.clone(),
    };
    Some(ValidatedPolicy {
        json_source,
        loaded,
        shadows,
    })
}

/// Compile one or more evaluated policy JSON sources into a [`CompiledPolicy`] tree.
///
/// Each tuple is `(level, json_source, source_display_path)`.
/// When a single source is provided, uses `compile_to_tree`. When multiple
/// sources are provided, uses `compile_multi_level_to_tree` to merge them
/// with level-based precedence.
pub fn compile_policies(level_sources: &[(PolicyLevel, String, String)]) -> Result<CompiledPolicy> {
    let level_refs: Vec<(PolicyLevel, &str, &str)> = level_sources
        .iter()
        .map(|(l, s, p)| (*l, s.as_str(), p.as_str()))
        .collect();
    compile::compile_multi_level_to_tree(&level_refs)
}

/// Compile a raw policy JSON source string directly into a [`CompiledPolicy`] tree.
///
/// This is a thin wrapper around [`compile::compile_to_tree`] for callers that
/// have a single source string rather than level-tagged sources.
pub fn compile_source(source: &str) -> Result<CompiledPolicy> {
    compile::compile_to_tree(source)
}

/// Validate and load a policy file with full diagnostics, then compile it.
///
/// Produces detailed error messages suitable for surfacing to users.
/// Used by the test-only `load_policy_from_path` in settings.
#[cfg(test)]
pub fn load_and_compile_single(
    path: &Path,
    policy_error: &mut Option<String>,
) -> Option<CompiledPolicy> {
    let metadata = match validate_policy_file_with_diagnostics(path) {
        Ok(m) => m,
        Err(ValidationError::NotFound) => return None,
        Err(e) => {
            warn!(path = %path.display(), "Policy file invalid: {e}");
            *policy_error = Some(e.to_string());
            return None;
        }
    };

    #[cfg(unix)]
    check_permissions_warning(path, PolicyLevel::User, &metadata);
    #[cfg(not(unix))]
    let _ = metadata;

    let is_json = path.extension().is_some_and(|ext| ext == "json");
    let eval_result = if is_json {
        Err(legacy_json_error(path))
    } else {
        evaluate_star_policy(path).map(|o| o.json)
    };

    match eval_result {
        Ok(json_source) => match compile::compile_to_tree(&json_source) {
            Ok(tree) => {
                info!(path = %path.display(), "Loaded policy");
                Some(tree)
            }
            Err(e) => {
                let msg = format!("Failed to compile policy: {}", e);
                warn!(path = %path.display(), error = %e, "Failed to compile policy");
                *policy_error = Some(msg);
                None
            }
        },
        Err(e) => {
            let msg = format!("Failed to evaluate policy: {}", e);
            warn!(path = %path.display(), error = %e, "Failed to evaluate policy");
            *policy_error = Some(msg);
            None
        }
    }
}

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

    /// Legacy JSON parsing is still tested, but only via the migrate code path.
    mod migrate_tests {
        use super::*;

        #[test]
        fn load_json_policy_without_includes() {
            let dir = tempfile::tempdir().unwrap();
            let json_path = dir.path().join("policy.json");
            std::fs::write(
                &json_path,
                r#"{
                "default_effect": "deny",
                "sandboxes": {},
                "tree": [{
                    "condition": {
                        "observe": "tool_name",
                        "pattern": {"literal": {"literal": "Bash"}},
                        "children": [{"decision": {"allow": null}}]
                    }
                }]
            }"#,
            )
            .unwrap();

            let source = migrate_load_json_policy(&json_path).unwrap();
            let policy: CompiledPolicy = serde_json::from_str(&source).unwrap();
            assert_eq!(policy.tree.len(), 1);
        }

        #[test]
        fn load_json_policy_with_star_include() {
            let dir = tempfile::tempdir().unwrap();

            // Write a local .star include file.
            let star_path = dir.path().join("extra.star");
            std::fs::write(
                &star_path,
                r#"
load("@clash//std.star", "policy", "settings", "deny")
settings(default = deny())
policy("include", {tool("Read"): allow()})
"#,
            )
            .unwrap();

            // Write policy.json that includes extra.star and has its own inline rule.
            let json_path = dir.path().join("policy.json");
            std::fs::write(
                &json_path,
                r#"{
                "default_effect": "deny",
                "sandboxes": {},
                "includes": [{"path": "extra.star"}],
                "tree": [{
                    "condition": {
                        "observe": "tool_name",
                        "pattern": {"literal": {"literal": "Bash"}},
                        "children": [{"decision": {"allow": null}}]
                    }
                }]
            }"#,
            )
            .unwrap();

            let source = migrate_load_json_policy(&json_path).unwrap();
            let policy: CompiledPolicy = serde_json::from_str(&source).unwrap();
            // Should have inline (Bash) + included (Read) rules.
            assert!(
                policy.tree.len() >= 2,
                "expected at least 2 rules, got {}",
                policy.tree.len()
            );
        }

        #[test]
        fn load_json_policy_with_stdlib_include() {
            let dir = tempfile::tempdir().unwrap();
            let json_path = dir.path().join("policy.json");
            std::fs::write(
                &json_path,
                r#"{
                "default_effect": "deny",
                "sandboxes": {},
                "includes": [{"path": "@clash//builtin.star"}],
                "tree": []
            }"#,
            )
            .unwrap();

            let source = migrate_load_json_policy(&json_path).unwrap();
            let policy: CompiledPolicy = serde_json::from_str(&source).unwrap();
            // builtin.star exports rules for clash commands + claude tools.
            assert!(
                !policy.tree.is_empty(),
                "builtin.star should contribute rules"
            );
        }
    }
}