flagon-io/g1t

public

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

g1t/crates/runner/src/guard.rs

1,051 lines41,388 bytesCodeBlame
1//! Guardrails inside the sandbox: the command rules the agent's harness
2//! enforces, its cost and time caps, and trusting the certificate the
3//! sandbox's HTTPS is re-signed with when its network is restricted.
4//!
5//! The runner service passes the run's guardrails as `GUARDRAILS`. Before
6//! Claude Code starts, `install` writes them where the harness reads them:
7//!
8//! - Claude Code's managed settings (`/etc/claude-code/managed-settings.json`,
9//! root-owned, which no other settings file can override) get a
10//! `PreToolUse` hook that runs this program in `MODE=guard` before every
11//! tool call, and `permissions.deny` rules as a second layer.
12//! - With the `sudo` rule on, the sandbox then gives up root, so the agent
13//! cannot change either. Where that cannot be done (no sudo), the same
14//! settings are passed with `--settings` instead.
15//!
16//! The hook (`hook_main`) decides with `decide`: a refused call is not
17//! made, Claude Code tells the agent why, and the refusal is appended to
18//! `DENIED_LOG`, which the harness reads and reports as a step of the run.
19//!
20//! Matching shell commands against rules is a guard against an agent's
21//! mistakes, not a sandbox: a command can always be written in a way no
22//! rule foresees. The network list, the credentials a sandbox holds, and
23//! branch protection on g1t's side are the hard boundaries.
24
25use std::collections::BTreeMap;
26use std::fmt;
27use std::io::{Read, Write};
28use std::path::Path;
29use std::process::{Command, Stdio};
30
31use serde::Deserialize;
32use serde_json::{Value, json};
33
34/// Where the guardrails are kept for the hook: root-owned where it can be.
35const POLICY_FILES: [&str; 2] = ["/etc/g1t/guard.json", "/work/.g1t/guard.json"];
36const MANAGED_SETTINGS: &str = "/etc/claude-code/managed-settings.json";
37/// Settings passed with `--settings` when the managed file cannot be written.
38pub const FALLBACK_SETTINGS: &str = "/work/.g1t/settings.json";
39/// Refusals, one per line, for the harness to report.
40pub const DENIED_LOG: &str = "/work/.g1t/denied.log";
41/// The certificate the sandbox's HTTPS is re-signed with, when it is guarded.
42const EGRESS_CA: &str = "/etc/cloudflare/certs/cloudflare-containers-ca.crt";
43const HOOK_COMMAND: &str = "MODE=guard /usr/local/bin/g1t-runner";
44
45/// The run's guardrails, as the runner service passes them.
46#[derive(Clone, Debug, Default, Deserialize)]
47#[serde(rename_all = "camelCase", default)]
48pub struct Policy {
49 pub rules: BTreeMap<String, bool>,
50 pub deny: Vec<String>,
51 pub budget_usd: Option<f64>,
52 /// This run's time cap, in minutes.
53 pub minutes: Option<u32>,
54 pub restrict_network: bool,
55 /// The branch everything lands on, when the runner knows it.
56 pub default_branch: Option<String>,
57}
58
59impl Policy {
60 pub fn from_env() -> Option<Policy> {
61 serde_json::from_str(&std::env::var("GUARDRAILS").ok()?).ok()
62 }
63
64 fn on(&self, rule: &str) -> bool {
65 self.rules.get(rule).copied().unwrap_or(false)
66 }
67}
68
69/// Why g1t stopped a run by itself: it reached a cap.
70#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub enum Halted {
72 Budget,
73 Time,
74}
75
76impl Halted {
77 pub fn reason(self) -> &'static str {
78 match self {
79 Halted::Budget => "budget",
80 Halted::Time => "time",
81 }
82 }
83}
84
85impl fmt::Display for Halted {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 match self {
88 Halted::Budget => write!(f, "the run reached its cost cap"),
89 Halted::Time => write!(f, "the run reached its time cap"),
90 }
91 }
92}
93
94impl std::error::Error for Halted {}
95
96/// Whether a run failed because it reached a cap, rather than failing.
97pub fn is_halt(error: &anyhow::Error) -> bool {
98 error.downcast_ref::<Halted>().is_some()
99}
100
101/// Runs a command as root without asking. False where that is not allowed.
102fn sudo(args: &[&str], input: Option<&str>) -> bool {
103 let child = Command::new("sudo")
104 .arg("-n")
105 .args(args)
106 .stdin(if input.is_some() { Stdio::piped() } else { Stdio::null() })
107 .stdout(Stdio::null())
108 .stderr(Stdio::null())
109 .spawn();
110 let Ok(mut child) = child else {
111 return false;
112 };
113 if let (Some(input), Some(mut stdin)) = (input, child.stdin.take()) {
114 let _ = stdin.write_all(input.as_bytes());
115 }
116 child.wait().is_ok_and(|status| status.success())
117}
118
119/// Writes `contents` to a root-owned file that others can read.
120fn write_as_root(path: &str, contents: &str) -> bool {
121 let dir = Path::new(path).parent().and_then(Path::to_str).unwrap_or("/");
122 sudo(&["mkdir", "-p", dir], None)
123 && sudo(&["tee", path], Some(contents))
124 && sudo(&["chmod", "0644", path], None)
125}
126
127/// Trusts the certificate a guarded sandbox's HTTPS is re-signed with, so
128/// that git, package managers and this program can reach allowed hosts.
129/// Does nothing in a sandbox whose network is open. Called first thing,
130/// before any request is made.
131pub fn trust_egress_ca() {
132 const TRUSTED: &str = "/usr/local/share/ca-certificates/cloudflare-containers-ca.crt";
133 // Once per sandbox: the hooks run this program after every tool call.
134 if !Path::new(EGRESS_CA).exists() || Path::new(TRUSTED).exists() {
135 return;
136 }
137 let trusted = sudo(&["cp", EGRESS_CA, TRUSTED], None) && sudo(&["update-ca-certificates"], None);
138 if !trusted {
139 eprintln!("g1t-runner: could not trust the sandbox's egress certificate; HTTPS will fail");
140 }
141}
142
143/// The permission rules that back up each built-in rule. The hook is what
144/// enforces them; these are a second layer the harness applies itself.
145fn rule_patterns(rule: &str) -> &'static [&'static str] {
146 match rule {
147 "force_push" => &[
148 "Bash(git push --force:*)",
149 "Bash(git push -f:*)",
150 "Bash(git push --force-with-lease:*)",
151 "Bash(git push --mirror:*)",
152 ],
153 "rewrite_default_branch" => &[
154 "Bash(git filter-branch:*)",
155 "Bash(git filter-repo:*)",
156 "Bash(git replace:*)",
157 ],
158 "outside_workspace" => &[
159 "Read(//proc/**)",
160 "Read(//etc/claude-code/**)",
161 "Read(//etc/g1t/**)",
162 "Read(//work/.g1t/**)",
163 "Read(//work/g1t-mcp.json)",
164 "Read(//work/g1t-steer.json)",
165 "Read(~/.claude/**)",
166 ],
167 "print_env" => &["Bash(env)", "Bash(printenv:*)", "Bash(export -p)"],
168 "sudo" => &["Bash(sudo:*)", "Bash(su:*)", "Bash(doas:*)"],
169 _ => &[],
170 }
171}
172
173/// Claude Code's settings for a guarded run: the hook before every tool
174/// call, the permission rules, and nothing sent anywhere but the model.
175pub fn harness_settings(policy: &Policy) -> Value {
176 let mut deny: Vec<String> = Vec::new();
177 for (rule, on) in &policy.rules {
178 if *on {
179 deny.extend(rule_patterns(rule).iter().map(|pattern| (*pattern).to_owned()));
180 }
181 }
182 for pattern in &policy.deny {
183 if !deny.contains(pattern) {
184 deny.push(pattern.clone());
185 }
186 }
187 let mut settings = json!({
188 "permissions": { "deny": deny },
189 "hooks": {
190 "PreToolUse": [{
191 "matcher": "*",
192 "hooks": [{ "type": "command", "command": HOOK_COMMAND, "timeout": 10 }],
193 }],
194 },
195 });
196 if policy.restrict_network {
197 // Only the model and the allowed hosts are reachable: the harness
198 // is told not to try anything else.
199 settings["skipWebFetchPreflight"] = json!(true);
200 settings["env"] = json!({
201 "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
202 "DISABLE_TELEMETRY": "1",
203 "DISABLE_ERROR_REPORTING": "1",
204 "DISABLE_AUTOUPDATER": "1",
205 });
206 }
207 settings
208}
209
210/// What `install` managed to do.
211#[derive(Debug, Default)]
212pub struct Installed {
213 /// Settings to pass with `--settings`, when they could not be managed.
214 pub settings_file: Option<String>,
215 /// Whether the sandbox gave up root.
216 pub dropped_root: bool,
217}
218
219/// Puts the guardrails where the harness and the hook read them, then, if
220/// the `sudo` rule is on, gives up root for the rest of the sandbox.
221pub fn install(policy: &Policy, raw: &str) -> Installed {
222 let _ = std::fs::create_dir_all("/work/.g1t");
223 let _ = std::fs::write(DENIED_LOG, "");
224 let settings = harness_settings(policy).to_string();
225 let managed = write_as_root(POLICY_FILES[0], raw) && write_as_root(MANAGED_SETTINGS, &settings);
226 let mut installed = Installed::default();
227 if !managed {
228 let _ = std::fs::write(POLICY_FILES[1], raw);
229 if std::fs::write(FALLBACK_SETTINGS, &settings).is_ok() {
230 installed.settings_file = Some(FALLBACK_SETTINGS.to_owned());
231 }
232 }
233 if policy.on("sudo") && managed {
234 installed.dropped_root = sudo(&["rm", "-f", "/etc/sudoers.d/node"], None);
235 }
236 installed
237}
238
239/// A remote as `namespace/name`, lower case, whatever host or suffix it has.
240fn repo_of(remote: &str) -> String {
241 let path = remote.split("://").nth(1).map_or(remote, |rest| rest.split_once('/').map_or("", |(_, path)| path));
242 path.trim_end_matches('/').trim_end_matches(".git").to_lowercase()
243}
244
245/// Whether the checkout the agent works in is the repository's own: a
246/// branch of the repository itself (the default branch, or one pushed to
247/// it), never a fork. A fork's files are anyone's, so the harness must not
248/// load their CLAUDE.md, settings, hooks, MCP servers or commands. Same
249/// rule as the instructions the runner service reads (repo-instructions.ts).
250/// Unsure is untrusted.
251pub fn checkout_trusted(remote: Option<&str>, upstream: Option<&str>, repo: Option<&str>) -> bool {
252 let Some(remote) = remote.map(repo_of).filter(|remote| !remote.is_empty()) else {
253 return false;
254 };
255 let own = upstream
256 .map(repo_of)
257 .or_else(|| repo.map(|repo| repo.trim_matches('/').to_lowercase()))
258 .filter(|own| !own.is_empty());
259 own.is_some_and(|own| own == remote)
260}
261
262/// The same, from the sandbox's environment.
263pub fn checkout_trusted_from_env() -> bool {
264 let var = |name: &str| std::env::var(name).ok();
265 checkout_trusted(
266 var("GIT_REMOTE").as_deref(),
267 var("UPSTREAM_REMOTE").as_deref(),
268 var("G1T_REPO").as_deref(),
269 )
270}
271
272/// Flags that keep Claude Code from loading anything from an untrusted
273/// checkout: its `.claude/settings.json` and `settings.local.json` (with
274/// their hooks and permissions), its `.mcp.json`, and its commands and
275/// skills. Managed settings (the guard hook), `--settings` and
276/// `--mcp-config` still apply. CLAUDE.md is turned off by
277/// `UNTRUSTED_ENV`.
278pub const UNTRUSTED_FLAGS: [&str; 4] = ["--setting-sources", "user", "--strict-mcp-config", "--disable-slash-commands"];
279/// Turns off every CLAUDE.md, the checkout's included.
280pub const UNTRUSTED_ENV: (&str, &str) = ("CLAUDE_CODE_DISABLE_CLAUDE_MDS", "1");
281
282/// Refusals the hook has written since the last call, as run steps.
283#[derive(Default)]
284pub struct Denials {
285 seen: usize,
286}
287
288impl Denials {
289 pub fn take(&mut self) -> Vec<String> {
290 let Ok(text) = std::fs::read_to_string(DENIED_LOG) else {
291 return Vec::new();
292 };
293 let lines: Vec<String> = text.lines().map(str::to_owned).collect();
294 let new = lines.iter().skip(self.seen).cloned().collect();
295 self.seen = lines.len();
296 new
297 }
298}
299
300/// `MODE=guard`: Claude Code's `PreToolUse` hook. Reads the call on stdin;
301/// exits 2 with the reason on stderr to refuse it, which Claude Code shows
302/// the agent, and 0 to let it through.
303pub fn hook_main() -> i32 {
304 let mut input = String::new();
305 let _ = std::io::stdin().read_to_string(&mut input);
306 let Ok(call) = serde_json::from_str::<Value>(&input) else {
307 return 0;
308 };
309 let Some(policy) = POLICY_FILES
310 .iter()
311 .find_map(|path| std::fs::read_to_string(path).ok())
312 .and_then(|raw| serde_json::from_str::<Policy>(&raw).ok())
313 else {
314 return 0;
315 };
316 let tool = call["tool_name"].as_str().unwrap_or_default();
317 let home = std::env::var("HOME").unwrap_or_else(|_| "/home/node".to_owned());
318 let place = Place {
319 workdir: call["cwd"].as_str().unwrap_or(crate::WORKDIR).to_owned(),
320 home,
321 default_branch: policy
322 .default_branch
323 .clone()
324 .or_else(origin_default_branch)
325 .unwrap_or_else(|| "main".to_owned()),
326 };
327 let Some(reason) = decide(&policy, tool, &call["tool_input"], &place) else {
328 return 0;
329 };
330 let what = crate::progress::describe_tool(tool, &call["tool_input"]);
331 if let Ok(mut log) = std::fs::OpenOptions::new().create(true).append(true).open(DENIED_LOG) {
332 let _ = writeln!(log, "{}", crate::progress::one_line(&format!("Denied: {what} ({reason})")));
333 }
334 eprintln!(
335 "Blocked by g1t guardrails: {reason}. This project does not allow it. Do not try to get around it; if the task cannot be done without it, stop and say so in your summary."
336 );
337 2
338}
339
340/// The default branch of the clone's origin, if git knows it.
341fn origin_default_branch() -> Option<String> {
342 let output = Command::new("git")
343 .current_dir(crate::WORKDIR)
344 .args(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
345 .output()
346 .ok()?;
347 let name = String::from_utf8_lossy(&output.stdout).trim().to_owned();
348 name.strip_prefix("origin/").map(str::to_owned)
349}
350
351/// Where a call is made from.
352pub struct Place {
353 pub workdir: String,
354 pub home: String,
355 pub default_branch: String,
356}
357
358/// Why a tool call is refused, or None to let it through.
359pub fn decide(policy: &Policy, tool: &str, input: &Value, place: &Place) -> Option<String> {
360 let field = |name: &str| input.get(name).and_then(Value::as_str).unwrap_or_default();
361 if tool == "Bash" {
362 let command = field("command");
363 // Always on, whatever the project's rules: no sandbox mines.
364 if let Some(miner) = crate::abuse::miner_in(command) {
365 return Some(format!("no cryptocurrency mining ({miner})"));
366 }
367 for segment in segments(command) {
368 let words = words(&segment);
369 if let Some(reason) = builtin_shell(policy, &words, &segment, place) {
370 return Some(reason);
371 }
372 }
373 }
374 if let Some(path) = file_path(tool, input) {
375 let resolved = resolve(&path, place);
376 if policy.on("outside_workspace") && !inside_allowed(&resolved, place) {
377 return Some(format!("{resolved} is outside the project"));
378 }
379 }
380 custom(policy, tool, input, place)
381}
382
383/// The path a file tool works on.
384fn file_path(tool: &str, input: &Value) -> Option<String> {
385 let field = |name: &str| input.get(name).and_then(Value::as_str).map(str::to_owned);
386 match tool {
387 "Read" | "Write" | "Edit" | "MultiEdit" => field("file_path"),
388 "NotebookEdit" | "NotebookRead" => field("notebook_path"),
389 "Glob" | "Grep" | "LS" => field("path"),
390 _ => None,
391 }
392}
393
394/// `path` made absolute against the working directory, without `.` or
395/// `..`. Always with `/`, as in the sandbox.
396fn resolve(path: &str, place: &Place) -> String {
397 let expanded = match path.strip_prefix("~/") {
398 Some(rest) => format!("{}/{rest}", place.home),
399 None if path == "~" => place.home.clone(),
400 None => path.to_owned(),
401 };
402 let joined = if expanded.starts_with('/') {
403 expanded
404 } else {
405 format!("{}/{expanded}", place.workdir)
406 };
407 let mut parts: Vec<&str> = Vec::new();
408 for part in joined.split('/') {
409 match part {
410 "" | "." => {}
411 ".." => {
412 parts.pop();
413 }
414 name => parts.push(name),
415 }
416 }
417 format!("/{}", parts.join("/"))
418}
419
420/// Where file tools may go: the project, scratch space, and the caches
421/// where dependencies' sources are.
422fn inside_allowed(path: &str, place: &Place) -> bool {
423 let roots = [
424 crate::WORKDIR.to_owned(),
425 "/tmp".to_owned(),
426 format!("{}/.cargo/registry", place.home),
427 format!("{}/.cargo/git", place.home),
428 format!("{}/go/pkg/mod", place.home),
429 format!("{}/.rustup/toolchains", place.home),
430 ];
431 roots
432 .iter()
433 .any(|root| path == root || path.strip_prefix(root.as_str()).is_some_and(|rest| rest.starts_with('/')))
434}
435
436/// Paths of g1t's own a shell command may not touch.
437fn protected_paths(place: &Place) -> Vec<String> {
438 vec![
439 "/etc/claude-code".to_owned(),
440 "/etc/g1t".to_owned(),
441 "/etc/cloudflare".to_owned(),
442 "/work/.g1t".to_owned(),
443 "/work/g1t-mcp.json".to_owned(),
444 crate::steer::CONFIG.to_owned(),
445 format!("{}/.claude", place.home),
446 "~/.claude".to_owned(),
447 "$HOME/.claude".to_owned(),
448 ]
449}
450
451/// A shell command split into the commands it runs.
452pub fn segments(command: &str) -> Vec<String> {
453 let mut out = Vec::new();
454 let mut current = String::new();
455 let mut quote: Option<char> = None;
456 let chars: Vec<char> = command.chars().collect();
457 let mut i = 0;
458 while i < chars.len() {
459 let c = chars[i];
460 match quote {
461 Some(q) => {
462 if c == q {
463 quote = None;
464 }
465 current.push(c);
466 }
467 None if c == '\'' || c == '"' => {
468 quote = Some(c);
469 current.push(c);
470 }
471 None if c == ';' || c == '\n' || c == '|' || c == '&' => {
472 out.push(std::mem::take(&mut current));
473 // `&&` and `||` are one separator.
474 if (c == '|' || c == '&') && chars.get(i + 1) == Some(&c) {
475 i += 1;
476 }
477 }
478 None if c == '(' || c == ')' || c == '`' || (c == '$' && chars.get(i + 1) == Some(&'(')) => {
479 // A subshell or a command substitution runs a command of
480 // its own.
481 out.push(std::mem::take(&mut current));
482 }
483 None => current.push(c),
484 }
485 i += 1;
486 }
487 out.push(current);
488 out.into_iter()
489 .map(|segment| segment.split_whitespace().collect::<Vec<_>>().join(" "))
490 .filter(|segment| !segment.is_empty())
491 .collect()
492}
493
494/// A command's words, with quotes removed, leading `VAR=value`
495/// assignments and wrappers such as `nohup` skipped.
496pub fn words(segment: &str) -> Vec<String> {
497 let mut out = Vec::new();
498 let mut current = String::new();
499 let mut quote: Option<char> = None;
500 let mut started = false;
501 for c in segment.chars() {
502 match quote {
503 Some(q) if c == q => quote = None,
504 Some(_) => current.push(c),
505 None if c == '\'' || c == '"' => {
506 quote = Some(c);
507 started = true;
508 }
509 None if c.is_whitespace() => {
510 if started || !current.is_empty() {
511 out.push(std::mem::take(&mut current));
512 started = false;
513 }
514 }
515 None if c == '{' || c == '}' => {}
516 None => current.push(c),
517 }
518 }
519 if started || !current.is_empty() {
520 out.push(current);
521 }
522 let skip = out
523 .iter()
524 .take_while(|word| {
525 is_assignment(word)
526 || matches!(word.as_str(), "nohup" | "time" | "exec" | "command" | "builtin" | "then" | "do" | "else" | "!")
527 })
528 .count();
529 out.split_off(skip)
530}
531
532fn is_assignment(word: &str) -> bool {
533 word.split_once('=').is_some_and(|(name, _)| {
534 !name.is_empty() && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
535 })
536}
537
538/// The name of a program, without its directory.
539fn program(word: &str) -> &str {
540 word.rsplit('/').next().unwrap_or(word)
541}
542
543/// git's subcommand and its arguments, past options such as `-C dir`.
544fn git_command(words: &[String]) -> Option<(&str, &[String])> {
545 if words.first().map(|word| program(word)) != Some("git") {
546 return None;
547 }
548 let mut i = 1;
549 while i < words.len() {
550 let word = words[i].as_str();
551 if word == "-C" || word == "-c" || word == "--git-dir" || word == "--work-tree" {
552 i += 2;
553 } else if word.starts_with('-') {
554 i += 1;
555 } else {
556 return Some((word, &words[i + 1..]));
557 }
558 }
559 None
560}
561
562/// Whether a variable's name looks like it holds a secret.
563fn secret_name(name: &str) -> bool {
564 let upper = name.to_uppercase();
565 ["TOKEN", "KEY", "SECRET", "PASSWORD", "PASSWD", "CREDENTIAL", "AUTH"]
566 .iter()
567 .any(|part| upper.contains(part))
568}
569
570/// Variables a command reads, by name: `$NAME` and `${NAME}`.
571fn variables(segment: &str) -> Vec<String> {
572 let mut out = Vec::new();
573 let chars: Vec<char> = segment.chars().collect();
574 let mut i = 0;
575 while i < chars.len() {
576 if chars[i] == '$' {
577 let mut j = i + 1;
578 if chars.get(j) == Some(&'{') {
579 j += 1;
580 }
581 let start = j;
582 while j < chars.len() && (chars[j].is_ascii_alphanumeric() || chars[j] == '_') {
583 j += 1;
584 }
585 if j > start {
586 out.push(chars[start..j].iter().collect());
587 }
588 i = j;
589 } else {
590 i += 1;
591 }
592 }
593 out
594}
595
596/// The built-in rules, for one command of a shell line.
597fn builtin_shell(policy: &Policy, words: &[String], segment: &str, place: &Place) -> Option<String> {
598 let first = words.first().map(|word| program(word)).unwrap_or_default();
599 let args = words.get(1..).unwrap_or_default();
600
601 if policy.on("sudo") && matches!(first, "sudo" | "su" | "doas" | "pkexec") {
602 return Some("no sudo".to_owned());
603 }
604
605 if let Some((sub, rest)) = git_command(words) {
606 if sub == "push" {
607 let options: Vec<&str> = rest.iter().map(String::as_str).filter(|a| a.starts_with('-')).collect();
608 let positional: Vec<&str> = rest.iter().map(String::as_str).filter(|a| !a.starts_with('-')).collect();
609 let refspecs = positional.get(1..).unwrap_or_default();
610 if policy.on("force_push") {
611 let forced = options.iter().any(|option| {
612 matches!(*option, "--force" | "--mirror" | "--delete" | "--prune" | "--force-if-includes")
613 || option.starts_with("--force-with-lease")
614 || (!option.starts_with("--") && (option.contains('f') || option.contains('d')))
615 });
616 if forced || refspecs.iter().any(|spec| spec.starts_with('+') || spec.starts_with(':')) {
617 return Some("no force-pushing".to_owned());
618 }
619 }
620 if policy.on("rewrite_default_branch") {
621 let branch = place.default_branch.as_str();
622 let targets_default = refspecs.iter().any(|spec| {
623 let target = spec.rsplit(':').next().unwrap_or(spec).trim_start_matches('+');
624 target == branch || target == format!("refs/heads/{branch}")
625 });
626 if targets_default || options.contains(&"--all") {
627 return Some(format!("no pushing to {branch}, the default branch"));
628 }
629 }
630 }
631 if policy.on("rewrite_default_branch") {
632 let branch = place.default_branch.as_str();
633 let names_default = rest
634 .iter()
635 .any(|arg| arg == branch || *arg == format!("refs/heads/{branch}"));
636 let moves = rest
637 .iter()
638 .any(|arg| matches!(arg.as_str(), "-f" | "--force" | "-D" | "-d" | "--delete" | "-m" | "-M" | "--move"));
639 match sub {
640 "filter-branch" | "filter-repo" | "replace" => {
641 return Some("no rewriting history".to_owned());
642 }
643 "branch" if names_default && moves => {
644 return Some(format!("no moving or deleting {branch}, the default branch"));
645 }
646 "update-ref" if names_default => {
647 return Some(format!("no moving {branch}, the default branch"));
648 }
649 _ => {}
650 }
651 }
652 }
653
654 if policy.on("print_env") {
655 let prints = match first {
656 "printenv" => true,
657 // `env` alone, or with only options and assignments: no command.
658 "env" => args.iter().all(|arg| arg.starts_with('-') || is_assignment(arg)),
659 "export" | "declare" | "typeset" => args.is_empty() || args.iter().any(|arg| arg == "-p" || arg == "-x"),
660 "set" => args.is_empty(),
661 "compgen" => args.iter().any(|arg| arg == "-e" || arg == "-v"),
662 _ => false,
663 };
664 let environ = segment.contains("/proc/") && segment.contains("environ");
665 let secret = variables(segment).iter().any(|name| secret_name(name));
666 if prints || environ || secret {
667 return Some("no printing the environment".to_owned());
668 }
669 }
670
671 if policy.on("outside_workspace") {
672 let touched = protected_paths(place)
673 .into_iter()
674 .find(|path| segment.contains(path.as_str()));
675 if let Some(path) = touched {
676 return Some(format!("{path} is g1t's, not the project's"));
677 }
678 if segment.contains("/proc/") && segment.contains("environ") {
679 return Some("no reading other processes' environments".to_owned());
680 }
681 }
682 None
683}
684
685/// The tools a permission rule's tool name covers, as Claude Code reads
686/// them: an `Edit` rule covers every tool that writes a file.
687fn rule_covers(rule_tool: &str, tool: &str) -> bool {
688 match rule_tool {
689 "Edit" | "Write" => matches!(tool, "Edit" | "Write" | "MultiEdit" | "NotebookEdit"),
690 "Read" => matches!(tool, "Read" | "Glob" | "Grep" | "NotebookRead" | "LS"),
691 other => other == tool,
692 }
693}
694
695/// The workspace's own deny patterns.
696fn custom(policy: &Policy, tool: &str, input: &Value, place: &Place) -> Option<String> {
697 for pattern in &policy.deny {
698 let (rule_tool, spec) = match pattern.split_once('(') {
699 Some((name, rest)) => (name, rest.strip_suffix(')')),
700 None => (pattern.as_str(), None),
701 };
702 if !rule_covers(rule_tool, tool) {
703 continue;
704 }
705 let matched = match spec {
706 None => true,
707 Some(spec) if tool == "Bash" => {
708 let command = input.get("command").and_then(Value::as_str).unwrap_or_default();
709 segments(command).iter().any(|segment| shell_matches(spec, segment))
710 }
711 Some(spec) if rule_tool == "WebFetch" => {
712 let url = input.get("url").and_then(Value::as_str).unwrap_or_default();
713 let host = url.split("://").nth(1).unwrap_or(url).split(['/', ':']).next().unwrap_or_default();
714 let domain = spec.strip_prefix("domain:").unwrap_or(spec);
715 host == domain || host.ends_with(&format!(".{domain}"))
716 }
717 Some(spec) => match file_path(tool, input) {
718 Some(path) => {
719 let path = resolve(&path, place);
720 glob(&expand_rule_path(spec, place), &path)
721 }
722 None => false,
723 },
724 };
725 if matched {
726 return Some(format!("{pattern} is on this workspace's deny list"));
727 }
728 }
729 None
730}
731
732/// A rule's path made absolute, as Claude Code reads it: `//` is the root
733/// and `~/` the home directory; anything else is the project's.
734fn expand_rule_path(spec: &str, place: &Place) -> String {
735 if let Some(rest) = spec.strip_prefix("//") {
736 format!("/{rest}")
737 } else if let Some(rest) = spec.strip_prefix("~/") {
738 format!("{}/{rest}", place.home)
739 } else if let Some(rest) = spec.strip_prefix('/') {
740 format!("{}/{rest}", crate::WORKDIR)
741 } else {
742 format!("{}/{spec}", crate::WORKDIR)
743 }
744}
745
746/// Whether one command matches a `Bash(...)` rule: `prefix:*` for a
747/// command that starts with those words, `*` anywhere as a wildcard, or
748/// the exact command.
749pub fn shell_matches(spec: &str, segment: &str) -> bool {
750 let spec = spec.split_whitespace().collect::<Vec<_>>().join(" ");
751 let segment = words(segment).join(" ");
752 if let Some(prefix) = spec.strip_suffix(":*") {
753 return segment == prefix
754 || segment
755 .strip_prefix(prefix)
756 .is_some_and(|rest| rest.starts_with(' '));
757 }
758 if spec.contains('*') {
759 return wildcard(&spec, &segment, false);
760 }
761 segment == spec
762}
763
764/// A path glob: `**` crosses directories, `*` and `?` do not.
765pub fn glob(pattern: &str, path: &str) -> bool {
766 wildcard(pattern, path, true)
767}
768
769fn wildcard(pattern: &str, text: &str, paths: bool) -> bool {
770 let p: Vec<char> = pattern.chars().collect();
771 let t: Vec<char> = text.chars().collect();
772 fn go(p: &[char], t: &[char], paths: bool) -> bool {
773 match p.first() {
774 None => t.is_empty(),
775 Some('*') if paths && p.get(1) == Some(&'*') => {
776 let rest = if p.get(2) == Some(&'/') { &p[3..] } else { &p[2..] };
777 (0..=t.len()).any(|i| go(rest, &t[i..], paths))
778 || (p.get(2) == Some(&'/') && go(&p[2..], t, paths))
779 }
780 Some('*') => (0..=t.len())
781 .take_while(|i| !paths || *i == 0 || t[i - 1] != '/')
782 .any(|i| go(&p[1..], &t[i..], paths)),
783 Some('?') => !t.is_empty() && (!paths || t[0] != '/') && go(&p[1..], &t[1..], paths),
784 Some(c) => t.first() == Some(c) && go(&p[1..], &t[1..], paths),
785 }
786 }
787 go(&p, &t, paths)
788}
789
790#[cfg(test)]
791mod tests {
792 use super::*;
793
794 fn all_on() -> Policy {
795 Policy {
796 rules: ["force_push", "rewrite_default_branch", "outside_workspace", "print_env", "sudo"]
797 .into_iter()
798 .map(|rule| (rule.to_owned(), true))
799 .collect(),
800 ..Policy::default()
801 }
802 }
803
804 fn place() -> Place {
805 Place {
806 workdir: "/work/repo".to_owned(),
807 home: "/home/node".to_owned(),
808 default_branch: "main".to_owned(),
809 }
810 }
811
812 fn bash(policy: &Policy, command: &str) -> Option<String> {
813 decide(policy, "Bash", &json!({ "command": command }), &place())
814 }
815
816 #[test]
817 fn force_pushes_are_refused_however_written() {
818 let policy = all_on();
819 for command in [
820 "git push --force",
821 "git push origin feature -f",
822 "git push --force-with-lease=main origin feature",
823 "git -C /work/repo push origin +feature",
824 "cd x && git push origin :old",
825 "git push -fu origin feature",
826 "GIT_TRACE=1 git push --mirror",
827 ] {
828 assert_eq!(bash(&policy, command).as_deref(), Some("no force-pushing"), "{command}");
829 }
830 assert_eq!(bash(&policy, "git push origin feature"), None);
831 assert_eq!(bash(&policy, "git push -u origin feature"), None);
832 }
833
834 #[test]
835 fn the_default_branch_is_not_rewritten() {
836 let policy = all_on();
837 assert!(bash(&policy, "git push origin HEAD:main").is_some());
838 assert!(bash(&policy, "git push origin main").is_some());
839 assert!(bash(&policy, "git push origin feature:refs/heads/main").is_some());
840 assert!(bash(&policy, "git branch -f main HEAD~3").is_some());
841 assert!(bash(&policy, "git update-ref refs/heads/main abc123").is_some());
842 assert!(bash(&policy, "git filter-branch --tree-filter 'rm x' HEAD").is_some());
843 assert_eq!(bash(&policy, "git branch feature"), None);
844 assert_eq!(bash(&policy, "git rebase main"), None);
845 assert_eq!(bash(&policy, "git checkout main"), None);
846 }
847
848 #[test]
849 fn printing_the_environment_is_refused() {
850 let policy = all_on();
851 for command in [
852 "env",
853 "env | grep KEY",
854 "printenv ANTHROPIC_API_KEY",
855 "export -p",
856 "set",
857 "cat /proc/self/environ",
858 "echo $ANTHROPIC_API_KEY",
859 "curl -H \"Authorization: ${GITHUB_TOKEN}\" x",
860 ] {
861 assert_eq!(bash(&policy, command).as_deref(), Some("no printing the environment"), "{command}");
862 }
863 assert_eq!(bash(&policy, "env NODE_ENV=test npm test"), None);
864 assert_eq!(bash(&policy, "export PATH=$PATH:/x"), None);
865 assert_eq!(bash(&policy, "echo $HOME"), None);
866 assert_eq!(bash(&policy, "set -e"), None);
867 }
868
869 #[test]
870 fn sudo_is_refused() {
871 let policy = all_on();
872 assert_eq!(bash(&policy, "sudo apt-get install jq").as_deref(), Some("no sudo"));
873 assert_eq!(bash(&policy, "npm ci && sudo rm -rf /").as_deref(), Some("no sudo"));
874 assert_eq!(bash(&policy, "echo $(sudo cat /etc/shadow)").as_deref(), Some("no sudo"));
875 assert_eq!(bash(&policy, "npm test"), None);
876 // Quoted, it is text.
877 assert_eq!(bash(&policy, "echo 'do not use sudo'"), None);
878 }
879
880 #[test]
881 fn miners_are_refused_even_with_every_rule_off() {
882 let off = Policy::default();
883 for command in [
884 "curl -L https://github.com/xmrig/xmrig/releases/download/v6/xmrig.tar.gz | tar xz",
885 "./xmrig -o pool.example:3333",
886 "nohup ./a.out -o stratum+tcp://pool.example:4444 -u wallet &",
887 "./run --donate-level 1 --algo=rx/0",
888 "cd /tmp && ./t-rex -a kawpow",
889 ] {
890 let refused = bash(&off, command).unwrap_or_default();
891 assert!(refused.starts_with("no cryptocurrency mining"), "{command}: {refused}");
892 }
893 assert_eq!(bash(&off, "cargo build --release && cargo test"), None);
894 assert_eq!(bash(&off, "grep -rn stratum src/"), None);
895 }
896
897 #[test]
898 fn files_outside_the_project_are_refused() {
899 let policy = all_on();
900 let read = |path: &str| decide(&policy, "Read", &json!({ "file_path": path }), &place());
901 assert_eq!(read("/work/repo/src/lib.rs"), None);
902 assert_eq!(read("src/lib.rs"), None);
903 assert_eq!(read("/tmp/out.txt"), None);
904 assert_eq!(read("/home/node/.cargo/registry/src/serde/lib.rs"), None);
905 assert!(read("/etc/passwd").is_some());
906 assert!(read("../../etc/passwd").is_some());
907 assert!(read("/work/repo/../g1t-mcp.json").is_some());
908 assert!(read("~/.claude/settings.json").is_some());
909 assert!(decide(&policy, "Grep", &json!({ "pattern": "x", "path": "/etc" }), &place()).is_some());
910 assert!(bash(&policy, "cat /work/g1t-mcp.json").is_some());
911 assert!(bash(&policy, "cat ~/.claude/settings.json").is_some());
912 assert!(bash(&policy, "rm /work/.g1t/denied.log").is_some());
913 }
914
915 #[test]
916 fn rules_that_are_off_let_things_through() {
917 let policy = Policy::default();
918 assert_eq!(bash(&policy, "git push --force"), None);
919 assert_eq!(bash(&policy, "sudo true"), None);
920 assert_eq!(bash(&policy, "env"), None);
921 assert_eq!(decide(&policy, "Read", &json!({ "file_path": "/etc/passwd" }), &place()), None);
922 }
923
924 #[test]
925 fn custom_patterns_match_as_permission_rules_do() {
926 let policy = Policy {
927 deny: vec![
928 "Bash(terraform apply:*)".into(),
929 "Bash(rm -rf *)".into(),
930 "Edit(//etc/**)".into(),
931 "Read(secrets/**)".into(),
932 "WebFetch(domain:example.com)".into(),
933 "WebSearch".into(),
934 ],
935 ..Policy::default()
936 };
937 assert!(bash(&policy, "terraform apply -auto-approve").is_some());
938 assert!(bash(&policy, "cd infra && terraform apply").is_some());
939 assert_eq!(bash(&policy, "terraform applyx"), None);
940 assert_eq!(bash(&policy, "terraform plan"), None);
941 assert!(bash(&policy, "rm -rf build").is_some());
942 let write = |path: &str| decide(&policy, "Write", &json!({ "file_path": path }), &place());
943 assert!(write("/etc/hosts").is_some());
944 assert_eq!(write("/work/repo/etc/hosts"), None);
945 let read = |path: &str| decide(&policy, "Read", &json!({ "file_path": path }), &place());
946 assert!(read("secrets/prod/key.pem").is_some());
947 assert_eq!(read("src/secrets.rs"), None);
948 assert!(decide(&policy, "WebFetch", &json!({ "url": "https://docs.example.com/x" }), &place()).is_some());
949 assert_eq!(decide(&policy, "WebFetch", &json!({ "url": "https://example.org" }), &place()), None);
950 assert!(decide(&policy, "WebSearch", &json!({ "query": "x" }), &place()).is_some());
951 }
952
953 #[test]
954 fn commands_split_where_the_shell_does() {
955 assert_eq!(segments("a && b || c; d | e & f"), vec!["a", "b", "c", "d", "e", "f"]);
956 assert_eq!(segments("echo 'a; b' && c"), vec!["echo 'a; b'", "c"]);
957 assert_eq!(segments("x $(sudo y) `z`"), vec!["x", "sudo y", "z"]);
958 assert_eq!(words("FOO=1 nohup \"git\" push"), vec!["git", "push"]);
959 }
960
961 #[test]
962 fn globs_respect_directories() {
963 assert!(glob("/etc/**", "/etc/a/b"));
964 assert!(glob("/work/repo/**/*.pem", "/work/repo/a/b/key.pem"));
965 assert!(glob("/work/repo/**/*.pem", "/work/repo/key.pem"));
966 assert!(!glob("/work/repo/*.pem", "/work/repo/a/key.pem"));
967 assert!(glob("/work/repo/?.rs", "/work/repo/a.rs"));
968 }
969
970 #[test]
971 fn harness_settings_carry_the_hook_and_the_rules() {
972 let mut policy = all_on();
973 policy.deny = vec!["Bash(kubectl:*)".into()];
974 policy.restrict_network = true;
975 let settings = harness_settings(&policy);
976 let deny: Vec<&str> = settings["permissions"]["deny"]
977 .as_array()
978 .unwrap()
979 .iter()
980 .filter_map(Value::as_str)
981 .collect();
982 assert!(deny.contains(&"Bash(git push --force:*)"));
983 assert!(deny.contains(&"Bash(sudo:*)"));
984 assert!(deny.contains(&"Bash(kubectl:*)"));
985 assert_eq!(
986 settings["hooks"]["PreToolUse"][0]["hooks"][0]["command"],
987 "MODE=guard /usr/local/bin/g1t-runner"
988 );
989 assert_eq!(settings["env"]["CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC"], "1");
990
991 let open = harness_settings(&Policy::default());
992 assert_eq!(open["permissions"]["deny"].as_array().unwrap().len(), 0);
993 assert!(open.get("env").is_none());
994 // The hook runs whatever the rules, for the workspace's own patterns.
995 assert!(open["hooks"]["PreToolUse"].is_array());
996 }
997
998 #[test]
999 fn the_policy_reads_as_the_runner_sends_it() {
1000 let policy: Policy = serde_json::from_str(
1001 r#"{"rules":{"sudo":true,"print_env":false},"deny":["Bash(x:*)"],"budgetUsd":5,"minutes":90,"restrictNetwork":true,"defaultBranch":null}"#,
1002 )
1003 .unwrap();
1004 assert!(policy.on("sudo"));
1005 assert!(!policy.on("print_env"));
1006 assert_eq!(policy.budget_usd, Some(5.0));
1007 assert_eq!(policy.minutes, Some(90));
1008 assert!(policy.restrict_network);
1009 }
1010
1011 #[test]
1012 fn only_the_repositorys_own_checkout_is_trusted() {
1013 let repo = Some("acme/site");
1014 // The default branch or a branch of the repository itself.
1015 assert!(checkout_trusted(Some("https://g1t.sh/acme/site.git"), None, repo));
1016 assert!(checkout_trusted(
1017 Some("https://g1t.sh/Acme/Site"),
1018 Some("https://g1t.sh/acme/site.git"),
1019 None
1020 ));
1021 // A fork's head, whoever's fork it is.
1022 assert!(!checkout_trusted(Some("https://g1t.sh/ana/site-12.git"), None, repo));
1023 assert!(!checkout_trusted(
1024 Some("https://g1t.sh/someone/site.git"),
1025 Some("https://g1t.sh/acme/site.git"),
1026 repo
1027 ));
1028 // Not knowing is not trusting.
1029 assert!(!checkout_trusted(Some("https://g1t.sh/acme/site.git"), None, None));
1030 assert!(!checkout_trusted(None, None, repo));
1031 // A look-alike name is another repository.
1032 assert!(!checkout_trusted(Some("https://g1t.sh/acme/site-evil.git"), None, repo));
1033 }
1034
1035 #[test]
1036 fn untrusted_checkouts_load_nothing_of_their_own() {
1037 let flags = UNTRUSTED_FLAGS.join(" ");
1038 assert!(flags.contains("--setting-sources user"));
1039 assert!(!flags.contains("project") && !flags.contains("local"));
1040 assert!(flags.contains("--strict-mcp-config"));
1041 assert!(flags.contains("--disable-slash-commands"));
1042 assert_eq!(UNTRUSTED_ENV, ("CLAUDE_CODE_DISABLE_CLAUDE_MDS", "1"));
1043 }
1044
1045 #[test]
1046 fn halts_are_told_apart_from_failures() {
1047 assert!(is_halt(&anyhow::Error::new(Halted::Budget)));
1048 assert!(!is_halt(&anyhow::anyhow!("the agent reported an error")));
1049 assert_eq!(Halted::Time.reason(), "time");
1050 }
1051}