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 | """Project risk scanner — never prints secret values.""" |
| 3 | |
| 4 | from __future__ import annotations |
| 5 | |
| 6 | from dataclasses import dataclass, field |
| 7 | from pathlib import Path |
| 8 | |
| 9 | from agent_guard.config import GuardConfig, detect_project_signals, load_config |
| 10 | from agent_guard.filesystem import is_sensitive_filename |
| 11 | from agent_guard.redactor import find_secret_markers, redact |
| 12 | from agent_guard.rules.docker import _discover_volume_names |
| 13 | |
| 14 | |
| 15 | @dataclass |
| 16 | class ScanFinding: |
| 17 | severity: str # info | warn | risk |
| 18 | message: str |
| 19 | path: str | None = None |
| 20 | |
| 21 | |
| 22 | @dataclass |
| 23 | class ScanResult: |
| 24 | project_name: str |
| 25 | project_root: Path |
| 26 | detected: list[str] = field(default_factory=list) |
| 27 | protected: list[str] = field(default_factory=list) |
| 28 | risks: list[ScanFinding] = field(default_factory=list) |
| 29 | |
| 30 | def to_dict(self) -> dict[str, object]: |
| 31 | return { |
| 32 | "project": self.project_name, |
| 33 | "project_root": str(self.project_root), |
| 34 | "detected": list(self.detected), |
| 35 | "protected": list(self.protected), |
| 36 | "risks": [ |
| 37 | {"severity": r.severity, "message": r.message, "path": r.path} for r in self.risks |
| 38 | ], |
| 39 | } |
| 40 | |
| 41 | |
| 42 | _PROD_URL_HINTS = ("production.", "prod.", "://prod", "LIVE_DATABASE", "PRODUCTION_URL") |
| 43 | |
| 44 | |
| 45 | def scan_project(root: Path | None = None, config: GuardConfig | None = None) -> ScanResult: |
| 46 | """Scan project for risky configuration. Never reads/print secret values.""" |
| 47 | project_root = (root or Path.cwd()).resolve() |
| 48 | cfg = config or load_config(project_root=project_root) |
| 49 | signals = detect_project_signals(project_root) |
| 50 | |
| 51 | detected: list[str] = [] |
| 52 | if signals["git"]: |
| 53 | detected.append("Git repository") |
| 54 | if signals["node"]: |
| 55 | detected.append("Node.js") |
| 56 | if signals["python"]: |
| 57 | detected.append("Python") |
| 58 | if signals["docker"]: |
| 59 | detected.append("Docker Compose") |
| 60 | if signals["mongodb"]: |
| 61 | detected.append("MongoDB configuration") |
| 62 | if signals["postgres"]: |
| 63 | detected.append("PostgreSQL configuration") |
| 64 | if signals["mysql"]: |
| 65 | detected.append("MySQL configuration") |
| 66 | if signals["redis"]: |
| 67 | detected.append("Redis configuration") |
| 68 | |
| 69 | protected: list[str] = [] |
| 70 | for pattern in cfg.protected_paths: |
| 71 | # Check if something matching exists (names only) |
| 72 | if pattern.endswith("/**") or pattern.endswith("/"): |
| 73 | base = pattern.rstrip("/*") |
| 74 | if (project_root / base).exists(): |
| 75 | protected.append(pattern.rstrip("/")) |
| 76 | elif "*" in pattern: |
| 77 | matches = list(project_root.glob(pattern)) |
| 78 | if matches: |
| 79 | protected.append(pattern) |
| 80 | else: |
| 81 | if (project_root / pattern).exists(): |
| 82 | protected.append(pattern) |
| 83 | |
| 84 | risks: list[ScanFinding] = [] |
| 85 | |
| 86 | # Docker volumes |
| 87 | volumes = _discover_volume_names(project_root) |
| 88 | for vol in volumes: |
| 89 | if any(h in vol.lower() for h in ("mongo", "redis", "postgres", "mysql", "data", "db")): |
| 90 | risks.append( |
| 91 | ScanFinding( |
| 92 | severity="warn", |
| 93 | message=f"Docker volume: {vol}", |
| 94 | path=None, |
| 95 | ) |
| 96 | ) |
| 97 | |
| 98 | # Sensitive files outside protected list |
| 99 | unprotected_secrets = 0 |
| 100 | for path in project_root.rglob("*"): |
| 101 | if not path.is_file(): |
| 102 | continue |
| 103 | try: |
| 104 | rel = path.relative_to(project_root).as_posix() |
| 105 | except ValueError: |
| 106 | continue |
| 107 | # Skip huge trees |
| 108 | if any(part in {".git", "node_modules", ".venv", "venv", "dist", "build"} for part in path.parts): |
| 109 | continue |
| 110 | if is_sensitive_filename(rel) or is_sensitive_filename(path.name): |
| 111 | from agent_guard.filesystem import matches_protected_path |
| 112 | |
| 113 | if not matches_protected_path(rel, cfg.protected_paths, project_root): |
| 114 | unprotected_secrets += 1 |
| 115 | if unprotected_secrets <= 5: |
| 116 | risks.append( |
| 117 | ScanFinding( |
| 118 | severity="warn", |
| 119 | message="Sensitive file outside protected paths", |
| 120 | path=rel, |
| 121 | ) |
| 122 | ) |
| 123 | |
| 124 | if unprotected_secrets > 5: |
| 125 | risks.append( |
| 126 | ScanFinding( |
| 127 | severity="warn", |
| 128 | message=f"{unprotected_secrets} sensitive files outside protected paths", |
| 129 | ) |
| 130 | ) |
| 131 | elif unprotected_secrets == 2: |
| 132 | # Match example wording when exactly 2 |
| 133 | pass |
| 134 | |
| 135 | # Production URL hints in config files (names only — redact any values) |
| 136 | for fname in ( |
| 137 | "docker-compose.yml", |
| 138 | "docker-compose.yaml", |
| 139 | "compose.yml", |
| 140 | ".env.example", |
| 141 | "config.yml", |
| 142 | "config.yaml", |
| 143 | "appsettings.json", |
| 144 | "settings.py", |
| 145 | ): |
| 146 | fpath = project_root / fname |
| 147 | if not fpath.is_file(): |
| 148 | continue |
| 149 | try: |
| 150 | # Read limited bytes; never display secrets |
| 151 | text = fpath.read_text(encoding="utf-8", errors="replace")[:50_000] |
| 152 | except OSError: |
| 153 | continue |
| 154 | redacted = redact(text) |
| 155 | if any(h.lower() in redacted.lower() for h in _PROD_URL_HINTS): |
| 156 | risks.append( |
| 157 | ScanFinding( |
| 158 | severity="warn", |
| 159 | message="Production URL detected in configuration", |
| 160 | path=fname, |
| 161 | ) |
| 162 | ) |
| 163 | markers = find_secret_markers(text) |
| 164 | if markers and fname.endswith((".yml", ".yaml", ".json", ".py")): |
| 165 | # Only note presence of markers, not values |
| 166 | pass |
| 167 | |
| 168 | return ScanResult( |
| 169 | project_name=project_root.name, |
| 170 | project_root=project_root, |
| 171 | detected=detected, |
| 172 | protected=protected or [p for p in (".env", ".git", "secrets/") if True and ( |
| 173 | (project_root / p.rstrip("/")).exists() or p.endswith("/") |
| 174 | )], |
| 175 | risks=risks, |
| 176 | ) |