checkforge 0.1.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checkforge/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """checkforge — agregador de auditorías de repositorios, arquitectura de plugins."""
2
+
3
+ __version__ = "0.1.8"
checkforge/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
File without changes
@@ -0,0 +1,208 @@
1
+ """Ficheros Python que ningún otro fichero del repo importa.
2
+
3
+ Heurística estática basada en `import`/`from ... import` (con `ast`, así
4
+ que resuelve los imports relativos y `from paquete import submodulo`), sin
5
+ ejecutar código. También cuentan como uso los puntos de entrada de
6
+ `[project.scripts]`, los `python -m modulo` que aparezcan en el repo y los
7
+ directorios que Ansible carga por convención (`library/`, `module_utils/`). **Solo Python por ahora** (el soporte a otros lenguajes es el
8
+ caso de uso ideal para un plugin de terceros -- ver `plugin.py`). Como
9
+ toda heurística estática, puede haber falsos positivos (import dinámico,
10
+ entry points, ficheros cargados por un framework por convención) -- por
11
+ eso la severidad es baja y el mensaje lo deja claro.
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import ast
16
+ import re
17
+ import subprocess
18
+ import tomllib
19
+ from pathlib import Path
20
+
21
+ from ..plugin import CheckResult, Finding
22
+
23
+ _IMPORT_RE = re.compile(
24
+ r"^\s*(?:from\s+([.\w]+)\s+import|import\s+([.\w]+(?:\s*,\s*[.\w]+)*))",
25
+ re.MULTILINE,
26
+ )
27
+
28
+ # Ficheros que un import no referenciaria nunca pero que sí "se usan":
29
+ # puntos de entrada, convenciones de framework/test-runner, config.
30
+ _SPECIAL_NAMES = {
31
+ "setup.py", "conftest.py", "manage.py", "__init__.py", "__main__.py",
32
+ }
33
+ _SPECIAL_DIR_PREFIXES = ("tests/", "test/", "scripts/", "bin/", "examples/", "docs/")
34
+ # Directorios cuyos .py carga una herramienta por convención, no un import (en cualquier nivel)
35
+ _CONVENTION_DIRS = {"library", "module_utils", "filter_plugins", "lookup_plugins", "callback_plugins"}
36
+ _PYTHON_M = re.compile(r"python[\d.]*\s+-m\s+([A-Za-z_][\w.]*)")
37
+ _TEXT_SUFFIXES = {".md", ".rst", ".txt", ".py", ".sh", ".toml", ".yml", ".yaml", ".cfg", ".ini", ".service", ""}
38
+
39
+
40
+ def _tracked_py_files(repo_path: Path) -> list[Path] | None:
41
+ try:
42
+ out = subprocess.run(
43
+ ["git", "-c", "core.quotePath=false", "ls-files", "*.py"], cwd=repo_path, capture_output=True,
44
+ text=True, check=True, timeout=30,
45
+ )
46
+ except (subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired):
47
+ return None
48
+ return [repo_path / line for line in out.stdout.splitlines() if line]
49
+
50
+
51
+ def _module_candidates(repo_path: Path, file_path: Path) -> set[str]:
52
+ """Nombres por los que se podría importar `file_path` desde el repo."""
53
+ rel = file_path.relative_to(repo_path)
54
+ parts = list(rel.parts)
55
+ if parts[-1] == "__init__.py":
56
+ parts = parts[:-1]
57
+ else:
58
+ parts[-1] = parts[-1].removesuffix(".py")
59
+ if not parts:
60
+ return set()
61
+ # Todos los sufijos: con la estructura src/ (o un directorio que se mete en sys.path) el módulo
62
+ # src/pkg/mod.py se importa como «pkg.mod»; antes solo contaban «src.pkg.mod» y «mod», y
63
+ # todo el paquete salía como huérfano.
64
+ return {".".join(parts[i:]) for i in range(len(parts))}
65
+
66
+
67
+ def _is_script(file_path: Path) -> bool:
68
+ """Un .py con guion en el nombre no se puede importar; con shebang se ejecuta directamente."""
69
+ if "-" in file_path.stem:
70
+ return True
71
+ try:
72
+ with file_path.open("rb") as f:
73
+ return f.read(2) == b"#!"
74
+ except OSError:
75
+ return False
76
+
77
+
78
+ def _is_special(repo_path: Path, file_path: Path) -> bool:
79
+ rel = file_path.relative_to(repo_path)
80
+ if file_path.name in _SPECIAL_NAMES or _is_script(file_path):
81
+ return True
82
+ if file_path.name.startswith("test_") or file_path.name.endswith("_test.py"): # tests fuera de tests/
83
+ return True
84
+ if _CONVENTION_DIRS & set(rel.parts[:-1]):
85
+ return True
86
+ return any(str(rel).startswith(prefix) for prefix in _SPECIAL_DIR_PREFIXES)
87
+
88
+
89
+ def _with_prefixes(names: set[str], dotted: str) -> None:
90
+ """Añade "a.b.c" y sus prefijos ("a", "a.b"): importar un submódulo usa sus paquetes."""
91
+ segs = [s for s in dotted.split(".") if s]
92
+ for i in range(1, len(segs) + 1):
93
+ names.add(".".join(segs[:i]))
94
+
95
+
96
+ def _package_of(repo_path: Path, file_path: Path) -> list[str]:
97
+ """Paquete al que pertenece el fichero (base de sus imports relativos)."""
98
+ return list(file_path.relative_to(repo_path).parts[:-1])
99
+
100
+
101
+ def _imports_from_source(repo_path: Path, file_path: Path, text: str) -> set[str]:
102
+ """Nombres de módulo que importa el fichero, con los relativos ya resueltos."""
103
+ names: set[str] = set()
104
+ try:
105
+ tree = ast.parse(text)
106
+ except (SyntaxError, ValueError):
107
+ for match in _IMPORT_RE.finditer(text): # Python que no parsea: la heurística de siempre
108
+ for token in (match.group(1) or match.group(2) or "").split(","):
109
+ _with_prefixes(names, token.strip().lstrip("."))
110
+ return names
111
+ package = _package_of(repo_path, file_path)
112
+ for node in ast.walk(tree):
113
+ if isinstance(node, ast.Import):
114
+ for alias in node.names:
115
+ _with_prefixes(names, alias.name)
116
+ elif isinstance(node, ast.ImportFrom):
117
+ if node.level:
118
+ base = package[:len(package) - (node.level - 1)] if node.level > 1 else package
119
+ module = ".".join(base + ([node.module] if node.module else []))
120
+ else:
121
+ module = node.module or ""
122
+ _with_prefixes(names, module)
123
+ for alias in node.names: # "from paquete import submodulo"
124
+ if alias.name != "*":
125
+ _with_prefixes(names, f"{module}.{alias.name}" if module else alias.name)
126
+ names.add(alias.name)
127
+ return names
128
+
129
+
130
+ def _entry_point_modules(repo_path: Path) -> set[str]:
131
+ names: set[str] = set()
132
+ pyproject = repo_path / "pyproject.toml"
133
+ if pyproject.is_file():
134
+ try:
135
+ project = tomllib.loads(pyproject.read_text(encoding="utf-8", errors="ignore")).get("project", {})
136
+ except tomllib.TOMLDecodeError:
137
+ project = {}
138
+ groups = [project.get("scripts", {}), project.get("gui-scripts", {}), *project.get("entry-points", {}).values()]
139
+ for group in groups:
140
+ for target in group.values():
141
+ _with_prefixes(names, str(target).split(":")[0].strip())
142
+ return names
143
+
144
+
145
+ def _python_m_modules(repo_path: Path, tracked: list[str]) -> set[str]:
146
+ names: set[str] = set()
147
+ for rel in tracked:
148
+ path = repo_path / rel
149
+ if path.suffix not in _TEXT_SUFFIXES:
150
+ continue
151
+ try:
152
+ text = path.read_text(encoding="utf-8", errors="ignore")
153
+ except OSError:
154
+ continue
155
+ for match in _PYTHON_M.finditer(text):
156
+ _with_prefixes(names, match.group(1).rstrip("."))
157
+ return names
158
+
159
+
160
+ def _tracked_files(repo_path: Path) -> list[str]:
161
+ try:
162
+ out = subprocess.run(["git", "-c", "core.quotePath=false", "ls-files"], cwd=repo_path, capture_output=True, text=True,
163
+ check=True, timeout=30)
164
+ except (subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired):
165
+ return []
166
+ return [line for line in out.stdout.splitlines() if line]
167
+
168
+
169
+ class DeadFilesCheck:
170
+ name = "dead_files"
171
+ description = "Ficheros Python que ningún otro fichero del repo importa (heurística)."
172
+
173
+ def run(self, repo_path: Path) -> CheckResult:
174
+ py_files = _tracked_py_files(repo_path)
175
+ if py_files is None:
176
+ return CheckResult(
177
+ check_name=self.name,
178
+ summary="No aplica: no es un repositorio git.",
179
+ error="not_a_git_repo",
180
+ )
181
+ if not py_files:
182
+ return CheckResult(check_name=self.name, summary="No hay ficheros .py en el repo.")
183
+
184
+ imported_names = _entry_point_modules(repo_path) | _python_m_modules(repo_path, _tracked_files(repo_path))
185
+ for file_path in py_files:
186
+ try:
187
+ text = file_path.read_text(encoding="utf-8", errors="ignore")
188
+ except OSError:
189
+ continue
190
+ imported_names |= _imports_from_source(repo_path, file_path, text)
191
+
192
+ findings: list[Finding] = []
193
+ for file_path in py_files:
194
+ if _is_special(repo_path, file_path):
195
+ continue
196
+ candidates = _module_candidates(repo_path, file_path)
197
+ if candidates & imported_names:
198
+ continue
199
+ findings.append(Finding(
200
+ severity="low",
201
+ title="Fichero Python no importado por ningún otro fichero del repo",
202
+ detail="Heurística estática (sin ejecutar código) -- puede ser un falso "
203
+ "positivo si se carga dinámicamente o es un punto de entrada.",
204
+ path=str(file_path.relative_to(repo_path)),
205
+ ))
206
+
207
+ summary = f"{len(py_files)} fichero(s) .py analizados, {len(findings)} posible(s) huérfano(s)."
208
+ return CheckResult(check_name=self.name, summary=summary, findings=findings)
@@ -0,0 +1,131 @@
1
+ """Métricas basadas en el historial de git: hotspots de cambio, ramas
2
+ obsoletas, ficheros enormes en el repo.
3
+
4
+ Todo se calcula con un puñado de invocaciones a `git` (sin librerías
5
+ externas) -- si el directorio no es un repo git, el check lo señala como
6
+ no aplicable en vez de fallar.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import subprocess
11
+ import time
12
+ from collections import Counter
13
+ from pathlib import Path
14
+
15
+ from ..plugin import CheckResult, Finding
16
+
17
+ _STALE_BRANCH_DAYS = 180
18
+ _TOP_HOTSPOTS = 10
19
+ _LARGE_FILE_BYTES = 1 * 1024 * 1024
20
+
21
+
22
+ def _git(repo_path: Path, *args: str) -> str | None:
23
+ try:
24
+ out = subprocess.run(
25
+ # quotePath=false: sin esto git escapa las rutas no ASCII ("v\303\255deo.bin") y no se
26
+ # podían abrir: un fichero grande con tildes en el nombre se saltaba en silencio
27
+ ["git", "-c", "core.quotePath=false", *args], cwd=repo_path, capture_output=True, text=True,
28
+ check=True, timeout=60,
29
+ )
30
+ return out.stdout
31
+ except (subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired):
32
+ return None
33
+
34
+
35
+ def _is_git_repo(repo_path: Path) -> bool:
36
+ return _git(repo_path, "rev-parse", "--is-inside-work-tree") is not None
37
+
38
+
39
+ def _churn_hotspots(repo_path: Path) -> list[Finding]:
40
+ log = _git(repo_path, "log", "--pretty=format:__COMMIT__", "--name-only")
41
+ if not log:
42
+ return []
43
+ counts: Counter[str] = Counter()
44
+ for line in log.splitlines():
45
+ if line and line != "__COMMIT__":
46
+ counts[line] += 1
47
+ findings: list[Finding] = []
48
+ current = set((_git(repo_path, "ls-files") or "").splitlines())
49
+ counts = Counter({p: c for p, c in counts.items() if p in current}) # sin ficheros ya borrados
50
+ for path, count in counts.most_common(_TOP_HOTSPOTS):
51
+ if count < 5: # no merece la pena senalar ficheros con pocos cambios
52
+ continue
53
+ findings.append(Finding(
54
+ severity="info",
55
+ title=f"Hotspot de cambios: {count} commits lo tocan",
56
+ detail="Cambia con mucha frecuencia -- candidato a revisar cobertura de tests y complejidad.",
57
+ path=path,
58
+ ))
59
+ return findings
60
+
61
+
62
+ def _stale_branches(repo_path: Path) -> list[Finding]:
63
+ out = _git(
64
+ repo_path, "for-each-ref", "--format=%(refname)|%(committerdate:unix)|%(symref)",
65
+ "refs/heads", "refs/remotes",
66
+ )
67
+ if not out:
68
+ return []
69
+ # La rama actual y la rama por defecto del remoto (destino de origin/HEAD) no son «candidatas
70
+ # a borrar» aunque lleven tiempo sin commits: en un proyecto estable main salía como obsoleta.
71
+ current = (_git(repo_path, "symbolic-ref", "-q", "HEAD") or "").strip()
72
+ rows = [line.split("|") for line in out.splitlines() if line.count("|") == 2]
73
+ protected = {current} | {symref for _, _, symref in rows if symref}
74
+ now = time.time()
75
+ findings: list[Finding] = []
76
+ for ref, ts, symref in rows:
77
+ if symref or ref in protected or not ts.strip().isdigit():
78
+ continue
79
+ age_days = (now - int(ts)) / 86400
80
+ if age_days > _STALE_BRANCH_DAYS:
81
+ name = ref.removeprefix("refs/heads/").removeprefix("refs/remotes/")
82
+ findings.append(Finding(
83
+ severity="info",
84
+ title=f"Rama sin commits desde hace {int(age_days)} días: {name}",
85
+ detail="Candidata a borrar si ya no está en uso.",
86
+ ))
87
+ return findings
88
+
89
+
90
+ def _large_tracked_files(repo_path: Path) -> list[Finding]:
91
+ out = _git(repo_path, "ls-files")
92
+ if out is None:
93
+ return []
94
+ findings: list[Finding] = []
95
+ for rel in out.splitlines():
96
+ if not rel:
97
+ continue
98
+ full = repo_path / rel
99
+ try:
100
+ size = full.stat().st_size
101
+ except OSError:
102
+ continue
103
+ if size > _LARGE_FILE_BYTES:
104
+ findings.append(Finding(
105
+ severity="low",
106
+ title=f"Fichero grande en el repo: {size / (1024 * 1024):.1f} MB",
107
+ detail="Considera Git LFS o excluirlo si es un artefacto generado/binario.",
108
+ path=rel,
109
+ ))
110
+ return findings
111
+
112
+
113
+ class GitHotspotsCheck:
114
+ name = "git_hotspots"
115
+ description = "Hotspots de cambio, ramas obsoletas y ficheros enormes según el historial de git."
116
+
117
+ def run(self, repo_path: Path) -> CheckResult:
118
+ if not _is_git_repo(repo_path):
119
+ return CheckResult(
120
+ check_name=self.name,
121
+ summary="No aplica: no es un repositorio git.",
122
+ error="not_a_git_repo",
123
+ )
124
+
125
+ findings = [
126
+ *_churn_hotspots(repo_path),
127
+ *_stale_branches(repo_path),
128
+ *_large_tracked_files(repo_path),
129
+ ]
130
+ summary = f"{len(findings)} hallazgo(s) sobre el historial de git."
131
+ return CheckResult(check_name=self.name, summary=summary, findings=findings)
@@ -0,0 +1,110 @@
1
+ """Compara lo que dice el README con la realidad del proyecto.
2
+
3
+ Deliberadamente NO ejecuta nada del repo analizado (ni el propio CLI que
4
+ declare, ni ningún script) -- es puramente estático, comparando texto
5
+ contra `pyproject.toml`. Ejecutar el código de un repo ajeno solo para
6
+ "comprobar el README" sería una superficie de ataque real para una
7
+ herramienta que la gente corre contra repos que no controla.
8
+
9
+ Dos comprobaciones, ambas de bajo riesgo de falso positivo porque solo
10
+ disparan ante una discrepancia concreta y verificable:
11
+ 1. La versión mínima de Python que pide `pyproject.toml`
12
+ (`requires-python`) frente a versiones de Python mencionadas en el
13
+ README que ya no cumplirían ese mínimo.
14
+ 2. Comandos declarados en `[project.scripts]` que el README no menciona
15
+ ni una sola vez -- un CLI sin documentar.
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import re
20
+ import tomllib
21
+ from pathlib import Path
22
+
23
+ from ..plugin import CheckResult, Finding
24
+
25
+ _README_NAMES = ("README.md", "README.rst", "README.txt", "README")
26
+ _PY_VERSION_IN_README = re.compile(r"\bpython\s*(>=|==|~=)?\s*(\d+)\.(\d+)(\+)?", re.IGNORECASE)
27
+ # Solo cuenta una versión que el README da como requisito: con operador o "+", o en una línea que habla
28
+ # de requisitos. "workaround para python 3.7" en un ejemplo de salida no dice qué versión hace falta.
29
+ _REQUIREMENT_WORDS = re.compile(
30
+ r"requi|necesit|need|support|soport|compatib|m[ií]nim|minimum|instal|superior|posterior|or (later|newer)|"
31
+ r"at least|al menos", re.IGNORECASE)
32
+ _FENCE = re.compile(r"^(```|~~~).*?^\1", re.MULTILINE | re.DOTALL)
33
+ _MIN_VERSION_SPEC = re.compile(r"(?:>=|~=|==)\s*(\d+)\.(\d+)") # >=3.11, ~=3.11 y ==3.11.* fijan el mínimo
34
+
35
+
36
+ def _find_readme(repo_path: Path) -> Path | None:
37
+ for name in _README_NAMES:
38
+ candidate = repo_path / name
39
+ if candidate.is_file():
40
+ return candidate
41
+ return None
42
+
43
+
44
+ def _load_pyproject(repo_path: Path) -> dict | None:
45
+ pyproject = repo_path / "pyproject.toml"
46
+ if not pyproject.is_file():
47
+ return None
48
+ try:
49
+ return tomllib.loads(pyproject.read_text(encoding="utf-8", errors="ignore"))
50
+ except tomllib.TOMLDecodeError:
51
+ return None
52
+
53
+
54
+ def _min_python_version(requires_python: str) -> tuple[int, int] | None:
55
+ match = _MIN_VERSION_SPEC.search(requires_python)
56
+ if not match:
57
+ return None
58
+ return int(match.group(1)), int(match.group(2))
59
+
60
+
61
+ class ReadmeDriftCheck:
62
+ name = "readme_drift"
63
+ description = "Compara la versión de Python y los comandos de CLI del README contra pyproject.toml (sin ejecutar nada)."
64
+
65
+ def run(self, repo_path: Path) -> CheckResult:
66
+ data = _load_pyproject(repo_path)
67
+ if data is None:
68
+ return CheckResult(
69
+ check_name=self.name,
70
+ summary="No aplica: no hay pyproject.toml (o no es TOML válido).",
71
+ )
72
+ readme_path = _find_readme(repo_path)
73
+ if readme_path is None:
74
+ return CheckResult(check_name=self.name, summary="No aplica: no hay README.")
75
+
76
+ readme_text = readme_path.read_text(encoding="utf-8", errors="ignore")
77
+ project = data.get("project", {})
78
+ findings: list[Finding] = []
79
+
80
+ requires_python = project.get("requires-python", "")
81
+ min_version = _min_python_version(requires_python)
82
+ prose = _FENCE.sub("", readme_text) # los bloques de código son ejemplos, no requisitos
83
+ if min_version is not None:
84
+ for match in _PY_VERSION_IN_README.finditer(prose):
85
+ line = prose[prose.rfind("\n", 0, match.start()) + 1:prose.find("\n", match.end())]
86
+ if not (match.group(1) or match.group(4) or _REQUIREMENT_WORDS.search(line)):
87
+ continue
88
+ mentioned = (int(match.group(2)), int(match.group(3)))
89
+ if mentioned[0] == 3 and mentioned < min_version:
90
+ findings.append(Finding(
91
+ severity="medium",
92
+ title=(
93
+ f"El README menciona Python {mentioned[0]}.{mentioned[1]}, pero "
94
+ f"pyproject.toml pide requires-python {requires_python}"
95
+ ),
96
+ detail="El README puede haberse quedado desactualizado tras subir el mínimo.",
97
+ path=readme_path.name,
98
+ ))
99
+
100
+ scripts = project.get("scripts", {})
101
+ for command in sorted(scripts):
102
+ if not re.search(rf"\b{re.escape(command)}\b", readme_text):
103
+ findings.append(Finding(
104
+ severity="low",
105
+ title=f"Comando de CLI declarado pero no documentado en el README: {command}",
106
+ detail="Definido en [project.scripts] de pyproject.toml, no aparece ni una vez en el README.",
107
+ ))
108
+
109
+ summary = f"{len(findings)} hallazgo(s) al comparar el README con pyproject.toml."
110
+ return CheckResult(check_name=self.name, summary=summary, findings=findings)
@@ -0,0 +1,154 @@
1
+ """Detecta secretos y datos privados probables antes de un `git push`.
2
+
3
+ Va más allá de un simple grep de "password=": reconoce formatos de token
4
+ de proveedores reales (así evita en gran parte los falsos positivos de un
5
+ regex genérico de "secret\\s*=") y, por separado, señala datos que no son
6
+ técnicamente un secreto pero tampoco deberían acabar en un repo público
7
+ (IPs privadas, bloques de clave privada) con severidad más baja, porque
8
+ suelen necesitar revisión humana para distinguir un placeholder de un
9
+ dato real -- ver la lección de `feedback_no_confidential_data_in_repos`
10
+ en el historial de auditorías que motivó esta herramienta.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import re
15
+ import subprocess
16
+ from dataclasses import dataclass
17
+ from pathlib import Path
18
+
19
+ from ..plugin import CheckResult, Finding
20
+
21
+ # Tamaño máximo de fichero a inspeccionar -- evita atascarse con binarios
22
+ # grandes que hayan colado un .gitignore incompleto.
23
+ _MAX_FILE_SIZE = 2 * 1024 * 1024
24
+
25
+ _BINARY_EXTENSIONS = {
26
+ ".png", ".jpg", ".jpeg", ".gif", ".ico", ".pdf", ".zip", ".tar", ".gz",
27
+ ".woff", ".woff2", ".ttf", ".eot", ".mp4", ".mp3", ".so", ".dylib", ".dll",
28
+ ".exe", ".bin", ".pyc", ".class", ".jar", ".sqlite", ".sqlite3", ".db",
29
+ }
30
+
31
+
32
+ @dataclass
33
+ class _Pattern:
34
+ name: str
35
+ regex: re.Pattern[str]
36
+ severity: str
37
+
38
+
39
+ # Formatos de token de proveedores reales -- alta confianza, alta severidad.
40
+ _HIGH_CONFIDENCE_PATTERNS: list[_Pattern] = [
41
+ _Pattern("Clave privada (PEM)", re.compile(
42
+ r"-----BEGIN (?:(?:RSA|EC|OPENSSH|DSA|ENCRYPTED|PGP) )?PRIVATE KEY(?: BLOCK)?-----"), "high"),
43
+ _Pattern("AWS Access Key ID", re.compile(r"\b(AKIA|ASIA)[0-9A-Z]{16}\b"), "high"),
44
+ _Pattern("GitHub token", re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9]{36,}|github_pat_[A-Za-z0-9_]{60,})\b"), "high"),
45
+ _Pattern("Slack token", re.compile(r"\bxox[baprse]-[A-Za-z0-9-]{10,}\b"), "high"),
46
+ _Pattern("Clave de API de Stripe", re.compile(r"\b(sk|pk|rk)_(live|test)_[A-Za-z0-9]{16,}\b"), "high"),
47
+ # Antes el patrón decía «OpenAI/Stripe» pero solo veía las de Stripe.
48
+ _Pattern("Clave de API de OpenAI/Anthropic", re.compile(
49
+ r"\bsk-(?:(?:proj|svcacct|admin|ant-api\d+|ant-admin\d+)-)?[A-Za-z0-9_-]{20,}"), "high"),
50
+ _Pattern("Token de Slack webhook", re.compile(r"https://hooks\.slack\.com/services/[A-Za-z0-9/]{20,}"), "high"),
51
+ _Pattern("JWT (aspecto de)", re.compile(r"\beyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b"), "medium"),
52
+ ]
53
+
54
+ # Asignaciones genéricas tipo "password = '...'" -- mucho más ruidosas
55
+ # (placeholders, ejemplos de documentación), severidad media.
56
+ _GENERIC_ASSIGNMENT = re.compile(
57
+ r"""(?ix)
58
+ [\w-]*(password|passwd|secret|api[_-]?key|access[_-]?token|private[_-]?key)
59
+ ["']?\]? # cierre de subíndice si la clave iba entre
60
+ # comillas+corchetes: dict["password"] = ...
61
+ (?:\s*:\s*[A-Za-z_][\w\[\], .]*)? # anotación de tipo de Python opcional:
62
+ # "nombre: Tipo = valor" -- sin esto, el
63
+ # separador esperado tras la palabra clave
64
+ # sería "Tipo", nunca "=".
65
+ \s*[:=]\s*
66
+ ['"]([^'"\s]{8,})['"]
67
+ """
68
+ )
69
+ _GENERIC_PLACEHOLDER_VALUES = {
70
+ "changeme", "change_me", "your_key_here", "your-key-here", "xxx", "todo",
71
+ "example", "placeholder", "secret", "password", "test", "fake", "dummy",
72
+ }
73
+
74
+ _PRIVATE_IP = re.compile(
75
+ r"\b(?:10\.\d{1,3}\.\d{1,3}\.\d{1,3}"
76
+ r"|172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}"
77
+ r"|192\.168\.\d{1,3}\.\d{1,3})\b"
78
+ )
79
+
80
+
81
+ def _tracked_files(repo_path: Path) -> list[Path]:
82
+ try:
83
+ out = subprocess.run(
84
+ ["git", "-c", "core.quotePath=false", "ls-files"], cwd=repo_path, capture_output=True, text=True,
85
+ check=True, timeout=30,
86
+ )
87
+ return [repo_path / line for line in out.stdout.splitlines() if line]
88
+ except (subprocess.CalledProcessError, FileNotFoundError, subprocess.TimeoutExpired):
89
+ # No es un repo git (o no hay `git`) -- recorrer el arbol con exclusiones basicas.
90
+ skip_dirs = {".git", "node_modules", ".venv", "venv", "__pycache__", ".mypy_cache", ".ruff_cache"}
91
+ return [
92
+ p for p in repo_path.rglob("*")
93
+ # partes relativas a la raíz: con las absolutas, un repo dentro de «venv/…» no se analizaba
94
+ if p.is_file() and not any(part in skip_dirs for part in p.relative_to(repo_path).parts)
95
+ ]
96
+
97
+
98
+ def _looks_like_placeholder(value: str) -> bool:
99
+ return value.lower() in _GENERIC_PLACEHOLDER_VALUES
100
+
101
+
102
+ class SecretsCheck:
103
+ name = "secrets"
104
+ description = "Busca secretos probables (claves, tokens) e IPs privadas antes de publicar."
105
+
106
+ def run(self, repo_path: Path) -> CheckResult:
107
+ findings: list[Finding] = []
108
+ files_scanned = 0
109
+
110
+ for file_path in _tracked_files(repo_path):
111
+ if not file_path.is_file():
112
+ continue
113
+ if file_path.suffix.lower() in _BINARY_EXTENSIONS:
114
+ continue
115
+ try:
116
+ if file_path.stat().st_size > _MAX_FILE_SIZE:
117
+ continue
118
+ text = file_path.read_text(encoding="utf-8", errors="ignore")
119
+ except OSError:
120
+ continue
121
+ files_scanned += 1
122
+ rel = str(file_path.relative_to(repo_path))
123
+
124
+ for lineno, line in enumerate(text.splitlines(), start=1):
125
+ for pattern in _HIGH_CONFIDENCE_PATTERNS:
126
+ if pattern.regex.search(line):
127
+ findings.append(Finding(
128
+ severity=pattern.severity,
129
+ title=f"Posible secreto: {pattern.name}",
130
+ detail="Revisar y revocar si es real antes de publicar.",
131
+ path=rel, line=lineno,
132
+ ))
133
+
134
+ for match in _GENERIC_ASSIGNMENT.finditer(line):
135
+ value = match.group(2)
136
+ if _looks_like_placeholder(value):
137
+ continue
138
+ findings.append(Finding(
139
+ severity="medium",
140
+ title=f"Asignación con aspecto de secreto ({match.group(1)})",
141
+ detail="Puede ser un placeholder de ejemplo -- revisar el valor real.",
142
+ path=rel, line=lineno,
143
+ ))
144
+
145
+ for ip_match in _PRIVATE_IP.finditer(line):
146
+ findings.append(Finding(
147
+ severity="info",
148
+ title=f"IP privada en el código: {ip_match.group(0)}",
149
+ detail="Puede ser un ejemplo genérico o una IP real de tu infraestructura -- revisar.",
150
+ path=rel, line=lineno,
151
+ ))
152
+
153
+ summary = f"{files_scanned} fichero(s) analizados, {len(findings)} hallazgo(s)."
154
+ return CheckResult(check_name=self.name, summary=summary, findings=findings)