car-server-core 0.36.0

Transport-neutral library for the CAR daemon JSON-RPC dispatcher (used by car-server and tokhn-daemon)
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
//! The coder's inspector chain — policy hardening for host tool execution.
//!
//! Every tool call the coder makes (model-proposed AND contract checks) passes
//! through this chain before dispatch; first Deny wins. The checks are
//! deliberately conservative token/substring matchers, not a shell parser —
//! they block the unambiguous footguns. This is hardening, not a sandbox; the
//! real gates are contract confirmation and merge approval (see `coder::`
//! module docs).

use std::path::{Component, Path, PathBuf};

use car_policy::{InspectionResult, Inspector, InspectorChain};
use serde_json::Value;

/// Build the standard coder chain for a worktree.
pub fn coder_inspector_chain(worktree: &Path) -> InspectorChain {
    InspectorChain::new()
        .with(Box::new(DenyGitRemoteMutation))
        .with(Box::new(DenyHistoryRewrite))
        .with(Box::new(DenyPrivilegeEscalation))
        .with(Box::new(DenyCredentialAccess))
        .with(Box::new(DenyDestructiveOutsideWorktree {
            worktree: worktree.to_path_buf(),
        }))
        .with(Box::new(DenyPathEscape {
            worktree: worktree.to_path_buf(),
        }))
}

/// Lexically resolve `candidate` against `root` and decide whether it stays
/// under `root`. Purely lexical (`..` popping) — symlinks inside the worktree
/// are out of scope here, consistent with the hardening-not-sandbox stance.
pub(crate) fn stays_under(root: &Path, candidate: &str) -> bool {
    let p = Path::new(candidate);
    let joined = if p.is_absolute() {
        p.to_path_buf()
    } else {
        root.join(p)
    };
    let mut stack: Vec<Component> = Vec::new();
    for c in joined.components() {
        match c {
            Component::CurDir => {}
            Component::ParentDir => {
                if stack.pop().is_none() {
                    return false;
                }
            }
            other => stack.push(other),
        }
    }
    let normalized: PathBuf = stack.iter().collect();
    path_starts_with(&normalized, root)
}

/// Component-boundary prefix test. On Unix this is `Path::starts_with`. On
/// Windows it additionally strips the `\\?\` verbatim prefix (which
/// `Path::canonicalize` adds to the worktree root but a model-supplied absolute
/// path lacks) and folds case (NTFS is case-insensitive), so a legitimate
/// absolute write inside the worktree isn't spuriously denied.
#[cfg(not(windows))]
fn path_starts_with(path: &Path, base: &Path) -> bool {
    path.starts_with(base)
}

#[cfg(windows)]
fn path_starts_with(path: &Path, base: &Path) -> bool {
    fn key(p: &Path) -> String {
        let s = p.to_string_lossy().into_owned();
        let s = if let Some(r) = s.strip_prefix(r"\\?\UNC\") {
            format!(r"\\{r}")
        } else if let Some(r) = s.strip_prefix(r"\\?\") {
            r.to_string()
        } else {
            s
        };
        s.replace('/', "\\").to_ascii_lowercase()
    }
    let base_key = key(base);
    let base_trim = base_key.trim_end_matches('\\');
    let path_key = key(path);
    path_key == base_trim || path_key.starts_with(&format!("{base_trim}\\"))
}

/// True when a shell argument names an absolute path (POSIX `/…`, Windows
/// `C:\…` / `\\server\…`) or contains a `..` traversal — i.e. the argument may
/// point outside the worktree and must be checked against [`stays_under`].
/// The old code tested only `starts_with('/')`, which never matches a Windows
/// absolute path, so `del C:\…` slipped past the destructive-op guard.
fn is_abs_or_traversal(arg: &str) -> bool {
    arg.starts_with('/')
        || arg.starts_with('\\')
        || arg.contains("..")
        || Path::new(arg).is_absolute()
}

/// True for a Windows `cmd` switch like `/q`, `/s`, `/f` — a leading `/`
/// followed by one or two alphanumerics and nothing else. Distinguished from a
/// POSIX absolute path (`/etc`, `/wt/...`), which is longer or contains another
/// separator. Only ever true on Windows, so Unix argument handling (where a
/// leading `/` is always a path) is unchanged.
fn is_windows_switch(arg: &str) -> bool {
    #[cfg(not(windows))]
    {
        let _ = arg;
        false
    }
    #[cfg(windows)]
    {
        arg.strip_prefix('/')
            .map(|rest| {
                (1..=2).contains(&rest.len()) && rest.chars().all(|c| c.is_ascii_alphanumeric())
            })
            .unwrap_or(false)
    }
}

/// Split a shell command into segments at unquoted-ish separators and each
/// segment into whitespace tokens. Naive on purpose (no quote handling): a
/// quoted `";"` may split a segment too eagerly, which only ever makes the
/// chain MORE likely to deny — never less.
fn segments(command: &str) -> Vec<Vec<String>> {
    command
        .replace("&&", "\n")
        .replace("||", "\n")
        .replace(['', ';', '|'], "\n")
        .lines()
        .map(|seg| {
            seg.split_whitespace()
                .map(|t| t.trim_matches(|c| c == '"' || c == '\'').to_string())
                .filter(|t| !t.is_empty())
                .collect::<Vec<_>>()
        })
        .filter(|toks: &Vec<String>| !toks.is_empty())
        .collect()
}

/// First non-env-assignment token of a segment (`FOO=bar cmd …` → `cmd`).
fn verb(tokens: &[String]) -> Option<&str> {
    tokens.iter().map(String::as_str).find(|t| !t.contains('='))
}

fn shell_command(tool: &str, params: &Value) -> Option<String> {
    if tool != "shell" {
        return None;
    }
    params
        .get("command")
        .and_then(Value::as_str)
        .map(str::to_string)
}

/// `git push`, `git remote add/set-url`, `git fetch --force` — the coder's
/// output leaves the machine only via the approved merge branch.
struct DenyGitRemoteMutation;

impl Inspector for DenyGitRemoteMutation {
    fn name(&self) -> &'static str {
        "coder.deny_git_remote_mutation"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            let is_git = verb(&seg) == Some("git");
            if !is_git {
                continue;
            }
            if seg.iter().any(|t| t == "push") {
                return InspectionResult::Deny(
                    "git push is not allowed from a coder session — results are delivered \
                     via the approved local branch"
                        .into(),
                );
            }
            if seg.iter().any(|t| t == "remote")
                && seg
                    .iter()
                    .any(|t| t == "add" || t == "set-url" || t == "remove")
            {
                return InspectionResult::Deny("mutating git remotes is not allowed".into());
            }
        }
        InspectionResult::Allow
    }
}

/// `git rebase/reset --hard/filter-branch` — the worktree HEAD is detached;
/// history rewrite is never needed and only ever destroys evidence.
struct DenyHistoryRewrite;

impl Inspector for DenyHistoryRewrite {
    fn name(&self) -> &'static str {
        "coder.deny_history_rewrite"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            if verb(&seg) != Some("git") {
                continue;
            }
            if seg.iter().any(|t| t == "rebase" || t == "filter-branch") {
                return InspectionResult::Deny("git history rewrite is not allowed".into());
            }
            if seg.iter().any(|t| t == "reset") && seg.iter().any(|t| t == "--hard") {
                return InspectionResult::Deny("git reset --hard is not allowed".into());
            }
            if seg.iter().any(|t| t == "worktree") && seg.iter().any(|t| t == "remove") {
                return InspectionResult::Deny(
                    "removing worktrees is the runtime's job, not the agent's".into(),
                );
            }
        }
        InspectionResult::Allow
    }
}

/// `sudo`/`doas`/service managers — the coder runs with user privileges, full
/// stop.
struct DenyPrivilegeEscalation;

const PRIVILEGE_VERBS: &[&str] = &[
    // POSIX
    "sudo",
    "doas",
    "su",
    "launchctl",
    "systemctl", //
    // Windows privilege elevation / service control.
    "runas",
    "sc",
    "psexec",
];

impl Inspector for DenyPrivilegeEscalation {
    fn name(&self) -> &'static str {
        "coder.deny_privilege_escalation"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            if let Some(v) = verb(&seg) {
                if PRIVILEGE_VERBS.contains(&v.to_ascii_lowercase().as_str()) {
                    return InspectionResult::Deny(format!(
                        "'{v}' is not allowed in a coder session"
                    ));
                }
            }
        }
        InspectionResult::Allow
    }
}

/// Reads of key stores and credential directories, via shell or file tools.
struct DenyCredentialAccess;

const CREDENTIAL_PATH_MARKERS: [&str; 6] = [
    "/.ssh",
    "/.aws",
    "/.gnupg",
    "/.kube",
    "/.car/secrets",
    "/.netrc",
];

impl Inspector for DenyCredentialAccess {
    fn name(&self) -> &'static str {
        "coder.deny_credential_access"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let haystacks: Vec<String> = if let Some(cmd) = shell_command(tool, params) {
            if cmd.contains("find-generic-password") || cmd.contains("find-internet-password") {
                return InspectionResult::Deny("keychain access is not allowed".into());
            }
            // Windows Credential Manager / DPAPI vault tooling.
            let cmd_lower = cmd.to_ascii_lowercase();
            if cmd_lower.contains("cmdkey") || cmd_lower.contains("vaultcmd") {
                return InspectionResult::Deny(
                    "Windows Credential Manager access is not allowed".into(),
                );
            }
            vec![cmd]
        } else if matches!(
            tool,
            "read_file" | "write_file" | "edit_file" | "grep_files"
        ) {
            params
                .get("path")
                .and_then(Value::as_str)
                .map(|p| vec![p.to_string()])
                .unwrap_or_default()
        } else {
            return InspectionResult::Allow;
        };
        for hay in &haystacks {
            // Normalize Windows separators and the various home spellings
            // ("~/.ssh", "$HOME/.ssh", "%USERPROFILE%\.ssh") into the same
            // forward-slash marker space as POSIX absolute paths.
            let hay = hay.replace('\\', "/");
            let hay = hay
                .replace("~/", "/HOME/.")
                .replace("$HOME/", "/HOME/.")
                .replace("%USERPROFILE%/", "/HOME/.")
                .replace("%HOMEPATH%/", "/HOME/.");
            let hay = hay.replace("/HOME/..", "/."); // "~/.ssh" → "/.ssh"
            for marker in CREDENTIAL_PATH_MARKERS {
                if hay.contains(marker) {
                    return InspectionResult::Deny(format!(
                        "access to credential path matching '{marker}' is not allowed"
                    ));
                }
            }
        }
        InspectionResult::Allow
    }
}

/// Destructive shell verbs aimed outside the worktree (absolute paths, `..`
/// escapes, `~`).
struct DenyDestructiveOutsideWorktree {
    worktree: PathBuf,
}

const DESTRUCTIVE_VERBS: &[&str] = &[
    // POSIX
    "rm", "rmdir", "mv", "cp", "chmod", "chown", "truncate", "dd", //
    // Windows `cmd.exe` (the coder shell runs `cmd /C` there) — without these
    // the destructive-outside-worktree guard did nothing on Windows.
    "del", "erase", "rd", "move", "copy", "format", "ren", "rename",
];

impl Inspector for DenyDestructiveOutsideWorktree {
    fn name(&self) -> &'static str {
        "coder.deny_destructive_outside_worktree"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        let Some(cmd) = shell_command(tool, params) else {
            return InspectionResult::Allow;
        };
        for seg in segments(&cmd) {
            let Some(v) = verb(&seg) else { continue };
            // Case-insensitive: `cmd.exe` verbs are case-insensitive (DEL/del).
            let v_lower = v.to_ascii_lowercase();
            if !DESTRUCTIVE_VERBS.contains(&v_lower.as_str()) {
                continue;
            }
            // Skip flag-like args: POSIX `-x` and Windows `/x` (e.g. `del /q`).
            for arg in seg
                .iter()
                .skip(1)
                .filter(|a| !a.starts_with('-') && !is_windows_switch(a))
            {
                if arg.starts_with('~') {
                    return InspectionResult::Deny(format!(
                        "'{v}' on a home-relative path ('{arg}') is not allowed"
                    ));
                }
                if is_abs_or_traversal(arg) && !stays_under(&self.worktree, arg) {
                    return InspectionResult::Deny(format!(
                        "'{v}' outside the worktree ('{arg}') is not allowed"
                    ));
                }
            }
        }
        InspectionResult::Allow
    }
}

/// File-tool writes whose path resolves outside the worktree. (The executor
/// also clamps; defense in depth so a future executor change can't silently
/// drop the rule.)
struct DenyPathEscape {
    worktree: PathBuf,
}

impl Inspector for DenyPathEscape {
    fn name(&self) -> &'static str {
        "coder.deny_path_escape"
    }

    fn inspect(&self, tool: &str, params: &Value) -> InspectionResult {
        if !matches!(tool, "write_file" | "edit_file") {
            return InspectionResult::Allow;
        }
        let Some(path) = params.get("path").and_then(Value::as_str) else {
            return InspectionResult::Allow; // missing param fails in the tool itself
        };
        if stays_under(&self.worktree, path) {
            InspectionResult::Allow
        } else {
            InspectionResult::Deny(format!("write to '{path}' resolves outside the worktree"))
        }
    }
}

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

    fn chain() -> InspectorChain {
        coder_inspector_chain(Path::new("/wt"))
    }

    fn denied(tool: &str, params: Value) -> bool {
        chain().check(tool, &params).is_some()
    }

    fn sh(cmd: &str) -> Value {
        json!({ "command": cmd })
    }

    #[test]
    fn git_push_and_remote_mutation_denied() {
        assert!(denied("shell", sh("git push origin main")));
        assert!(denied("shell", sh("cargo test && git push --force")));
        assert!(denied("shell", sh("git remote add evil https://x")));
        assert!(denied("shell", sh("git remote set-url origin https://x")));
        // Reading remotes and committing are fine.
        assert!(!denied("shell", sh("git remote -v")));
        assert!(!denied("shell", sh("git commit -m 'x'")));
        assert!(!denied("shell", sh("git status && git diff")));
        // "push" in a non-git segment is fine.
        assert!(!denied("shell", sh("echo push")));
    }

    #[test]
    fn history_rewrite_denied() {
        assert!(denied("shell", sh("git rebase -i HEAD~3")));
        assert!(denied("shell", sh("git reset --hard HEAD~1")));
        assert!(denied("shell", sh("git filter-branch --all")));
        assert!(denied("shell", sh("git worktree remove /wt")));
        assert!(!denied("shell", sh("git reset HEAD file.txt"))); // soft reset ok
    }

    #[test]
    fn privilege_escalation_denied() {
        assert!(denied("shell", sh("sudo rm -rf /tmp/x")));
        assert!(denied("shell", sh("doas pkg_add x")));
        assert!(denied("shell", sh("FOO=1 sudo make install")));
        assert!(denied("shell", sh("launchctl unload foo")));
        assert!(!denied("shell", sh("echo sudo"))); // verb position only
    }

    #[test]
    fn credential_access_denied_for_shell_and_file_tools() {
        assert!(denied("shell", sh("cat ~/.ssh/id_rsa")));
        assert!(denied("shell", sh("cat $HOME/.aws/credentials")));
        assert!(denied("shell", sh("security find-generic-password -s x")));
        assert!(denied("read_file", json!({"path": "/Users/u/.ssh/id_rsa"})));
        assert!(denied("read_file", json!({"path": "~/.netrc"})));
        assert!(!denied("read_file", json!({"path": "src/main.rs"})));
        // ".ssh" as a repo-relative dir name is unfortunate but stays denied —
        // conservative beats clever here.
    }

    #[test]
    fn destructive_ops_scoped_to_worktree() {
        assert!(denied("shell", sh("rm -rf /etc")));
        assert!(denied("shell", sh("rm -rf ../other-checkout")));
        assert!(denied("shell", sh("mv target ~/elsewhere")));
        assert!(denied("shell", sh("chmod 777 /usr/local/bin/x")));
        // Inside the worktree: fine, relative or absolute.
        assert!(!denied("shell", sh("rm -rf target/debug")));
        assert!(!denied("shell", sh("rm /wt/scratch.txt")));
        assert!(!denied("shell", sh("cp a.txt b.txt")));
    }

    #[test]
    fn write_path_escape_denied_but_reads_allowed() {
        assert!(denied(
            "write_file",
            json!({"path": "/etc/hosts", "content": "x"})
        ));
        assert!(denied("edit_file", json!({"path": "../outside.txt"})));
        assert!(!denied(
            "write_file",
            json!({"path": "src/new.rs", "content": "x"})
        ));
        assert!(!denied(
            "write_file",
            json!({"path": "/wt/src/new.rs", "content": "x"})
        ));
        // Reads outside the worktree are allowed (context gathering) unless
        // they hit credential markers.
        assert!(!denied(
            "read_file",
            json!({"path": "/usr/include/stdio.h"})
        ));
    }

    #[test]
    fn stays_under_is_lexical_and_strict() {
        let root = Path::new("/wt");
        assert!(stays_under(root, "src/x.rs"));
        assert!(stays_under(root, "a/../b.txt"));
        assert!(stays_under(root, "/wt/deep/file"));
        assert!(!stays_under(root, "../escape"));
        assert!(!stays_under(root, "a/../../escape"));
        assert!(!stays_under(root, "/etc/passwd"));
        assert!(!stays_under(root, "/wtevil/file")); // prefix, not component, match
    }

    #[cfg(windows)]
    #[test]
    fn windows_destructive_and_privilege_denied() {
        let chain = coder_inspector_chain(Path::new(r"C:\wt"));
        let denied = |cmd: &str| chain.check("shell", &sh(cmd)).is_some();
        // `cmd.exe` destructive verbs aimed outside the worktree.
        assert!(denied(r"del C:\Windows\System32\drivers\etc\hosts"));
        assert!(denied(r"rd /s /q C:\Windows"));
        assert!(denied(r"del /q C:\Users\victim\file")); // `/q` switch is skipped
        assert!(denied(r"move C:\wt\keep.txt C:\Users\public\stolen.txt"));
        // Windows privilege elevation.
        assert!(denied("runas /user:Administrator cmd"));
        assert!(denied("sc stop windefend"));
        // Inside the worktree: allowed (absolute or relative).
        assert!(!denied(r"del C:\wt\target\debug\app.exe"));
        assert!(!denied(r"del build\out.txt"));
        assert!(!denied("dir")); // non-destructive verb untouched
    }

    #[cfg(windows)]
    #[test]
    fn windows_credential_access_denied() {
        let chain = coder_inspector_chain(Path::new(r"C:\wt"));
        assert!(chain
            .check("shell", &sh(r"type %USERPROFILE%\.ssh\id_rsa"))
            .is_some());
        assert!(chain.check("shell", &sh("cmdkey /list")).is_some());
        assert!(chain
            .check(
                "read_file",
                &json!({"path": r"C:\Users\u\.aws\credentials"})
            )
            .is_some());
        // A normal source read is fine.
        assert!(chain
            .check("read_file", &json!({"path": r"C:\wt\src\main.rs"}))
            .is_none());
    }

    #[cfg(windows)]
    #[test]
    fn stays_under_handles_verbatim_prefix_and_case() {
        // A canonicalized worktree carries the `\\?\` verbatim prefix; a plain
        // absolute candidate inside it (any case) must still count as inside,
        // and NTFS case-insensitivity is honoured.
        let root = Path::new(r"\\?\C:\wt");
        assert!(stays_under(root, r"C:\WT\src\main.rs"));
        assert!(stays_under(root, r"c:\wt\src\main.rs"));
        assert!(!stays_under(root, r"C:\other\x"));
        assert!(!stays_under(root, r"C:\wtevil\x")); // prefix, not component
    }
}