aeppo 0.8.0__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.
aeppo/lockfiles.py ADDED
@@ -0,0 +1,315 @@
1
+ """Read exact dependency versions from lockfiles, without running a package manager.
2
+
3
+ Each parser returns ``Package`` tuples (OSV ecosystem, name, version, line). Only packages that
4
+ resolve from the public registry of their ecosystem are returned: workspace members, local paths,
5
+ git checkouts and URLs are skipped, because their names say nothing about a registry release.
6
+ """
7
+ import json
8
+ import re
9
+ from collections import namedtuple
10
+
11
+
12
+ Package = namedtuple("Package", "ecosystem name version line")
13
+
14
+ _EXACT_VERSION = re.compile(r"^v?\d+(?:\.\d+)*(?:[-+.~][0-9A-Za-z.+~-]*)?$")
15
+ _REQUIREMENTS_NAME = re.compile(r"^(?:.*[-_.])?requirements(?:[-_.].*)?\.txt$", re.IGNORECASE)
16
+
17
+
18
+ def kind(path):
19
+ """Return the lockfile format of ``path``, or ``None``."""
20
+ name = path.name
21
+ if name in _PARSERS:
22
+ return name
23
+ if _REQUIREMENTS_NAME.match(name) or (path.parent.name == "requirements" and path.suffix == ".txt"):
24
+ return "requirements.txt"
25
+ return None
26
+
27
+
28
+ def parse(kind_name, text):
29
+ try:
30
+ return [package for package in _PARSERS[kind_name](text) if _EXACT_VERSION.match(package.version)]
31
+ except (ValueError, TypeError, AttributeError, KeyError):
32
+ # A malformed lockfile is not a scan error; it simply yields no packages.
33
+ return []
34
+
35
+
36
+ def _line_finder(text):
37
+ """Return a function mapping a substring to the 1-based line of its first occurrence."""
38
+ def line_of(needle, default=1):
39
+ index = text.find(needle)
40
+ return text.count("\n", 0, index) + 1 if index >= 0 else default
41
+ return line_of
42
+
43
+
44
+ def _npm_lock(text):
45
+ data = json.loads(text)
46
+ line_of = _line_finder(text)
47
+ packages = []
48
+ entries = data.get("packages")
49
+ if isinstance(entries, dict):
50
+ # lockfileVersion 2 and 3: keys are install paths such as node_modules/a/node_modules/@s/b.
51
+ for key, entry in entries.items():
52
+ if "node_modules/" not in key or not isinstance(entry, dict) or entry.get("link"):
53
+ continue
54
+ version = entry.get("version")
55
+ resolved = entry.get("resolved", "")
56
+ if not isinstance(version, str) or (isinstance(resolved, str) and resolved.startswith(("file:", "git", "http://", "https://")) and "/-/" not in resolved):
57
+ continue
58
+ name = entry.get("name") or key.rsplit("node_modules/", 1)[1]
59
+ packages.append(_npm_package(name, version, line_of(json.dumps(key) + ":")))
60
+ return packages
61
+ # lockfileVersion 1: nested "dependencies" objects.
62
+ def walk(dependencies):
63
+ for name, entry in dependencies.items():
64
+ if not isinstance(entry, dict):
65
+ continue
66
+ version = entry.get("version")
67
+ if isinstance(version, str):
68
+ line = line_of(json.dumps(name) + ":")
69
+ if version.startswith("npm:"):
70
+ name, _, version = version[4:].rpartition("@")
71
+ packages.append(_npm_package(name, version, line))
72
+ if isinstance(entry.get("dependencies"), dict):
73
+ walk(entry["dependencies"])
74
+ if isinstance(data.get("dependencies"), dict):
75
+ walk(data["dependencies"])
76
+ return packages
77
+
78
+
79
+ def _npm_package(name, version, line):
80
+ return Package("npm", name, version, line)
81
+
82
+
83
+ def _split_npm_spec(spec):
84
+ """Split ``@scope/name@range`` into name and range."""
85
+ at = spec.find("@", 1)
86
+ return (spec[:at], spec[at + 1:]) if at > 0 else (spec, "")
87
+
88
+
89
+ def _yarn_lock(text):
90
+ packages = []
91
+ header = None
92
+ for line_number, line in enumerate(text.splitlines(), start=1):
93
+ if not line or line.startswith("#"):
94
+ continue
95
+ if not line[0].isspace():
96
+ header = (line_number, line.rstrip(":").strip()) if line.rstrip().endswith(":") else None
97
+ continue
98
+ if header is None:
99
+ continue
100
+ match = re.match(r'^\s+version:?\s+"?([^"\s]+)"?\s*$', line)
101
+ if not match:
102
+ continue
103
+ header_line, specs = header
104
+ header = None
105
+ first = specs.split(",")[0].strip().strip('"')
106
+ if first.startswith("__metadata"):
107
+ continue
108
+ name, spec_range = _split_npm_spec(first)
109
+ # Yarn Berry protocols other than npm (workspace:, link:, portal:, file:, patch:) are local.
110
+ if ":" in spec_range and not spec_range.startswith("npm:"):
111
+ continue
112
+ if spec_range.startswith("npm:") and "@" in spec_range[5:]:
113
+ name = _split_npm_spec(spec_range[4:])[0]
114
+ packages.append(_npm_package(name, match.group(1), header_line))
115
+ return packages
116
+
117
+
118
+ def _pnpm_lock(text):
119
+ packages = []
120
+ in_packages = False
121
+ for line_number, line in enumerate(text.splitlines(), start=1):
122
+ if line and not line[0].isspace():
123
+ in_packages = line.rstrip() == "packages:"
124
+ continue
125
+ if not in_packages:
126
+ continue
127
+ match = re.match(r"^ (['\"]?)(/?[^\s'\"]+)\1:\s*$", line)
128
+ if not match:
129
+ continue
130
+ key = match.group(2).lstrip("/")
131
+ key = re.sub(r"\(.*$", "", key)
132
+ at = key.find("@", 1)
133
+ if at > 0 and key[:at].count("/") == (1 if key.startswith("@") else 0):
134
+ # pnpm 6 and 9: name@version, optionally followed by (peer@version).
135
+ name, version = key[:at], key[at + 1:]
136
+ else:
137
+ # pnpm 5: /name/version_peer@version
138
+ name, _, version = key.rpartition("/")
139
+ version = version.split("_", 1)[0]
140
+ if name and ":" not in version:
141
+ packages.append(_npm_package(name, version, line_number))
142
+ return packages
143
+
144
+
145
+ def _python_name(name):
146
+ return re.sub(r"[-_.]+", "-", name).lower()
147
+
148
+
149
+ def _requirements(text):
150
+ packages = []
151
+ for line_number, raw in enumerate(text.splitlines(), start=1):
152
+ line = raw.split(" #", 1)[0].strip()
153
+ if line.startswith("#"):
154
+ continue
155
+ match = re.match(r"^([A-Za-z0-9][A-Za-z0-9._-]*)\s*(?:\[[^\]]*\])?\s*===?\s*([^\s;,\\]+)\s*(?:[;\\].*)?$", line)
156
+ if match and "*" not in match.group(2):
157
+ packages.append(Package("PyPI", _python_name(match.group(1)), match.group(2), line_number))
158
+ return packages
159
+
160
+
161
+ def _toml_packages(text):
162
+ """Yield (line, fields) for each ``[[package]]`` table; values are raw TOML right-hand sides."""
163
+ current = None
164
+ table = ""
165
+ for line_number, line in enumerate(text.splitlines(), start=1):
166
+ stripped = line.strip()
167
+ if stripped.startswith("["):
168
+ if stripped == "[[package]]":
169
+ if current is not None:
170
+ yield current
171
+ current, table = (line_number, {}), ""
172
+ elif current is not None and stripped.startswith("[package.") and not stripped.startswith("[["):
173
+ table = stripped.strip("[]")[len("package."):] + "."
174
+ else:
175
+ if current is not None:
176
+ yield current
177
+ current = None
178
+ continue
179
+ if current is None:
180
+ continue
181
+ match = re.match(r"^([A-Za-z0-9_-]+)\s*=\s*(.+)$", stripped)
182
+ if match:
183
+ current[1].setdefault(table + match.group(1), match.group(2).strip())
184
+ if current is not None:
185
+ yield current
186
+
187
+
188
+ def _toml_string(value):
189
+ match = re.match(r'^"((?:[^"\\]|\\.)*)"|^\'([^\']*)\'', value or "")
190
+ if not match:
191
+ return None
192
+ return match.group(1) if match.group(1) is not None else match.group(2)
193
+
194
+
195
+ def _poetry_lock(text):
196
+ packages = []
197
+ seen = set()
198
+ for line, fields in _toml_packages(text):
199
+ name, version = _toml_string(fields.get("name")), _toml_string(fields.get("version"))
200
+ source_type = _toml_string(fields.get("source.type"))
201
+ if not name or not version or source_type in {"git", "directory", "file", "url"}:
202
+ continue
203
+ key = (name, version)
204
+ if key not in seen:
205
+ seen.add(key)
206
+ packages.append(Package("PyPI", _python_name(name), version, line))
207
+ return packages
208
+
209
+
210
+ def _uv_lock(text):
211
+ packages = []
212
+ for line, fields in _toml_packages(text):
213
+ name, version = _toml_string(fields.get("name")), _toml_string(fields.get("version"))
214
+ source = fields.get("source", "")
215
+ if name and version and re.match(r"^\{\s*registry\s*=", source):
216
+ packages.append(Package("PyPI", _python_name(name), version, line))
217
+ return packages
218
+
219
+
220
+ def _cargo_lock(text):
221
+ packages = []
222
+ for line, fields in _toml_packages(text):
223
+ name, version = _toml_string(fields.get("name")), _toml_string(fields.get("version"))
224
+ source = _toml_string(fields.get("source")) or ""
225
+ if name and version and source.startswith(("registry+", "sparse+")):
226
+ packages.append(Package("crates.io", name, version, line))
227
+ return packages
228
+
229
+
230
+ def _go_mod(text):
231
+ """Read ``require`` directives from go.mod (go.sum also lists versions that are not selected)."""
232
+ required = []
233
+ replaced = {}
234
+ block = None
235
+ for line_number, raw in enumerate(text.splitlines(), start=1):
236
+ line = raw.split("//", 1)[0].strip()
237
+ if not line:
238
+ continue
239
+ if block:
240
+ if line == ")":
241
+ block = None
242
+ continue
243
+ directive, rest = block, line
244
+ else:
245
+ match = re.match(r"^(require|replace)\s*(\(?)\s*(.*)$", line)
246
+ if not match:
247
+ continue
248
+ if match.group(2):
249
+ block = match.group(1)
250
+ continue
251
+ directive, rest = match.group(1), match.group(3)
252
+ if directive == "require":
253
+ parts = rest.split()
254
+ if len(parts) >= 2:
255
+ required.append((parts[0], parts[1], line_number))
256
+ elif "=>" in rest:
257
+ left, right = (part.split() for part in rest.split("=>", 1))
258
+ if left:
259
+ replaced[left[0]] = right
260
+ packages = []
261
+ for module, version, line_number in required:
262
+ if module in replaced:
263
+ target = replaced[module]
264
+ if len(target) < 2:
265
+ continue # replaced by a local directory
266
+ module, version = target[0], target[1]
267
+ packages.append(Package("Go", module, version[1:] if version.startswith("v") else version, line_number))
268
+ return packages
269
+
270
+
271
+ def _composer_lock(text):
272
+ data = json.loads(text)
273
+ line_of = _line_finder(text)
274
+ packages = []
275
+ for section in ("packages", "packages-dev"):
276
+ for entry in data.get(section) or []:
277
+ if not isinstance(entry, dict):
278
+ continue
279
+ name, version = entry.get("name"), entry.get("version")
280
+ if isinstance(name, str) and isinstance(version, str) and not version.startswith("dev-"):
281
+ packages.append(Package("Packagist", name, version[1:] if version[:1] in "vV" else version, line_of('"name": ' + json.dumps(name))))
282
+ return packages
283
+
284
+
285
+ _GEM_PLATFORM = re.compile(r"-(?:x86|x64|arm|aarch64|universal|java|mswin|mingw|darwin|linux|freebsd)[\w.-]*$")
286
+
287
+
288
+ def _gemfile_lock(text):
289
+ packages = []
290
+ section = None
291
+ for line_number, line in enumerate(text.splitlines(), start=1):
292
+ if line and not line[0].isspace():
293
+ section = line.strip()
294
+ continue
295
+ if section != "GEM":
296
+ continue
297
+ match = re.match(r"^ ([A-Za-z0-9_.-]+) \(([^)]+)\)\s*$", line)
298
+ if match:
299
+ packages.append(Package("RubyGems", match.group(1), _GEM_PLATFORM.sub("", match.group(2)), line_number))
300
+ return packages
301
+
302
+
303
+ _PARSERS = {
304
+ "package-lock.json": _npm_lock,
305
+ "npm-shrinkwrap.json": _npm_lock,
306
+ "yarn.lock": _yarn_lock,
307
+ "pnpm-lock.yaml": _pnpm_lock,
308
+ "requirements.txt": _requirements,
309
+ "poetry.lock": _poetry_lock,
310
+ "uv.lock": _uv_lock,
311
+ "Cargo.lock": _cargo_lock,
312
+ "go.mod": _go_mod,
313
+ "composer.lock": _composer_lock,
314
+ "Gemfile.lock": _gemfile_lock,
315
+ }
aeppo/osv.py ADDED
@@ -0,0 +1,263 @@
1
+ """Minimal OSV.dev client (https://google.github.io/osv.dev/api/), standard library only.
2
+
3
+ Only package names, versions and ecosystems are sent. ``querybatch`` returns advisory IDs with
4
+ their last-modified time; full records are fetched once and cached on disk until OSV reports a
5
+ newer ``modified`` time, so repeated scans cost one batch request per 1000 packages.
6
+ """
7
+ import json
8
+ import math
9
+ import os
10
+ import re
11
+ import tempfile
12
+ import time
13
+ import urllib.error
14
+ import urllib.request
15
+ from concurrent.futures import ThreadPoolExecutor
16
+ from pathlib import Path
17
+
18
+ from aeppo import __version__
19
+
20
+
21
+ API = "https://api.osv.dev/v1"
22
+ _BATCH_SIZE = 1000
23
+ _MAX_PAGES = 20
24
+ _TIMEOUT = 30
25
+ _ATTEMPTS = 3
26
+ _SAFE_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$")
27
+
28
+
29
+ class OSVError(Exception):
30
+ pass
31
+
32
+
33
+ def default_cache_dir():
34
+ if os.environ.get("AEPPO_CACHE_DIR"):
35
+ return Path(os.environ["AEPPO_CACHE_DIR"])
36
+ base = os.environ.get("XDG_CACHE_HOME") or os.path.join(os.path.expanduser("~"), ".cache")
37
+ return Path(base) / "aeppo" / "osv"
38
+
39
+
40
+ def _http_fetch(method, url, body=None):
41
+ data = json.dumps(body).encode("utf-8") if body is not None else None
42
+ request = urllib.request.Request(url, data=data, method=method, headers={
43
+ "Content-Type": "application/json",
44
+ "Accept": "application/json",
45
+ "User-Agent": "aeppo/{} (+https://github.com/emanuellzoe/aeppo)".format(__version__),
46
+ })
47
+ for attempt in range(_ATTEMPTS):
48
+ try:
49
+ with urllib.request.urlopen(request, timeout=_TIMEOUT) as response:
50
+ return json.loads(response.read().decode("utf-8"))
51
+ except urllib.error.HTTPError as error:
52
+ # Retry rate limiting and server errors; anything else is a real answer.
53
+ if error.code not in (429, 500, 502, 503, 504) or attempt == _ATTEMPTS - 1:
54
+ raise OSVError("{} {} returned HTTP {}".format(method, url, error.code))
55
+ except (urllib.error.URLError, OSError) as error:
56
+ if attempt == _ATTEMPTS - 1:
57
+ raise OSVError("{} {} failed: {}".format(method, url, getattr(error, "reason", error)))
58
+ except ValueError as error:
59
+ raise OSVError("{} {} returned invalid JSON: {}".format(method, url, error))
60
+ time.sleep(2 ** attempt)
61
+ raise OSVError("{} {} failed".format(method, url))
62
+
63
+
64
+ class Client:
65
+ """Query OSV. ``fetch(method, url, body)`` is injectable so tests never touch the network."""
66
+
67
+ def __init__(self, fetch=None, cache_dir=None, workers=8):
68
+ self.fetch = fetch or _http_fetch
69
+ self.cache_dir = Path(cache_dir) if cache_dir else None
70
+ self.workers = workers
71
+
72
+ def query(self, packages):
73
+ """Map each (ecosystem, name, version) to the list of full OSV records that affect it."""
74
+ keys = sorted(set(packages))
75
+ ids = {key: {} for key in keys}
76
+ for start in range(0, len(keys), _BATCH_SIZE):
77
+ chunk = keys[start:start + _BATCH_SIZE]
78
+ pending = [(key, None) for key in chunk]
79
+ for _page in range(_MAX_PAGES):
80
+ if not pending:
81
+ break
82
+ queries = []
83
+ for (ecosystem, name, version), token in pending:
84
+ query = {"package": {"ecosystem": ecosystem, "name": name}, "version": version}
85
+ if token:
86
+ query["page_token"] = token
87
+ queries.append(query)
88
+ response = self.fetch("POST", API + "/querybatch", {"queries": queries})
89
+ results = response.get("results") if isinstance(response, dict) else None
90
+ if not isinstance(results, list) or len(results) != len(pending):
91
+ raise OSVError("unexpected querybatch response")
92
+ next_pending = []
93
+ for (key, _token), result in zip(pending, results):
94
+ result = result if isinstance(result, dict) else {}
95
+ for vuln in result.get("vulns") or []:
96
+ if isinstance(vuln, dict) and isinstance(vuln.get("id"), str):
97
+ ids[key][vuln["id"]] = vuln.get("modified")
98
+ if result.get("next_page_token"):
99
+ next_pending.append((key, result["next_page_token"]))
100
+ pending = next_pending
101
+ wanted = {}
102
+ for found in ids.values():
103
+ wanted.update(found)
104
+ records = self._records(wanted)
105
+ return {key: [records[vuln_id] for vuln_id in sorted(found) if vuln_id in records] for key, found in ids.items()}
106
+
107
+ def _records(self, wanted):
108
+ records = {}
109
+ missing = []
110
+ for vuln_id, modified in wanted.items():
111
+ if not _SAFE_ID.match(vuln_id):
112
+ continue
113
+ cached = self._cached(vuln_id, modified)
114
+ if cached is not None:
115
+ records[vuln_id] = cached
116
+ else:
117
+ missing.append(vuln_id)
118
+ if missing:
119
+ with ThreadPoolExecutor(max_workers=self.workers) as pool:
120
+ for vuln_id, record in zip(missing, pool.map(self._fetch_record, missing)):
121
+ records[vuln_id] = record
122
+ self._store(vuln_id, record)
123
+ return records
124
+
125
+ def _fetch_record(self, vuln_id):
126
+ record = self.fetch("GET", API + "/vulns/" + vuln_id, None)
127
+ if not isinstance(record, dict) or record.get("id") != vuln_id:
128
+ raise OSVError("unexpected record for {}".format(vuln_id))
129
+ return record
130
+
131
+ def _cache_path(self, vuln_id):
132
+ return self.cache_dir / (vuln_id.replace(":", "_") + ".json")
133
+
134
+ def _cached(self, vuln_id, modified):
135
+ if not self.cache_dir or not modified:
136
+ return None
137
+ try:
138
+ record = json.loads(self._cache_path(vuln_id).read_text(encoding="utf-8"))
139
+ except (OSError, ValueError):
140
+ return None
141
+ return record if isinstance(record, dict) and record.get("modified") == modified else None
142
+
143
+ def _store(self, vuln_id, record):
144
+ if not self.cache_dir:
145
+ return
146
+ try:
147
+ self.cache_dir.mkdir(parents=True, exist_ok=True)
148
+ handle, temporary = tempfile.mkstemp(dir=str(self.cache_dir), suffix=".tmp")
149
+ with os.fdopen(handle, "w", encoding="utf-8") as stream:
150
+ json.dump(record, stream)
151
+ os.replace(temporary, str(self._cache_path(vuln_id)))
152
+ except OSError:
153
+ pass # The cache is an optimisation; a read-only home directory must not fail the scan.
154
+
155
+
156
+ # CVSS v3.x base score (https://www.first.org/cvss/v3.1/specification-document#7-1-Base-Metrics-Equations).
157
+ _CVSS3 = {
158
+ "AV": {"N": 0.85, "A": 0.62, "L": 0.55, "P": 0.2},
159
+ "AC": {"L": 0.77, "H": 0.44},
160
+ "UI": {"N": 0.85, "R": 0.62},
161
+ "C": {"H": 0.56, "L": 0.22, "N": 0.0},
162
+ "I": {"H": 0.56, "L": 0.22, "N": 0.0},
163
+ "A": {"H": 0.56, "L": 0.22, "N": 0.0},
164
+ }
165
+
166
+
167
+ def _roundup(value):
168
+ integer = int(round(value * 100000))
169
+ return integer / 100000.0 if integer % 10000 == 0 else (math.floor(integer / 10000) + 1) / 10.0
170
+
171
+
172
+ def cvss3_score(vector):
173
+ """Return the CVSS v3 base score of ``vector``, or ``None`` if it is not a valid v3 vector."""
174
+ if not isinstance(vector, str) or not vector.startswith("CVSS:3."):
175
+ return None
176
+ metrics = dict(part.split(":", 1) for part in vector.split("/")[1:] if ":" in part)
177
+ try:
178
+ scope_changed = metrics["S"] == "C"
179
+ privileges = {"N": 0.85, "L": 0.68 if scope_changed else 0.62, "H": 0.5 if scope_changed else 0.27}[metrics["PR"]]
180
+ values = {name: table[metrics[name]] for name, table in _CVSS3.items()}
181
+ except KeyError:
182
+ return None
183
+ impact_base = 1 - (1 - values["C"]) * (1 - values["I"]) * (1 - values["A"])
184
+ if scope_changed:
185
+ impact = 7.52 * (impact_base - 0.029) - 3.25 * (impact_base - 0.02) ** 15
186
+ else:
187
+ impact = 6.42 * impact_base
188
+ exploitability = 8.22 * values["AV"] * values["AC"] * privileges * values["UI"]
189
+ if impact <= 0:
190
+ return 0.0
191
+ total = impact + exploitability
192
+ return _roundup(min(1.08 * total if scope_changed else total, 10))
193
+
194
+
195
+ _LABELS = {"CRITICAL": "critical", "HIGH": "high", "MODERATE": "medium", "MEDIUM": "medium", "LOW": "low"}
196
+ _RANK = {"low": 0, "medium": 1, "high": 2, "critical": 3}
197
+
198
+
199
+ def severity_label(record):
200
+ """Return critical/high/medium/low for an OSV record, or ``None`` when it gives no severity."""
201
+ labels = []
202
+ sources = [record.get("database_specific")]
203
+ for affected in record.get("affected") or []:
204
+ if isinstance(affected, dict):
205
+ sources.extend([affected.get("database_specific"), affected.get("ecosystem_specific")])
206
+ for source in sources:
207
+ if isinstance(source, dict) and isinstance(source.get("severity"), str):
208
+ label = _LABELS.get(source["severity"].upper())
209
+ if label:
210
+ labels.append(label)
211
+ for entry in record.get("severity") or []:
212
+ score = cvss3_score(entry.get("score")) if isinstance(entry, dict) else None
213
+ if score is not None:
214
+ labels.append("critical" if score >= 9 else "high" if score >= 7 else "medium" if score >= 4 else "low" if score > 0 else None)
215
+ labels = [label for label in labels if label]
216
+ return max(labels, key=_RANK.get) if labels else None
217
+
218
+
219
+ def informational(record):
220
+ """RustSec marks advisories such as ``unmaintained`` or ``unsound`` as informational."""
221
+ for affected in record.get("affected") or []:
222
+ details = affected.get("database_specific") if isinstance(affected, dict) else None
223
+ if isinstance(details, dict) and isinstance(details.get("informational"), str):
224
+ return details["informational"]
225
+ return None
226
+
227
+
228
+ def version_key(version):
229
+ """Loose ordering key that works across ecosystems: numbers compare numerically, and a
230
+ pre-release suffix (1.0.0rc1, 1.0.0-beta) sorts before the release."""
231
+ parts = []
232
+ for token in re.findall(r"\d+|[A-Za-z]+", version):
233
+ parts.append((2, int(token), "") if token.isdigit() else (0, 0, token.lower()))
234
+ parts.append((1, 0, ""))
235
+ return parts
236
+
237
+
238
+ def _same_package(affected, ecosystem, name):
239
+ package = affected.get("package") if isinstance(affected, dict) else None
240
+ if not isinstance(package, dict):
241
+ return False
242
+ other = package.get("name", "")
243
+ if ecosystem == "PyPI":
244
+ other = re.sub(r"[-_.]+", "-", other).lower()
245
+ return package.get("ecosystem", "").split(":", 1)[0] == ecosystem and other == name
246
+
247
+
248
+ def fixed_versions(record, ecosystem, name, version):
249
+ """Return fixed versions newer than ``version`` for this package, smallest first."""
250
+ fixed = set()
251
+ for affected in record.get("affected") or []:
252
+ if not _same_package(affected, ecosystem, name):
253
+ continue
254
+ for range_ in affected.get("ranges") or []:
255
+ # GIT ranges hold commit hashes, which are not versions a lockfile can name.
256
+ if not isinstance(range_, dict) or range_.get("type") == "GIT":
257
+ continue
258
+ for event in range_.get("events") or []:
259
+ if isinstance(event, dict) and isinstance(event.get("fixed"), str):
260
+ fixed.add(event["fixed"])
261
+ current = version_key(version)
262
+ newer = [value for value in fixed if version_key(value) > current]
263
+ return sorted(newer, key=version_key)
aeppo/report.py ADDED
@@ -0,0 +1,83 @@
1
+ import json
2
+
3
+ from aeppo import __version__
4
+ from aeppo.scanner import RULES
5
+
6
+
7
+ _SARIF_LEVELS = {"high": "error", "medium": "warning", "low": "note"}
8
+ # GitHub code scanning reads ``security-severity`` (0.0-10.0) to rank security alerts.
9
+ _SECURITY_SEVERITY = {"high": "8.0", "medium": "5.0", "low": "2.0"}
10
+
11
+
12
+ def format_text(findings):
13
+ if not findings:
14
+ return "No findings."
15
+ lines = []
16
+ for finding in findings:
17
+ lines.append("{}:{}: [{}|{}] {} ({}, confidence={})".format(finding.path, finding.line, finding.rule_id, finding.severity, finding.message, finding.category, finding.confidence))
18
+ lines.append(" Recommendation: {}".format(finding.recommendation))
19
+ return "\n".join(lines)
20
+
21
+
22
+ def format_json(findings):
23
+ return json.dumps([finding.__dict__ for finding in findings], indent=2)
24
+
25
+
26
+ def format_sarif(findings, uri_for=lambda finding: finding.path):
27
+ """Render findings as SARIF 2.1.0; ``uri_for`` maps a finding to its artifact URI."""
28
+ rule_ids = sorted(RULES)
29
+ rule_index = {rule_id: index for index, rule_id in enumerate(rule_ids)}
30
+ rules = []
31
+ for rule_id in rule_ids:
32
+ rule = RULES[rule_id]
33
+ rules.append(
34
+ {
35
+ "id": rule_id,
36
+ "name": rule_id,
37
+ "shortDescription": {"text": rule.message},
38
+ "help": {"text": rule.recommendation},
39
+ "defaultConfiguration": {"level": _SARIF_LEVELS[rule.severity]},
40
+ "properties": {
41
+ "tags": ["security", rule.category],
42
+ "precision": rule.confidence,
43
+ "security-severity": _SECURITY_SEVERITY[rule.severity],
44
+ },
45
+ }
46
+ )
47
+ results = []
48
+ for finding in findings:
49
+ results.append(
50
+ {
51
+ "ruleId": finding.rule_id,
52
+ "ruleIndex": rule_index[finding.rule_id],
53
+ "level": _SARIF_LEVELS.get(finding.severity, "warning"),
54
+ "message": {"text": "{} {}".format(finding.message, finding.recommendation)},
55
+ "locations": [
56
+ {
57
+ "physicalLocation": {
58
+ "artifactLocation": {"uri": uri_for(finding)},
59
+ "region": {"startLine": finding.line},
60
+ }
61
+ }
62
+ ],
63
+ "partialFingerprints": {"aeppo/v1": finding.fingerprint},
64
+ }
65
+ )
66
+ document = {
67
+ "$schema": "https://json.schemastore.org/sarif-2.1.0.json",
68
+ "version": "2.1.0",
69
+ "runs": [
70
+ {
71
+ "tool": {
72
+ "driver": {
73
+ "name": "aeppo",
74
+ "version": __version__,
75
+ "informationUri": "https://github.com/emanuellzoe/aeppo",
76
+ "rules": rules,
77
+ }
78
+ },
79
+ "results": results,
80
+ }
81
+ ],
82
+ }
83
+ return json.dumps(document, indent=2)