1use parking_lot::Mutex;
2use serde::{Deserialize, Serialize};
3use std::path::{Path, PathBuf};
4use std::time::Instant;
5
6#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
8#[serde(rename_all = "lowercase")]
9pub enum AutonomyLevel {
10 ReadOnly,
12 #[default]
14 Supervised,
15 Full,
17}
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum CommandRiskLevel {
22 Low,
23 Medium,
24 High,
25}
26
27#[derive(Debug)]
29pub struct ActionTracker {
30 actions: Mutex<Vec<Instant>>,
32}
33
34impl Default for ActionTracker {
35 fn default() -> Self {
36 Self::new()
37 }
38}
39
40impl ActionTracker {
41 pub fn new() -> Self {
42 Self {
43 actions: Mutex::new(Vec::new()),
44 }
45 }
46
47 pub fn record(&self) -> usize {
49 let mut actions = self.actions.lock();
50 let cutoff = Instant::now()
51 .checked_sub(std::time::Duration::from_secs(3600))
52 .unwrap_or_else(Instant::now);
53 actions.retain(|t| *t > cutoff);
54 actions.push(Instant::now());
55 actions.len()
56 }
57
58 pub fn count(&self) -> usize {
60 let mut actions = self.actions.lock();
61 let cutoff = Instant::now()
62 .checked_sub(std::time::Duration::from_secs(3600))
63 .unwrap_or_else(Instant::now);
64 actions.retain(|t| *t > cutoff);
65 actions.len()
66 }
67}
68
69impl Clone for ActionTracker {
70 fn clone(&self) -> Self {
71 let actions = self.actions.lock();
72 Self {
73 actions: Mutex::new(actions.clone()),
74 }
75 }
76}
77
78#[derive(Debug, Clone)]
80pub struct SecurityPolicy {
81 pub autonomy: AutonomyLevel,
82 pub workspace_dir: PathBuf,
83 pub workspace_only: bool,
84 pub blocked_commands: Vec<String>,
85 pub forbidden_paths: Vec<String>,
86 pub max_actions_per_hour: u32,
87 pub max_cost_per_day_cents: u32,
88 pub require_approval_for_medium_risk: bool,
89 pub block_high_risk_commands: bool,
90 pub tracker: ActionTracker,
91 pub forwarded_env: Vec<(String, String)>,
96}
97
98impl Default for SecurityPolicy {
99 fn default() -> Self {
100 let home = std::env::var("HOME")
101 .map(PathBuf::from)
102 .unwrap_or_else(|_| PathBuf::from("."));
103 Self {
104 autonomy: AutonomyLevel::Supervised,
105 workspace_dir: home.join(".nenjo").join("workspace"),
106 workspace_only: true,
107 blocked_commands: default_blocked_commands(),
108 forbidden_paths: vec![
109 "/etc".into(),
111 "/root".into(),
112 "/home".into(),
113 "/usr".into(),
114 "/bin".into(),
115 "/sbin".into(),
116 "/lib".into(),
117 "/opt".into(),
118 "/boot".into(),
119 "/dev".into(),
120 "/proc".into(),
121 "/sys".into(),
122 "/var".into(),
123 "/tmp".into(),
124 "~/.ssh".into(),
126 "~/.gnupg".into(),
127 "~/.aws".into(),
128 "~/.config".into(),
129 ],
130 max_actions_per_hour: 1000,
131 max_cost_per_day_cents: 500,
132 require_approval_for_medium_risk: true,
133 block_high_risk_commands: true,
134 tracker: ActionTracker::new(),
135 forwarded_env: collect_forwarded_env(),
136 }
137 }
138}
139
140fn collect_forwarded_env() -> Vec<(String, String)> {
142 let mut env = Vec::new();
143
144 if let Ok(token) = std::env::var("GITHUB_TOKEN") {
145 env.push(("GITHUB_TOKEN".into(), token.clone()));
146 if std::env::var("GH_TOKEN").is_err() {
147 env.push(("GH_TOKEN".into(), token));
148 }
149 }
150 if let Ok(token) = std::env::var("GH_TOKEN") {
151 if !env.iter().any(|(k, _)| k == "GH_TOKEN") {
152 env.push(("GH_TOKEN".into(), token.clone()));
153 }
154 if !env.iter().any(|(k, _)| k == "GITHUB_TOKEN") {
155 env.push(("GITHUB_TOKEN".into(), token));
156 }
157 }
158
159 if let Ok(home) = std::env::var("HOME") {
160 let global_config = Path::new(&home).join(".gitconfig");
161 if global_config.exists() {
162 env.push((
163 "GIT_CONFIG_GLOBAL".into(),
164 global_config.to_string_lossy().into_owned(),
165 ));
166 }
167 }
168 env.push(("GIT_CONFIG_SYSTEM".into(), "/dev/null".into()));
169
170 env
171}
172
173fn default_blocked_commands() -> Vec<String> {
175 vec![
176 "rm".into(),
178 "mkfs".into(),
179 "dd".into(),
180 "shutdown".into(),
182 "reboot".into(),
183 "halt".into(),
184 "poweroff".into(),
185 "sudo".into(),
187 "su".into(),
188 "chown".into(),
190 "chmod".into(),
191 "useradd".into(),
192 "userdel".into(),
193 "usermod".into(),
194 "passwd".into(),
195 "mount".into(),
197 "umount".into(),
198 "iptables".into(),
200 "ufw".into(),
201 "firewall-cmd".into(),
202 "curl".into(),
204 "wget".into(),
205 "nc".into(),
206 "ncat".into(),
207 "netcat".into(),
208 "scp".into(),
209 "ssh".into(),
210 "ftp".into(),
211 "telnet".into(),
212 "killall".into(),
214 "kill".into(),
215 "pkill".into(),
216 "crontab".into(),
217 "at".into(),
218 "systemctl".into(),
219 "service".into(),
220 ]
221}
222
223fn contains_unquoted(s: &str, ch: char) -> bool {
225 let mut in_single = false;
226 let mut in_double = false;
227 let mut escaped = false;
228 for c in s.chars() {
229 if escaped {
230 escaped = false;
231 continue;
232 }
233 if c == '\\' && !in_single {
234 escaped = true;
235 continue;
236 }
237 if c == '\'' && !in_double {
238 in_single = !in_single;
239 continue;
240 }
241 if c == '"' && !in_single {
242 in_double = !in_double;
243 continue;
244 }
245 if !in_single && !in_double && c == ch {
246 return true;
247 }
248 }
249 false
250}
251
252fn split_on_unquoted_separators(command: &str) -> Vec<String> {
254 let mut segments: Vec<String> = Vec::new();
255 let mut current = String::new();
256 let mut in_single = false;
257 let mut in_double = false;
258 let mut escaped = false;
259 let chars: Vec<char> = command.chars().collect();
260 let len = chars.len();
261 let mut i = 0;
262
263 while i < len {
264 let c = chars[i];
265
266 if escaped {
267 current.push(c);
268 escaped = false;
269 i += 1;
270 continue;
271 }
272
273 if c == '\\' && !in_single {
274 current.push(c);
275 escaped = true;
276 i += 1;
277 continue;
278 }
279
280 if c == '\'' && !in_double {
281 in_single = !in_single;
282 current.push(c);
283 i += 1;
284 continue;
285 }
286
287 if c == '"' && !in_single {
288 in_double = !in_double;
289 current.push(c);
290 i += 1;
291 continue;
292 }
293
294 if !in_single && !in_double {
295 if i + 1 < len {
297 let two = &command[i..][..chars[i].len_utf8() + chars[i + 1].len_utf8()];
298 if two == "&&" || two == "||" {
299 if !current.trim().is_empty() {
300 segments.push(current.clone());
301 }
302 current.clear();
303 i += 2;
304 continue;
305 }
306 }
307 if c == '|' || c == ';' || c == '\n' {
309 if !current.trim().is_empty() {
310 segments.push(current.clone());
311 }
312 current.clear();
313 i += 1;
314 continue;
315 }
316 }
317
318 current.push(c);
319 i += 1;
320 }
321
322 if !current.trim().is_empty() {
323 segments.push(current);
324 }
325 segments
326}
327
328fn skip_env_assignments(s: &str) -> &str {
330 let mut rest = s;
331 loop {
332 let Some(word) = rest.split_whitespace().next() else {
333 return rest;
334 };
335 if word.contains('=')
336 && word
337 .chars()
338 .next()
339 .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
340 {
341 rest = rest[word.len()..].trim_start();
342 } else {
343 return rest;
344 }
345 }
346}
347
348impl SecurityPolicy {
349 pub fn with_workspace_dir(workspace_dir: PathBuf) -> Self {
354 Self {
355 workspace_dir,
356 ..Default::default()
357 }
358 }
359
360 pub fn command_risk_level(&self, command: &str) -> CommandRiskLevel {
362 let segments = split_on_unquoted_separators(command);
363 let mut saw_medium = false;
364
365 for segment in segments.iter().map(|s| s.trim()) {
366 let segment = segment.trim();
367 if segment.is_empty() {
368 continue;
369 }
370
371 let cmd_part = skip_env_assignments(segment);
372 let mut words = cmd_part.split_whitespace();
373 let Some(base_raw) = words.next() else {
374 continue;
375 };
376
377 let base = base_raw
378 .rsplit('/')
379 .next()
380 .unwrap_or("")
381 .to_ascii_lowercase();
382
383 let args: Vec<String> = words.map(|w| w.to_ascii_lowercase()).collect();
384 let joined_segment = cmd_part.to_ascii_lowercase();
385
386 if matches!(
388 base.as_str(),
389 "rm" | "mkfs"
390 | "dd"
391 | "shutdown"
392 | "reboot"
393 | "halt"
394 | "poweroff"
395 | "sudo"
396 | "su"
397 | "chown"
398 | "chmod"
399 | "useradd"
400 | "userdel"
401 | "usermod"
402 | "passwd"
403 | "mount"
404 | "umount"
405 | "iptables"
406 | "ufw"
407 | "firewall-cmd"
408 | "curl"
409 | "wget"
410 | "nc"
411 | "ncat"
412 | "netcat"
413 | "scp"
414 | "ssh"
415 | "ftp"
416 | "telnet"
417 ) {
418 return CommandRiskLevel::High;
419 }
420
421 if joined_segment.contains("rm -rf /")
422 || joined_segment.contains("rm -fr /")
423 || joined_segment.contains(":(){:|:&};:")
424 {
425 return CommandRiskLevel::High;
426 }
427
428 let medium = match base.as_str() {
430 "git" => args.first().is_some_and(|verb| {
431 matches!(
432 verb.as_str(),
433 "commit"
434 | "push"
435 | "reset"
436 | "clean"
437 | "rebase"
438 | "merge"
439 | "cherry-pick"
440 | "revert"
441 | "branch"
442 | "checkout"
443 | "switch"
444 | "tag"
445 )
446 }),
447 "npm" | "pnpm" | "yarn" => args.first().is_some_and(|verb| {
448 matches!(
449 verb.as_str(),
450 "install" | "add" | "remove" | "uninstall" | "update" | "publish"
451 )
452 }),
453 "cargo" => args.first().is_some_and(|verb| {
454 matches!(
455 verb.as_str(),
456 "add" | "remove" | "install" | "clean" | "publish"
457 )
458 }),
459 "pip" | "pip3" | "uv" => args
460 .first()
461 .is_some_and(|verb| matches!(verb.as_str(), "install" | "uninstall")),
462 "go" => args.first().is_some_and(|verb| {
463 matches!(verb.as_str(), "install" | "get" | "mod" | "clean")
464 }),
465 "gh" => args.first().is_some_and(|verb| {
466 matches!(verb.as_str(), "pr" | "issue" | "release" | "repo")
467 }),
468 "make" | "cmake" => true,
469 "touch" | "mkdir" | "mv" | "cp" | "ln" => true,
470 _ => false,
471 };
472
473 saw_medium |= medium;
474 }
475
476 if saw_medium {
477 CommandRiskLevel::Medium
478 } else {
479 CommandRiskLevel::Low
480 }
481 }
482
483 pub fn validate_command_execution(
485 &self,
486 command: &str,
487 approved: bool,
488 ) -> Result<CommandRiskLevel, String> {
489 if !self.is_command_allowed(command) {
490 return Err(format!("Command not allowed by security policy: {command}"));
491 }
492
493 let risk = self.command_risk_level(command);
494
495 if risk == CommandRiskLevel::High {
496 if self.block_high_risk_commands {
497 return Err("Command blocked: high-risk command is disallowed by policy".into());
498 }
499 if self.autonomy == AutonomyLevel::Supervised && !approved {
500 return Err(
501 "Command requires explicit approval (approved=true): high-risk operation"
502 .into(),
503 );
504 }
505 }
506
507 if risk == CommandRiskLevel::Medium
508 && self.autonomy == AutonomyLevel::Supervised
509 && self.require_approval_for_medium_risk
510 && !approved
511 {
512 return Err(
513 "Command requires explicit approval (approved=true): medium-risk operation".into(),
514 );
515 }
516
517 Ok(risk)
518 }
519
520 fn is_within_workspace(&self, arg: &str) -> bool {
523 let expanded = if let Some(stripped) = arg.strip_prefix("~/") {
524 if let Ok(home) = std::env::var("HOME") {
525 PathBuf::from(home).join(stripped)
526 } else {
527 return false;
528 }
529 } else {
530 PathBuf::from(arg)
531 };
532
533 match (expanded.canonicalize(), self.workspace_dir.canonicalize()) {
534 (Ok(resolved), Ok(workspace)) => resolved.starts_with(&workspace),
535 _ => expanded.starts_with(&self.workspace_dir),
536 }
537 }
538
539 pub fn is_command_allowed(&self, command: &str) -> bool {
540 if self.autonomy == AutonomyLevel::ReadOnly {
541 return false;
542 }
543
544 {
546 let mut outside_quotes = String::new();
547 let mut in_single = false;
548 let mut in_double = false;
549 let mut escaped = false;
550 for c in command.chars() {
551 if escaped {
552 escaped = false;
553 continue;
554 }
555 if c == '\\' && !in_single {
556 escaped = true;
557 continue;
558 }
559 if c == '\'' && !in_double {
560 in_single = !in_single;
561 continue;
562 }
563 if c == '"' && !in_single {
564 in_double = !in_double;
565 continue;
566 }
567 if !in_single && !in_double {
568 outside_quotes.push(c);
569 }
570 }
571 if outside_quotes.contains('`')
572 || outside_quotes.contains("$(")
573 || outside_quotes.contains("${")
574 {
575 return false;
576 }
577 }
578
579 {
581 let stripped = command
582 .replace("2>&1", "")
583 .replace(">&2", "")
584 .replace(">/dev/null", "")
585 .replace("2>/dev/null", "")
586 .replace("1>/dev/null", "");
587 if contains_unquoted(&stripped, '>') {
588 return false;
589 }
590 }
591
592 let segments = split_on_unquoted_separators(command);
593
594 for segment in segments.iter().map(|s| s.trim()) {
595 let segment = segment.trim();
596 if segment.is_empty() {
597 continue;
598 }
599
600 let cmd_part = skip_env_assignments(segment);
601
602 let base_cmd = cmd_part
603 .split_whitespace()
604 .next()
605 .unwrap_or("")
606 .rsplit('/')
607 .next()
608 .unwrap_or("");
609
610 if base_cmd.is_empty() {
611 continue;
612 }
613
614 if self
615 .blocked_commands
616 .iter()
617 .any(|blocked| blocked == base_cmd)
618 {
619 return false;
620 }
621
622 if self.workspace_only {
624 for arg in cmd_part.split_whitespace().skip(1) {
625 if arg.starts_with('-') {
626 continue;
627 }
628 if Path::new(arg)
629 .components()
630 .any(|c| matches!(c, std::path::Component::ParentDir))
631 {
632 return false;
633 }
634 if (arg.starts_with('/') || arg.starts_with("~/"))
635 && !self.is_within_workspace(arg)
636 {
637 return false;
638 }
639 }
640 }
641 }
642
643 segments.iter().any(|s| {
644 let s = skip_env_assignments(s.trim());
645 s.split_whitespace().next().is_some_and(|w| !w.is_empty())
646 })
647 }
648
649 pub fn is_path_allowed(&self, path: &str) -> bool {
651 if path.contains('\0') {
652 return false;
653 }
654
655 if Path::new(path)
656 .components()
657 .any(|c| matches!(c, std::path::Component::ParentDir))
658 {
659 return false;
660 }
661
662 let lower = path.to_lowercase();
663 if lower.contains("..%2f") || lower.contains("%2f..") {
664 return false;
665 }
666
667 let expanded = if let Some(stripped) = path.strip_prefix("~/") {
668 if let Some(home) = std::env::var("HOME").ok().map(PathBuf::from) {
669 home.join(stripped).to_string_lossy().to_string()
670 } else {
671 path.to_string()
672 }
673 } else {
674 path.to_string()
675 };
676
677 if self.workspace_only
678 && Path::new(&expanded).is_absolute()
679 && !self.is_within_workspace(path)
680 {
681 return false;
682 }
683
684 let expanded_path = Path::new(&expanded);
685 for forbidden in &self.forbidden_paths {
686 let forbidden_expanded = if let Some(stripped) = forbidden.strip_prefix("~/") {
687 if let Some(home) = std::env::var("HOME").ok().map(PathBuf::from) {
688 home.join(stripped).to_string_lossy().to_string()
689 } else {
690 forbidden.clone()
691 }
692 } else {
693 forbidden.clone()
694 };
695 let forbidden_path = Path::new(&forbidden_expanded);
696 if expanded_path.starts_with(forbidden_path) {
697 return false;
698 }
699 }
700
701 true
702 }
703
704 pub fn is_resolved_path_allowed(&self, resolved: &Path) -> bool {
706 let workspace_root = self
707 .workspace_dir
708 .canonicalize()
709 .unwrap_or_else(|_| self.workspace_dir.clone());
710 resolved.starts_with(workspace_root)
711 }
712
713 pub fn can_act(&self) -> bool {
715 self.autonomy != AutonomyLevel::ReadOnly
716 }
717
718 pub fn record_action(&self) -> bool {
720 let count = self.tracker.record();
721 count <= self.max_actions_per_hour as usize
722 }
723
724 pub fn is_rate_limited(&self) -> bool {
726 self.tracker.count() >= self.max_actions_per_hour as usize
727 }
728
729 pub fn resolved_path_violation_message(&self, resolved: &Path) -> String {
731 format!(
732 "Path escapes workspace: resolved to '{}' which is outside '{}'",
733 resolved.display(),
734 self.workspace_dir.display()
735 )
736 }
737}
738
739#[cfg(test)]
740mod tests {
741 use super::*;
742
743 fn default_policy() -> SecurityPolicy {
744 SecurityPolicy::default()
745 }
746
747 fn readonly_policy() -> SecurityPolicy {
748 SecurityPolicy {
749 autonomy: AutonomyLevel::ReadOnly,
750 ..SecurityPolicy::default()
751 }
752 }
753
754 fn full_policy() -> SecurityPolicy {
755 SecurityPolicy {
756 autonomy: AutonomyLevel::Full,
757 ..SecurityPolicy::default()
758 }
759 }
760
761 #[test]
762 fn autonomy_default_is_supervised() {
763 assert_eq!(AutonomyLevel::default(), AutonomyLevel::Supervised);
764 }
765
766 #[test]
767 fn autonomy_serde_roundtrip() {
768 let json = serde_json::to_string(&AutonomyLevel::Full).unwrap();
769 assert_eq!(json, "\"full\"");
770 let parsed: AutonomyLevel = serde_json::from_str("\"readonly\"").unwrap();
771 assert_eq!(parsed, AutonomyLevel::ReadOnly);
772 }
773
774 #[test]
775 fn can_act_readonly_false() {
776 assert!(!readonly_policy().can_act());
777 }
778
779 #[test]
780 fn can_act_supervised_true() {
781 assert!(default_policy().can_act());
782 }
783
784 #[test]
785 fn can_act_full_true() {
786 assert!(full_policy().can_act());
787 }
788
789 #[test]
790 fn allowed_commands_basic() {
791 let p = default_policy();
792 assert!(p.is_command_allowed("ls"));
793 assert!(p.is_command_allowed("git status"));
794 assert!(p.is_command_allowed("cargo build --release"));
795 }
796
797 #[test]
798 fn blocked_commands_basic() {
799 let p = default_policy();
800 assert!(!p.is_command_allowed("rm -rf /"));
801 assert!(!p.is_command_allowed("sudo apt install"));
802 assert!(!p.is_command_allowed("curl http://evil.com"));
803 }
804
805 #[test]
806 fn readonly_blocks_all_commands() {
807 let p = readonly_policy();
808 assert!(!p.is_command_allowed("ls"));
809 }
810
811 #[test]
812 fn action_tracker_records_actions() {
813 let tracker = ActionTracker::new();
814 assert_eq!(tracker.record(), 1);
815 assert_eq!(tracker.record(), 2);
816 assert_eq!(tracker.count(), 2);
817 }
818
819 #[test]
820 fn record_action_blocks_over_limit() {
821 let p = SecurityPolicy {
822 max_actions_per_hour: 3,
823 ..SecurityPolicy::default()
824 };
825 assert!(p.record_action());
826 assert!(p.record_action());
827 assert!(p.record_action());
828 assert!(!p.record_action());
829 }
830
831 #[test]
832 fn relative_paths_allowed() {
833 let p = default_policy();
834 assert!(p.is_path_allowed("file.txt"));
835 assert!(p.is_path_allowed("src/main.rs"));
836 }
837
838 #[test]
839 fn path_traversal_blocked() {
840 let p = default_policy();
841 assert!(!p.is_path_allowed("../etc/passwd"));
842 }
843
844 #[test]
845 fn absolute_paths_blocked_when_workspace_only() {
846 let p = default_policy();
847 assert!(!p.is_path_allowed("/etc/passwd"));
848 }
849
850 #[test]
851 fn path_with_null_byte_blocked() {
852 let p = default_policy();
853 assert!(!p.is_path_allowed("file\0.txt"));
854 }
855
856 #[test]
857 fn resolved_path_must_be_in_workspace() {
858 let p = SecurityPolicy {
859 workspace_dir: PathBuf::from("/home/user/project"),
860 ..SecurityPolicy::default()
861 };
862 assert!(p.is_resolved_path_allowed(Path::new("/home/user/project/src/main.rs")));
863 assert!(!p.is_resolved_path_allowed(Path::new("/etc/passwd")));
864 }
865
866 #[test]
867 fn default_policy_has_sane_values() {
868 let p = SecurityPolicy::default();
869 assert_eq!(p.autonomy, AutonomyLevel::Supervised);
870 assert!(p.workspace_only);
871 assert!(!p.blocked_commands.is_empty());
872 }
873}