codefactory-cli 0.20.1__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.
Files changed (61) hide show
  1. codefactory/__init__.py +3 -0
  2. codefactory/__main__.py +5 -0
  3. codefactory/accept.py +68 -0
  4. codefactory/analyzers/__init__.py +55 -0
  5. codefactory/analyzers/generic.py +392 -0
  6. codefactory/analyzers/parallel.py +113 -0
  7. codefactory/analyzers/python.py +279 -0
  8. codefactory/analyzers/python_parse.py +402 -0
  9. codefactory/analyzers/treewalk.py +299 -0
  10. codefactory/analyzers/ts_helper.js +483 -0
  11. codefactory/analyzers/typescript.py +118 -0
  12. codefactory/apple.py +80 -0
  13. codefactory/audit.py +227 -0
  14. codefactory/baseline.py +58 -0
  15. codefactory/brief.py +330 -0
  16. codefactory/cache.py +93 -0
  17. codefactory/checks.py +608 -0
  18. codefactory/cli.py +782 -0
  19. codefactory/config.py +157 -0
  20. codefactory/coverage.py +104 -0
  21. codefactory/deps.py +182 -0
  22. codefactory/diff.py +197 -0
  23. codefactory/efficiency.py +250 -0
  24. codefactory/flags.py +263 -0
  25. codefactory/graph.py +95 -0
  26. codefactory/hotspots.py +344 -0
  27. codefactory/infra.py +242 -0
  28. codefactory/intent.py +106 -0
  29. codefactory/layers.py +143 -0
  30. codefactory/org.py +131 -0
  31. codefactory/owners.py +72 -0
  32. codefactory/patch.py +81 -0
  33. codefactory/paths.py +93 -0
  34. codefactory/plan.py +476 -0
  35. codefactory/privacy.py +221 -0
  36. codefactory/profile.py +667 -0
  37. codefactory/rerank.py +161 -0
  38. codefactory/review.py +1504 -0
  39. codefactory/rules.py +50 -0
  40. codefactory/sarif.py +661 -0
  41. codefactory/sbom.py +78 -0
  42. codefactory/security.py +537 -0
  43. codefactory/similar.py +199 -0
  44. codefactory/skill.py +144 -0
  45. codefactory/skill_template/SKILL.md +68 -0
  46. codefactory/skill_template/__init__.py +0 -0
  47. codefactory/sqlgraph.py +109 -0
  48. codefactory/suppress.py +92 -0
  49. codefactory/taint.py +439 -0
  50. codefactory/trace.py +72 -0
  51. codefactory/viewer/__init__.py +19 -0
  52. codefactory/viewer/dashboard.html +43 -0
  53. codefactory/viewer/factory.css +61 -0
  54. codefactory/viewer/factory.js +665 -0
  55. codefactory/viewer/template.html +47 -0
  56. codefactory_cli-0.20.1.dist-info/METADATA +250 -0
  57. codefactory_cli-0.20.1.dist-info/RECORD +61 -0
  58. codefactory_cli-0.20.1.dist-info/WHEEL +5 -0
  59. codefactory_cli-0.20.1.dist-info/entry_points.txt +2 -0
  60. codefactory_cli-0.20.1.dist-info/licenses/LICENSE +21 -0
  61. codefactory_cli-0.20.1.dist-info/top_level.txt +1 -0
codefactory/config.py ADDED
@@ -0,0 +1,157 @@
1
+ """Optional per-repo settings from factory.toml: layer globs, forbidden layer pairs, thresholds, ignores."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+ import tomllib
7
+ from dataclasses import dataclass, field
8
+ from pathlib import Path
9
+
10
+ DEFAULT_IGNORE = [
11
+ ".git",
12
+ ".hg",
13
+ "node_modules",
14
+ ".venv",
15
+ "venv",
16
+ "env",
17
+ "__pycache__",
18
+ "build",
19
+ "dist",
20
+ ".tox",
21
+ ".mypy_cache",
22
+ ".pytest_cache",
23
+ ".ruff_cache",
24
+ "site-packages",
25
+ ".eggs",
26
+ ".codefactory",
27
+ ".expo",
28
+ "coverage",
29
+ ]
30
+
31
+
32
+ @dataclass
33
+ class Config:
34
+ layers: dict[str, list[str]] = field(default_factory=dict) # layer name -> glob patterns
35
+ forbid: list[tuple[str, str]] = field(default_factory=list)
36
+ ignore: list[str] = field(default_factory=lambda: list(DEFAULT_IGNORE))
37
+ large_file: int = 400
38
+ long_function: int = 60
39
+ duplicate_min_lines: int = 6
40
+ similar_threshold: float = 0.75 # near-duplicates: share of structure in common (0-1)
41
+ hub_callers: int = 12
42
+ queries: list[dict] = field(default_factory=list) # saved SQL checks that become flags
43
+ silence: list[dict] = field(default_factory=list) # [[silence]] kind / where (glob) / reason (+ by, on)
44
+ rules: list[dict] = field(default_factory=list) # [[rule]] custom pattern checks: id, pattern, files, severity…
45
+ profile: dict = field(default_factory=dict) # [profile] corrections to the detected project profile
46
+
47
+
48
+ def parse_rule(rule: str) -> tuple[str, str]:
49
+ left, sep, right = rule.partition("->")
50
+ if not sep or not left.strip() or not right.strip():
51
+ raise ValueError(f"Bad rule {rule!r}: write it as 'ui -> db'")
52
+ return left.strip(), right.strip()
53
+
54
+
55
+ def _read(path: Path, seen: tuple = ()) -> dict:
56
+ """factory.toml, merged over the policy it `extends` (an organisation's shared file): tables merge, lists append,
57
+ so a team adds to the shared rules and thresholds rather than replacing them."""
58
+ try:
59
+ data = tomllib.loads(path.read_text(encoding="utf-8"))
60
+ except tomllib.TOMLDecodeError as e:
61
+ raise ValueError(f"{path.name} isn't valid TOML: {e}") from None
62
+ except OSError as e:
63
+ raise ValueError(f"can't read {path}: {e.strerror}") from None
64
+ parent = data.pop("extends", None)
65
+ if not parent:
66
+ return data
67
+ base_path = (path.parent / parent).resolve()
68
+ if base_path in seen:
69
+ raise ValueError(f"factory.toml `extends` loops back to {base_path}")
70
+ merged = _read(base_path, (*seen, path.resolve()))
71
+ for key, value in data.items():
72
+ if isinstance(value, dict) and isinstance(merged.get(key), dict):
73
+ merged[key] = {**merged[key], **value}
74
+ elif isinstance(value, list) and isinstance(merged.get(key), list):
75
+ merged[key] = merged[key] + value
76
+ else:
77
+ merged[key] = value
78
+ return merged
79
+
80
+
81
+ def load_config(root: Path) -> Config:
82
+ path = root / "factory.toml"
83
+ cfg = Config()
84
+ if not path.is_file():
85
+ return cfg
86
+ data = _read(path)
87
+ layers = data.get("layers", {})
88
+ cfg.layers = {name: [globs] if isinstance(globs, str) else list(globs) for name, globs in layers.items()}
89
+ cfg.forbid = [parse_rule(r) for r in data.get("rules", {}).get("forbid", [])]
90
+ cfg.ignore += list(data.get("ignore", []))
91
+ t = data.get("thresholds", {})
92
+ cfg.large_file = int(t.get("large_file", cfg.large_file))
93
+ cfg.long_function = int(t.get("long_function", cfg.long_function))
94
+ cfg.duplicate_min_lines = int(t.get("duplicate_min_lines", cfg.duplicate_min_lines))
95
+ cfg.similar_threshold = float(t.get("similar", cfg.similar_threshold))
96
+ cfg.hub_callers = int(t.get("hub_callers", cfg.hub_callers))
97
+ for q in data.get("queries", []):
98
+ if not q.get("name") or not q.get("sql"):
99
+ raise ValueError("Each [[queries]] entry in factory.toml needs a name and sql")
100
+ if q.get("severity", "warn") not in ("high", "warn", "info"):
101
+ raise ValueError(f"Query {q['name']!r}: severity must be high, warn or info")
102
+ cfg.queries.append({k: q[k] for k in ("name", "sql", "severity", "message") if k in q})
103
+ for rule in data.get("silence", []):
104
+ if not rule.get("where"):
105
+ raise ValueError("Each [[silence]] entry in factory.toml needs `where` (a file or file::function glob)")
106
+ reason = rule.get("reason", "")
107
+ if rule.get("by") or rule.get("on"): # who accepted it, and when (written by `codefactory accept`)
108
+ by = f" by {rule['by']}" if rule.get("by") else ""
109
+ on = f" on {rule['on']}" if rule.get("on") else ""
110
+ reason += f" (accepted{by}{on})"
111
+ cfg.silence.append({"kind": rule.get("kind", "*"), "where": rule["where"], "reason": reason})
112
+ for r in data.get("rule", []):
113
+ if not r.get("id") or not r.get("pattern"):
114
+ raise ValueError("Each [[rule]] entry in factory.toml needs an id and a pattern (a regular expression)")
115
+ if r.get("severity", "warn") not in ("high", "warn", "info"):
116
+ raise ValueError(f"Rule {r['id']!r}: severity must be high, warn or info")
117
+ try:
118
+ regex = re.compile(r["pattern"])
119
+ except re.error as e:
120
+ raise ValueError(f"Rule {r['id']!r}: the pattern isn't a valid regular expression ({e})") from None
121
+ files = r.get("files", ["**/*"])
122
+ cfg.rules.append({
123
+ "id": r["id"], "regex": regex, "files": [files] if isinstance(files, str) else list(files),
124
+ "severity": r.get("severity", "warn"), "message": r.get("message", r["id"]), "fix": r.get("fix", ""),
125
+ }) # fmt: skip
126
+ cfg.profile = _profile(data.get("profile", {}))
127
+ return cfg
128
+
129
+
130
+ PROFILE_KEYS = {
131
+ "kind": ("mobile app", "web app", "web service", "desktop app", "web front-end", "command-line tool",
132
+ "data pipeline", "library"),
133
+ "deployment": ("local-first", "client app", "local server", "LAN server", "network server", "deployed server",
134
+ "user's machine", "browser"),
135
+ "users": ("single user", "multi-user", "no sign-in"),
136
+ } # fmt: skip
137
+
138
+
139
+ def _profile(data: dict) -> dict:
140
+ """[profile] in factory.toml: what the detection got wrong. Values are checked so a typo can't silently do nothing."""
141
+ from .profile import SENSITIVE
142
+
143
+ out: dict = {}
144
+ for key, value in data.items():
145
+ if key == "sensitive":
146
+ values = [value] if isinstance(value, str) else list(value)
147
+ bad = [v for v in values if v not in SENSITIVE and v != "none"]
148
+ if bad:
149
+ raise ValueError(f'[profile] sensitive: {bad[0]!r} isn\'t one of {", ".join(SENSITIVE)} (or "none")')
150
+ out[key] = [v for v in values if v != "none"]
151
+ elif key in PROFILE_KEYS:
152
+ if value not in PROFILE_KEYS[key]:
153
+ raise ValueError(f"[profile] {key}: {value!r} isn't one of {', '.join(PROFILE_KEYS[key])}")
154
+ out[key] = value
155
+ else:
156
+ raise ValueError(f"[profile] has no setting {key!r} (kind, deployment, users, sensitive)")
157
+ return out
@@ -0,0 +1,104 @@
1
+ """Measured test coverage, when the repository has a coverage report: which functions ran under the tests.
2
+
3
+ Static reachability ("a test calls something that calls it") guesses; a coverage report knows. Read, in order:
4
+ coverage/lcov.info and other lcov files (Jest, Vitest, c8, pytest-cov --cov-report=lcov, Go and Rust tools),
5
+ coverage/coverage-final.json (Istanbul: Jest, Vitest, nyc) and coverage.json (coverage.py's `coverage json`).
6
+ A function counts as covered when a line of its body ran; its first line doesn't count, because in Python the `def`
7
+ line runs on import whether or not the function is ever called.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ import os
14
+ from collections import defaultdict
15
+ from dataclasses import dataclass
16
+ from datetime import datetime
17
+ from pathlib import Path
18
+
19
+ CANDIDATES = (
20
+ "coverage/lcov.info",
21
+ "lcov.info",
22
+ "coverage.lcov",
23
+ "coverage/coverage-final.json",
24
+ "coverage.json",
25
+ "htmlcov/coverage.json",
26
+ )
27
+
28
+
29
+ @dataclass
30
+ class Coverage:
31
+ covered: set[str] # function ids
32
+ source: str # the report, relative to the root
33
+ written: str # its date, YYYY-MM-DD
34
+ seen: set[str] # source files the report has data for (others fall back to the static estimate)
35
+
36
+
37
+ def _rel(root: Path, path: str) -> str:
38
+ p = Path(path)
39
+ if p.is_absolute():
40
+ try:
41
+ p = p.resolve().relative_to(root.resolve())
42
+ except ValueError:
43
+ return path.replace("\\", "/")
44
+ return p.as_posix()
45
+
46
+
47
+ def _lcov(text: str, root: Path) -> dict[str, set[int]]:
48
+ lines: dict[str, set[int]] = defaultdict(set)
49
+ current = None
50
+ for raw in text.splitlines():
51
+ if raw.startswith("SF:"):
52
+ current = _rel(root, raw[3:].strip())
53
+ elif raw.startswith("DA:") and current:
54
+ parts = raw[3:].split(",")
55
+ if len(parts) >= 2 and parts[1].strip().isdigit() and int(parts[1]) > 0:
56
+ lines[current].add(int(parts[0]))
57
+ elif raw.startswith("end_of_record"):
58
+ current = None
59
+ return lines
60
+
61
+
62
+ def _istanbul(data: dict, root: Path) -> dict[str, set[int]]:
63
+ lines: dict[str, set[int]] = defaultdict(set)
64
+ for path, cov in data.items():
65
+ if not isinstance(cov, dict) or "statementMap" not in cov:
66
+ continue
67
+ rel = _rel(root, cov.get("path", path))
68
+ for sid, hits in cov.get("s", {}).items():
69
+ loc = cov["statementMap"].get(sid)
70
+ if hits and loc:
71
+ lines[rel].update(range(loc["start"]["line"], loc["end"]["line"] + 1))
72
+ return lines
73
+
74
+
75
+ def _coverage_py(data: dict, root: Path) -> dict[str, set[int]]:
76
+ return {_rel(root, p): set(f.get("executed_lines", [])) for p, f in data.get("files", {}).items()}
77
+
78
+
79
+ def _body(f: dict) -> range:
80
+ """The lines that run only when the function is called (a one-line function: its only line)."""
81
+ return range(f["line"] + 1, f["end"] + 1) if f["end"] > f["line"] else range(f["line"], f["line"] + 1)
82
+
83
+
84
+ def measured(root: Path, functions: list[dict]) -> Coverage | None:
85
+ """The covered functions per the first coverage report found, or None if there is none (or it can't be read)."""
86
+ for name in CANDIDATES:
87
+ path = root / name
88
+ if not path.is_file():
89
+ continue
90
+ try:
91
+ text = path.read_text(encoding="utf-8", errors="replace")
92
+ if name.endswith(".json"):
93
+ data = json.loads(text)
94
+ lines = _coverage_py(data, root) if "files" in data and "meta" in data else _istanbul(data, root)
95
+ else:
96
+ lines = _lcov(text, root)
97
+ except (OSError, ValueError, KeyError, TypeError):
98
+ continue
99
+ if not lines:
100
+ continue
101
+ covered = {f["id"] for f in functions if f["kind"] != "module" and any(n in lines.get(f["file"], ()) for n in _body(f))}
102
+ written = datetime.fromtimestamp(os.path.getmtime(path)).strftime("%Y-%m-%d")
103
+ return Coverage(covered, name, written, set(lines))
104
+ return None
codefactory/deps.py ADDED
@@ -0,0 +1,182 @@
1
+ """Known vulnerabilities in dependencies, from OSV.dev (Google's free, open vulnerability database).
2
+
3
+ Off unless asked for (`--online`): it's the one check that leaves the machine. It sends package names and versions,
4
+ nothing else: no code, no file names, no repository name. Versions come from lockfiles, so they're exactly what's
5
+ installed: package-lock.json, yarn.lock (v1), pnpm-lock.yaml, poetry.lock, uv.lock, Pipfile.lock, pinned
6
+ requirements files, Cargo.lock, go.sum, Gemfile.lock and composer.lock.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import json
12
+ import re
13
+ import urllib.request
14
+ from dataclasses import dataclass
15
+ from pathlib import Path
16
+
17
+ API = "https://api.osv.dev/v1"
18
+ BATCH = 500
19
+ DETAILS = 60 # vulnerabilities whose details are fetched (summary, severity, fixed version); the rest are counted
20
+
21
+
22
+ @dataclass(frozen=True)
23
+ class Package:
24
+ ecosystem: str # OSV's names: npm, PyPI, crates.io, Go, RubyGems, Packagist
25
+ name: str
26
+ version: str
27
+ source: str # the lockfile
28
+ dev: bool = False # a development-only dependency (tests, builds): not shipped
29
+
30
+
31
+ @dataclass
32
+ class Vulnerability:
33
+ package: Package
34
+ id: str
35
+ summary: str = ""
36
+ severity: str = "" # CRITICAL | HIGH | MODERATE | LOW | ""
37
+ fixed: str = "" # the first fixed version, when OSV gives one
38
+
39
+
40
+ def _npm_lock(text: str, src: str) -> list[Package]:
41
+ data = json.loads(text)
42
+ out = []
43
+ for path, info in (data.get("packages") or {}).items():
44
+ if path and info.get("version") and not info.get("link"):
45
+ name = info.get("name") or path.rsplit("node_modules/", 1)[-1]
46
+ out.append(Package("npm", name, info["version"], src, bool(info.get("dev"))))
47
+ for name, info in (data.get("dependencies") or {}).items(): # lockfile v1
48
+ if info.get("version") and not data.get("packages"):
49
+ out.append(Package("npm", name, info["version"], src))
50
+ return out
51
+
52
+
53
+ def _yarn_lock(text: str, src: str) -> list[Package]:
54
+ out, names = [], []
55
+ for line in text.splitlines():
56
+ if line and not line.startswith((" ", "#")) and line.rstrip().endswith(":"):
57
+ names = [re.sub(r"@[^@]*$", "", s.strip().strip('"')) for s in line.rstrip(":").split(",")]
58
+ elif (m := re.match(r'\s+version:?\s+"?([^"\s]+)"?', line)) and names:
59
+ out += [Package("npm", n, m.group(1), src) for n in dict.fromkeys(names) if n]
60
+ names = []
61
+ return out
62
+
63
+
64
+ def _pnpm_lock(text: str, src: str) -> list[Package]:
65
+ found = re.findall(r"^\s{2}/?((?:@[^/@\s]+/)?[^/@\s:]+)[@/](\d[^\s:(]*)", text, re.M)
66
+ return [Package("npm", n, v, src) for n, v in dict.fromkeys(found)]
67
+
68
+
69
+ def _toml_packages(text: str, src: str, eco: str) -> list[Package]:
70
+ import tomllib
71
+
72
+ data = tomllib.loads(text)
73
+ return [Package(eco, p["name"], p["version"], src) for p in data.get("package", []) if p.get("name") and p.get("version")]
74
+
75
+
76
+ def _pipfile_lock(text: str, src: str) -> list[Package]:
77
+ data = json.loads(text)
78
+ return [
79
+ Package("PyPI", n, info["version"].lstrip("="), src)
80
+ for section in ("default", "develop")
81
+ for n, info in (data.get(section) or {}).items()
82
+ if str(info.get("version", "")).startswith("==")
83
+ ]
84
+
85
+
86
+ def _requirements(text: str, src: str) -> list[Package]:
87
+ return [
88
+ Package("PyPI", m.group(1), m.group(2), src)
89
+ for m in re.finditer(r"^\s*([\w.\-]+)(?:\[[^\]]*\])?\s*==\s*([\w.!+\-]+)", text, re.M)
90
+ ]
91
+
92
+
93
+ def _go_sum(text: str, src: str) -> list[Package]:
94
+ found = re.findall(r"^(\S+) (v[^\s/]+?)(?:/go\.mod)? ", text, re.M)
95
+ return [Package("Go", n, v.removeprefix("v"), src) for n, v in dict.fromkeys(found)]
96
+
97
+
98
+ def _gemfile_lock(text: str, src: str) -> list[Package]:
99
+ return [Package("RubyGems", n, v, src) for n, v in re.findall(r"^ ([\w.\-]+) \(([\w.\-]+)\)$", text, re.M)]
100
+
101
+
102
+ def _composer_lock(text: str, src: str) -> list[Package]:
103
+ data = json.loads(text)
104
+ return [
105
+ Package("Packagist", p["name"], str(p["version"]).lstrip("v"), src)
106
+ for section in ("packages", "packages-dev")
107
+ for p in data.get(section) or []
108
+ if p.get("name") and p.get("version")
109
+ ]
110
+
111
+
112
+ READERS = {
113
+ "package-lock.json": _npm_lock,
114
+ "npm-shrinkwrap.json": _npm_lock,
115
+ "yarn.lock": _yarn_lock,
116
+ "pnpm-lock.yaml": _pnpm_lock,
117
+ "poetry.lock": lambda t, s: _toml_packages(t, s, "PyPI"),
118
+ "uv.lock": lambda t, s: _toml_packages(t, s, "PyPI"),
119
+ "Pipfile.lock": _pipfile_lock,
120
+ "Cargo.lock": lambda t, s: _toml_packages(t, s, "crates.io"),
121
+ "go.sum": _go_sum,
122
+ "Gemfile.lock": _gemfile_lock,
123
+ "composer.lock": _composer_lock,
124
+ }
125
+
126
+
127
+ def packages(root: Path) -> list[Package]:
128
+ """Every pinned dependency in the repository's lockfiles (at the root and one level down, for monorepos)."""
129
+ out: list[Package] = []
130
+ candidates = [root / n for n in READERS] + [p for p in root.glob("*/*") if p.name in READERS]
131
+ candidates += (
132
+ sorted(root.glob("requirements*.txt")) + sorted(root.glob("requirements/*.txt")) + sorted(root.glob("constraints*.txt"))
133
+ )
134
+ for path in candidates:
135
+ if not path.is_file() or "node_modules" in path.relative_to(root).parts:
136
+ continue
137
+ reader = READERS.get(path.name, _requirements)
138
+ try:
139
+ out += reader(path.read_text(encoding="utf-8", errors="replace"), path.relative_to(root).as_posix())
140
+ except (ValueError, KeyError, TypeError):
141
+ continue # an unreadable lockfile: skip it rather than fail the review
142
+ return list(dict.fromkeys(out))
143
+
144
+
145
+ def _post(url: str, body: dict, timeout: int) -> dict:
146
+ req = urllib.request.Request(url, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})
147
+ with urllib.request.urlopen(req, timeout=timeout) as r: # noqa: S310 (a fixed https URL)
148
+ return json.loads(r.read())
149
+
150
+
151
+ def _get(url: str, timeout: int) -> dict:
152
+ with urllib.request.urlopen(url, timeout=timeout) as r: # noqa: S310
153
+ return json.loads(r.read())
154
+
155
+
156
+ SEVERITY_ORDER = {"CRITICAL": 0, "HIGH": 1, "MODERATE": 2, "MEDIUM": 2, "LOW": 3, "": 4}
157
+
158
+
159
+ def vulnerabilities(pkgs: list[Package], timeout: int = 30) -> list[Vulnerability]:
160
+ """Known vulnerabilities of these exact versions. Raises OSError when OSV can't be reached."""
161
+ found: list[Vulnerability] = []
162
+ for i in range(0, len(pkgs), BATCH):
163
+ chunk = pkgs[i : i + BATCH]
164
+ queries = [{"package": {"name": p.name, "ecosystem": p.ecosystem}, "version": p.version} for p in chunk]
165
+ # codefactory: ignore io_in_loop — one request per 500 packages, OSV's batch size
166
+ results = _post(f"{API}/querybatch", {"queries": queries}, timeout).get("results", [])
167
+ for p, res in zip(chunk, results, strict=False):
168
+ found += [Vulnerability(p, v["id"]) for v in res.get("vulns") or []]
169
+ for v in found[:DETAILS]:
170
+ try:
171
+ # codefactory: ignore io_in_loop — OSV has no batch endpoint for details; capped at DETAILS requests
172
+ d = _get(f"{API}/vulns/{v.id}", timeout)
173
+ except (OSError, ValueError):
174
+ continue
175
+ v.summary = (d.get("summary") or d.get("details", "").split("\n")[0])[:160]
176
+ v.severity = str((d.get("database_specific") or {}).get("severity") or "").upper()
177
+ for a in d.get("affected", []):
178
+ if a.get("package", {}).get("name") == v.package.name:
179
+ fixes = [e["fixed"] for r in a.get("ranges", []) for e in r.get("events", []) if "fixed" in e]
180
+ v.fixed = ", ".join(dict.fromkeys(fixes))
181
+ found.sort(key=lambda v: (SEVERITY_ORDER.get(v.severity, 4), v.package.name))
182
+ return found
codefactory/diff.py ADDED
@@ -0,0 +1,197 @@
1
+ """What a change adds and removes: findings on the working tree compared with a base commit (a pull request's target).
2
+
3
+ The base is extracted once per commit into `.codefactory/diff/<sha>/` and analyzed with the same per-file caches as
4
+ anything else, so comparing again after a push re-reads only what changed. Findings are matched by identity, not line:
5
+ kind + file + function for graph findings (as in the baseline), kind + file + the flagged line's text for source
6
+ checks, so code moving down a file doesn't look new.
7
+ """
8
+
9
+ from __future__ import annotations
10
+
11
+ import os
12
+ import shutil
13
+ import subprocess
14
+ import tarfile
15
+ import tempfile
16
+ from collections import Counter
17
+ from dataclasses import dataclass
18
+ from pathlib import Path
19
+
20
+ from .baseline import issue_key
21
+
22
+ SEV_RANK = {"high": 0, "warn": 1, "info": 2}
23
+
24
+
25
+ @dataclass
26
+ class Item:
27
+ key: str
28
+ kind: str
29
+ severity: str # high | warn | info
30
+ file: str
31
+ line: int
32
+ function: str
33
+ message: str
34
+
35
+
36
+ def git(root: Path, *args: str) -> str:
37
+ proc = subprocess.run(["git", "-C", str(root), *args], capture_output=True, text=True, encoding="utf-8", errors="replace")
38
+ if proc.returncode != 0:
39
+ raise RuntimeError(f"git {' '.join(args)} failed: {proc.stderr.strip()[:300]}")
40
+ return proc.stdout.strip()
41
+
42
+
43
+ def default_base(root: Path) -> str:
44
+ for ref in ("origin/HEAD", "origin/main", "origin/master", "main", "master"):
45
+ try:
46
+ git(root, "rev-parse", "--verify", "-q", ref)
47
+ return ref
48
+ except RuntimeError:
49
+ continue
50
+ raise RuntimeError("no base branch found: pass --base (a branch, tag or commit)")
51
+
52
+
53
+ def merge_base(root: Path, ref: str) -> str:
54
+ try:
55
+ return git(root, "merge-base", ref, "HEAD")
56
+ except RuntimeError:
57
+ return git(root, "rev-parse", ref) # unrelated or shallow history: compare with the ref itself
58
+
59
+
60
+ def extract(root: Path, sha: str) -> Path:
61
+ """The tree at `sha`, extracted once (git archive) into the cache folder."""
62
+ target = root / ".codefactory" / "diff" / sha[:12]
63
+ if (target / ".complete").exists():
64
+ return target
65
+ shutil.rmtree(target, ignore_errors=True)
66
+ target.mkdir(parents=True)
67
+ with tempfile.TemporaryDirectory() as tmp:
68
+ archive = Path(tmp) / "base.tar"
69
+ # the analyzed folder only, with paths relative to it (a subfolder of a monorepo is compared with itself)
70
+ prefix = git(root, "rev-parse", "--show-prefix").rstrip("/")
71
+ top = git(root, "rev-parse", "--show-toplevel") # run there: from a subfolder, `sha:path` is read relative to it
72
+ git(Path(top), "archive", "--format=tar", "-o", str(archive), f"{sha}:{prefix}" if prefix else sha)
73
+ with tarfile.open(archive) as tar:
74
+ try: # the data filter refuses absolute paths, links out of the folder and special files
75
+ tar.extractall(target, filter="data")
76
+ except TypeError: # Python 3.11 before 3.11.4 has no filters: our own git archive, so still safe
77
+ tar.extractall(target) # noqa: S202
78
+ (target / ".complete").write_text(sha, encoding="utf-8")
79
+ # older bases don't keep more than three around
80
+ olds = sorted((p for p in target.parent.iterdir() if p != target), key=lambda p: p.stat().st_mtime)
81
+ for old in olds[:-2]:
82
+ shutil.rmtree(old, ignore_errors=True)
83
+ return target
84
+
85
+
86
+ def changed_files(root: Path, sha: str) -> set[str]:
87
+ out = git(root, "diff", "--name-only", "--relative", sha) # committed and uncommitted changes, this folder only
88
+ untracked = git(root, "ls-files", "--others", "--exclude-standard")
89
+ return {p for p in (out + "\n" + untracked).splitlines() if p}
90
+
91
+
92
+ def items(root: Path, graph: dict) -> list[Item]:
93
+ """Every finding: graph flags and the review's source and repository checks (git history aside: it's the same
94
+ history on both sides)."""
95
+ from .audit import scan_config
96
+ from .checks import scan_sources, source_files
97
+ from .sarif import RULES
98
+
99
+ fns = {f["id"]: f for f in graph["functions"]}
100
+ out = []
101
+ for f in graph["flags"]:
102
+ fn = fns.get(f["target"])
103
+ out.append(Item(issue_key(graph, f, fns), f["kind"], f["severity"], fn["file"] if fn else f["target"],
104
+ f.get("line") or (fn["line"] if fn else 0), fn["qualname"] if fn and fn["kind"] != "module" else "",
105
+ f["message"])) # fmt: skip
106
+ from .privacy import scan as privacy_scan
107
+
108
+ sources = source_files(root, graph) # parsed or not: line checks need no parser
109
+ checks = scan_sources(root, sources)
110
+ checks.update(scan_config(root))
111
+ checks.update(privacy_scan(root, sources))
112
+ from .apple import scan as apple_scan
113
+
114
+ checks.update(apple_scan(root, sources))
115
+ from .config import load_config
116
+ from .infra import scan as infra_scan
117
+
118
+ checks.update(infra_scan(root, set(load_config(root).ignore)))
119
+ for kind, check in checks.items():
120
+ if kind not in RULES:
121
+ continue
122
+ for e in check.hits:
123
+ text = " ".join(e.text.split())
124
+ out.append(Item(f"{kind}|{e.file}|{text}", kind, RULES[kind][3], e.file, e.line, "", f"{RULES[kind][1]}: {e.text}"))
125
+ return out
126
+
127
+
128
+ def compare(base: list[Item], head: list[Item]) -> tuple[list[Item], list[Item]]:
129
+ """(new on head, gone from base), matching by key and counting repeats."""
130
+ left = Counter(i.key for i in base)
131
+ new = []
132
+ for i in head:
133
+ if left[i.key] > 0:
134
+ left[i.key] -= 1
135
+ else:
136
+ new.append(i)
137
+ remaining = Counter(i.key for i in head)
138
+ gone = []
139
+ for i in base:
140
+ if remaining[i.key] > 0:
141
+ remaining[i.key] -= 1
142
+ else:
143
+ gone.append(i)
144
+ return new, gone
145
+
146
+
147
+ def run(root: Path, base_ref: str, load) -> dict:
148
+ """load(path) -> graph. Returns base sha, changed files, new and fixed findings."""
149
+ root = root.resolve()
150
+ sha = merge_base(root, base_ref)
151
+ base_dir = extract(root, sha)
152
+ if (root / "node_modules" / "typescript").is_dir() and not os.environ.get("CODEFACTORY_TYPESCRIPT"):
153
+ # the base has no node_modules: use the same compiler for both sides, so only the code differs
154
+ os.environ["CODEFACTORY_TYPESCRIPT"] = str(root / "node_modules" / "typescript")
155
+ head_items = items(root, load(root))
156
+ base_items = items(base_dir, load(base_dir))
157
+ new, gone = compare(base_items, head_items)
158
+ changed = changed_files(root, sha)
159
+ order = lambda i: (SEV_RANK.get(i.severity, 3), i.file, i.line) # noqa: E731
160
+ return {"base": sha, "changed": sorted(changed), "new": sorted(new, key=order), "fixed": sorted(gone, key=order)}
161
+
162
+
163
+ def markdown(result: dict, limit: int = 30, owners=None) -> str:
164
+ """A pull-request comment (with each finding's owners, when the repository has a CODEOWNERS file)."""
165
+ new, fixed, changed = result["new"], result["fixed"], set(result["changed"])
166
+ counts = Counter(i.severity for i in new)
167
+ head = (
168
+ f"**codefactory:** {len(new)} new finding{'s' if len(new) != 1 else ''}"
169
+ + (f" ({', '.join(f'{counts[s]} {s}' for s in ('high', 'warn', 'info') if counts[s])})" if new else "")
170
+ + (
171
+ f" in the {result['added']:,} lines this patch adds ({len(changed)} files; line checks only, graph checks "
172
+ "need the repository)."
173
+ if result.get("patch")
174
+ else f", {len(fixed)} fixed, compared with `{result['base'][:10]}`."
175
+ )
176
+ )
177
+ lines = [head, ""]
178
+ if new:
179
+ lines += ["| | Finding | Where |", "|---|---|---|"]
180
+ for i in new[:limit]:
181
+ where = f"`{i.file}:{i.line}`" + (f" {i.function}" if i.function else "")
182
+ if owners and (who := owners.of(i.file)):
183
+ where += " · " + " ".join(who)
184
+ note = (
185
+ ""
186
+ if i.file in changed or result.get("patch")
187
+ else " (a file this change didn't touch: a consequence, such as a caller removed)"
188
+ )
189
+ lines.append(f"| {i.severity} | {i.message.replace('|', '/')} | {where}{note} |")
190
+ if len(new) > limit:
191
+ lines.append(f"| | … {len(new) - limit} more | |")
192
+ lines += ["", "Intended? Mark it with `codefactory: ignore <kind> — why` or `codefactory accept`."]
193
+ if fixed:
194
+ lines += ["", f"<details><summary>{len(fixed)} fixed</summary>", ""]
195
+ lines += [f"- {i.kind}: `{i.file}`" + (f" {i.function}" if i.function else "") for i in fixed[:limit]]
196
+ lines += ["", "</details>"]
197
+ return "\n".join(lines) + "\n"