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 | """Docker volume and prune protection rules.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | import re |
| 7 | from pathlib import Path |
| 8 | |
| 9 | from agent_guard.config import GuardConfig |
| 10 | from agent_guard.models import Decision, Finding, ParsedCommand, RiskLevel |
| 11 | from agent_guard.risk import SCORE_DOCKER_VOLUME_DELETE |
| 12 | from agent_guard.rules import RuleDefinition, register_rule |
| 13 | |
| 14 | _DB_VOLUME_HINTS = ( |
| 15 | "mongo", |
| 16 | "postgres", |
| 17 | "postgresql", |
| 18 | "mysql", |
| 19 | "mariadb", |
| 20 | "redis", |
| 21 | "data", |
| 22 | "db", |
| 23 | ) |
| 24 | |
| 25 | |
| 26 | def _prog(parsed: ParsedCommand) -> str: |
| 27 | prog = parsed.program.lower().replace("\\", "/").split("/")[-1] |
| 28 | if prog.endswith(".exe"): |
| 29 | prog = prog[:-4] |
| 30 | return prog |
| 31 | |
| 32 | |
| 33 | def _is_docker(parsed: ParsedCommand) -> bool: |
| 34 | return _prog(parsed) in {"docker", "docker-compose", "podman"} |
| 35 | |
| 36 | |
| 37 | def _compose_subcommand(parsed: ParsedCommand) -> str | None: |
| 38 | sub = (parsed.subcommand or "").lower() |
| 39 | if sub.startswith("compose"): |
| 40 | parts = sub.split() |
| 41 | return parts[1] if len(parts) > 1 else None |
| 42 | if _prog(parsed) in {"docker-compose", "podman-compose"}: |
| 43 | return (parsed.subcommand or "").lower() or None |
| 44 | return None |
| 45 | |
| 46 | |
| 47 | def _discover_volume_names(project_root: Path) -> list[str]: |
| 48 | names: list[str] = [] |
| 49 | for fname in ("docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml"): |
| 50 | path = project_root / fname |
| 51 | if not path.is_file(): |
| 52 | continue |
| 53 | try: |
| 54 | text = path.read_text(encoding="utf-8", errors="replace") |
| 55 | except OSError: |
| 56 | continue |
| 57 | # volumes: section keys (simple YAML heuristic — no execution) |
| 58 | in_volumes = False |
| 59 | for line in text.splitlines(): |
| 60 | if re.match(r"^volumes:\s*$", line): |
| 61 | in_volumes = True |
| 62 | continue |
| 63 | if in_volumes: |
| 64 | if line and not line[0].isspace() and not line.startswith("#"): |
| 65 | in_volumes = False |
| 66 | continue |
| 67 | m = re.match(r"^\s{2,}([A-Za-z0-9._-]+):\s*(?:$|#|null|{})", line) |
| 68 | if m: |
| 69 | names.append(m.group(1)) |
| 70 | # Also named volumes under services |
| 71 | for m in re.finditer(r"^\s+-\s+([A-Za-z0-9._-]+):", text, re.MULTILINE): |
| 72 | vol = m.group(1) |
| 73 | if vol not in names and any(h in vol.lower() for h in _DB_VOLUME_HINTS): |
| 74 | names.append(vol) |
| 75 | return names |
| 76 | |
| 77 | |
| 78 | @register_rule( |
| 79 | RuleDefinition( |
| 80 | id="docker.volume_delete", |
| 81 | category="docker_volume_delete", |
| 82 | risk=RiskLevel.CRITICAL, |
| 83 | default_decision=Decision.BLOCK, |
| 84 | description="Detects Docker volume deletion and compose down -v.", |
| 85 | ) |
| 86 | ) |
| 87 | def rule_docker_volume(parsed: ParsedCommand, config: GuardConfig) -> list[Finding]: |
| 88 | if not _is_docker(parsed): |
| 89 | return [] |
| 90 | |
| 91 | prog = _prog(parsed) |
| 92 | sub = (parsed.subcommand or "").lower() |
| 93 | flags = set(parsed.flags) |
| 94 | args = [a.lower() for a in parsed.arguments] |
| 95 | findings: list[Finding] = [] |
| 96 | |
| 97 | compose_sub = _compose_subcommand(parsed) |
| 98 | if compose_sub == "down" and ( |
| 99 | "-v" in flags or "--volumes" in flags or "-v" in args or "--volumes" in args |
| 100 | ): |
| 101 | volumes = _discover_volume_names(config.project_root) |
| 102 | db_vols = [v for v in volumes if any(h in v.lower() for h in _DB_VOLUME_HINTS)] |
| 103 | detected = tuple(db_vols or volumes or ("named volumes",)) |
| 104 | findings.append( |
| 105 | Finding( |
| 106 | rule_id="docker.compose_down_volumes", |
| 107 | category="docker_volume_delete", |
| 108 | risk=RiskLevel.CRITICAL, |
| 109 | decision=Decision.BLOCK, |
| 110 | reason="Docker volumes may contain persistent application data.", |
| 111 | score_delta=SCORE_DOCKER_VOLUME_DELETE, |
| 112 | detected=detected, |
| 113 | suggestions=( |
| 114 | "Omit -v/--volumes to preserve data.", |
| 115 | "Back up volumes before removal.", |
| 116 | ), |
| 117 | ) |
| 118 | ) |
| 119 | |
| 120 | if sub == "volume": |
| 121 | # positional may still include "volume" as first token depending on parser |
| 122 | tokens = [p.lower() for p in parsed.positional] |
| 123 | if tokens and tokens[0] == "volume": |
| 124 | tokens = tokens[1:] |
| 125 | action = tokens[0] if tokens else "" |
| 126 | if action in {"rm", "remove", "prune"}: |
| 127 | targets = tuple(tokens[1:]) if len(tokens) > 1 else () |
| 128 | findings.append( |
| 129 | Finding( |
| 130 | rule_id="docker.volume_rm", |
| 131 | category="docker_volume_delete", |
| 132 | risk=RiskLevel.CRITICAL, |
| 133 | decision=Decision.BLOCK, |
| 134 | reason="Persistent Docker volumes may be deleted.", |
| 135 | target=" ".join(targets) if targets else None, |
| 136 | score_delta=SCORE_DOCKER_VOLUME_DELETE, |
| 137 | detected=targets or ("volume prune",), |
| 138 | ) |
| 139 | ) |
| 140 | |
| 141 | if sub == "system" and "prune" in [p.lower() for p in parsed.positional]: |
| 142 | aggressive = "-a" in flags or "--all" in flags |
| 143 | findings.append( |
| 144 | Finding( |
| 145 | rule_id="docker.system_prune", |
| 146 | category="docker_volume_delete", |
| 147 | risk=RiskLevel.CRITICAL if aggressive else RiskLevel.HIGH, |
| 148 | decision=Decision.BLOCK if aggressive else Decision.WARN, |
| 149 | reason="docker system prune can remove unused images, containers, and networks" |
| 150 | + (" (including all unused images with -a)." if aggressive else "."), |
| 151 | score_delta=SCORE_DOCKER_VOLUME_DELETE if aggressive else 50, |
| 152 | ) |
| 153 | ) |
| 154 | |
| 155 | if sub == "rm" and ("-f" in flags or "--force" in flags): |
| 156 | findings.append( |
| 157 | Finding( |
| 158 | rule_id="docker.rm_force", |
| 159 | category="docker_volume_delete", |
| 160 | risk=RiskLevel.MEDIUM, |
| 161 | decision=Decision.WARN, |
| 162 | reason="Force-removing containers may interrupt running workloads.", |
| 163 | score_delta=30, |
| 164 | ) |
| 165 | ) |
| 166 | |
| 167 | # docker-compose / podman-compose as binary |
| 168 | if prog in {"docker-compose", "podman-compose"} or prog.endswith("docker-compose"): |
| 169 | compose_action = (parsed.subcommand or "").lower() |
| 170 | if not compose_action and parsed.positional: |
| 171 | compose_action = parsed.positional[0].lower() |
| 172 | if compose_action == "down" and ("-v" in flags or "--volumes" in flags): |
| 173 | volumes = _discover_volume_names(config.project_root) |
| 174 | db_vols = [v for v in volumes if any(h in v.lower() for h in _DB_VOLUME_HINTS)] |
| 175 | findings.append( |
| 176 | Finding( |
| 177 | rule_id="docker.compose_down_volumes", |
| 178 | category="docker_volume_delete", |
| 179 | risk=RiskLevel.CRITICAL, |
| 180 | decision=Decision.BLOCK, |
| 181 | reason="Docker volumes may contain persistent application data.", |
| 182 | score_delta=SCORE_DOCKER_VOLUME_DELETE, |
| 183 | detected=tuple(db_vols or volumes or ("named volumes",)), |
| 184 | ) |
| 185 | ) |
| 186 | |
| 187 | return findings |