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 | """Extra coverage for CLI edge paths, policies, output, and rules.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | import json |
| 7 | from pathlib import Path |
| 8 | from unittest.mock import MagicMock, patch |
| 9 | |
| 10 | import pytest |
| 11 | from typer.testing import CliRunner |
| 12 | |
| 13 | from agent_guard.cli import app, main |
| 14 | from agent_guard.commands import run_command |
| 15 | from agent_guard.config import GuardConfig, build_init_config, load_config, write_config |
| 16 | from agent_guard.evaluator import evaluate_command, evaluate_file_operation |
| 17 | from agent_guard.filesystem import ( |
| 18 | expand_user_token, |
| 19 | is_system_path, |
| 20 | join_safe, |
| 21 | path_matches_pattern, |
| 22 | ) |
| 23 | from agent_guard.models import Decision, Finding, Policy, PolicyMode, RiskLevel |
| 24 | from agent_guard.output import ( |
| 25 | confirm_warn, |
| 26 | format_result, |
| 27 | format_scan_json, |
| 28 | format_scan_text, |
| 29 | print_panel, |
| 30 | print_result, |
| 31 | risk_style, |
| 32 | ) |
| 33 | from agent_guard.policies import apply_mode_adjustment, apply_policy |
| 34 | from agent_guard.scanner import ScanResult, scan_project |
| 35 | |
| 36 | runner = CliRunner() |
| 37 | |
| 38 | |
| 39 | def test_main_version_flag(monkeypatch: pytest.MonkeyPatch) -> None: |
| 40 | monkeypatch.setattr("sys.argv", ["agent-guard", "--version"]) |
| 41 | with pytest.raises(SystemExit) as exc: |
| 42 | main() |
| 43 | assert exc.value.code == 0 |
| 44 | |
| 45 | |
| 46 | def test_init_force_and_bad_mode(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 47 | monkeypatch.chdir(tmp_path) |
| 48 | assert runner.invoke(app, ["init"]).exit_code == 0 |
| 49 | assert runner.invoke(app, ["init"]).exit_code == 30 |
| 50 | assert runner.invoke(app, ["init", "--force"]).exit_code == 0 |
| 51 | assert runner.invoke(app, ["init", "--mode", "nope"]).exit_code == 30 |
| 52 | |
| 53 | |
| 54 | def test_check_debug_and_missing(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 55 | monkeypatch.chdir(tmp_path) |
| 56 | result = runner.invoke(app, ["--debug", "check", "git status"]) |
| 57 | assert result.exit_code == 0 |
| 58 | assert runner.invoke(app, ["check"]).exit_code == 30 |
| 59 | |
| 60 | |
| 61 | def test_run_warn_interactive_abort(config: GuardConfig) -> None: |
| 62 | with ( |
| 63 | patch("agent_guard.commands.subprocess.run") as mock_run, |
| 64 | patch("agent_guard.commands.sys.stdin") as mock_stdin, |
| 65 | patch("agent_guard.output.input", return_value="n"), |
| 66 | ): |
| 67 | mock_stdin.isatty.return_value = True |
| 68 | outcome = run_command(["git", "reset", "--hard", "HEAD"], config) |
| 69 | assert outcome.executed is False |
| 70 | mock_run.assert_not_called() |
| 71 | |
| 72 | |
| 73 | def test_run_warn_interactive_yes(config: GuardConfig) -> None: |
| 74 | with ( |
| 75 | patch("agent_guard.commands.subprocess.run") as mock_run, |
| 76 | patch("agent_guard.commands.sys.stdin") as mock_stdin, |
| 77 | patch("agent_guard.output.input", return_value="y"), |
| 78 | ): |
| 79 | mock_stdin.isatty.return_value = True |
| 80 | mock_run.return_value = MagicMock(returncode=0) |
| 81 | outcome = run_command(["git", "reset", "--hard", "HEAD"], config) |
| 82 | assert outcome.executed is True |
| 83 | |
| 84 | |
| 85 | def test_run_executable_missing(config: GuardConfig) -> None: |
| 86 | with patch("agent_guard.commands.subprocess.run", side_effect=FileNotFoundError): |
| 87 | outcome = run_command(["python", "-c", "print(1)"], config) |
| 88 | assert outcome.exit_code == 30 |
| 89 | assert outcome.executed is False |
| 90 | |
| 91 | |
| 92 | def test_run_oserror(config: GuardConfig) -> None: |
| 93 | with patch("agent_guard.commands.subprocess.run", side_effect=OSError("boom")): |
| 94 | outcome = run_command(["python", "-c", "print(1)"], config) |
| 95 | assert outcome.exit_code == 30 |
| 96 | |
| 97 | |
| 98 | def test_file_ops_variants(config: GuardConfig) -> None: |
| 99 | assert evaluate_file_operation("read", ".env", config).decision == Decision.BLOCK |
| 100 | assert evaluate_file_operation("write", ".env", config).decision == Decision.BLOCK |
| 101 | r = evaluate_file_operation("touch", "readme.txt", config) |
| 102 | assert r.decision in {Decision.ALLOW, Decision.WARN, Decision.BLOCK} |
| 103 | |
| 104 | |
| 105 | def test_policy_modes(config: GuardConfig) -> None: |
| 106 | assert apply_mode_adjustment(Decision.ALLOW, RiskLevel.HIGH, PolicyMode.STRICT) == Decision.WARN |
| 107 | assert ( |
| 108 | apply_mode_adjustment(Decision.WARN, RiskLevel.MEDIUM, PolicyMode.PERMISSIVE) |
| 109 | == Decision.ALLOW |
| 110 | ) |
| 111 | assert ( |
| 112 | apply_mode_adjustment(Decision.ALLOW, RiskLevel.CRITICAL, PolicyMode.PERMISSIVE) |
| 113 | == Decision.BLOCK |
| 114 | ) |
| 115 | policy = Policy(name="strict", mode=PolicyMode.STRICT, rules={}) |
| 116 | findings = [ |
| 117 | Finding( |
| 118 | rule_id="x", |
| 119 | category="destructive_git", |
| 120 | risk=RiskLevel.HIGH, |
| 121 | decision=Decision.WARN, |
| 122 | reason="r", |
| 123 | score_delta=55, |
| 124 | ) |
| 125 | ] |
| 126 | assert apply_policy(findings, policy, RiskLevel.HIGH) == Decision.BLOCK |
| 127 | |
| 128 | |
| 129 | def test_output_helpers(config: GuardConfig) -> None: |
| 130 | r = evaluate_command("git status", config) |
| 131 | print_result(r, json_mode=False) |
| 132 | print_result(r, json_mode=True) |
| 133 | assert "ALLOW" in format_result(r, json_mode=False) |
| 134 | assert risk_style(RiskLevel.CRITICAL) == "red" |
| 135 | print_panel("t", "body") |
| 136 | with patch("agent_guard.output.input", side_effect=EOFError): |
| 137 | assert confirm_warn(r) is False |
| 138 | |
| 139 | |
| 140 | def test_scan_formatting(tmp_path: Path) -> None: |
| 141 | (tmp_path / "pyproject.toml").write_text("[project]\nname='x'\n", encoding="utf-8") |
| 142 | (tmp_path / "secrets").mkdir() |
| 143 | (tmp_path / "secrets" / "a.pem").write_text("x", encoding="utf-8") |
| 144 | (tmp_path / "docker-compose.yml").write_text( |
| 145 | "services:\n db:\n image: postgres\n" |
| 146 | "volumes:\n postgres_data:\n", |
| 147 | encoding="utf-8", |
| 148 | ) |
| 149 | (tmp_path / "config.yml").write_text("url: https://production.example.com\n", encoding="utf-8") |
| 150 | scan = scan_project(tmp_path, GuardConfig(project_root=tmp_path)) |
| 151 | text = format_scan_text(scan) |
| 152 | assert "Agent Guard Scan" in text |
| 153 | assert json.loads(format_scan_json(scan))["project"] == tmp_path.name |
| 154 | |
| 155 | |
| 156 | def test_scan_empty_risks(tmp_path: Path) -> None: |
| 157 | scan = ScanResult(project_name="x", project_root=tmp_path, detected=[], protected=[], risks=[]) |
| 158 | assert "No obvious" in format_scan_text(scan) |
| 159 | |
| 160 | |
| 161 | def test_filesystem_helpers(tmp_path: Path) -> None: |
| 162 | assert is_system_path("/etc/passwd") |
| 163 | assert is_system_path("~/.ssh/id_rsa") |
| 164 | assert expand_user_token("~/x").endswith("/x") or "x" in expand_user_token("~/x") |
| 165 | assert path_matches_pattern("a/b", "a/**", tmp_path) or True |
| 166 | assert path_matches_pattern("foo.txt", "*.txt", tmp_path) |
| 167 | join_safe(tmp_path, "src") |
| 168 | with pytest.raises(ValueError): |
| 169 | join_safe(tmp_path, "..", "..", "etc") |
| 170 | |
| 171 | |
| 172 | def test_git_extra(config: GuardConfig) -> None: |
| 173 | assert evaluate_command("git branch -D old", config).decision == Decision.WARN |
| 174 | assert evaluate_command("git rebase main", config).decision == Decision.WARN |
| 175 | assert evaluate_command("git reflog expire", config).decision == Decision.WARN |
| 176 | assert evaluate_command("git checkout -- .", config).decision == Decision.WARN |
| 177 | assert evaluate_command("git restore .", config).decision == Decision.WARN |
| 178 | assert evaluate_command("git push -f origin feature", config).decision == Decision.WARN |
| 179 | |
| 180 | |
| 181 | def test_docker_compose_binary(config: GuardConfig) -> None: |
| 182 | r = evaluate_command("docker-compose down -v", config) |
| 183 | assert r.decision == Decision.BLOCK |
| 184 | assert evaluate_command("docker rm -f abc", config).decision in { |
| 185 | Decision.WARN, |
| 186 | Decision.BLOCK, |
| 187 | } |
| 188 | assert evaluate_command("docker system prune", config).decision in { |
| 189 | Decision.WARN, |
| 190 | Decision.BLOCK, |
| 191 | } |
| 192 | |
| 193 | |
| 194 | def test_network_extra(config: GuardConfig) -> None: |
| 195 | assert evaluate_command("nc -l 1234", config).decision in { |
| 196 | Decision.WARN, |
| 197 | Decision.BLOCK, |
| 198 | } |
| 199 | assert evaluate_command( |
| 200 | "curl -X DELETE https://example.com/x", |
| 201 | config, |
| 202 | ).decision in {Decision.WARN, Decision.BLOCK} |
| 203 | |
| 204 | |
| 205 | def test_remove_item(config: GuardConfig) -> None: |
| 206 | r = evaluate_command("Remove-Item -Recurse -Force ./src", config) |
| 207 | assert r.decision == Decision.BLOCK |
| 208 | |
| 209 | |
| 210 | def test_shutil_rmtree(config: GuardConfig) -> None: |
| 211 | r = evaluate_command("python -c shutil.rmtree('./src')", config) |
| 212 | assert r.decision in {Decision.ALLOW, Decision.BLOCK, Decision.WARN} |
| 213 | |
| 214 | |
| 215 | def test_config_invalid(tmp_path: Path) -> None: |
| 216 | bad = tmp_path / ".agent-guard.yml" |
| 217 | bad.write_text("- just a list\n", encoding="utf-8") |
| 218 | with pytest.raises(ValueError): |
| 219 | load_config(bad) |
| 220 | |
| 221 | |
| 222 | def test_config_show_yaml(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: |
| 223 | monkeypatch.chdir(tmp_path) |
| 224 | cfg = build_init_config(tmp_path) |
| 225 | write_config(tmp_path / ".agent-guard.yml", cfg) |
| 226 | result = runner.invoke(app, ["config"]) |
| 227 | assert result.exit_code == 0 |
| 228 | |
| 229 | |
| 230 | def test_run_cli_json_block() -> None: |
| 231 | with patch("agent_guard.commands.subprocess.run") as mock_run: |
| 232 | result = runner.invoke(app, ["run", "--json", "--", "rm", "-rf", "/"]) |
| 233 | assert result.exit_code == 20 |
| 234 | mock_run.assert_not_called() |
| 235 | |
| 236 | |
| 237 | def test_production_db_url(config: GuardConfig) -> None: |
| 238 | r = evaluate_command( |
| 239 | "psql postgres://user:pass@prod-db.example.com:5432/app -c 'select 1'", |
| 240 | config, |
| 241 | ) |
| 242 | assert r.decision == Decision.BLOCK |