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 | """Configuration loading and project init helpers.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | from dataclasses import dataclass, field |
| 7 | from pathlib import Path |
| 8 | from typing import Any |
| 9 | |
| 10 | import yaml |
| 11 | |
| 12 | from agent_guard.models import Decision, Policy, PolicyMode |
| 13 | |
| 14 | CONFIG_FILENAME = ".agent-guard.yml" |
| 15 | DEFAULT_PROTECTED_BRANCHES = ("main", "master", "production", "prod") |
| 16 | |
| 17 | DEFAULT_PROTECTED_PATHS = ( |
| 18 | ".env", |
| 19 | ".env.*", |
| 20 | ".git/", |
| 21 | ".git/**", |
| 22 | "~/.ssh/", |
| 23 | "~/.ssh/**", |
| 24 | "~/.aws/", |
| 25 | "~/.aws/**", |
| 26 | "~/.config/", |
| 27 | "credentials.json", |
| 28 | "service-account.json", |
| 29 | "*.pem", |
| 30 | "*.key", |
| 31 | "id_rsa", |
| 32 | "id_ed25519", |
| 33 | "secrets/**", |
| 34 | ) |
| 35 | |
| 36 | DEFAULT_WRITABLE_PATHS = ( |
| 37 | "src/", |
| 38 | "tests/", |
| 39 | "docs/", |
| 40 | ) |
| 41 | |
| 42 | DEFAULT_RULES: dict[str, str] = { |
| 43 | "destructive_filesystem": "block", |
| 44 | "destructive_git": "warn", |
| 45 | "protected_branch_force_push": "block", |
| 46 | "secret_access": "block", |
| 47 | "docker_volume_delete": "block", |
| 48 | "production_network": "block", |
| 49 | "database_destructive": "block", |
| 50 | "shell_chain_destructive": "warn", |
| 51 | } |
| 52 | |
| 53 | |
| 54 | @dataclass |
| 55 | class GuardConfig: |
| 56 | """Runtime configuration for agent-guard.""" |
| 57 | |
| 58 | version: int = 1 |
| 59 | project_root: Path = field(default_factory=Path.cwd) |
| 60 | protected_paths: list[str] = field(default_factory=lambda: list(DEFAULT_PROTECTED_PATHS)) |
| 61 | writable_paths: list[str] = field(default_factory=lambda: list(DEFAULT_WRITABLE_PATHS)) |
| 62 | protected_branches: list[str] = field( |
| 63 | default_factory=lambda: list(DEFAULT_PROTECTED_BRANCHES) |
| 64 | ) |
| 65 | protected_hosts: list[str] = field(default_factory=list) |
| 66 | rules: dict[str, Decision] = field(default_factory=dict) |
| 67 | mode: PolicyMode = PolicyMode.DEFAULT |
| 68 | config_path: Path | None = None |
| 69 | |
| 70 | def __post_init__(self) -> None: |
| 71 | if not self.rules: |
| 72 | self.rules = {k: Decision(v.upper()) for k, v in DEFAULT_RULES.items()} |
| 73 | |
| 74 | def to_policy(self) -> Policy: |
| 75 | return Policy(name=self.mode.value, mode=self.mode, rules=dict(self.rules)) |
| 76 | |
| 77 | def to_dict(self) -> dict[str, Any]: |
| 78 | return { |
| 79 | "version": self.version, |
| 80 | "project_root": ".", |
| 81 | "mode": self.mode.value, |
| 82 | "protected_paths": list(self.protected_paths), |
| 83 | "writable_paths": list(self.writable_paths), |
| 84 | "protected_branches": list(self.protected_branches), |
| 85 | "network": {"protected_hosts": list(self.protected_hosts)}, |
| 86 | "rules": {k: v.value.lower() for k, v in self.rules.items()}, |
| 87 | } |
| 88 | |
| 89 | |
| 90 | def _parse_decision(value: Any) -> Decision: |
| 91 | text = str(value).strip().upper() |
| 92 | try: |
| 93 | return Decision(text) |
| 94 | except ValueError as exc: |
| 95 | raise ValueError(f"Invalid decision value: {value!r}") from exc |
| 96 | |
| 97 | |
| 98 | def _parse_mode(value: Any) -> PolicyMode: |
| 99 | text = str(value).strip().lower() |
| 100 | try: |
| 101 | return PolicyMode(text) |
| 102 | except ValueError as exc: |
| 103 | raise ValueError(f"Invalid policy mode: {value!r}") from exc |
| 104 | |
| 105 | |
| 106 | def find_config_file(start: Path | None = None) -> Path | None: |
| 107 | """Walk upward from *start* looking for ``.agent-guard.yml``.""" |
| 108 | current = (start or Path.cwd()).resolve() |
| 109 | for directory in [current, *current.parents]: |
| 110 | candidate = directory / CONFIG_FILENAME |
| 111 | if candidate.is_file(): |
| 112 | return candidate |
| 113 | return None |
| 114 | |
| 115 | |
| 116 | def load_config(path: Path | None = None, *, project_root: Path | None = None) -> GuardConfig: |
| 117 | """Load config from disk or return defaults.""" |
| 118 | root = (project_root or Path.cwd()).resolve() |
| 119 | config_path = path or find_config_file(root) |
| 120 | |
| 121 | if config_path is None: |
| 122 | return GuardConfig(project_root=root) |
| 123 | |
| 124 | raw = yaml.safe_load(config_path.read_text(encoding="utf-8")) or {} |
| 125 | if not isinstance(raw, dict): |
| 126 | raise ValueError(f"Invalid config format in {config_path}") |
| 127 | |
| 128 | cfg_root = raw.get("project_root", ".") |
| 129 | resolved_root = (config_path.parent / str(cfg_root)).resolve() |
| 130 | |
| 131 | rules_raw = raw.get("rules") or {} |
| 132 | rules: dict[str, Decision] = { |
| 133 | k: Decision(v.upper()) if isinstance(v, str) else _parse_decision(v) |
| 134 | for k, v in {**DEFAULT_RULES, **rules_raw}.items() |
| 135 | } |
| 136 | |
| 137 | network = raw.get("network") or {} |
| 138 | protected_hosts = list(network.get("protected_hosts") or raw.get("protected_hosts") or []) |
| 139 | |
| 140 | mode_raw = raw.get("mode", PolicyMode.DEFAULT.value) |
| 141 | return GuardConfig( |
| 142 | version=int(raw.get("version", 1)), |
| 143 | project_root=resolved_root, |
| 144 | protected_paths=list(raw.get("protected_paths") or DEFAULT_PROTECTED_PATHS), |
| 145 | writable_paths=list(raw.get("writable_paths") or DEFAULT_WRITABLE_PATHS), |
| 146 | protected_branches=list(raw.get("protected_branches") or DEFAULT_PROTECTED_BRANCHES), |
| 147 | protected_hosts=protected_hosts, |
| 148 | rules=rules, |
| 149 | mode=_parse_mode(mode_raw), |
| 150 | config_path=config_path, |
| 151 | ) |
| 152 | |
| 153 | |
| 154 | def dump_config(config: GuardConfig) -> str: |
| 155 | """Serialize config to YAML with relative paths only.""" |
| 156 | data = config.to_dict() |
| 157 | return yaml.safe_dump(data, default_flow_style=False, sort_keys=False) |
| 158 | |
| 159 | |
| 160 | def write_config(path: Path, config: GuardConfig) -> None: |
| 161 | path.write_text(dump_config(config), encoding="utf-8") |
| 162 | |
| 163 | |
| 164 | def detect_project_signals(root: Path) -> dict[str, bool]: |
| 165 | """Detect common project tooling without reading secret values.""" |
| 166 | root = root.resolve() |
| 167 | return { |
| 168 | "git": (root / ".git").exists(), |
| 169 | "node": (root / "package.json").is_file(), |
| 170 | "python": any( |
| 171 | (root / name).is_file() |
| 172 | for name in ("pyproject.toml", "setup.py", "requirements.txt", "Pipfile") |
| 173 | ), |
| 174 | "docker": any( |
| 175 | (root / name).is_file() |
| 176 | for name in ("Dockerfile", "docker-compose.yml", "docker-compose.yaml", "compose.yml") |
| 177 | ), |
| 178 | "mongodb": _mentions_in_compose(root, ("mongo", "mongodb")), |
| 179 | "postgres": _mentions_in_compose(root, ("postgres", "postgresql")), |
| 180 | "mysql": _mentions_in_compose(root, ("mysql", "mariadb")), |
| 181 | "redis": _mentions_in_compose(root, ("redis",)), |
| 182 | "env_file": (root / ".env").is_file() or any(root.glob(".env.*")), |
| 183 | } |
| 184 | |
| 185 | |
| 186 | def _mentions_in_compose(root: Path, needles: tuple[str, ...]) -> bool: |
| 187 | for name in ("docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml"): |
| 188 | path = root / name |
| 189 | if not path.is_file(): |
| 190 | continue |
| 191 | try: |
| 192 | text = path.read_text(encoding="utf-8", errors="replace").lower() |
| 193 | except OSError: |
| 194 | continue |
| 195 | if any(n in text for n in needles): |
| 196 | return True |
| 197 | return False |
| 198 | |
| 199 | |
| 200 | def build_init_config(root: Path, mode: PolicyMode = PolicyMode.DEFAULT) -> GuardConfig: |
| 201 | """Build a starter config for the current project.""" |
| 202 | signals = detect_project_signals(root) |
| 203 | protected = list(DEFAULT_PROTECTED_PATHS) |
| 204 | writable = list(DEFAULT_WRITABLE_PATHS) |
| 205 | |
| 206 | if signals["node"]: |
| 207 | writable.extend([".", "public/", "scripts/"]) |
| 208 | if signals["python"]: |
| 209 | writable.extend([".", "scripts/"]) |
| 210 | |
| 211 | # Deduplicate while preserving order |
| 212 | def uniq(items: list[str]) -> list[str]: |
| 213 | seen: set[str] = set() |
| 214 | out: list[str] = [] |
| 215 | for item in items: |
| 216 | if item not in seen: |
| 217 | seen.add(item) |
| 218 | out.append(item) |
| 219 | return out |
| 220 | |
| 221 | return GuardConfig( |
| 222 | project_root=root.resolve(), |
| 223 | protected_paths=uniq(protected), |
| 224 | writable_paths=uniq(writable), |
| 225 | mode=mode, |
| 226 | rules={k: Decision(v.upper()) for k, v in DEFAULT_RULES.items()}, |
| 227 | ) |