| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162 |
- """Tests for the cross-tool agent guard."""
- from __future__ import annotations
- import json
- import os
- import subprocess
- import sys
- import tempfile
- import unittest
- from pathlib import Path
- from typing import Any
- ROOT = Path(__file__).resolve().parents[2]
- GUARD_PATH = ROOT / "tools" / "agent_guard.py"
- def _git(*args: str, cwd: Path) -> subprocess.CompletedProcess[str]:
- return subprocess.run(["git", *args], cwd=cwd, capture_output=True, text=True)
- def _init_temp_repo() -> Path:
- """Create a temporary git repository with a single commit."""
- tmp = Path(tempfile.mkdtemp(prefix="agent_guard_repo_"))
- _git("init", cwd=tmp)
- _git("config", "user.email", "guard-test@example.com", cwd=tmp)
- _git("config", "user.name", "Guard Test", cwd=tmp)
- (tmp / ".gitignore").write_text("*.local\n", encoding="utf-8")
- (tmp / "README.md").write_text("# temp\n", encoding="utf-8")
- _git("add", ".", cwd=tmp)
- _git("commit", "-m", "init", cwd=tmp)
- _git("checkout", "-b", "devin/test-guard", cwd=tmp)
- return tmp
- def _head(repo: Path) -> str:
- return _git("rev-parse", "HEAD", cwd=repo).stdout.strip()
- def _write_local_config(
- repo: Path,
- *,
- active_worktree: str | None = None,
- expected_branch: str = "devin/test-guard",
- expected_head: str | None = None,
- owned_paths: list[str] | None = None,
- protected_roots: list[str] | None = None,
- ) -> None:
- devin = repo / ".devin"
- devin.mkdir(exist_ok=True)
- tracked = {
- "project_id": "prod2u-door-temp",
- "denied_commands": ["git reset"],
- "hardware_access": {"com": False, "jtag": False},
- }
- (devin / "config.json").write_text(json.dumps(tracked, indent=2), encoding="utf-8")
- local: dict[str, Any] = {}
- if active_worktree is not None:
- local["active_worktree"] = active_worktree
- local["expected_branch"] = expected_branch
- if expected_head is not None:
- local["expected_head"] = expected_head
- if owned_paths is not None:
- local["owned_paths"] = owned_paths
- if protected_roots is not None:
- local["protected_roots"] = protected_roots
- (devin / "config.local.json").write_text(json.dumps(local, indent=2), encoding="utf-8")
- def _guard(
- cwd: Path,
- *,
- target: str | None = None,
- command: str | None = None,
- env: dict[str, str] | None = None,
- ) -> tuple[int, str]:
- env = env or os.environ.copy()
- argv = [str(sys.executable), str(GUARD_PATH), "--event", "pre_tool_use", "--cwd", str(cwd)]
- if target:
- argv.extend(["--target-path", target])
- if command:
- argv.extend(["--command", command])
- result = subprocess.run(
- argv,
- cwd=cwd,
- capture_output=True,
- text=True,
- env=env,
- )
- return result.returncode, result.stdout
- class AgentGuardTests(unittest.TestCase):
- def test_error_cwd_not_a_git_repository(self):
- tmp = Path(tempfile.mkdtemp(prefix="agent_guard_not_git_"))
- rc, stdout = _guard(tmp)
- self.assertEqual(rc, 1)
- self.assertIn("not_a_git_repository", stdout)
- def test_protected_repository(self):
- repo = _init_temp_repo()
- _write_local_config(
- repo,
- active_worktree=str(repo),
- expected_head=_head(repo),
- protected_roots=[str(repo)],
- )
- rc, stdout = _guard(repo)
- self.assertEqual(rc, 1)
- self.assertIn("protected_repository", stdout)
- def test_outside_owned_paths(self):
- repo = _init_temp_repo()
- _write_local_config(
- repo,
- active_worktree=str(repo),
- expected_branch="devin/test-guard",
- expected_head=_head(repo),
- owned_paths=["src/**"],
- )
- target = str(repo / "tests" / "example.v")
- os.makedirs(Path(target).parent, exist_ok=True)
- Path(target).write_text("module example; endmodule\n", encoding="utf-8")
- rc, stdout = _guard(repo, target=target)
- self.assertEqual(rc, 1)
- self.assertIn("outside_owned_paths", stdout)
- def test_allowed_inside_owned_paths(self):
- repo = _init_temp_repo()
- _write_local_config(
- repo,
- active_worktree=str(repo),
- expected_branch="devin/test-guard",
- expected_head=_head(repo),
- owned_paths=["src/**", "tests/**"],
- )
- target = str(repo / "src" / "example.v")
- os.makedirs(Path(target).parent, exist_ok=True)
- Path(target).write_text("module example; endmodule\n", encoding="utf-8")
- rc, stdout = _guard(repo, target=target)
- self.assertEqual(rc, 0)
- self.assertIn('"allowed": true', stdout)
- def test_forbidden_command(self):
- repo = _init_temp_repo()
- _write_local_config(
- repo,
- active_worktree=str(repo),
- expected_branch="devin/test-guard",
- expected_head=_head(repo),
- owned_paths=["src/**"],
- )
- target = str(repo / "src" / "example.v")
- os.makedirs(Path(target).parent, exist_ok=True)
- Path(target).write_text("module example; endmodule\n", encoding="utf-8")
- rc, stdout = _guard(repo, target=target, command="git reset --hard")
- self.assertEqual(rc, 1)
- self.assertIn("denied_git_command", stdout)
- if __name__ == "__main__":
- unittest.main()
|