1use serde::{Deserialize, Serialize};
8use serde_json::Value;
9
10use super::paths::{Protected, normalise};
11
12pub const MCP_PREFIX: &str = "mcp__";
14
15#[derive(Debug, Clone, PartialEq, Eq)]
17pub enum Decision {
18 Allow,
20 Approval(String),
22 Deny(String),
24}
25
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
28#[serde(rename_all = "snake_case")]
29pub enum Class {
30 Write,
32 Command,
34 Network,
36 Mcp,
38 Agent,
40}
41
42impl Class {
43 #[must_use]
45 pub const fn as_str(self) -> &'static str {
46 match self {
47 Self::Write => "write",
48 Self::Command => "command",
49 Self::Network => "network",
50 Self::Mcp => "mcp",
51 Self::Agent => "agent",
52 }
53 }
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize)]
62#[serde(tag = "kind", rename_all = "snake_case", deny_unknown_fields)]
63pub enum Object {
64 Path {
66 canonical: String,
68 asked: String,
70 },
71 Command {
73 argv: Vec<String>,
75 argv_sha256: String,
77 cwd: String,
79 executable: String,
81 network: bool,
83 },
84 Tool {
86 name: String,
88 digest: String,
90 },
91 Agent {
95 agent: String,
97 call: String,
99 argvs: Vec<Vec<String>>,
101 paths: Vec<String>,
103 input: String,
106 },
107}
108
109pub const NOT_FOUND: &str = "not found";
111
112pub const NOT_ALLOWED: &str = "not a configured check or allowed command";
114
115#[must_use]
120pub fn unasked(pending: &Value, decide: &str) -> String {
121 let tool = pending["tool"].as_str().unwrap_or_default();
122 let reason = pending["reason"].as_str().unwrap_or_default();
123 let arguments = &pending["arguments"];
124 if tool == "run_command" {
125 let argv = argv_of(arguments);
126 let shown = crate::approvals::present::shell_quote(&argv);
127 if reason == NOT_ALLOWED {
128 let entry = argv
129 .iter()
130 .map(|a| serde_json::to_string(a).unwrap_or_default())
131 .collect::<Vec<_>>()
132 .join(", ");
133 return format!(
134 "`{shown}` needs approval: it is {NOT_ALLOWED} — allow exactly it in speccoder.toml (`[commands] allow = [[{entry}]]`), or {decide}"
135 );
136 }
137 return format!("`{shown}` needs approval: {reason} — {decide}");
138 }
139 if let Ok(o @ Object::Agent { .. }) =
141 serde_json::from_value::<Object>(pending["object"].clone())
142 {
143 return format!("{} needs approval: {reason} — {decide}", o.describe());
144 }
145 let object = arguments["path"]
146 .as_str()
147 .map(|p| format!(" `{p}`"))
148 .unwrap_or_default();
149 format!("`{tool}`{object} needs approval: {reason} — {decide}")
150}
151
152impl PartialEq for Object {
153 fn eq(&self, other: &Self) -> bool {
156 match (self, other) {
157 (Self::Path { canonical: a, .. }, Self::Path { canonical: b, .. }) => a == b,
158 (
159 Self::Command {
160 argv: a1,
161 argv_sha256: a2,
162 cwd: a3,
163 executable: a4,
164 network: a5,
165 },
166 Self::Command {
167 argv: b1,
168 argv_sha256: b2,
169 cwd: b3,
170 executable: b4,
171 network: b5,
172 },
173 ) => a1 == b1 && a2 == b2 && a3 == b3 && a4 == b4 && a5 == b5,
174 (Self::Tool { name: a, digest: x }, Self::Tool { name: b, digest: y }) => {
175 a == b && x == y
176 }
177 (
178 Self::Agent {
179 agent: a1,
180 call: a2,
181 argvs: a3,
182 paths: a4,
183 input: a5,
184 },
185 Self::Agent {
186 agent: b1,
187 call: b2,
188 argvs: b3,
189 paths: b4,
190 input: b5,
191 },
192 ) => a1 == b1 && a2 == b2 && a3 == b3 && a4 == b4 && a5 == b5,
193 _ => false,
194 }
195 }
196}
197
198impl Eq for Object {}
199
200#[must_use]
202pub fn argv_sha256(argv: &[String]) -> String {
203 use sha2::{Digest as _, Sha256};
204 let json = serde_json::to_string(argv).unwrap_or_default();
205 Sha256::digest(json.as_bytes())
206 .iter()
207 .map(|b| format!("{b:02x}"))
208 .collect()
209}
210
211fn first12(hex: &str) -> &str {
212 hex.get(..12).unwrap_or(hex)
213}
214
215impl Object {
216 #[must_use]
218 pub fn command(argv: Vec<String>, cwd: String, executable: String, network: bool) -> Self {
219 Self::Command {
220 argv_sha256: argv_sha256(&argv),
221 argv,
222 cwd,
223 executable,
224 network,
225 }
226 }
227
228 #[must_use]
230 pub const fn class(&self) -> Class {
231 match self {
232 Self::Path { .. } => Class::Write,
233 Self::Command { network: true, .. } => Class::Network,
234 Self::Command { .. } => Class::Command,
235 Self::Tool { .. } => Class::Mcp,
236 Self::Agent { .. } => Class::Agent,
237 }
238 }
239
240 #[must_use]
242 pub fn describe(&self) -> String {
243 match self {
244 Self::Path { canonical, .. } => format!("write `{canonical}`"),
245 Self::Command {
246 argv, cwd, network, ..
247 } => {
248 let place = if cwd == "." {
249 String::new()
250 } else {
251 format!(" in `{cwd}`")
252 };
253 let net = if *network { " with the network" } else { "" };
254 format!("run `{}`{place}{net}", argv.join(" "))
255 }
256 Self::Tool { name, digest } => format!("use `{name}`@{}", first12(digest)),
257 Self::Agent {
258 agent,
259 call: kind,
260 argvs,
261 paths,
262 ..
263 } => {
264 if kind == "reads" {
265 return format!("{agent}'s plain reads of one file each, for the task");
266 }
267 let what: Vec<String> = argvs
268 .iter()
269 .map(|a| format!("`{}`", a.join(" ")))
270 .chain(paths.iter().map(|p| format!("`{p}`")))
271 .collect();
272 format!("{agent} itself: {kind} {}", what.join(", "))
273 }
274 }
275 }
276
277 #[must_use]
281 pub fn grant_id(&self) -> String {
282 use sha2::{Digest as _, Sha256};
283 let identity = match self {
284 Self::Path { canonical, .. } => serde_json::json!({ "path": canonical }),
285 Self::Command {
286 argv,
287 argv_sha256,
288 cwd,
289 executable,
290 network,
291 } => serde_json::json!({
292 "argv": argv, "argv_sha256": argv_sha256, "cwd": cwd,
293 "executable": executable, "network": network,
294 }),
295 Self::Tool { name, digest } => serde_json::json!({ "tool": name, "digest": digest }),
296 Self::Agent {
297 agent,
298 call,
299 argvs,
300 paths,
301 input,
302 } => {
303 serde_json::json!({ "agent": agent, "call": call, "argvs": argvs, "paths": paths, "input": input })
304 }
305 };
306 let hex: String = Sha256::digest(identity.to_string().as_bytes())
307 .iter()
308 .take(8)
309 .map(|b| format!("{b:02x}"))
310 .collect();
311 format!("g-{hex}")
312 }
313
314 #[must_use]
317 pub fn short(&self) -> String {
318 match self {
319 Self::Path { canonical, .. } => canonical.clone(),
320 Self::Command { argv_sha256, .. } => format!("argv#{}", first12(argv_sha256)),
321 Self::Tool { name, digest } => format!("{name}@{}", first12(digest)),
322 Self::Agent { agent, call, .. } => {
323 format!("{agent}:{call}#{}", first12(&self.grant_id()))
324 }
325 }
326 }
327
328 #[must_use]
332 pub fn same_name(&self, other: &Self) -> bool {
333 match (self, other) {
334 (Self::Path { asked: a, .. }, Self::Path { asked: b, .. }) => a == b,
335 (
336 Self::Command {
337 argv: a,
338 network: x,
339 ..
340 },
341 Self::Command {
342 argv: b,
343 network: y,
344 ..
345 },
346 ) => a == b && x == y,
347 (Self::Tool { name: a, .. }, Self::Tool { name: b, .. }) => a == b,
348 _ => false,
349 }
350 }
351
352 #[must_use]
355 pub fn changed_from(&self, earlier: &Self) -> Option<String> {
356 if self == earlier || !self.same_name(earlier) {
357 return None;
358 }
359 let mut what = Vec::new();
360 match (earlier, self) {
361 (Self::Path { canonical: a, .. }, Self::Path { canonical: b, .. }) => {
362 what.push(format!("resolves to {b}, was {a}"));
363 }
364 (
365 Self::Command {
366 cwd: c1,
367 executable: e1,
368 ..
369 },
370 Self::Command {
371 cwd: c2,
372 executable: e2,
373 ..
374 },
375 ) => {
376 if e1 != e2 {
377 what.push(format!("executable {e1} → {e2}"));
378 }
379 if c1 != c2 {
380 what.push(format!("directory {c1} → {c2}"));
381 }
382 }
383 (Self::Tool { digest: a, .. }, Self::Tool { digest: b, .. }) => {
384 what.push(format!(
385 "definition @{} → @{} (the tool's definition changed since it was approved)",
386 first12(a),
387 first12(b)
388 ));
389 }
390 _ => {}
391 }
392 (!what.is_empty()).then(|| what.join("; "))
393 }
394
395 #[must_use]
397 pub fn tool_name(&self) -> Option<&str> {
398 match self {
399 Self::Tool { name, .. } => Some(name),
400 _ => None,
401 }
402 }
403
404 #[must_use]
406 pub fn path(&self) -> Option<&str> {
407 match self {
408 Self::Path { canonical, .. } => Some(canonical),
409 _ => None,
410 }
411 }
412}
413
414#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
416#[serde(deny_unknown_fields)]
417pub struct Rejection {
418 pub object: Object,
420 pub reason: String,
422}
423
424#[derive(Debug, Clone, Default)]
426pub struct Policy {
427 checks: Vec<Vec<String>>,
430 exact: std::collections::BTreeSet<Vec<String>>,
432 prefix: Vec<Vec<String>>,
434 protected: Protected,
435 frozen: std::collections::BTreeSet<String>,
436 approved: Vec<Object>,
437 rejected: Vec<Rejection>,
438 mcp: std::collections::BTreeMap<String, String>,
440 authoring: bool,
442 planning: Option<String>,
445 network_exact: std::collections::BTreeSet<Vec<String>>,
447 network_prefix: Vec<Vec<String>>,
449 in_place: bool,
452 hidden: Vec<String>,
455 autopilot: bool,
458 exploring: Option<Exploring>,
461}
462
463#[derive(Debug, Clone, Copy)]
465pub struct Exploring {
466 pub paths: fn(&str) -> bool,
468 pub commands: &'static [&'static [&'static str]],
470}
471
472pub const EXPLORING_WRITE: &str = "exploring writes nothing — the brief is made when the person chooses, and *Start spec* writes the spec";
474
475pub const AUTOPILOT_DENIED: &str = "autopilot: not asked — listed for you";
477
478#[must_use]
481pub fn prefix_matches(prefix: &[String], argv: &[String]) -> bool {
482 prefix.len() >= 2 && argv.starts_with(prefix)
483}
484
485#[must_use]
488pub fn prefix_refusal(prefix: &[String]) -> Option<&'static str> {
489 (prefix.len() < 2).then_some(
490 "a bare program allows any argument; add the exact command to [commands] allow instead",
491 )
492}
493
494const SHELLS: &[&str] = &[
495 "sh", "bash", "zsh", "fish", "dash", "ksh", "csh", "tcsh", "pwsh",
496];
497const PRIVILEGE: &[&str] = &["sudo", "su", "doas", "pkexec"];
498const NETWORK: &[&str] = &[
499 "curl", "wget", "nc", "ncat", "ssh", "scp", "sftp", "rsync", "ftp", "telnet",
500];
501const GIT_REMOTE: &[&str] = &[
502 "push",
503 "fetch",
504 "pull",
505 "clone",
506 "remote",
507 "ls-remote",
508 "submodule",
509];
510const GIT_IN_PLACE: &[&str] = &[
512 "checkout",
513 "switch",
514 "reset",
515 "commit",
516 "merge",
517 "rebase",
518 "cherry-pick",
519 "revert",
520 "stash",
521 "branch",
522 "tag",
523 "update-ref",
524 "worktree",
525 "am",
526];
527
528const RUNNERS: &[&[&str]] = &[
530 &["uv", "run"],
531 &["uv", "tool", "run"],
532 &["uvx"],
533 &["poetry", "run"],
534 &["pipx", "run"],
535 &["pdm", "run"],
536 &["hatch", "run"],
537];
538
539impl Policy {
540 #[must_use]
544 pub fn new(checks: &[Vec<String>], exact: &[Vec<String>]) -> Self {
545 let mut allowed: Vec<Vec<String>> = checks
546 .iter()
547 .map(|argv| {
548 let prefix: Vec<String> = argv
549 .iter()
550 .take_while(|a| !a.starts_with('-'))
551 .cloned()
552 .collect();
553 if (prefix.len() == 1
559 || RUNNERS.iter().any(|r| {
560 prefix
561 .iter()
562 .map(String::as_str)
563 .take(r.len())
564 .eq(r.iter().copied())
565 }))
566 && argv.len() > prefix.len()
567 {
568 argv.clone()
569 } else {
570 prefix
571 }
572 })
573 .filter(|p: &Vec<String>| !p.is_empty())
574 .collect();
575 allowed.sort();
576 allowed.dedup();
577 Self {
578 checks: allowed,
579 exact: exact.iter().filter(|p| !p.is_empty()).cloned().collect(),
580 ..Self::default()
581 }
582 }
583
584 #[must_use]
587 pub fn with_prefixes(mut self, prefixes: Vec<Vec<String>>) -> Self {
588 self.prefix = prefixes.into_iter().filter(|p| p.len() >= 2).collect();
589 self
590 }
591
592 #[must_use]
594 pub fn check_prefixes(&self) -> &[Vec<String>] {
595 &self.checks
596 }
597
598 #[must_use]
601 pub fn with_hidden(mut self, hidden: impl IntoIterator<Item = String>) -> Self {
602 self.hidden = hidden.into_iter().collect();
603 self
604 }
605
606 fn is_hidden(&self, rel: &str) -> bool {
609 self.protected.write_class(rel).is_none()
610 && !self.protected.is_context(rel)
611 && self.hidden.iter().any(|h| match h.strip_suffix('/') {
612 Some(dir) => rel == dir || rel.starts_with(h.as_str()),
613 None => rel == h,
614 })
615 }
616
617 #[must_use]
620 pub fn in_place(mut self) -> Self {
621 self.in_place = true;
622 self
623 }
624
625 #[must_use]
627 pub const fn autopilot(mut self) -> Self {
628 self.autopilot = true;
629 self
630 }
631
632 #[must_use]
634 pub const fn is_autopilot(&self) -> bool {
635 self.autopilot
636 }
637
638 #[must_use]
643 pub fn settle(&self, decision: Decision) -> Decision {
644 match decision {
645 Decision::Approval(_) if self.autopilot => Decision::Deny(AUTOPILOT_DENIED.to_owned()),
646 d => d,
647 }
648 }
649
650 #[must_use]
655 pub const fn exploring(mut self, e: Exploring) -> Self {
656 self.exploring = Some(e);
657 self
658 }
659
660 #[must_use]
664 pub fn authoring(mut self) -> Self {
665 self.authoring = true;
666 self
667 }
668
669 #[must_use]
674 pub fn planning(mut self, dir: &str) -> Self {
675 let dir = dir.trim_matches('/');
676 self.planning = (!dir.is_empty()).then(|| dir.to_owned());
677 self
678 }
679
680 #[must_use]
684 pub fn is_planning_write(&self, rel: &str) -> bool {
685 let Some(dir) = &self.planning else {
686 return false;
687 };
688 rel.strip_prefix(dir.as_str())
689 .and_then(|r| r.strip_prefix('/'))
690 .is_some_and(|r| {
691 !r.is_empty()
692 && !r.split('/').any(|s| s == ".." || s == ".")
693 && !(self.protected.rules().judged)(r.trim_end_matches('/'))
694 && self.protected.is_design_doc(rel)
695 && !self.protected.is_review(rel)
696 })
697 }
698
699 #[must_use]
702 pub fn rules(mut self, rules: &'static crate::format::Rules) -> Self {
703 self.protected = Protected::new(rules);
704 self
705 }
706
707 #[must_use]
709 pub fn with_network(mut self, exact: Vec<Vec<String>>) -> Self {
710 self.network_exact = exact.into_iter().filter(|p| !p.is_empty()).collect();
711 self
712 }
713
714 #[must_use]
717 pub fn with_network_prefixes(mut self, prefixes: Vec<Vec<String>>) -> Self {
718 self.network_prefix = prefixes.into_iter().filter(|p| p.len() >= 2).collect();
719 self
720 }
721
722 #[must_use]
725 pub fn network_allowed(&self, argv: &[String]) -> bool {
726 self.network_exact.contains(argv)
727 || self.network_prefix.iter().any(|p| prefix_matches(p, argv))
728 }
729
730 #[must_use]
732 pub fn with_mcp(mut self, tools: impl IntoIterator<Item = (String, String)>) -> Self {
733 self.mcp = tools.into_iter().collect();
734 self
735 }
736
737 #[must_use]
741 pub fn with_decisions(mut self, approved: Vec<Object>, rejected: Vec<Rejection>) -> Self {
742 self.approved = approved;
743 self.rejected = rejected;
744 self
745 }
746
747 #[must_use]
749 pub fn with_frozen(mut self, frozen: impl IntoIterator<Item = String>) -> Self {
750 self.frozen = frozen.into_iter().collect();
751 self
752 }
753
754 #[must_use]
756 pub fn protected(&self) -> &Protected {
757 &self.protected
758 }
759
760 #[must_use]
764 pub fn write_protected(&self, rel: &str) -> Option<super::paths::Class> {
765 if self.is_planning_write(rel) {
766 return None;
767 }
768 if self.authoring
769 && (self.protected.rules().authoring_path)(rel)
770 && !self.protected.is_secret(rel)
771 && !self.protected.is_review(rel)
772 {
773 return None;
774 }
775 self.protected.write_class(rel)
776 }
777
778 #[must_use]
783 pub fn classify(&self, tool: &str, args: &Value, object: Option<&Object>) -> Decision {
784 let decision = self.base(tool, args);
785 if !matches!(decision, Decision::Approval(_)) {
786 return decision;
787 }
788 let Some(object) = object else {
789 return decision;
790 };
791 if let Some(r) = self.rejected.iter().find(|r| r.object == *object) {
792 return Decision::Deny(format!("a person rejected this: {}", r.reason));
793 }
794 if self.approved.iter().any(|a| a == object) {
795 return Decision::Allow;
796 }
797 decision
798 }
799
800 #[must_use]
802 pub fn rejection(&self, object: &Object) -> Option<&Rejection> {
803 self.rejected.iter().find(|r| r.object == *object)
804 }
805
806 #[must_use]
808 pub fn approved(&self) -> &[Object] {
809 &self.approved
810 }
811
812 #[must_use]
816 pub fn rule(&self, tool: &str, args: &Value, object: Option<&Object>) -> String {
817 if self.autopilot && matches!(self.classify(tool, args, object), Decision::Approval(_)) {
818 return "autopilot".to_owned();
819 }
820 if let Some(object) = object
821 && matches!(self.base(tool, args), Decision::Approval(_))
822 {
823 if self.rejected.iter().any(|r| r.object == *object) {
824 return format!("rejection of {} for the task", object.describe());
825 }
826 if self.approved.iter().any(|a| a == object) {
827 return format!("grant {} for the task", object.describe());
828 }
829 }
830 if tool.starts_with(MCP_PREFIX) {
831 let entry = self.mcp.get(tool).map_or("unlisted", String::as_str);
832 return format!("[mcp] {entry}");
833 }
834 match tool {
835 "read_file" | "list_files" | "search_code" => "workspace read".to_owned(),
836 "write_file" | "edit_file" => "workspace write".to_owned(),
837 "git_status" | "git_diff" => "read-only git".to_owned(),
838 "run_command" => {
839 let argv = argv_of(args);
840 if self.exact.contains(&argv) {
841 return format!("exact command `{}`", argv.join(" "));
842 }
843 if let Some(p) = self
844 .checks
845 .iter()
846 .find(|p| argv.len() >= p.len() && argv[..p.len()] == p[..])
847 {
848 return format!("check prefix `{}`", p.join(" "));
849 }
850 match self.prefix.iter().find(|p| prefix_matches(p, &argv)) {
851 Some(p) => format!("allowed prefix `{}`", p.join(" ")),
852 None => "command policy".to_owned(),
853 }
854 }
855 _ => "tool policy".to_owned(),
856 }
857 }
858
859 #[must_use]
862 pub fn base(&self, tool: &str, args: &Value) -> Decision {
863 self.base_of(tool, args)
864 }
865
866 fn base_of(&self, tool: &str, args: &Value) -> Decision {
867 if let Some(e) = self.exploring {
868 return self.explore_of(e, tool, args);
869 }
870 if tool.starts_with(MCP_PREFIX) {
871 return match self.mcp.get(tool).map(String::as_str) {
872 Some("allow") => Decision::Allow,
873 Some("deny") => Decision::Deny(format!("`{tool}` is denied in [mcp]")),
874 Some(_) => Decision::Approval(format!(
875 "`{tool}` is an MCP tool; speccoder cannot know what it does"
876 )),
877 None => Decision::Deny(format!("unknown tool `{tool}`")),
878 };
879 }
880 match tool {
881 "read_file" | "list_files" | "search_code" => self.read(args),
882 "write_file" | "edit_file" => self.write(args),
883 "run_command" => self.with_network_rule(args, self.command(args)),
884 "git_status" | "git_diff" => Decision::Allow,
885 "git_log" | "git_show" | "journal_account" | "task_evidence" | "report" | "inbox"
888 | "explain" => Decision::Allow,
889 other => Decision::Deny(format!("unknown tool `{other}`")),
890 }
891 }
892
893 fn explore_of(&self, e: Exploring, tool: &str, args: &Value) -> Decision {
895 match tool {
896 "read_file" | "list_files" | "search_code" => self.read(args),
897 "git_status" | "git_diff" => Decision::Allow,
898 "write_file" | "edit_file" => {
899 let rel = args["path"]
900 .as_str()
901 .and_then(|p| super::paths::normalise(p).ok());
902 match rel {
905 Some(rel)
906 if (e.paths)(&rel)
907 && !self.protected.is_secret(&rel)
908 && !self.protected.is_review(&rel) =>
909 {
910 Decision::Allow
911 }
912 _ => Decision::Deny(EXPLORING_WRITE.to_owned()),
913 }
914 }
915 "run_command" => {
916 let argv = argv_of(args);
917 if args.get("network").and_then(Value::as_bool) == Some(true) {
918 return Decision::Deny("exploring has no network".to_owned());
919 }
920 if e.commands.iter().any(|p| {
921 argv.len() >= p.len() && argv.iter().zip(p.iter()).all(|(a, b)| a == b)
922 }) {
923 Decision::Allow
924 } else {
925 Decision::Deny(format!(
926 "exploring runs only the format's read-only commands; `{}` is not one",
927 argv.join(" ")
928 ))
929 }
930 }
931 other => Decision::Deny(format!("`{other}` is not used while exploring")),
932 }
933 }
934
935 fn with_network_rule(&self, args: &Value, decision: Decision) -> Decision {
938 if args.get("network").and_then(Value::as_bool) != Some(true)
939 || matches!(decision, Decision::Deny(_))
940 {
941 return decision;
942 }
943 let argv = argv_of(args);
944 if self.network_allowed(&argv) {
945 return decision;
946 }
947 Decision::Approval(format!(
948 "`{}` asks for the network; commands run without it",
949 argv.join(" ")
950 ))
951 }
952
953 fn read(&self, args: &Value) -> Decision {
954 let Some(path) = super::below_root(args.get("path").and_then(Value::as_str)) else {
955 return Decision::Allow; };
957 match normalise(path) {
958 Err(e) => Decision::Deny(e.0),
959 Ok(p) if self.protected.is_secret(&p) => {
960 Decision::Deny(format!("`{p}` looks like a credential"))
961 }
962 Ok(p) if self.is_hidden(&p) => Decision::Deny(format!(
963 "`{p}` is ignored by git in this checkout; an in-place run works only with what a worktree would hold"
964 )),
965 Ok(_) => Decision::Allow,
966 }
967 }
968
969 fn write(&self, args: &Value) -> Decision {
970 let Some(path) = args.get("path").and_then(Value::as_str) else {
971 return Decision::Deny("no `path`".to_owned());
972 };
973 let p = match normalise(path) {
974 Ok(p) => p,
975 Err(e) => return Decision::Deny(e.0),
976 };
977 if (self.authoring
978 && (self.protected.rules().authoring_path)(&p)
979 && !self.protected.is_secret(&p)
980 && !self.protected.is_review(&p))
981 || self.is_planning_write(&p)
982 {
983 return Decision::Allow;
984 }
985 if self.is_hidden(&p) {
986 return Decision::Deny(format!(
987 "`{p}` is ignored by git in this checkout; an in-place run does not write it"
988 ));
989 }
990 if self.protected.is_review(&p) {
991 return Decision::Deny(format!(
992 "`{p}` is protected: it records a person's review of the spec; only the person writes it (`speccoder review`)"
993 ));
994 }
995 if let Some(class) = self.protected.write_class(&p) {
996 return Decision::Deny(format!(
997 "`{p}` is protected: {}",
998 self.protected.reason(class)
999 ));
1000 }
1001 if self.authoring {
1002 return Decision::Approval((self.protected.rules().authoring_refusal)(&p));
1003 }
1004 if self.protected.is_context(&p) {
1005 return Decision::Approval(format!(
1006 "`{p}` is an agent context file: every later agent session reads it"
1007 ));
1008 }
1009 if self
1010 .frozen
1011 .iter()
1012 .any(|f| f.to_lowercase() == p.to_lowercase())
1013 {
1014 return Decision::Approval(format!(
1015 "`{p}` is a frozen test (it existed when the attempt started)"
1016 ));
1017 }
1018 if self.protected.is_manifest(&p) {
1019 return Decision::Approval(format!("`{p}` is a dependency manifest"));
1020 }
1021 Decision::Allow
1022 }
1023
1024 fn command(&self, args: &Value) -> Decision {
1025 let argv = argv_of(args);
1026 match (self.protected.rules().command)(&argv, self.authoring) {
1027 Some(Ok(())) => return Decision::Allow,
1028 Some(Err(why)) => return Decision::Deny(why),
1029 None => {}
1030 }
1031 let Some(program) = argv.first() else {
1032 return Decision::Deny("empty `argv`".to_owned());
1033 };
1034 let name = program.rsplit('/').next().unwrap_or(program);
1035 let has = |flag: &str| argv.iter().any(|a| a == flag);
1036
1037 if PRIVILEGE.contains(&name) {
1038 return Decision::Deny(format!("`{name}` raises privileges"));
1039 }
1040 if name == "git" {
1041 let sub = argv.get(1).map_or("", String::as_str);
1042 if GIT_REMOTE.contains(&sub) {
1043 return Decision::Deny(format!(
1044 "`git {sub}` talks to a remote; speccoder never does"
1045 ));
1046 }
1047 let notes_action = argv[2..]
1049 .iter()
1050 .find(|a| !a.starts_with('-'))
1051 .map_or("list", String::as_str);
1052 if (sub == "notes" && !matches!(notes_action, "show" | "list"))
1053 || (sub == "update-ref" && argv.iter().any(|a| a.starts_with("refs/notes")))
1054 {
1055 return Decision::Deny(
1056 "git notes are speccoder's attestations; only speccoder writes them".to_owned(),
1057 );
1058 }
1059 let listing_branches = sub == "branch"
1061 && argv[2..].iter().all(|a| {
1062 matches!(
1063 a.as_str(),
1064 "--show-current" | "--list" | "-l" | "-a" | "--all" | "-v" | "-vv"
1065 )
1066 });
1067 if matches!(
1068 sub,
1069 "rev-parse" | "status" | "log" | "diff" | "show" | "ls-files" | "describe"
1070 ) || listing_branches
1071 {
1072 return Decision::Allow;
1073 }
1074 if self.in_place
1075 && !listing_branches
1076 && (GIT_IN_PLACE.contains(&sub)
1077 || (sub == "apply" && has("--index"))
1078 || (sub == "restore" && has("--staged")))
1079 {
1080 return Decision::Deny(format!(
1081 "`git {sub}` would move the checkout of an in-place run; speccoder commits and switches it"
1082 ));
1083 }
1084 if sub == "clean" || (sub == "reset" && has("--hard")) || sub == "filter-branch" {
1085 return Decision::Deny(format!("`git {sub}` destroys work"));
1086 }
1087 if matches!(
1088 sub,
1089 "commit"
1090 | "checkout"
1091 | "switch"
1092 | "rebase"
1093 | "merge"
1094 | "stash"
1095 | "branch"
1096 | "tag"
1097 | "config"
1098 | "worktree"
1099 ) {
1100 return Decision::Approval(format!("`git {sub}` changes repository state"));
1101 }
1102 }
1103 if SHELLS.contains(&name) || name == "eval" || name == "env" || name == "xargs" {
1104 return Decision::Approval(format!("`{name}` runs arbitrary commands"));
1105 }
1106 if NETWORK.contains(&name) {
1107 return Decision::Approval(format!("`{name}` uses the network"));
1108 }
1109 if name == "rm" && argv.iter().any(|a| a.starts_with('-') && a.contains('r')) {
1110 return Decision::Approval("recursive `rm`".to_owned());
1111 }
1112 if argv.len() == 2 && matches!(argv[1].as_str(), "--version" | "-V" | "version") {
1114 return Decision::Allow;
1115 }
1116 if self.exact.contains(&argv)
1119 || self
1120 .checks
1121 .iter()
1122 .any(|prefix| argv.len() >= prefix.len() && argv[..prefix.len()] == prefix[..])
1123 || self.prefix.iter().any(|p| prefix_matches(p, &argv))
1124 {
1125 return Decision::Allow;
1126 }
1127 Decision::Approval(NOT_ALLOWED.to_owned())
1128 }
1129}
1130
1131#[must_use]
1133pub fn argv_of(args: &Value) -> Vec<String> {
1134 args.get("argv")
1135 .and_then(Value::as_array)
1136 .map(|a| {
1137 a.iter()
1138 .filter_map(|v| v.as_str().map(str::to_owned))
1139 .collect()
1140 })
1141 .unwrap_or_default()
1142}
1143
1144#[cfg(test)]
1145mod tests {
1146 use super::*;
1147 use serde_json::json;
1148
1149 fn policy() -> Policy {
1150 let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
1151 Policy::new(
1152 &[
1153 argv("cargo nextest run --workspace --profile speccoder"),
1154 argv("cargo clippy --workspace -- -D warnings"),
1155 ],
1156 &[],
1157 )
1158 .with_prefixes(vec![argv("cargo fmt"), argv("cargo check")])
1159 }
1160
1161 #[test]
1162 fn an_unasked_call_is_named_with_how_to_let_it_run() {
1163 let decide = "run with prompts";
1164 let refused = policy().classify("run_command", &json!({"argv": ["npm", "i"]}), None);
1165 let Decision::Approval(reason) = refused else {
1166 panic!("{refused:?}")
1167 };
1168 let m = unasked(
1169 &json!({"tool": "run_command", "arguments": {"argv": ["make", "it's"]}, "reason": reason}),
1170 decide,
1171 );
1172 assert_eq!(
1173 m,
1174 "`make 'it'\\''s'` needs approval: it is not a configured check or allowed command — allow exactly it in speccoder.toml (`[commands] allow = [[\"make\", \"it's\"]]`), or run with prompts"
1175 );
1176 let m = unasked(
1178 &json!({"tool": "run_command", "arguments": {"argv": ["sh", "-c", "x"]}, "reason": "`sh` runs arbitrary commands"}),
1179 decide,
1180 );
1181 assert_eq!(
1182 m,
1183 "`sh -c x` needs approval: `sh` runs arbitrary commands — run with prompts"
1184 );
1185 let m = unasked(
1186 &json!({"tool": "write_file", "arguments": {"path": "Cargo.toml"}, "reason": "`Cargo.toml` is a dependency manifest"}),
1187 decide,
1188 );
1189 assert_eq!(
1190 m,
1191 "`write_file` `Cargo.toml` needs approval: `Cargo.toml` is a dependency manifest — run with prompts"
1192 );
1193 }
1194
1195 fn path(canonical: &str, asked: &str) -> Object {
1196 Object::Path {
1197 canonical: canonical.to_owned(),
1198 asked: asked.to_owned(),
1199 }
1200 }
1201
1202 fn command(s: &str) -> Object {
1203 Object::command(
1204 s.split(' ').map(str::to_owned).collect(),
1205 ".".to_owned(),
1206 "/usr/bin/x".to_owned(),
1207 false,
1208 )
1209 }
1210
1211 fn cmd(s: &str) -> Value {
1212 json!({ "argv": s.split(' ').collect::<Vec<_>>() })
1213 }
1214
1215 #[test]
1216 fn classifies_the_table() {
1217 use Decision::{Allow, Approval, Deny};
1218 let p = policy();
1219 let kind = |d: Decision| match d {
1220 Allow => "allow",
1221 Approval(_) => "approval",
1222 Deny(_) => "deny",
1223 };
1224 let cases: &[(&str, Value, &str)] = &[
1225 ("read_file", json!({"path": "src/lib.rs"}), "allow"),
1226 ("read_file", json!({"path": ".env"}), "deny"),
1227 ("read_file", json!({"path": "../secret"}), "deny"),
1228 ("list_files", json!({}), "allow"),
1229 ("search_code", json!({"pattern": "fn main"}), "allow"),
1230 ("write_file", json!({"path": "src/new.rs"}), "allow"),
1231 ("edit_file", json!({"path": "specs/001-x/tasks.md"}), "deny"),
1232 ("write_file", json!({"path": "speccoder.toml"}), "deny"),
1233 (
1234 "write_file",
1235 json!({"path": ".github/workflows/ci.yml"}),
1236 "deny",
1237 ),
1238 (
1239 "write_file",
1240 json!({"path": ".git/hooks/pre-commit"}),
1241 "deny",
1242 ),
1243 ("edit_file", json!({"path": "Cargo.toml"}), "approval"),
1244 ("edit_file", json!({"path": "web/package.json"}), "approval"),
1245 ("run_command", cmd("cargo nextest run -p x"), "allow"),
1246 ("run_command", cmd("cargo clippy --all-targets"), "allow"),
1247 ("run_command", cmd("cargo fmt --all"), "allow"),
1248 ("run_command", cmd("cargo build"), "approval"),
1249 ("run_command", cmd("cargo --version"), "allow"),
1250 ("run_command", cmd("rustc -V"), "allow"),
1251 ("run_command", cmd("sudo --version"), "deny"),
1252 ("run_command", cmd("npm install left-pad"), "approval"),
1253 ("run_command", cmd("git push origin main"), "deny"),
1254 ("run_command", cmd("git fetch"), "deny"),
1255 ("run_command", cmd("git reset --hard HEAD"), "deny"),
1256 ("run_command", cmd("git clean -fdx"), "deny"),
1257 ("run_command", cmd("git commit -m x"), "approval"),
1258 (
1259 "run_command",
1260 cmd("git rev-parse --is-inside-work-tree"),
1261 "allow",
1262 ),
1263 ("run_command", cmd("git branch --show-current"), "allow"),
1264 ("run_command", cmd("git branch feature-x"), "approval"),
1265 ("run_command", cmd("git log --oneline -3"), "allow"),
1266 ("run_command", cmd("sh -c ls"), "approval"),
1267 ("run_command", cmd("sudo cargo test"), "deny"),
1268 ("run_command", cmd("curl https://example.com"), "approval"),
1269 ("run_command", cmd("rm -rf target"), "approval"),
1270 ("run_command", json!({"argv": []}), "deny"),
1271 ("git_status", json!({}), "allow"),
1272 ("git_diff", json!({}), "allow"),
1273 ("delete_everything", json!({}), "deny"),
1274 ];
1275 for (tool, args, want) in cases {
1276 assert_eq!(kind(p.classify(tool, args, None)), *want, "{tool} {args}");
1277 }
1278 }
1279
1280 #[test]
1281 fn decisions_cover_classes_and_never_override_a_denial() {
1282 let approved = vec![
1283 path("Cargo.toml", "Cargo.toml"),
1284 command("cargo build"),
1285 path("speccoder.toml", "speccoder.toml"),
1286 command("curl https://x"),
1288 ];
1289 let rejected = vec![Rejection {
1290 object: command("curl https://x"),
1291 reason: "no network".to_owned(),
1292 }];
1293 let p = policy().with_decisions(approved, rejected);
1294 assert_eq!(
1296 p.classify(
1297 "edit_file",
1298 &json!({"path": "./Cargo.toml", "old_string": "a"}),
1299 Some(&path("Cargo.toml", "./Cargo.toml"))
1300 ),
1301 Decision::Allow
1302 );
1303 assert!(matches!(
1305 p.classify("edit_file", &json!({"path": "Cargo.toml"}), None),
1306 Decision::Approval(_)
1307 ));
1308 assert_eq!(
1309 p.classify(
1310 "run_command",
1311 &cmd("cargo build"),
1312 Some(&command("cargo build"))
1313 ),
1314 Decision::Allow
1315 );
1316 assert!(matches!(
1317 p.classify(
1318 "run_command",
1319 &cmd("cargo build --release"),
1320 Some(&command("cargo build --release"))
1321 ),
1322 Decision::Approval(_)
1323 ));
1324 assert_eq!(
1326 p.classify(
1327 "run_command",
1328 &cmd("curl https://x"),
1329 Some(&command("curl https://x"))
1330 ),
1331 Decision::Deny("a person rejected this: no network".to_owned())
1332 );
1333 assert!(matches!(
1335 p.classify("write_file", &json!({"path": "speccoder.toml"}), None),
1336 Decision::Deny(_)
1337 ));
1338 let p = Policy::new(&[], &[]);
1340 for argv in [
1341 vec![
1342 "git",
1343 "notes",
1344 "--ref=speccoder",
1345 "add",
1346 "-f",
1347 "-m",
1348 "x",
1349 "HEAD",
1350 ],
1351 vec!["git", "notes", "remove", "HEAD"],
1352 vec!["git", "update-ref", "refs/notes/speccoder", "HEAD"],
1353 ] {
1354 assert!(
1355 matches!(
1356 p.classify("run_command", &json!({ "argv": argv }), None),
1357 Decision::Deny(_)
1358 ),
1359 "{argv:?}"
1360 );
1361 }
1362 for argv in [
1363 vec!["git", "notes", "--ref=speccoder", "show", "HEAD"],
1364 vec!["git", "notes", "list"],
1365 ] {
1366 assert!(
1367 !matches!(
1368 p.classify("run_command", &json!({ "argv": argv }), None),
1369 Decision::Deny(_)
1370 ),
1371 "{argv:?}"
1372 );
1373 }
1374 let in_place = Policy::new(&[], &[]).in_place();
1376 for argv in [
1377 vec!["git", "switch", "main"],
1378 vec!["git", "commit", "-m", "x"],
1379 vec!["git", "reset", "HEAD~1"],
1380 vec!["git", "stash"],
1381 vec!["git", "branch", "x"],
1382 vec!["git", "apply", "--index", "p.diff"],
1383 vec!["git", "restore", "--staged", "a"],
1384 vec!["git", "update-ref", "HEAD", "x"],
1385 ] {
1386 assert!(
1387 matches!(
1388 in_place.classify("run_command", &json!({ "argv": argv }), None),
1389 Decision::Deny(_)
1390 ),
1391 "{argv:?}"
1392 );
1393 }
1394 for argv in [
1395 vec!["git", "status"],
1396 vec!["git", "branch", "--show-current"],
1397 ] {
1398 assert_eq!(
1399 in_place.classify("run_command", &json!({ "argv": argv }), None),
1400 Decision::Allow,
1401 "{argv:?}"
1402 );
1403 }
1404 let hidden = Policy::new(&[], &[]).in_place().with_hidden([
1406 "target/".to_owned(),
1407 "notes.txt".to_owned(),
1408 "specs/".to_owned(),
1409 ]);
1410 for (tool, path) in [
1411 ("read_file", "target/debug/x"),
1412 ("read_file", "notes.txt"),
1413 ("list_files", "target"),
1414 ("write_file", "notes.txt"),
1415 ] {
1416 assert!(
1417 matches!(
1418 hidden.classify(tool, &json!({ "path": path }), None),
1419 Decision::Deny(_)
1420 ),
1421 "{tool} {path}"
1422 );
1423 }
1424 assert_eq!(
1425 hidden.classify("read_file", &json!({ "path": "specs/001-x/spec.md" }), None),
1426 Decision::Allow
1427 );
1428 assert_eq!(
1429 hidden.classify("read_file", &json!({ "path": "src/lib.rs" }), None),
1430 Decision::Allow
1431 );
1432 assert!(matches!(
1433 Policy::new(&[], &[]).classify(
1434 "run_command",
1435 &json!({ "argv": ["git", "switch", "main"] }),
1436 None
1437 ),
1438 Decision::Approval(_)
1439 ));
1440 }
1441
1442 #[test]
1443 fn a_check_through_a_runner_allows_only_itself() {
1444 let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
1445 let check = "uv run --locked --offline python -m pytest -q --junitxml=.speccoder/junit.xml";
1446 let p = Policy::new(&[argv(check), argv("poetry run pytest -q")], &[]);
1447 assert_eq!(
1448 p.classify("run_command", &cmd(check), None),
1449 Decision::Allow
1450 );
1451 for other in [
1452 "uv run python -c print(1)",
1453 "uv run --locked --offline sh",
1454 "poetry run sh",
1455 ] {
1456 assert!(
1457 matches!(
1458 p.classify("run_command", &cmd(other), None),
1459 Decision::Approval(_)
1460 ),
1461 "{other}"
1462 );
1463 }
1464 }
1465
1466 #[test]
1467 fn a_check_whose_prefix_is_its_bare_program_allows_only_itself() {
1468 let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
1469 let p = Policy::new(
1470 &[argv("python3 -m pytest -q --junitxml=.speccoder/junit.xml")],
1471 &[],
1472 );
1473 assert_eq!(
1474 p.classify(
1475 "run_command",
1476 &cmd("python3 -m pytest -q --junitxml=.speccoder/junit.xml"),
1477 None
1478 ),
1479 Decision::Allow
1480 );
1481 assert!(matches!(
1482 p.classify("run_command", &cmd("python3 -c print(1)"), None),
1483 Decision::Approval(_)
1484 ));
1485 assert!(matches!(
1486 p.classify("run_command", &cmd("python3 -m pytest tests/x.py"), None),
1487 Decision::Approval(_)
1488 ));
1489 let q = Policy::new(&[], &[argv("python3 -m pytest")]);
1491 assert!(matches!(
1492 q.classify("run_command", &cmd("python3 -m pytest tests/x.py"), None),
1493 Decision::Approval(_)
1494 ));
1495 assert_eq!(
1496 q.classify("run_command", &cmd("python3 -m pytest"), None),
1497 Decision::Allow
1498 );
1499 }
1500
1501 #[test]
1502 fn mcp_tools_follow_their_configured_decision_and_unknown_ones_are_denied() {
1503 let p = Policy::new(&[], &[]).with_mcp([
1504 ("mcp__db__query".to_owned(), "allow".to_owned()),
1505 ("mcp__db__drop".to_owned(), "deny".to_owned()),
1506 ("mcp__db__insert".to_owned(), "approval".to_owned()),
1507 ]);
1508 assert_eq!(
1509 p.classify("mcp__db__query", &json!({}), None),
1510 Decision::Allow
1511 );
1512 assert!(matches!(
1513 p.classify("mcp__db__drop", &json!({}), None),
1514 Decision::Deny(_)
1515 ));
1516 assert!(matches!(
1517 p.classify("mcp__db__insert", &json!({}), None),
1518 Decision::Approval(_)
1519 ));
1520 assert!(matches!(
1521 p.classify("mcp__db__other", &json!({}), None),
1522 Decision::Deny(_)
1523 ));
1524 let tool = |name: &str, digest: &str| Object::Tool {
1526 name: name.to_owned(),
1527 digest: digest.to_owned(),
1528 };
1529 let q = p.clone().with_decisions(
1530 vec![tool("mcp__db__insert", "d1"), tool("mcp__db__drop", "d1")],
1531 Vec::new(),
1532 );
1533 assert_eq!(
1534 q.classify(
1535 "mcp__db__insert",
1536 &json!({ "row": 1 }),
1537 Some(&tool("mcp__db__insert", "d1"))
1538 ),
1539 Decision::Allow
1540 );
1541 assert!(matches!(
1543 q.classify(
1544 "mcp__db__insert",
1545 &json!({ "row": 1 }),
1546 Some(&tool("mcp__db__insert", "d2"))
1547 ),
1548 Decision::Approval(_)
1549 ));
1550 assert!(matches!(
1551 q.classify(
1552 "mcp__db__drop",
1553 &json!({}),
1554 Some(&tool("mcp__db__drop", "d1"))
1555 ),
1556 Decision::Deny(_)
1557 ));
1558 assert_eq!(
1559 tool("mcp__db__insert", "9f8e7d6c5b4a3210").short(),
1560 "mcp__db__insert@9f8e7d6c5b4a"
1561 );
1562 assert!(
1563 tool("mcp__db__insert", "d2")
1564 .changed_from(&tool("mcp__db__insert", "d1"))
1565 .is_some_and(|c| c.contains("definition changed"))
1566 );
1567 }
1568
1569 #[test]
1570 fn a_planning_task_writes_design_docs_in_its_unit_never_a_judged_file() {
1571 let p = Policy::new(&[], &[]).planning("specs/001-x/");
1572 let w = |path: &str| p.classify("write_file", &json!({ "path": path }), None);
1573 assert_eq!(w("specs/001-x/contracts/cli.md"), Decision::Allow);
1574 assert_eq!(w("specs/001-x/data-model.md"), Decision::Allow);
1575 assert_eq!(w("specs/001-x/plan.md"), Decision::Allow);
1576 assert_eq!(p.write_protected("specs/001-x/contracts/cli.md"), None);
1577 for judged in [
1580 "specs/001-x/spec.md",
1581 "specs/001-x/tasks.md",
1582 "specs/001-x/review.json",
1583 "specs/001-x/checklists/ux.md",
1584 "specs/001-x/contracts/../spec.md",
1585 ".specify/memory/constitution.md",
1586 "specs/002-y/contracts/cli.md",
1587 "specs/001-x/.env",
1588 "specs/001-x/.git/config",
1591 "specs/001-x/speccoder.toml",
1592 "specs/001-x/vitest.config.ts",
1593 "specs/001-x/.mcp.json",
1594 "specs/001-x/.claude/settings.json",
1595 "specs/001-x/AGENTS.md",
1596 "specs/001-x/CLAUDE.md",
1597 "specs/001-x/package.json",
1598 "specs/001-x/Cargo.toml",
1599 "specs/001-x/.hidden.md",
1600 ] {
1601 assert!(matches!(w(judged), Decision::Deny(_)), "{judged}");
1602 assert!(!p.is_planning_write(judged), "{judged}");
1603 }
1604 assert!(p.write_protected("specs/001-x/spec.md").is_some());
1605 assert_eq!(w("src/lib.rs"), Decision::Allow);
1607 assert!(matches!(w("Cargo.toml"), Decision::Approval(_)));
1608 let normal = Policy::new(&[], &[]);
1610 assert!(matches!(
1611 normal.classify(
1612 "write_file",
1613 &json!({ "path": "specs/001-x/contracts/cli.md" }),
1614 None
1615 ),
1616 Decision::Deny(_)
1617 ));
1618 let o = Policy::new(&[], &[])
1620 .rules(crate::format::Adapter::rules(
1621 &crate::format::openspec::OPENSPEC,
1622 ))
1623 .planning("openspec/changes/add-x");
1624 assert!(o.is_planning_write("openspec/changes/add-x/design.md"));
1625 for judged in ["proposal.md", "tasks.md", "specs/auth/spec.md"] {
1626 assert!(
1627 !o.is_planning_write(&format!("openspec/changes/add-x/{judged}")),
1628 "{judged}"
1629 );
1630 }
1631 }
1632
1633 #[test]
1634 fn the_authoring_profile_writes_spec_kit_artifacts_and_runs_its_scripts_only() {
1635 let p = Policy::new(&[], &[]).authoring();
1636 let w = |path: &str| p.classify("write_file", &json!({ "path": path }), None);
1637 assert_eq!(w("specs/002-login/spec.md"), Decision::Allow);
1638 assert_eq!(w(".specify/feature.json"), Decision::Allow);
1639 assert_eq!(w(".specify/memory/constitution.md"), Decision::Allow);
1640 assert!(matches!(
1641 w(".specify/scripts/bash/common.sh"),
1642 Decision::Deny(_)
1643 ));
1644 assert!(matches!(
1645 w(".specify/templates/spec-template.md"),
1646 Decision::Deny(_)
1647 ));
1648 assert!(matches!(w("speccoder.toml"), Decision::Deny(_)));
1649 assert!(matches!(w("specs/.env"), Decision::Deny(_)));
1650 assert!(
1652 matches!(w("specs/002-login/review.json"), Decision::Deny(ref why) if why.contains("review")),
1653 "{:?}",
1654 w("specs/002-login/review.json")
1655 );
1656 assert!(p.write_protected("specs/002-login/review.json").is_some());
1657 assert!(matches!(w("src/lib.rs"), Decision::Approval(_)));
1658 let run = |argv: &[&str]| p.classify("run_command", &json!({ "argv": argv }), None);
1659 assert_eq!(
1660 run(&[".specify/scripts/bash/setup-plan.sh", "--json"]),
1661 Decision::Allow
1662 );
1663 assert_eq!(
1664 run(&[
1665 "bash",
1666 "./.specify/scripts/bash/check-prerequisites.sh",
1667 "--json"
1668 ]),
1669 Decision::Allow
1670 );
1671 assert!(matches!(
1672 run(&["bash", ".specify/scripts/bash/../../evil.sh"]),
1673 Decision::Approval(_)
1674 ));
1675 assert_eq!(
1676 run(&[
1677 "bash",
1678 ".specify/extensions/git/scripts/bash/create-new-feature-branch.sh",
1679 "--json"
1680 ]),
1681 Decision::Allow
1682 );
1683 assert!(matches!(
1684 run(&["bash", ".specify/extensions/git/other.sh"]),
1685 Decision::Approval(_)
1686 ));
1687 assert!(matches!(
1688 run(&["bash", "-c", "rm -rf /"]),
1689 Decision::Approval(_)
1690 ));
1691 assert!(matches!(
1693 Policy::new(&[], &[]).classify(
1694 "write_file",
1695 &json!({ "path": "specs/002-login/spec.md" }),
1696 None
1697 ),
1698 Decision::Deny(_)
1699 ));
1700 }
1701
1702 #[test]
1703 fn asking_for_the_network_needs_a_person_unless_allowed() {
1704 let checks = [vec!["cargo".to_owned(), "test".to_owned()]];
1705 let p = Policy::new(&checks, &[]);
1706 let net = json!({ "argv": ["cargo", "test"], "network": true });
1707 assert!(matches!(
1708 p.classify("run_command", &net, None),
1709 Decision::Approval(_)
1710 ));
1711 assert_eq!(
1713 p.classify("run_command", &json!({ "argv": ["cargo", "test"] }), None),
1714 Decision::Allow
1715 );
1716 assert!(matches!(
1717 p.classify(
1718 "run_command",
1719 &json!({ "argv": ["git", "push"], "network": true }),
1720 None
1721 ),
1722 Decision::Deny(_)
1723 ));
1724 let exact = p
1726 .clone()
1727 .with_network(vec![vec!["cargo".to_owned(), "test".to_owned()]]);
1728 assert_eq!(exact.classify("run_command", &net, None), Decision::Allow);
1729 let longer = json!({ "argv": ["cargo", "test", "--release"], "network": true });
1730 assert!(matches!(
1731 exact.classify("run_command", &longer, None),
1732 Decision::Approval(_)
1733 ));
1734 let bare = p.clone().with_network(vec![vec!["cargo".to_owned()]]);
1735 assert!(matches!(
1736 bare.classify("run_command", &net, None),
1737 Decision::Approval(_)
1738 ));
1739 let prefixed = p.clone().with_network_prefixes(vec![
1740 vec!["cargo".to_owned()],
1741 vec!["cargo".to_owned(), "test".to_owned()],
1742 ]);
1743 assert_eq!(
1744 prefixed.classify("run_command", &longer, None),
1745 Decision::Allow
1746 );
1747 let object = Object::command(
1748 vec!["cargo".to_owned(), "test".to_owned()],
1749 ".".to_owned(),
1750 "/usr/bin/cargo".to_owned(),
1751 true,
1752 );
1753 let approved = Policy::new(&checks, &[]).with_decisions(vec![object.clone()], vec![]);
1754 assert_eq!(
1755 approved.classify("run_command", &net, Some(&object)),
1756 Decision::Allow
1757 );
1758 let shadowed = Object::command(
1760 vec!["cargo".to_owned(), "test".to_owned()],
1761 ".".to_owned(),
1762 "/w/bin/cargo".to_owned(),
1763 true,
1764 );
1765 assert!(matches!(
1766 approved.classify("run_command", &net, Some(&shadowed)),
1767 Decision::Approval(_)
1768 ));
1769 assert!(
1770 shadowed
1771 .changed_from(&object)
1772 .is_some_and(|c| c == "executable /usr/bin/cargo → /w/bin/cargo")
1773 );
1774 }
1775
1776 #[test]
1777 fn commands_allow_is_exact_and_prefixes_need_two_elements() {
1778 let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
1779 let p = Policy::new(&[], &[argv("npm run build")]);
1780 assert_eq!(
1781 p.classify("run_command", &cmd("npm run build"), None),
1782 Decision::Allow
1783 );
1784 for longer in [
1785 "npm run build --script-shell=/tmp/x",
1786 "npm run build x",
1787 "npm run",
1788 ] {
1789 assert!(
1790 matches!(
1791 p.classify("run_command", &cmd(longer), None),
1792 Decision::Approval(_)
1793 ),
1794 "{longer}"
1795 );
1796 }
1797 assert_eq!(
1798 p.rule("run_command", &cmd("npm run build"), None),
1799 "exact command `npm run build`"
1800 );
1801 let q = Policy::new(&[], &[]).with_prefixes(vec![argv("npm"), argv("npm run")]);
1802 assert_eq!(
1803 q.classify("run_command", &cmd("npm run build"), None),
1804 Decision::Allow
1805 );
1806 assert_eq!(
1807 q.rule("run_command", &cmd("npm run build"), None),
1808 "allowed prefix `npm run`"
1809 );
1810 assert!(matches!(
1812 q.classify("run_command", &cmd("npm install x"), None),
1813 Decision::Approval(_)
1814 ));
1815 assert!(
1816 prefix_refusal(&argv("npm")).is_some() && prefix_refusal(&argv("npm run")).is_none()
1817 );
1818 let r = Policy::new(&[], &[argv("sh -c ls")]).with_prefixes(vec![argv("git push")]);
1820 assert!(matches!(
1821 r.classify("run_command", &cmd("sh -c ls"), None),
1822 Decision::Approval(_)
1823 ));
1824 assert!(matches!(
1825 r.classify("run_command", &cmd("git push origin"), None),
1826 Decision::Deny(_)
1827 ));
1828 }
1829
1830 #[test]
1831 fn autopilot_never_asks_never_lifts_a_denial_and_names_its_rule() {
1832 let argv = |s: &str| s.split(' ').map(str::to_owned).collect::<Vec<_>>();
1833 let p = Policy::new(&[], &[argv("cargo test")]).autopilot();
1834 assert!(p.is_autopilot());
1835 assert_eq!(
1837 p.settle(p.classify("run_command", &cmd("cargo test"), None)),
1838 Decision::Allow
1839 );
1840 assert_eq!(
1841 p.settle(p.classify("run_command", &cmd("cargo add x"), None)),
1842 Decision::Deny(AUTOPILOT_DENIED.to_owned())
1843 );
1844 assert_eq!(
1845 p.rule("run_command", &cmd("cargo add x"), None),
1846 "autopilot"
1847 );
1848 assert!(matches!(
1849 p.settle(p.classify("run_command", &cmd("git push origin"), None)),
1850 Decision::Deny(r) if r != AUTOPILOT_DENIED
1851 ));
1852 let q = Policy::new(&[], &[]);
1854 assert!(matches!(
1855 q.settle(q.classify("run_command", &cmd("cargo add x"), None)),
1856 Decision::Approval(_)
1857 ));
1858 let a = command("make check");
1860 let mut b = a.clone();
1861 if let Object::Command { cwd, .. } = &mut b {
1862 *cwd = "sub".to_owned();
1863 }
1864 assert_ne!(a.grant_id(), b.grant_id());
1865 assert_eq!(a.grant_id(), a.clone().grant_id());
1866 assert_eq!(
1867 path("src/b/x.rs", "src/a/x.rs").grant_id(),
1868 path("src/b/x.rs", "src/b/x.rs").grant_id()
1869 );
1870 assert!(a.grant_id().starts_with("g-") && a.grant_id().len() == 18);
1871 }
1872
1873 proptest::proptest! {
1874 #[test]
1875 fn on_autopilot_no_call_waits_for_a_person(words in proptest::collection::vec("[a-z]{1,6}", 1..4), tool in 0usize..4) {
1876 let p = Policy::new(&[], &[]).autopilot();
1877 let argv: Vec<String> = words.clone();
1878 let (name, args) = match tool {
1879 0 => ("run_command", json!({ "argv": argv })),
1880 1 => ("write_file", json!({ "path": format!("src/{}.rs", words[0]), "content": "" })),
1881 2 => ("write_file", json!({ "path": format!(".github/{}.yml", words[0]), "content": "" })),
1882 _ => ("mcp__x__y", json!({})),
1883 };
1884 let before = Policy::new(&[], &[]).classify(name, &args, None);
1885 let after = p.settle(p.classify(name, &args, None));
1886 proptest::prop_assert!(!matches!(after, Decision::Approval(_)));
1887 if matches!(before, Decision::Deny(_)) {
1888 proptest::prop_assert!(matches!(after, Decision::Deny(_)));
1889 }
1890 if before == Decision::Allow {
1891 proptest::prop_assert_eq!(after, Decision::Allow);
1892 }
1893 }
1894 }
1895
1896 const OPENSPEC_READS: &[&[&str]] = &[&["openspec", "list"], &["openspec", "show"]];
1897
1898 fn exploring() -> Policy {
1899 Policy::new(&[vec!["cargo".to_owned(), "test".to_owned()]], &[]).exploring(Exploring {
1900 paths: |rel| rel.starts_with(".specify/assessments/"),
1901 commands: OPENSPEC_READS,
1902 })
1903 }
1904
1905 proptest::proptest! {
1906 #[test]
1910 fn exploring_denies_what_it_does_not_allow_and_never_asks(words in proptest::collection::vec("[a-z]{1,6}", 1..4), tool in 0usize..6) {
1911 let p = exploring();
1912 let (name, args) = match tool {
1913 0 => ("run_command", json!({ "argv": words })),
1914 1 => ("run_command", json!({ "argv": ["cargo", "test"] })),
1915 2 => ("write_file", json!({ "path": format!("src/{}.rs", words[0]), "content": "" })),
1916 3 => ("edit_file", json!({ "path": format!("specs/{}/spec.md", words[0]), "old_string": "a", "new_string": "b" })),
1917 4 => ("run_command", json!({ "argv": ["openspec", "list", words[0].clone()], "network": true })),
1918 _ => ("mcp__x__y", json!({})),
1919 };
1920 let d = p.classify(name, &args, None);
1921 proptest::prop_assert!(matches!(d, Decision::Deny(_)), "{name} {args} → {d:?}");
1922 }
1923 }
1924
1925 #[test]
1926 fn exploring_reads_and_runs_the_formats_read_only_commands() {
1927 let p = exploring();
1928 assert_eq!(
1929 p.classify("read_file", &json!({ "path": "src/lib.rs" }), None),
1930 Decision::Allow
1931 );
1932 assert_eq!(
1933 p.classify(
1934 "run_command",
1935 &json!({ "argv": ["openspec", "list", "--json"] }),
1936 None
1937 ),
1938 Decision::Allow
1939 );
1940 assert_eq!(
1941 p.classify(
1942 "write_file",
1943 &json!({ "path": ".specify/assessments/csv/notes.md", "content": "" }),
1944 None
1945 ),
1946 Decision::Allow
1947 );
1948 let Decision::Deny(why) = p.classify(
1949 "write_file",
1950 &json!({ "path": "notes.md", "content": "" }),
1951 None,
1952 ) else {
1953 panic!("a write outside the exploration paths is denied");
1954 };
1955 assert_eq!(why, EXPLORING_WRITE);
1956 }
1957
1958 #[test]
1959 fn a_path_object_is_its_canonical_file_whatever_the_spelling() {
1960 assert_eq!(
1961 path("src/b/x.rs", "src/a/x.rs"),
1962 path("src/b/x.rs", "src/b/x.rs")
1963 );
1964 assert_ne!(
1965 path("src/b/x.rs", "src/a/x.rs"),
1966 path("src/a/x.rs", "src/a/x.rs")
1967 );
1968 assert!(
1969 path("src/b/x.rs", "src/a/x.rs")
1970 .changed_from(&path("src/a/x.rs", "src/a/x.rs"))
1971 .is_some_and(|c| c == "resolves to src/b/x.rs, was src/a/x.rs")
1972 );
1973 let a = command("make check");
1975 let mut b = a.clone();
1976 if let Object::Command { cwd, .. } = &mut b {
1977 *cwd = "sub".to_owned();
1978 }
1979 assert_ne!(a, b);
1980 assert_eq!(a.class(), Class::Command);
1981 assert!(a.short().starts_with("argv#") && a.short().len() == 17);
1982 let back: Object = serde_json::from_value(serde_json::to_value(&a).unwrap()).unwrap();
1984 assert_eq!(back, a);
1985 assert!(serde_json::from_value::<Object>(json!({ "kind": "write", "path": "x" })).is_err());
1986 assert!(
1987 serde_json::from_value::<Rejection>(json!({ "grant": { "kind": "path", "canonical": "x", "asked": "x" }, "reason": "r" }))
1988 .is_err()
1989 );
1990 }
1991
1992 #[test]
1993 fn the_grant_path_has_no_pattern() {
1994 let source = include_str!("policy.rs");
1996 let classify = source
1997 .split("pub fn classify(")
1998 .nth(1)
1999 .and_then(|s| s.split("\n }\n").next())
2000 .unwrap_or_default();
2001 assert!(!classify.is_empty());
2002 for pattern in ["starts_with", "glob", "prefix"] {
2003 assert!(!classify.contains(pattern), "{pattern} in the grant path");
2004 }
2005 }
2006}