test_agent_guard.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162
  1. """Tests for the cross-tool agent guard."""
  2. from __future__ import annotations
  3. import json
  4. import os
  5. import subprocess
  6. import sys
  7. import tempfile
  8. import unittest
  9. from pathlib import Path
  10. from typing import Any
  11. ROOT = Path(__file__).resolve().parents[2]
  12. GUARD_PATH = ROOT / "tools" / "agent_guard.py"
  13. def _git(*args: str, cwd: Path) -> subprocess.CompletedProcess[str]:
  14. return subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True)
  15. def _init_temp_repo() -> Path:
  16. """Create a temporary git repository with a single commit."""
  17. tmp = Path(tempfile.mkdtemp(prefix="agent_guard_repo_"))
  18. _git("init", cwd=tmp)
  19. _git("config", "user.email", "guard-test@example.com", cwd=tmp)
  20. _git("config", "user.name", "Guard Test", cwd=tmp)
  21. (tmp / ".gitignore").write_text("*.local\n", encoding="utf-8")
  22. (tmp / "README.md").write_text("# temp\n", encoding="utf-8")
  23. _git("add", ".", cwd=tmp)
  24. _git("commit", "-m", "init", cwd=tmp)
  25. _git("checkout", "-b", "devin/test-guard", cwd=tmp)
  26. return tmp
  27. def _head(repo: Path) -> str:
  28. return _git("rev-parse", "HEAD", cwd=repo).stdout.strip()
  29. def _write_local_config(
  30. repo: Path,
  31. *,
  32. active_worktree: str | None = None,
  33. expected_branch: str = "devin/test-guard",
  34. expected_head: str | None = None,
  35. owned_paths: list[str] | None = None,
  36. protected_roots: list[str] | None = None,
  37. ) -> None:
  38. devin = repo / ".devin"
  39. devin.mkdir(exist_ok=True)
  40. tracked = {
  41. "project_id": "prod2u-door-temp",
  42. "denied_commands": ["git reset"],
  43. "hardware_access": {"com": False, "jtag": False},
  44. }
  45. (devin / "config.json").write_text(json.dumps(tracked, indent=2), encoding="utf-8")
  46. local: dict[str, Any] = {}
  47. if active_worktree is not None:
  48. local["active_worktree"] = active_worktree
  49. local["expected_branch"] = expected_branch
  50. if expected_head is not None:
  51. local["expected_head"] = expected_head
  52. if owned_paths is not None:
  53. local["owned_paths"] = owned_paths
  54. if protected_roots is not None:
  55. local["protected_roots"] = protected_roots
  56. (devin / "config.local.json").write_text(json.dumps(local, indent=2), encoding="utf-8")
  57. def _guard(
  58. cwd: Path,
  59. *,
  60. target: str | None = None,
  61. command: str | None = None,
  62. env: dict[str, str] | None = None,
  63. ) -> tuple[int, str]:
  64. env = env or os.environ.copy()
  65. argv = [str(sys.executable), str(GUARD_PATH), "--event", "pre_tool_use", "--cwd", str(cwd)]
  66. if target:
  67. argv.extend(["--target-path", target])
  68. if command:
  69. argv.extend(["--command", command])
  70. result = subprocess.run(
  71. argv,
  72. cwd=cwd,
  73. capture_output=True,
  74. text=True,
  75. env=env,
  76. )
  77. return result.returncode, result.stdout
  78. class AgentGuardTests(unittest.TestCase):
  79. def test_error_cwd_not_a_git_repository(self):
  80. tmp = Path(tempfile.mkdtemp(prefix="agent_guard_not_git_"))
  81. rc, stdout = _guard(tmp)
  82. self.assertEqual(rc, 1)
  83. self.assertIn("not_a_git_repository", stdout)
  84. def test_protected_repository(self):
  85. repo = _init_temp_repo()
  86. _write_local_config(
  87. repo,
  88. active_worktree=str(repo),
  89. expected_head=_head(repo),
  90. protected_roots=[str(repo)],
  91. )
  92. rc, stdout = _guard(repo)
  93. self.assertEqual(rc, 1)
  94. self.assertIn("protected_repository", stdout)
  95. def test_outside_owned_paths(self):
  96. repo = _init_temp_repo()
  97. _write_local_config(
  98. repo,
  99. active_worktree=str(repo),
  100. expected_branch="devin/test-guard",
  101. expected_head=_head(repo),
  102. owned_paths=["src/**"],
  103. )
  104. target = str(repo / "tests" / "example.v")
  105. os.makedirs(Path(target).parent, exist_ok=True)
  106. Path(target).write_text("module example; endmodule\n", encoding="utf-8")
  107. rc, stdout = _guard(repo, target=target)
  108. self.assertEqual(rc, 1)
  109. self.assertIn("outside_owned_paths", stdout)
  110. def test_allowed_inside_owned_paths(self):
  111. repo = _init_temp_repo()
  112. _write_local_config(
  113. repo,
  114. active_worktree=str(repo),
  115. expected_branch="devin/test-guard",
  116. expected_head=_head(repo),
  117. owned_paths=["src/**", "tests/**"],
  118. )
  119. target = str(repo / "src" / "example.v")
  120. os.makedirs(Path(target).parent, exist_ok=True)
  121. Path(target).write_text("module example; endmodule\n", encoding="utf-8")
  122. rc, stdout = _guard(repo, target=target)
  123. self.assertEqual(rc, 0)
  124. self.assertIn('"allowed": true', stdout)
  125. def test_forbidden_command(self):
  126. repo = _init_temp_repo()
  127. _write_local_config(
  128. repo,
  129. active_worktree=str(repo),
  130. expected_branch="devin/test-guard",
  131. expected_head=_head(repo),
  132. owned_paths=["src/**"],
  133. )
  134. target = str(repo / "src" / "example.v")
  135. os.makedirs(Path(target).parent, exist_ok=True)
  136. Path(target).write_text("module example; endmodule\n", encoding="utf-8")
  137. rc, stdout = _guard(repo, target=target, command="git reset --hard")
  138. self.assertEqual(rc, 1)
  139. self.assertIn("denied_git_command", stdout)
  140. if __name__ == "__main__":
  141. unittest.main()