AI coding agents can edit files, run shell commands, and touch infrastructure. One bad rm -rf, force-push, or docker compose down -v can wipe hours of work or production data.
| 1 | # SPDX-License-Identifier: MIT |
| 2 | from __future__ import annotations |
| 3 | |
| 4 | from unittest.mock import MagicMock, patch |
| 5 | |
| 6 | from agent_guard.commands import run_command |
| 7 | from agent_guard.config import GuardConfig |
| 8 | from agent_guard.models import Decision |
| 9 | |
| 10 | |
| 11 | def test_allow_runs_process(config: GuardConfig) -> None: |
| 12 | with patch("agent_guard.commands.subprocess.run") as mock_run: |
| 13 | mock_run.return_value = MagicMock(returncode=0) |
| 14 | outcome = run_command(["python", "-c", "print('hello')"], config) |
| 15 | assert outcome.result.decision == Decision.ALLOW |
| 16 | assert outcome.executed is True |
| 17 | mock_run.assert_called_once() |
| 18 | assert mock_run.call_args.kwargs.get("shell") is False |
| 19 | |
| 20 | |
| 21 | def test_block_never_runs(config: GuardConfig) -> None: |
| 22 | with patch("agent_guard.commands.subprocess.run") as mock_run: |
| 23 | outcome = run_command(["rm", "-rf", "/"], config) |
| 24 | assert outcome.result.decision == Decision.BLOCK |
| 25 | assert outcome.executed is False |
| 26 | mock_run.assert_not_called() |
| 27 | |
| 28 | |
| 29 | def test_warn_allow_risk_runs(config: GuardConfig) -> None: |
| 30 | with patch("agent_guard.commands.subprocess.run") as mock_run: |
| 31 | mock_run.return_value = MagicMock(returncode=0) |
| 32 | outcome = run_command( |
| 33 | ["git", "reset", "--hard", "HEAD"], |
| 34 | config, |
| 35 | allow_risk=True, |
| 36 | ) |
| 37 | assert outcome.result.decision == Decision.WARN |
| 38 | assert outcome.executed is True |
| 39 | mock_run.assert_called_once() |
| 40 | |
| 41 | |
| 42 | def test_warn_noninteractive_denied(config: GuardConfig) -> None: |
| 43 | with ( |
| 44 | patch("agent_guard.commands.subprocess.run") as mock_run, |
| 45 | patch("agent_guard.commands.sys.stdin") as mock_stdin, |
| 46 | ): |
| 47 | mock_stdin.isatty.return_value = False |
| 48 | outcome = run_command(["git", "reset", "--hard", "HEAD"], config) |
| 49 | assert outcome.executed is False |
| 50 | assert outcome.exit_code == 10 |
| 51 | mock_run.assert_not_called() |
| 52 | assert outcome.message is not None |
| 53 | assert "Non-interactive" in outcome.message |
| 54 | |
| 55 | |
| 56 | def test_allow_risk_does_not_bypass_block(config: GuardConfig) -> None: |
| 57 | with patch("agent_guard.commands.subprocess.run") as mock_run: |
| 58 | outcome = run_command(["rm", "-rf", "/"], config, allow_risk=True) |
| 59 | assert outcome.result.decision == Decision.BLOCK |
| 60 | mock_run.assert_not_called() |
| 61 | |
| 62 | |
| 63 | def test_empty_argv(config: GuardConfig) -> None: |
| 64 | outcome = run_command([], config) |
| 65 | assert outcome.executed is False |
| 66 | assert outcome.exit_code == 30 |