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 | """Git operation protection rules.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | from agent_guard.config import GuardConfig |
| 7 | from agent_guard.models import Decision, Finding, ParsedCommand, RiskLevel |
| 8 | from agent_guard.risk import SCORE_DESTRUCTIVE_GIT, SCORE_FORCE_PUSH_PROTECTED |
| 9 | from agent_guard.rules import RuleDefinition, register_rule |
| 10 | |
| 11 | |
| 12 | def _prog(parsed: ParsedCommand) -> str: |
| 13 | prog = parsed.program.lower().replace("\\", "/").split("/")[-1] |
| 14 | if prog.endswith(".exe"): |
| 15 | prog = prog[:-4] |
| 16 | return prog |
| 17 | |
| 18 | |
| 19 | def _flags_set(flags: tuple[str, ...]) -> set[str]: |
| 20 | result: set[str] = set() |
| 21 | for f in flags: |
| 22 | result.add(f) |
| 23 | if f.startswith("--") and "=" in f: |
| 24 | result.add(f.split("=", 1)[0]) |
| 25 | # expand combined shorts already as whole tokens |
| 26 | return result |
| 27 | |
| 28 | |
| 29 | @register_rule( |
| 30 | RuleDefinition( |
| 31 | id="git.destructive", |
| 32 | category="destructive_git", |
| 33 | risk=RiskLevel.HIGH, |
| 34 | default_decision=Decision.WARN, |
| 35 | description="Detects destructive git operations (reset --hard, clean -fdx, restore .).", |
| 36 | ) |
| 37 | ) |
| 38 | def rule_destructive_git(parsed: ParsedCommand, config: GuardConfig) -> list[Finding]: |
| 39 | if _prog(parsed) != "git": |
| 40 | return [] |
| 41 | |
| 42 | sub = (parsed.subcommand or "").lower() |
| 43 | flags = _flags_set(parsed.flags) |
| 44 | pos = [p.lower() for p in parsed.positional] |
| 45 | args_lower = [a.lower() for a in parsed.arguments] |
| 46 | findings: list[Finding] = [] |
| 47 | |
| 48 | if sub == "reset" and ("--hard" in flags or "-hard" in flags): |
| 49 | findings.append( |
| 50 | Finding( |
| 51 | rule_id="git.reset_hard", |
| 52 | category="destructive_git", |
| 53 | risk=RiskLevel.HIGH, |
| 54 | decision=Decision.WARN, |
| 55 | reason="This operation can permanently discard uncommitted changes.", |
| 56 | target=" ".join(parsed.positional[1:]) or "HEAD", |
| 57 | score_delta=SCORE_DESTRUCTIVE_GIT, |
| 58 | suggestions=( |
| 59 | "Commit or stash changes first.", |
| 60 | "Use git reset --soft if you only need to move HEAD.", |
| 61 | ), |
| 62 | ) |
| 63 | ) |
| 64 | |
| 65 | if sub == "clean": |
| 66 | # -fd, -fdx, -ffd, etc. |
| 67 | destructive = False |
| 68 | for f in parsed.flags: |
| 69 | body = f[1:] if f.startswith("-") and not f.startswith("--") else "" |
| 70 | if "x" in body.lower() and "d" in body.lower(): |
| 71 | destructive = True |
| 72 | if f in {"-fdx", "-ffdx", "-fd", "-f", "-x", "-d", "--force"}: |
| 73 | if "x" in f or "--force" in flags or "-f" in flags or "f" in body: |
| 74 | destructive = True |
| 75 | if set(body.lower()) >= {"f", "d"} or set(body.lower()) >= {"f", "d", "x"}: |
| 76 | destructive = True |
| 77 | if any(f in {"-fdx", "-ffdx"} for f in parsed.flags) or ( |
| 78 | ("-f" in flags or "--force" in flags or any("f" in f[1:] for f in parsed.flags if f.startswith("-") and not f.startswith("--"))) |
| 79 | and any("d" in f[1:] for f in parsed.flags if f.startswith("-") and not f.startswith("--")) |
| 80 | ): |
| 81 | destructive = True |
| 82 | if destructive: |
| 83 | has_x = any("x" in f.lower() for f in parsed.flags) |
| 84 | findings.append( |
| 85 | Finding( |
| 86 | rule_id="git.clean_force", |
| 87 | category="destructive_git", |
| 88 | risk=RiskLevel.HIGH, |
| 89 | decision=Decision.WARN, |
| 90 | reason="git clean can permanently delete untracked files" |
| 91 | + (" and ignored files (-x)." if has_x else "."), |
| 92 | score_delta=SCORE_DESTRUCTIVE_GIT + (10 if has_x else 0), |
| 93 | suggestions=("Run git clean -n first to preview deletions.",), |
| 94 | ) |
| 95 | ) |
| 96 | |
| 97 | if sub in {"checkout", "restore"}: |
| 98 | # git checkout -- . / git restore . |
| 99 | if "." in parsed.positional or ("--" in parsed.arguments and "." in parsed.arguments): |
| 100 | # Discard working tree changes |
| 101 | if sub == "checkout" and "--" in args_lower: |
| 102 | findings.append( |
| 103 | Finding( |
| 104 | rule_id="git.discard_workdir", |
| 105 | category="destructive_git", |
| 106 | risk=RiskLevel.HIGH, |
| 107 | decision=Decision.WARN, |
| 108 | reason="This can discard local working tree changes.", |
| 109 | target=".", |
| 110 | score_delta=SCORE_DESTRUCTIVE_GIT, |
| 111 | ) |
| 112 | ) |
| 113 | if sub == "restore" and ("." in parsed.positional or not parsed.positional): |
| 114 | if "." in parsed.positional: |
| 115 | findings.append( |
| 116 | Finding( |
| 117 | rule_id="git.restore_all", |
| 118 | category="destructive_git", |
| 119 | risk=RiskLevel.HIGH, |
| 120 | decision=Decision.WARN, |
| 121 | reason="Restoring '.' can discard local modifications.", |
| 122 | target=".", |
| 123 | score_delta=SCORE_DESTRUCTIVE_GIT, |
| 124 | ) |
| 125 | ) |
| 126 | |
| 127 | if sub == "branch" and ("-D" in parsed.flags or "-D" in flags): |
| 128 | findings.append( |
| 129 | Finding( |
| 130 | rule_id="git.branch_force_delete", |
| 131 | category="destructive_git", |
| 132 | risk=RiskLevel.MEDIUM, |
| 133 | decision=Decision.WARN, |
| 134 | reason="Force-deleting a branch may lose commits.", |
| 135 | score_delta=30, |
| 136 | ) |
| 137 | ) |
| 138 | |
| 139 | if sub == "rebase": |
| 140 | findings.append( |
| 141 | Finding( |
| 142 | rule_id="git.rebase", |
| 143 | category="destructive_git", |
| 144 | risk=RiskLevel.MEDIUM, |
| 145 | decision=Decision.WARN, |
| 146 | reason="Rebase rewrites commit history and can cause conflicts.", |
| 147 | score_delta=35, |
| 148 | suggestions=("Prefer merge for shared branches.",), |
| 149 | ) |
| 150 | ) |
| 151 | |
| 152 | if sub == "reflog" and any(p == "expire" for p in pos): |
| 153 | findings.append( |
| 154 | Finding( |
| 155 | rule_id="git.reflog_expire", |
| 156 | category="destructive_git", |
| 157 | risk=RiskLevel.HIGH, |
| 158 | decision=Decision.WARN, |
| 159 | reason="Expiring reflog entries can make recovery impossible.", |
| 160 | score_delta=SCORE_DESTRUCTIVE_GIT, |
| 161 | ) |
| 162 | ) |
| 163 | |
| 164 | return findings |
| 165 | |
| 166 | |
| 167 | @register_rule( |
| 168 | RuleDefinition( |
| 169 | id="git.force_push_protected", |
| 170 | category="protected_branch_force_push", |
| 171 | risk=RiskLevel.CRITICAL, |
| 172 | default_decision=Decision.BLOCK, |
| 173 | description="Blocks force-push to protected branches (main, master, production, prod).", |
| 174 | ) |
| 175 | ) |
| 176 | def rule_force_push(parsed: ParsedCommand, config: GuardConfig) -> list[Finding]: |
| 177 | if _prog(parsed) != "git": |
| 178 | return [] |
| 179 | if (parsed.subcommand or "").lower() != "push": |
| 180 | return [] |
| 181 | |
| 182 | flags = _flags_set(parsed.flags) |
| 183 | force = ( |
| 184 | "--force" in flags |
| 185 | or "-f" in flags |
| 186 | or "--force-with-lease" in flags |
| 187 | or any(f == "-f" or f.startswith("--force") for f in parsed.flags) |
| 188 | ) |
| 189 | if not force: |
| 190 | return [] |
| 191 | |
| 192 | protected = {b.lower() for b in config.protected_branches} |
| 193 | # positional after push: [remote, refspec...] |
| 194 | [p for p in parsed.positional[1:]] # skip remote if present |
| 195 | # Also check all positional tokens |
| 196 | tokens = list(parsed.positional) |
| 197 | branch_hit: str | None = None |
| 198 | for tok in tokens: |
| 199 | # refspec main, origin/main, +main, refs/heads/main |
| 200 | clean = tok.lstrip("+").split(":")[0] |
| 201 | name = clean.split("/")[-1].lower() |
| 202 | if name in protected: |
| 203 | branch_hit = name |
| 204 | break |
| 205 | |
| 206 | if branch_hit: |
| 207 | return [ |
| 208 | Finding( |
| 209 | rule_id="git.force_push_protected", |
| 210 | category="protected_branch_force_push", |
| 211 | risk=RiskLevel.CRITICAL, |
| 212 | decision=Decision.BLOCK, |
| 213 | reason="Force pushing can rewrite shared repository history.", |
| 214 | target=branch_hit, |
| 215 | score_delta=SCORE_FORCE_PUSH_PROTECTED, |
| 216 | detected=(branch_hit,), |
| 217 | suggestions=( |
| 218 | "Push to a feature branch instead.", |
| 219 | "Remove --force / -f for protected branches.", |
| 220 | ), |
| 221 | ) |
| 222 | ] |
| 223 | |
| 224 | # Force push without clear branch still dangerous |
| 225 | return [ |
| 226 | Finding( |
| 227 | rule_id="git.force_push", |
| 228 | category="destructive_git", |
| 229 | risk=RiskLevel.HIGH, |
| 230 | decision=Decision.WARN, |
| 231 | reason="Force push can overwrite remote history.", |
| 232 | score_delta=60, |
| 233 | suggestions=("Prefer --force-with-lease and confirm the target branch.",), |
| 234 | ) |
| 235 | ] |