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
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
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
use crate::policy::sandbox_types::{NetworkPolicy, PathMatch, SandboxPolicy};
use crate::sandbox;
use crate::style;
use anyhow::{Context, Result};
use clap::Subcommand;
use tracing::{Level, info, instrument};

#[derive(Subcommand, Debug)]
pub enum SandboxCmd {
    /// Apply sandbox restrictions and exec a command
    Exec {
        /// Sandbox config: inline JSON or a named sandbox from the policy
        #[arg(long)]
        sandbox: Option<String>,

        /// Working directory for path resolution
        #[arg(long, default_value = ".")]
        cwd: String,

        /// Session ID for logging sandbox violations to the audit trail.
        /// When provided with --tool-use-id, violations captured from the
        /// kernel are written to the session audit.jsonl for PostToolUse.
        #[arg(long)]
        session_id: Option<String>,

        /// Tool use ID for correlating violations with the tool invocation.
        #[arg(long)]
        tool_use_id: Option<String>,

        /// Command and arguments to execute under sandbox
        #[arg(trailing_var_arg = true)]
        command: Vec<String>,
    },

    /// Test sandbox enforcement interactively
    Test {
        /// Sandbox config: inline JSON or a named sandbox from the policy
        #[arg(long)]
        sandbox: Option<String>,

        /// Working directory for path resolution
        #[arg(long, default_value = ".")]
        cwd: String,

        /// Command and arguments to test
        #[arg(trailing_var_arg = true)]
        command: Vec<String>,
    },

    /// Check if sandboxing is supported on this platform
    Check,

    /// Create a new named sandbox profile
    Create {
        /// Name for the sandbox
        name: String,
        /// Default capabilities (e.g. "read + execute")
        #[arg(long)]
        default: String,
        /// Network policy: deny, allow, localhost
        #[arg(long, default_value = "deny")]
        network: String,
        /// Description of the sandbox
        #[arg(long)]
        doc: Option<String>,
        /// Policy scope: "user" or "project" (default: auto-detect)
        #[arg(long)]
        scope: Option<String>,
    },

    /// Delete a named sandbox profile
    Delete {
        /// Name of the sandbox to delete
        name: String,
        /// Policy scope: "user" or "project" (default: auto-detect)
        #[arg(long)]
        scope: Option<String>,
    },

    /// List all named sandbox profiles
    #[command(name = "list")]
    ListSandboxes {
        /// Output as JSON
        #[arg(long)]
        json: bool,
    },

    /// Add a filesystem rule to a named sandbox
    #[command(name = "add-rule")]
    AddRule {
        /// Name of the sandbox
        name: String,
        /// Allow capabilities (e.g. "read + write")
        #[arg(long, group = "effect_group")]
        allow: Option<String>,
        /// Deny capabilities (e.g. "write + delete")
        #[arg(long, group = "effect_group")]
        deny: Option<String>,
        /// Path the rule applies to (supports $PWD, $HOME, $TMPDIR)
        #[arg(long)]
        path: String,
        /// Path matching mode: subpath, literal, regex
        #[arg(long, default_value = "subpath")]
        path_match: String,
        /// Description of the rule
        #[arg(long)]
        doc: Option<String>,
        /// Policy scope: "user" or "project" (default: auto-detect)
        #[arg(long)]
        scope: Option<String>,
    },

    /// Remove a filesystem rule from a named sandbox by path
    #[command(name = "remove-rule")]
    RemoveRule {
        /// Name of the sandbox
        name: String,
        /// Path of the rule to remove
        #[arg(long)]
        path: String,
        /// Policy scope: "user" or "project" (default: auto-detect)
        #[arg(long)]
        scope: Option<String>,
    },
}

/// Resolve `--cwd` to an absolute path.
pub(crate) fn resolve_cwd(cwd: &str) -> Result<String> {
    let path = std::path::Path::new(cwd);
    let abs = if path.is_absolute() {
        path.to_path_buf()
    } else {
        std::env::current_dir()
            .context("failed to determine current directory")?
            .join(path)
    };
    Ok(abs.to_string_lossy().into_owned())
}

/// Resolve sandbox policy from `--sandbox` flag.
///
/// If the value looks like JSON (starts with `{`), parse it inline.
/// Otherwise treat it as a named sandbox from the compiled policy.
/// If no value is provided, falls back to the default sandbox.
fn resolve_sandbox_policy(sandbox_arg: Option<&str>, cwd: &str) -> Result<SandboxPolicy> {
    match sandbox_arg {
        Some(val) if val.starts_with('{') => {
            serde_json::from_str(val).context("failed to parse --sandbox JSON")
        }
        Some(name) => load_sandbox_for_profile(name, cwd),
        None => load_sandbox_for_profile("", cwd),
    }
}

/// Load the policy file, compile it, and generate a sandbox policy.
fn load_sandbox_for_profile(profile_name: &str, _cwd: &str) -> Result<SandboxPolicy> {
    use crate::settings::ClashSettings;

    let path = ClashSettings::policy_file()?;
    let json = crate::settings::evaluate_policy_file(&path)
        .with_context(|| format!("failed to evaluate {}", path.display()))?;
    let policy = crate::policy::compile::compile_to_tree(&json)
        .with_context(|| format!("failed to compile {}", path.display()))?;

    policy.sandboxes.get(profile_name).cloned().ok_or_else(|| {
        anyhow::anyhow!(
            "policy has no sandbox named '{}' (available: {:?})",
            profile_name,
            policy.sandboxes.keys().collect::<Vec<_>>()
        )
    })
}

/// Run a command inside a sandbox.
#[instrument(level = Level::TRACE)]
pub fn run_sandbox(cmd: SandboxCmd) -> Result<()> {
    match cmd {
        SandboxCmd::Exec {
            sandbox,
            cwd,
            session_id,
            tool_use_id,
            command,
        } => {
            let cwd = resolve_cwd(&cwd)?;
            let sandbox_policy = resolve_sandbox_policy(sandbox.as_deref(), &cwd)?;
            let cwd_path = std::path::PathBuf::from(&cwd);

            run_sandboxed_command(
                &sandbox_policy,
                &cwd_path,
                &command,
                session_id.as_deref(),
                tool_use_id.as_deref(),
            )
        }
        SandboxCmd::Test {
            sandbox,
            cwd,
            command,
        } => {
            let cwd = resolve_cwd(&cwd)?;
            let sandbox_policy = resolve_sandbox_policy(sandbox.as_deref(), &cwd)?;
            let cwd_path = std::path::PathBuf::from(&cwd);

            eprintln!("Testing sandbox with policy:");
            eprintln!("  default: {}", sandbox_policy.default.display());
            eprintln!("  network: {:?}", sandbox_policy.network);
            for rule in &sandbox_policy.rules {
                use crate::policy::sandbox_types::PathMatch;
                let path_display = match rule.path_match {
                    PathMatch::Subpath => format!("{}/**", rule.path),
                    PathMatch::ChildOf => format!("{}/*", rule.path),
                    PathMatch::Regex => format!("{} (regex)", rule.path),
                    PathMatch::Literal => rule.path.clone(),
                };
                eprintln!(
                    "  {:?} {} in {}",
                    rule.effect,
                    rule.caps.short(),
                    path_display
                );
            }
            eprintln!("  command: {:?}", command);
            eprintln!("---");

            run_sandboxed_command(&sandbox_policy, &cwd_path, &command, None, None)
        }
        SandboxCmd::Check => {
            let support = sandbox::check_support();
            match support {
                sandbox::SupportLevel::Full => {
                    println!("Sandbox: fully supported");
                }
                sandbox::SupportLevel::Partial { missing } => {
                    println!("Sandbox: partially supported");
                    for m in &missing {
                        println!("  missing: {}", m);
                    }
                }
                sandbox::SupportLevel::Unsupported { reason } => {
                    println!("Sandbox: not supported ({})", reason);
                    std::process::exit(1);
                }
            }
            Ok(())
        }
        SandboxCmd::Create {
            name,
            default,
            network,
            doc,
            scope,
        } => handle_create(&name, &default, &network, doc, scope),
        SandboxCmd::Delete { name, scope } => handle_delete(&name, scope),
        SandboxCmd::ListSandboxes { json } => handle_list_sandboxes(json),
        SandboxCmd::AddRule {
            name,
            allow,
            deny,
            path,
            path_match,
            doc,
            scope,
        } => handle_add_rule(&name, allow, deny, &path, &path_match, doc, scope),
        SandboxCmd::RemoveRule { name, path, scope } => handle_remove_rule(&name, &path, scope),
    }
}

// ---------------------------------------------------------------------------
// Sandbox CRUD handlers
// ---------------------------------------------------------------------------

/// Check policy file type and return the path.
/// Errors if JSON (with conversion hint) or if no policy exists.
fn require_star_policy(scope: Option<String>) -> Result<std::path::PathBuf> {
    let path = crate::cmd::policy::resolve_manifest_path(scope)?;
    if path.extension().is_some_and(|e| e == "json") {
        anyhow::bail!(
            "sandbox commands require a .star policy file.\n\
             Convert your policy with: clash policy convert --file {} --replace",
            path.display()
        );
    }
    Ok(path)
}

fn handle_create(
    name: &str,
    default: &str,
    network: &str,
    _doc: Option<String>,
    scope: Option<String>,
) -> Result<()> {
    let path = require_star_policy(scope)?;
    let mut doc = clash_starlark::codegen::StarDocument::open(&path)?;

    let default_effect = match default.trim().to_lowercase().as_str() {
        s if s.contains("deny") => clash_starlark::codegen::mutate::Effect::Deny,
        s if s.contains("allow") => clash_starlark::codegen::mutate::Effect::Allow,
        _ => clash_starlark::codegen::mutate::Effect::Ask,
    };
    let net_allow = network == "allow";

    clash_starlark::codegen::mutate::add_sandbox(&mut doc.stmts, name, default_effect, net_allow)
        .map_err(|e| anyhow::anyhow!("{e}"))?;
    doc.save()?;

    println!("{} Sandbox '{}' created", style::green_bold(""), name);
    println!("  {}", style::dim(&path.display().to_string()));
    Ok(())
}

fn handle_delete(name: &str, scope: Option<String>) -> Result<()> {
    let path = require_star_policy(scope)?;
    let mut doc = clash_starlark::codegen::StarDocument::open(&path)?;

    clash_starlark::codegen::mutate::remove_sandbox(&mut doc.stmts, name)
        .map_err(|e| anyhow::anyhow!("{e}"))?;
    doc.save()?;

    println!("{} Sandbox '{}' deleted", style::green_bold(""), name);
    println!("  {}", style::dim(&path.display().to_string()));
    Ok(())
}

fn handle_list_sandboxes(json: bool) -> Result<()> {
    // Try compiled policy first (has full sandbox details for referenced sandboxes).
    let settings = crate::settings::ClashSettings::load_or_create()?;
    let policy = settings.policy_tree();

    if let Some(policy) = policy {
        if !policy.sandboxes.is_empty() {
            if json {
                let output = serde_json::to_string_pretty(&policy.sandboxes)?;
                println!("{output}");
            } else {
                for (name, sb) in &policy.sandboxes {
                    println!(
                        "{} default={}, network={:?}, {} rules",
                        style::cyan(name),
                        sb.default.display(),
                        sb.network,
                        sb.rules.len(),
                    );
                    if let Some(ref doc) = sb.doc {
                        println!("  {}", style::dim(doc));
                    }
                    for rule in &sb.rules {
                        println!(
                            "    {:?} {} in {}{}",
                            rule.effect,
                            rule.caps.short(),
                            rule.path,
                            match rule.path_match {
                                PathMatch::Subpath => "",
                                PathMatch::Literal => " (literal)",
                                PathMatch::ChildOf => " (child_of)",
                                PathMatch::Regex => " (regex)",
                            },
                        );
                    }
                }
            }
            return Ok(());
        }
    }

    // Fall back to AST scan — picks up sandboxes not yet referenced by any rule.
    let path = crate::cmd::policy::resolve_manifest_path(None)?;
    if path.extension().is_some_and(|e| e == "star") {
        let doc = clash_starlark::codegen::StarDocument::open(&path)?;
        let sandboxes = clash_starlark::codegen::mutate::find_sandboxes(&doc.stmts);
        if sandboxes.is_empty() {
            println!("No sandboxes defined.");
        } else {
            for (_, name) in &sandboxes {
                println!("{}", style::cyan(name));
            }
        }
    } else {
        println!("No sandboxes defined.");
    }
    Ok(())
}

fn handle_add_rule(
    name: &str,
    allow: Option<String>,
    deny: Option<String>,
    path: &str,
    _path_match: &str,
    _doc: Option<String>,
    scope: Option<String>,
) -> Result<()> {
    let caps_str = match (allow, deny) {
        (Some(caps), None) => caps,
        (None, Some(_)) => {
            anyhow::bail!(
                "deny rules in sandbox fs are not yet supported via CLI — use `clash policy edit`"
            )
        }
        _ => anyhow::bail!("provide exactly one of --allow or --deny with capabilities"),
    };

    let policy_path = require_star_policy(scope)?;
    let mut doc = clash_starlark::codegen::StarDocument::open(&policy_path)?;

    clash_starlark::codegen::mutate::add_sandbox_rule(&mut doc.stmts, name, path, &caps_str)
        .map_err(|e| anyhow::anyhow!("{e}"))?;
    doc.save()?;

    println!(
        "{} Rule added to sandbox '{}'",
        style::green_bold(""),
        name
    );
    println!("  {}", style::dim(&policy_path.display().to_string()));
    Ok(())
}

fn handle_remove_rule(name: &str, path: &str, scope: Option<String>) -> Result<()> {
    let policy_path = require_star_policy(scope)?;
    let mut doc = clash_starlark::codegen::StarDocument::open(&policy_path)?;

    let removed = clash_starlark::codegen::mutate::remove_sandbox_rule(&mut doc.stmts, name, path)
        .map_err(|e| anyhow::anyhow!("{e}"))?;

    if removed {
        doc.save()?;
        println!(
            "{} Rule removed from sandbox '{}'",
            style::green_bold(""),
            name
        );
        println!("  {}", style::dim(&policy_path.display().to_string()));
    } else {
        println!("No rule matching path '{}' in sandbox '{}'", path, name);
    }
    Ok(())
}

/// Run a command under sandbox enforcement.
///
/// On macOS: spawns `sandbox-exec` as a child process, waits for it to complete,
/// then queries the unified log for sandbox violations. Any violations found are
/// written to the session audit log so PostToolUse can read them and provide
/// context to the model.
///
/// On other platforms: applies the sandbox in-process and execs the command
/// directly via `exec_sandboxed()` (no violation capture).
pub(crate) fn run_sandboxed_command(
    policy: &SandboxPolicy,
    cwd: &std::path::Path,
    command: &[String],
    session_id: Option<&str>,
    tool_use_id: Option<&str>,
) -> Result<()> {
    #[cfg(target_os = "macos")]
    {
        spawn_and_capture_macos(policy, cwd, command, session_id, tool_use_id)
    }

    #[cfg(not(target_os = "macos"))]
    {
        let _ = (session_id, tool_use_id);
        exec_with_proxy(policy, cwd, command)
    }
}

// ── macOS: spawn + violation capture ─────────────────────────────────────

/// Spawn `sandbox-exec` as a child process, wait for it, and capture violations.
///
/// Instead of `exec_sandboxed()` (which replaces the process via execvp and
/// prevents any post-execution work), this function:
/// 1. Compiles the policy to an SBPL profile
/// 2. Starts a domain-filtering proxy if `AllowDomains` is active
/// 3. Spawns `sandbox-exec -p <profile> -- <command...>` as a child
/// 4. Waits for the child to exit
/// 5. Queries `log show` for sandbox violations by the child's PID
/// 6. Writes violations to the session audit log
/// 7. Exits with the child's exit code
#[cfg(target_os = "macos")]
fn spawn_and_capture_macos(
    policy: &SandboxPolicy,
    cwd: &std::path::Path,
    command: &[String],
    session_id: Option<&str>,
    tool_use_id: Option<&str>,
) -> Result<()> {
    let profile = sandbox::compile_sandbox_profile(policy, cwd)
        .context("failed to compile sandbox profile")?;

    // Start domain-filtering proxy if the policy uses AllowDomains.
    let proxy_handle = match &policy.network {
        NetworkPolicy::AllowDomains(domains) => {
            let handle = sandbox::proxy::start_proxy(sandbox::proxy::ProxyConfig {
                allowed_domains: domains.clone(),
            })
            .context("failed to start domain-filtering proxy")?;
            info!(addr = %handle.addr, "started domain-filtering proxy");
            Some(handle)
        }
        _ => None,
    };

    // Build: sandbox-exec -p <profile> -- <command...>
    let mut cmd = std::process::Command::new("sandbox-exec");
    cmd.args(["-p", &profile, "--"]);
    cmd.args(command);
    cmd.current_dir(cwd);
    cmd.stdin(std::process::Stdio::inherit());
    cmd.stdout(std::process::Stdio::inherit());
    cmd.stderr(std::process::Stdio::inherit());

    if let Some(ref handle) = proxy_handle {
        let proxy_url = format!("http://{}", handle.addr);
        cmd.env("HTTP_PROXY", &proxy_url)
            .env("HTTPS_PROXY", &proxy_url)
            .env("http_proxy", &proxy_url)
            .env("https_proxy", &proxy_url);
    }

    let start = std::time::Instant::now();
    let mut child = cmd.spawn().context("failed to spawn sandbox-exec")?;
    let child_pid = child.id();
    let status = child
        .wait()
        .context("failed to wait for sandboxed process")?;
    let elapsed = start.elapsed();

    // Shut down the proxy now that the child has exited.
    drop(proxy_handle);

    // Capture violations from the unified log and write to audit log.
    if let (Some(sid), Some(tuid)) = (session_id, tool_use_id) {
        capture_and_log_violations(child_pid, elapsed, sid, tuid, command);
    }

    // Exit with the child's exit code.
    let code = status.code().unwrap_or(1);
    if code != 0 {
        std::process::exit(code);
    }
    Ok(())
}

/// Query the macOS unified log for sandbox violations from a sandboxed process
/// and write them to the session audit log.
///
/// sandboxd log messages look like:
///   `Sandbox: bash(12345) deny(1) file-write-create /path/to/file`
///
/// We search a tight time window (command duration + buffer) for any file-deny
/// events. We intentionally do NOT filter by PID because the sandboxed process
/// may fork children (e.g., bash → mkdir) whose PIDs differ from the top-level
/// process but still inherit the sandbox profile.
#[cfg(target_os = "macos")]
fn capture_and_log_violations(
    _child_pid: u32,
    elapsed: std::time::Duration,
    session_id: &str,
    tool_use_id: &str,
    command: &[String],
) {
    // Brief sleep to let the unified log flush sandboxd messages.
    std::thread::sleep(std::time::Duration::from_millis(150));

    let last_secs = elapsed.as_secs() + 3; // 3s buffer for log propagation
    let last_arg = format!("{}s", last_secs.max(5)); // at least 5s window

    // No PID filter — sandbox-exec children (e.g., bash → mkdir) inherit the
    // sandbox but get their own PIDs, so filtering by the top-level PID misses
    // their violations. The time window is tight enough to avoid stray matches.
    let predicate =
        "eventMessage CONTAINS \"deny\" AND eventMessage CONTAINS \"file-\"".to_string();

    info!(
        predicate = %predicate,
        last = %last_arg,
        "Querying unified log for sandbox violations"
    );

    let output = match std::process::Command::new("log")
        .args([
            "show",
            "--last",
            &last_arg,
            "--predicate",
            &predicate,
            "--style",
            "compact",
            "--no-pager",
        ])
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .output()
    {
        Ok(o) if o.status.success() => o,
        Ok(o) => {
            info!(exit_code = ?o.status.code(), "log show returned non-zero");
            return;
        }
        Err(e) => {
            info!(error = %e, "Failed to run log show");
            return;
        }
    };

    let content = String::from_utf8_lossy(&output.stdout);
    let violations = parse_log_violations(&content);

    if violations.is_empty() {
        return;
    }

    info!(
        count = violations.len(),
        "Captured sandbox violations from unified log"
    );

    let tool_input_summary = if command.len() <= 3 {
        command.join(" ")
    } else {
        format!("{} {} {} ...", command[0], command[1], command[2])
    };

    crate::audit::log_sandbox_violations(
        session_id,
        "Bash",
        tool_use_id,
        &tool_input_summary,
        &violations,
    );
}

/// Paths that are commonly denied by macOS Seatbelt on process startup but
/// aren't user-visible errors. Filtered out to reduce noise in audit entries.
#[cfg(target_os = "macos")]
const NOISE_PATH_PREFIXES: &[&str] = &["/dev/dtrace", "/dev/dtracehelper", "/dev/oslog"];

/// Parse sandbox violations from macOS unified log (`log show`) output.
///
/// Extracts the operation and path from sandboxd deny messages:
///   `Sandbox: bash(12345) deny(1) file-write-create /Users/user/.fly/config`
///
/// Filters out known noise paths (e.g., `/dev/dtracehelper`) that appear on
/// every process startup and aren't meaningful violations.
#[cfg(target_os = "macos")]
fn parse_log_violations(content: &str) -> Vec<crate::audit::SandboxViolation> {
    let re = match regex::Regex::new(r"deny\(\d+\)\s+(file-\S+)\s+(/\S+)") {
        Ok(re) => re,
        Err(_) => return Vec::new(),
    };

    let mut violations = Vec::new();
    let mut seen = std::collections::BTreeSet::new();

    for line in content.lines() {
        if !line.contains("deny") || !line.contains("file-") {
            continue;
        }
        for cap in re.captures_iter(line) {
            if let (Some(op), Some(path)) = (cap.get(1), cap.get(2)) {
                let path_str = path.as_str().to_string();
                // Skip noise paths and duplicates.
                if path_str.starts_with('/')
                    && !NOISE_PATH_PREFIXES
                        .iter()
                        .any(|prefix| path_str.starts_with(prefix))
                    && seen.insert(path_str.clone())
                {
                    violations.push(crate::audit::SandboxViolation {
                        operation: op.as_str().to_string(),
                        path: path_str,
                    });
                }
            }
        }
    }

    violations
}

// ── Non-macOS: exec-based fallback ───────────────────────────────────────

/// Execute a command under the sandbox using exec (replaces the process).
///
/// When `AllowDomains` is active, forks first so the parent can run the
/// domain-filtering proxy while the child applies the sandbox and execs.
#[cfg(not(target_os = "macos"))]
fn exec_with_proxy(
    policy: &SandboxPolicy,
    cwd: &std::path::Path,
    command: &[String],
) -> Result<()> {
    match &policy.network {
        NetworkPolicy::Localhost => {
            // Localhost-only: kernel enforces the restriction directly,
            // no proxy needed. Exec the sandboxed command directly.
            match sandbox::exec_sandboxed(policy, cwd, command, None) {
                Err(e) => anyhow::bail!("sandbox exec failed: {}", e),
            }
        }
        NetworkPolicy::AllowDomains(domains) => {
            let proxy_handle = sandbox::proxy::start_proxy(sandbox::proxy::ProxyConfig {
                allowed_domains: domains.clone(),
            })
            .context("failed to start domain-filtering proxy")?;
            let proxy_url = format!("http://{}", proxy_handle.addr);
            info!(addr = %proxy_handle.addr, "started domain-filtering proxy for exec");

            let pid = unsafe { libc::fork() };
            match pid {
                -1 => {
                    anyhow::bail!("fork failed: {}", std::io::Error::last_os_error());
                }
                0 => {
                    // Child: set proxy env vars, then apply sandbox + exec.
                    unsafe {
                        set_env_cstr("HTTP_PROXY", &proxy_url);
                        set_env_cstr("HTTPS_PROXY", &proxy_url);
                        set_env_cstr("http_proxy", &proxy_url);
                        set_env_cstr("https_proxy", &proxy_url);
                    }
                    match sandbox::exec_sandboxed(policy, cwd, command, None) {
                        Err(e) => {
                            eprintln!("sandbox exec failed: {}", e);
                            std::process::exit(1);
                        }
                    }
                }
                child_pid => {
                    // Parent: wait for the child, then clean up.
                    let mut status: libc::c_int = 0;
                    unsafe {
                        libc::waitpid(child_pid, &mut status, 0);
                    }
                    drop(proxy_handle);
                    if libc::WIFEXITED(status) {
                        let code = libc::WEXITSTATUS(status);
                        if code != 0 {
                            std::process::exit(code);
                        }
                    } else {
                        std::process::exit(1);
                    }
                    Ok(())
                }
            }
        }
        _ => {
            // No proxy needed — exec directly.
            match sandbox::exec_sandboxed(policy, cwd, command, None) {
                Err(e) => anyhow::bail!("sandbox exec failed: {}", e),
            }
        }
    }
}

/// Set an environment variable using libc (safe to call after fork).
#[cfg(not(target_os = "macos"))]
unsafe fn set_env_cstr(key: &str, val: &str) {
    use std::ffi::CString;
    if let (Ok(k), Ok(v)) = (CString::new(key), CString::new(val)) {
        unsafe { libc::setenv(k.as_ptr(), v.as_ptr(), 1) };
    }
}

#[cfg(all(test, target_os = "macos"))]
mod tests {
    use super::*;

    #[test]
    fn test_parse_log_violations_basic() {
        let log = "2025-01-15 10:00:00.123 sandboxd Sandbox: bash(12345) deny(1) file-write-create /Users/user/.fly/perms.123";
        let violations = parse_log_violations(log);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].operation, "file-write-create");
        assert_eq!(violations[0].path, "/Users/user/.fly/perms.123");
    }

    #[test]
    fn test_parse_log_violations_multiple() {
        let log = "2025-01-15 10:00:00.123 sandboxd Sandbox: bash(12345) deny(1) file-write-create /Users/user/.fly/config\n\
                   2025-01-15 10:00:00.456 sandboxd Sandbox: bash(12345) deny(1) file-read-data /Users/user/.cache/db";
        let violations = parse_log_violations(log);
        assert_eq!(violations.len(), 2);
        assert_eq!(violations[0].operation, "file-write-create");
        assert_eq!(violations[0].path, "/Users/user/.fly/config");
        assert_eq!(violations[1].operation, "file-read-data");
        assert_eq!(violations[1].path, "/Users/user/.cache/db");
    }

    #[test]
    fn test_parse_log_violations_deduplicates() {
        let log = "2025-01-15 10:00:00.123 sandboxd Sandbox: bash(12345) deny(1) file-write-create /tmp/foo\n\
                   2025-01-15 10:00:00.456 sandboxd Sandbox: bash(12345) deny(1) file-write-data /tmp/foo";
        let violations = parse_log_violations(log);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].path, "/tmp/foo");
    }

    #[test]
    fn test_parse_log_violations_no_denies() {
        let log = "2025-01-15 10:00:00.123 sandboxd Sandbox: bash(12345) allow file-read-data /usr/lib/libSystem.B.dylib";
        let violations = parse_log_violations(log);
        assert!(violations.is_empty());
    }

    #[test]
    fn test_parse_log_violations_ignores_non_file() {
        let log = "2025-01-15 10:00:00.123 sandboxd Sandbox: bash(12345) deny(1) network-outbound 1.2.3.4:443\n\
                   2025-01-15 10:00:00.456 sandboxd Sandbox: bash(12345) deny(1) file-write-create /Users/user/.fly/perms";
        let violations = parse_log_violations(log);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].path, "/Users/user/.fly/perms");
    }

    #[test]
    fn test_parse_log_violations_empty_input() {
        let violations = parse_log_violations("");
        assert!(violations.is_empty());
    }

    #[test]
    fn test_parse_log_violations_filters_noise_paths() {
        let log = "2025-01-15 10:00:00.123 sandboxd Sandbox: bash(12345) deny(1) file-read-data /dev/dtracehelper\n\
                   2025-01-15 10:00:00.456 sandboxd Sandbox: bash(12345) deny(1) file-write-create /Users/user/.fly/config";
        let violations = parse_log_violations(log);
        assert_eq!(violations.len(), 1);
        assert_eq!(violations[0].path, "/Users/user/.fly/config");
    }

    #[test]
    fn test_parse_log_violations_filters_all_noise() {
        let log = "2025-01-15 10:00:00.123 sandboxd Sandbox: bash(12345) deny(1) file-read-data /dev/dtracehelper\n\
                   2025-01-15 10:00:00.456 sandboxd Sandbox: bash(12345) deny(1) file-read-data /dev/oslog/foo";
        let violations = parse_log_violations(log);
        assert!(violations.is_empty());
    }
}