slopthreshold 2.1.0.dev22__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.
- slopthreshold/__init__.py +1 -0
- slopthreshold/guide/STYLE_GUIDE.md +495 -0
- slopthreshold/packs/editorconfig-pack/.editorconfig +899 -0
- slopthreshold/packs/editorconfig-pack/Directory.Build.props +47 -0
- slopthreshold/packs/editorconfig-pack/Directory.Build.targets +16 -0
- slopthreshold/packs/editorconfig-pack/Directory.Packages.props +29 -0
- slopthreshold/packs/editorconfig-pack/README.md +141 -0
- slopthreshold/packs/editorconfig-pack/global.json +7 -0
- slopthreshold/packs/editorconfig-pack/nuget.config +19 -0
- slopthreshold/packs/editorconfig-pack/ruff.toml +29 -0
- slopthreshold/packs/editorconfig-pack/sonar-drift-allowlist.json +10 -0
- slopthreshold/packs/frontend-lint-pack/.prettierrc.json +7 -0
- slopthreshold/packs/frontend-lint-pack/.stylelintrc.json +64 -0
- slopthreshold/packs/frontend-lint-pack/README.md +64 -0
- slopthreshold/packs/frontend-lint-pack/eslint.config.mjs +108 -0
- slopthreshold/packs/frontend-lint-pack/package.json +23 -0
- slopthreshold/packs/frontend-lint-pack/tsconfig.app.json +17 -0
- slopthreshold/packs/frontend-lint-pack/tsconfig.base.json +20 -0
- slopthreshold/packs/frontend-lint-pack/tsconfig.json +4 -0
- slopthreshold/packs/frontend-lint-pack/tsconfig.spec.json +8 -0
- slopthreshold/packs/project-guide-starters/app-STYLE_GUIDE.md +35 -0
- slopthreshold/packs/project-guide-starters/frontend-STYLE_GUIDE.md +33 -0
- slopthreshold/packs/project-guide-starters/library-STYLE_GUIDE.md +36 -0
- slopthreshold/packs/three-layer-wiring/.githooks/commit-msg +13 -0
- slopthreshold/packs/three-layer-wiring/.githooks/post-merge +8 -0
- slopthreshold/packs/three-layer-wiring/.githooks/pre-commit +10 -0
- slopthreshold/packs/three-layer-wiring/.githooks/pre-push +14 -0
- slopthreshold/packs/three-layer-wiring/.github/actionlint.yaml +3 -0
- slopthreshold/packs/three-layer-wiring/.github/workflows/quality.yml +164 -0
- slopthreshold/packs/three-layer-wiring/.gitleaks.toml +16 -0
- slopthreshold/packs/three-layer-wiring/.hadolint.yaml +6 -0
- slopthreshold/packs/three-layer-wiring/README.md +62 -0
- slopthreshold/packs/three-layer-wiring/budget.json +14 -0
- slopthreshold/tools/check_characters.py +104 -0
- slopthreshold/tools/check_ci_config.py +405 -0
- slopthreshold/tools/check_package_health.py +554 -0
- slopthreshold/tools/check_sonar_drift.py +1123 -0
- slopthreshold/tools/mine_sonar_metrics.py +1259 -0
- slopthreshold/tools/validate_guide_tags.py +795 -0
- slopthreshold/zh.py +973 -0
- slopthreshold-2.1.0.dev22.dist-info/METADATA +49 -0
- slopthreshold-2.1.0.dev22.dist-info/RECORD +44 -0
- slopthreshold-2.1.0.dev22.dist-info/WHEEL +4 -0
- slopthreshold-2.1.0.dev22.dist-info/entry_points.txt +2 -0
|
@@ -0,0 +1,554 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Grade third-party packages against the Generalized Style Guide health
|
|
3
|
+
gate (ST-DEP-01..05, ST-FE-DEP-01).
|
|
4
|
+
|
|
5
|
+
FAIL (ST-DEP-02, REQUIRED): latest stable release older than 18 months or
|
|
6
|
+
prerelease-only; no commit in 12 months or archived; unmaintained backlog;
|
|
7
|
+
unpatched vulnerability advisory on the pinned version; does not run on
|
|
8
|
+
the target frameworks; non-permissive licence on a shipped package
|
|
9
|
+
(ST-DEP-01).
|
|
10
|
+
|
|
11
|
+
WARN (ST-DEP-03, DEFAULT): release 12-18 months old; last commit 6-12
|
|
12
|
+
months; more than 50 open PRs or recent unanswered issues;
|
|
13
|
+
compatibility-only target framework; unknown licence. A warn needs one
|
|
14
|
+
decision line in the project guide with a review date within 6 months.
|
|
15
|
+
|
|
16
|
+
Usage:
|
|
17
|
+
check_package_health.py --props Directory.Packages.props [--write-evidence]
|
|
18
|
+
check_package_health.py --package Newtonsoft.Json@12.0.3
|
|
19
|
+
check_package_health.py --npm package.json
|
|
20
|
+
|
|
21
|
+
Exit 1 when any package FAILs. GITHUB_TOKEN env raises GitHub rate limits.
|
|
22
|
+
Exemptions (build-time-only packages, recorded decisions) live in
|
|
23
|
+
health-gate.json beside the props file:
|
|
24
|
+
{"exemptions": {"SonarAnalyzer.CSharp": {"buildOnly": true}}}
|
|
25
|
+
"""
|
|
26
|
+
import argparse
|
|
27
|
+
import contextlib
|
|
28
|
+
import datetime
|
|
29
|
+
import json
|
|
30
|
+
import os
|
|
31
|
+
import pathlib
|
|
32
|
+
import re
|
|
33
|
+
import sys
|
|
34
|
+
|
|
35
|
+
sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
|
|
36
|
+
from safe_paths import read_text_under, resolve_under, write_text_under # noqa: E402
|
|
37
|
+
from http_util import open_https # noqa: E402
|
|
38
|
+
|
|
39
|
+
PERMISSIVE = {"MIT", "Apache-2.0", "BSD-2-Clause", "BSD-3-Clause", "0BSD"}
|
|
40
|
+
COMPAT_TFMS = {"netstandard2.0", "netstandard2.1"}
|
|
41
|
+
MODERN_TFM_RE = re.compile(r"^net([5-9]|10)\.0$")
|
|
42
|
+
MONTH_DAYS = 30.44
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def months_between(earlier, later):
|
|
46
|
+
return (later - earlier).days / MONTH_DAYS
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def http_json(url, headers=None):
|
|
50
|
+
merged = {"User-Agent": "health-gate-checker/1.0", **(headers or {})}
|
|
51
|
+
with open_https(url, headers=merged, timeout=30) as resp:
|
|
52
|
+
raw = resp.read()
|
|
53
|
+
if raw[:2] == b"\x1f\x8b": # NuGet registration5-gz endpoints
|
|
54
|
+
import gzip
|
|
55
|
+
raw = gzip.decompress(raw)
|
|
56
|
+
return json.loads(raw.decode("utf-8")), resp.headers
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def gh_headers():
|
|
60
|
+
token = os.environ.get("GITHUB_TOKEN")
|
|
61
|
+
return {"Authorization": f"Bearer {token}"} if token else {}
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def parse_github_repo(url):
|
|
65
|
+
if not url:
|
|
66
|
+
return None
|
|
67
|
+
m = re.search(r"github\.com[/:]([^/]+)/([^/#]+)", url)
|
|
68
|
+
if not m:
|
|
69
|
+
return None
|
|
70
|
+
return m.group(1), m.group(2).removesuffix(".git")
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def fetch_github(owner, repo):
|
|
74
|
+
data = {"archived": None, "last_commit": None, "open_prs": None, "unanswered_recent": None}
|
|
75
|
+
try:
|
|
76
|
+
info, _ = http_json(f"https://api.github.com/repos/{owner}/{repo}", gh_headers())
|
|
77
|
+
data["archived"] = bool(info.get("archived"))
|
|
78
|
+
except Exception as e:
|
|
79
|
+
data["error"] = f"github repo lookup failed: {e}"
|
|
80
|
+
return data
|
|
81
|
+
# Best-effort enrichment: a failed lookup leaves the field as None.
|
|
82
|
+
with contextlib.suppress(Exception):
|
|
83
|
+
commits, _ = http_json(f"https://api.github.com/repos/{owner}/{repo}/commits?per_page=1", gh_headers())
|
|
84
|
+
if commits:
|
|
85
|
+
data["last_commit"] = commits[0]["commit"]["committer"]["date"][:10]
|
|
86
|
+
with contextlib.suppress(Exception):
|
|
87
|
+
_, headers = http_json(f"https://api.github.com/repos/{owner}/{repo}/pulls?state=open&per_page=1", gh_headers())
|
|
88
|
+
link = headers.get("Link", "")
|
|
89
|
+
m = re.search(r'[?&]page=(\d+)>; rel="last"', link)
|
|
90
|
+
data["open_prs"] = int(m.group(1)) if m else None
|
|
91
|
+
with contextlib.suppress(Exception):
|
|
92
|
+
issues, _ = http_json(
|
|
93
|
+
f"https://api.github.com/repos/{owner}/{repo}/issues?state=open&sort=created&direction=desc&per_page=10",
|
|
94
|
+
gh_headers())
|
|
95
|
+
cutoff = (datetime.date.today() - datetime.timedelta(days=30)).isoformat()
|
|
96
|
+
data["unanswered_recent"] = sum(
|
|
97
|
+
1 for i in issues if "pull_request" not in i and i.get("comments", 0) == 0 and i["created_at"][:10] < cutoff)
|
|
98
|
+
return data
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def fetch_nuget(package_id):
|
|
102
|
+
url = f"https://api.nuget.org/v3/registration5-gz-semver2/{package_id.lower()}/index.json"
|
|
103
|
+
index, _ = http_json(url)
|
|
104
|
+
entries = []
|
|
105
|
+
for page in index.get("items", []):
|
|
106
|
+
items = page.get("items")
|
|
107
|
+
if items is None:
|
|
108
|
+
page_data, _ = http_json(page["@id"])
|
|
109
|
+
items = page_data.get("items", [])
|
|
110
|
+
for item in items:
|
|
111
|
+
entries.append(item["catalogEntry"])
|
|
112
|
+
return entries
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def is_stable(version):
|
|
116
|
+
return "-" not in version
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _osv_cve(vuln):
|
|
120
|
+
return next((a for a in vuln.get("aliases", []) or [] if a.startswith("CVE-")), None)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _osv_severity_from_list(vuln):
|
|
124
|
+
for entry in vuln.get("severity", []) or []:
|
|
125
|
+
score = entry.get("score", "")
|
|
126
|
+
return "see advisory" if re.search(r"CVSS:3\.[01]/.*", score) else score
|
|
127
|
+
return None
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def _osv_severity(vuln):
|
|
131
|
+
severity = (vuln.get("database_specific") or {}).get("severity")
|
|
132
|
+
if severity:
|
|
133
|
+
return severity
|
|
134
|
+
return _osv_severity_from_list(vuln)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _osv_fixed_in_events(events):
|
|
138
|
+
for event in events or []:
|
|
139
|
+
if event.get("fixed"):
|
|
140
|
+
return event["fixed"]
|
|
141
|
+
return None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _osv_fixed_in_ranges(ranges):
|
|
145
|
+
for rng in ranges or []:
|
|
146
|
+
fixed = _osv_fixed_in_events(rng.get("events", []))
|
|
147
|
+
if fixed:
|
|
148
|
+
return fixed
|
|
149
|
+
return None
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _osv_fixed(vuln):
|
|
153
|
+
for affected in vuln.get("affected", []) or []:
|
|
154
|
+
fixed = _osv_fixed_in_ranges(affected.get("ranges", []))
|
|
155
|
+
if fixed:
|
|
156
|
+
return fixed
|
|
157
|
+
return None
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _osv_advisory(vuln):
|
|
161
|
+
severity = _osv_severity(vuln)
|
|
162
|
+
return {"id": vuln.get("id", "unknown"), "cve": _osv_cve(vuln),
|
|
163
|
+
"severity": str(severity).lower() if severity else "unknown",
|
|
164
|
+
"fixed": _osv_fixed(vuln),
|
|
165
|
+
"summary": (vuln.get("summary") or "")[:120]}
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def parse_osv_vulns(payload):
|
|
169
|
+
"""Normalize an OSV /v1/query payload into advisory dicts."""
|
|
170
|
+
vulns = []
|
|
171
|
+
for v in (payload or {}).get("vulns", []) or []:
|
|
172
|
+
if v.get("withdrawn"):
|
|
173
|
+
continue
|
|
174
|
+
vulns.append(_osv_advisory(v))
|
|
175
|
+
return vulns
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def fetch_osv(ecosystem, name, version):
|
|
179
|
+
"""Known vulnerabilities affecting name@version via OSV (api.osv.dev).
|
|
180
|
+
|
|
181
|
+
Returns a list of advisory dicts, or None when OSV is unreachable so
|
|
182
|
+
callers can fall back instead of silently passing.
|
|
183
|
+
"""
|
|
184
|
+
body = json.dumps({"version": version, "package": {"name": name, "ecosystem": ecosystem}}).encode()
|
|
185
|
+
headers = {"User-Agent": "health-gate-checker/1.1", "Content-Type": "application/json"}
|
|
186
|
+
for _ in range(2):
|
|
187
|
+
try:
|
|
188
|
+
with open_https("https://api.osv.dev/v1/query", data=body, headers=headers, timeout=30) as resp:
|
|
189
|
+
return parse_osv_vulns(json.loads(resp.read().decode("utf-8")))
|
|
190
|
+
except Exception: # noqa: S112 - retry-then-fallback is the documented contract
|
|
191
|
+
# One retry, then None: callers fall back to nuget.org WARN,
|
|
192
|
+
# never a silent pass, so the failure detail adds nothing here.
|
|
193
|
+
continue
|
|
194
|
+
return None
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def grade_vulns(vulns, version, fails, facts):
|
|
198
|
+
facts["vulns"] = len(vulns)
|
|
199
|
+
for v in vulns:
|
|
200
|
+
label = v["id"] + (f" / {v['cve']}" if v.get("cve") else "")
|
|
201
|
+
fixed = f"fixed in {v['fixed']}" if v.get("fixed") else "no fix published"
|
|
202
|
+
fails.append(f"vulnerability {label} (severity {v['severity']}) affects {version}; {fixed} (ST-DEP-02)")
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _grade_release_age(subject, published, today, fails, warns):
|
|
206
|
+
age = months_between(published, today)
|
|
207
|
+
if age > 18:
|
|
208
|
+
fails.append(f"{subject} is {age:.0f} months old (ST-DEP-02)")
|
|
209
|
+
elif age > 12:
|
|
210
|
+
warns.append(f"{subject} is {age:.0f} months old (ST-DEP-03)")
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _resolve_pinned(entries, pinned_version, latest, warns):
|
|
214
|
+
if not pinned_version:
|
|
215
|
+
return latest
|
|
216
|
+
pinned = next((e for e in entries if e["version"] == pinned_version), None)
|
|
217
|
+
if pinned is None:
|
|
218
|
+
warns.append(f"pinned version {pinned_version} not found in registration data")
|
|
219
|
+
return latest
|
|
220
|
+
return pinned
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
def _grade_nuget_vulns(vulns, pinned, fails, warns):
|
|
224
|
+
if vulns is not None:
|
|
225
|
+
grade_vulns(vulns, pinned["version"], fails, {})
|
|
226
|
+
return
|
|
227
|
+
warns.append("vulnerability check via OSV unavailable; fell back to nuget.org advisory data (ST-DEP-03)")
|
|
228
|
+
for vuln in pinned.get("vulnerabilities", []) or []:
|
|
229
|
+
fails.append(f"unpatched advisory on {pinned['version']}: {vuln.get('advisoryUrl', 'see nuget.org')} (ST-DEP-02)")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def _licence_is_permissive(licence):
|
|
233
|
+
normalized = " ".join(licence.split())
|
|
234
|
+
parts = [p.strip("() ") for p in re.split(r" (?:AND|OR) ", normalized)]
|
|
235
|
+
return all(p in PERMISSIVE for p in parts)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _grade_nuget_licence(latest, build_only, fails, warns):
|
|
239
|
+
licence = (latest.get("licenseExpression") or "").strip()
|
|
240
|
+
if not licence:
|
|
241
|
+
warns.append("no licence expression on nuget.org (ST-DEP-03)")
|
|
242
|
+
return licence
|
|
243
|
+
if _licence_is_permissive(licence):
|
|
244
|
+
return licence
|
|
245
|
+
if build_only:
|
|
246
|
+
warns.append(f"licence {licence} accepted as build-time-only tooling (ST-DEP-01 exemption)")
|
|
247
|
+
return licence
|
|
248
|
+
fails.append(f"licence {licence} is not MIT/Apache-2.0/BSD (ST-DEP-01)")
|
|
249
|
+
return licence
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _nuget_tfms(latest, build_only):
|
|
253
|
+
tfms = [g.get("targetFramework", "").lower().lstrip(".") for g in latest.get("dependencyGroups", []) or []]
|
|
254
|
+
tfms = [t for t in tfms if t]
|
|
255
|
+
if build_only:
|
|
256
|
+
return [] # analyzers/tooling target netstandard2.0 by design; app TFM does not apply
|
|
257
|
+
return tfms
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def _grade_nuget_tfms(latest, build_only, fails, warns):
|
|
261
|
+
tfms = _nuget_tfms(latest, build_only)
|
|
262
|
+
if not tfms:
|
|
263
|
+
return
|
|
264
|
+
if any(MODERN_TFM_RE.match(t) for t in tfms):
|
|
265
|
+
return
|
|
266
|
+
if any(t in COMPAT_TFMS for t in tfms):
|
|
267
|
+
warns.append(f"compatibility-only target frameworks {tfms} (ST-DEP-03)")
|
|
268
|
+
return
|
|
269
|
+
fails.append(f"does not run on target frameworks {tfms} (ST-DEP-02)")
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def _verdict(fails, warns):
|
|
273
|
+
if fails:
|
|
274
|
+
return "FAIL"
|
|
275
|
+
if warns:
|
|
276
|
+
return "WARN"
|
|
277
|
+
return "PASS"
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def grade_nuget(pinned_version, entries, github, today, build_only=False, vulns=None):
|
|
281
|
+
fails, warns = [], []
|
|
282
|
+
stable = [e for e in entries if is_stable(e["version"])]
|
|
283
|
+
if not stable:
|
|
284
|
+
return "FAIL", ["prerelease-only (ST-DEP-02)"], {}
|
|
285
|
+
latest = stable[-1]
|
|
286
|
+
published = datetime.date.fromisoformat(latest["published"][:10])
|
|
287
|
+
_grade_release_age(f"latest stable {latest['version']}", published, today, fails, warns)
|
|
288
|
+
if latest.get("deprecation"):
|
|
289
|
+
fails.append("package is deprecated on nuget.org (ST-DEP-02)")
|
|
290
|
+
pinned = _resolve_pinned(entries, pinned_version, latest, warns)
|
|
291
|
+
_grade_nuget_vulns(vulns, pinned, fails, warns)
|
|
292
|
+
licence = _grade_nuget_licence(latest, build_only, fails, warns)
|
|
293
|
+
_grade_nuget_tfms(latest, build_only, fails, warns)
|
|
294
|
+
facts = {"last_release": published.isoformat(), "latest": latest["version"], "licence": licence or "unknown",
|
|
295
|
+
"vulns": len(vulns) if vulns is not None else "unchecked"}
|
|
296
|
+
grade_github(github, today, fails, warns, facts)
|
|
297
|
+
return _verdict(fails, warns), fails + warns, facts
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def grade_github(github, today, fails, warns, facts):
|
|
301
|
+
if not github:
|
|
302
|
+
warns.append("no GitHub repository found; commit activity unchecked (ST-DEP-03)")
|
|
303
|
+
return
|
|
304
|
+
if github.get("error"):
|
|
305
|
+
warns.append(github["error"])
|
|
306
|
+
return
|
|
307
|
+
if github.get("archived"):
|
|
308
|
+
fails.append("repository archived (ST-DEP-02)")
|
|
309
|
+
if github.get("last_commit"):
|
|
310
|
+
commit = datetime.date.fromisoformat(github["last_commit"])
|
|
311
|
+
facts["last_commit"] = github["last_commit"]
|
|
312
|
+
age = months_between(commit, today)
|
|
313
|
+
if age > 12:
|
|
314
|
+
fails.append(f"no commit in {age:.0f} months (ST-DEP-02)")
|
|
315
|
+
elif age > 6:
|
|
316
|
+
warns.append(f"last commit {age:.0f} months ago (ST-DEP-03)")
|
|
317
|
+
if github.get("open_prs") is not None and github["open_prs"] > 50:
|
|
318
|
+
warns.append(f"{github['open_prs']} open PRs (ST-DEP-03)")
|
|
319
|
+
if github.get("unanswered_recent"):
|
|
320
|
+
warns.append(f"{github['unanswered_recent']} recent issues without any reply (ST-DEP-03)")
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
def _npm_published(registry, latest_version):
|
|
324
|
+
if not latest_version:
|
|
325
|
+
return None
|
|
326
|
+
raw = registry.get("time", {}).get(latest_version)
|
|
327
|
+
if not raw:
|
|
328
|
+
return None
|
|
329
|
+
return datetime.date.fromisoformat(raw[:10])
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
def _npm_licence(registry, latest_version):
|
|
333
|
+
return registry.get("license") or (registry.get("versions", {}).get(latest_version, {}) or {}).get("license", "")
|
|
334
|
+
|
|
335
|
+
|
|
336
|
+
def _grade_npm_licence(licence, fails, warns):
|
|
337
|
+
if not licence:
|
|
338
|
+
warns.append("no licence in registry metadata (ST-DEP-03)")
|
|
339
|
+
return
|
|
340
|
+
if licence not in PERMISSIVE:
|
|
341
|
+
fails.append(f"licence {licence} is not MIT/Apache-2.0/BSD (ST-FE-DEP-01)")
|
|
342
|
+
|
|
343
|
+
|
|
344
|
+
def _grade_npm_vulns(vulns, pinned_version, latest_version, fails, warns, facts):
|
|
345
|
+
if vulns is None:
|
|
346
|
+
warns.append("vulnerability check via OSV unavailable; verdict does not cover advisories (ST-DEP-03)")
|
|
347
|
+
return
|
|
348
|
+
grade_vulns(vulns, pinned_version or latest_version, fails, facts)
|
|
349
|
+
|
|
350
|
+
|
|
351
|
+
def grade_npm(registry, github, today, pinned_version=None, vulns=None):
|
|
352
|
+
fails, warns = [], []
|
|
353
|
+
latest_version = registry.get("dist-tags", {}).get("latest")
|
|
354
|
+
facts = {"latest": latest_version}
|
|
355
|
+
published = _npm_published(registry, latest_version)
|
|
356
|
+
if published:
|
|
357
|
+
facts["last_release"] = published.isoformat()
|
|
358
|
+
_grade_release_age(f"latest release {latest_version}", published, today, fails, warns)
|
|
359
|
+
licence = _npm_licence(registry, latest_version)
|
|
360
|
+
facts["licence"] = licence or "unknown"
|
|
361
|
+
_grade_npm_licence(licence, fails, warns)
|
|
362
|
+
_grade_npm_vulns(vulns, pinned_version, latest_version, fails, warns, facts)
|
|
363
|
+
grade_github(github, today, fails, warns, facts)
|
|
364
|
+
return _verdict(fails, warns), fails + warns, facts
|
|
365
|
+
|
|
366
|
+
|
|
367
|
+
def parse_props(text):
|
|
368
|
+
pins = []
|
|
369
|
+
for m in re.finditer(r'<PackageVersion\s+Include="([^"]+)"\s+Version="([^"]+)"', text):
|
|
370
|
+
pins.append((m.group(1), m.group(2)))
|
|
371
|
+
return pins
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def write_evidence(props_path, results, today):
|
|
375
|
+
text = read_text_under(props_path, pathlib.Path.cwd())
|
|
376
|
+
for package_id, _version, verdict, facts in results:
|
|
377
|
+
comment = (f"<!-- checked {today.isoformat()} | last release {facts.get('last_release', '?')} "
|
|
378
|
+
f"| last commit {facts.get('last_commit', '?')} | licence {facts.get('licence', '?')} "
|
|
379
|
+
f"| verdict {verdict} -->")
|
|
380
|
+
# Tempered token in the comment body: it cannot consume the -->
|
|
381
|
+
# delimiter, so matching stays linear (no [^>]* / --> overlap).
|
|
382
|
+
pattern = re.compile(
|
|
383
|
+
r'(?P<indent>[ \t]*)(<!-- checked (?:[^>-]|-(?!->))*-->\n[ \t]*)?(?P<tag><PackageVersion\s+Include="'
|
|
384
|
+
+ re.escape(package_id) + r'"\s+Version="[^"]+"\s*/>)')
|
|
385
|
+
text, n = pattern.subn(lambda m, comment=comment: f"{m.group('indent')}{comment}\n{m.group('indent')}{m.group('tag')}", text, count=1)
|
|
386
|
+
if n == 0:
|
|
387
|
+
print(f"WARN: could not place evidence comment for {package_id}", file=sys.stderr)
|
|
388
|
+
write_text_under(props_path, pathlib.Path.cwd(), text)
|
|
389
|
+
|
|
390
|
+
|
|
391
|
+
def load_exemptions(props_path):
|
|
392
|
+
base = pathlib.Path(props_path).expanduser().parent if props_path else pathlib.Path.cwd()
|
|
393
|
+
candidate = resolve_under(base / "health-gate.json", base)
|
|
394
|
+
if candidate.is_file():
|
|
395
|
+
return json.loads(candidate.read_text(encoding="utf-8")).get("exemptions", {})
|
|
396
|
+
return {}
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
def apply_bypass(package_id, verdict, reasons, exemptions, today):
|
|
400
|
+
"""A recorded ST-DEP-02 bypass (approver + unexpired review date) downgrades FAIL to WARN."""
|
|
401
|
+
entry = exemptions.get(package_id, {})
|
|
402
|
+
bypass = entry.get("bypass")
|
|
403
|
+
if verdict != "FAIL" or not bypass:
|
|
404
|
+
return verdict, reasons
|
|
405
|
+
review = bypass.get("review", "")
|
|
406
|
+
approver = bypass.get("approved", "")
|
|
407
|
+
try:
|
|
408
|
+
review_date = datetime.date.fromisoformat(review)
|
|
409
|
+
except ValueError:
|
|
410
|
+
return verdict, reasons + [f"bypass for {package_id} has no valid review date; FAIL stands"]
|
|
411
|
+
if not approver:
|
|
412
|
+
return verdict, reasons + [f"bypass for {package_id} has no approver; FAIL stands"]
|
|
413
|
+
if review_date < today:
|
|
414
|
+
return verdict, reasons + [f"bypass for {package_id} expired {review}; FAIL stands"]
|
|
415
|
+
return "WARN", reasons + [f"FAIL downgraded by recorded bypass (approved: {approver}, review: {review})"]
|
|
416
|
+
|
|
417
|
+
|
|
418
|
+
def fetch_nuspec_facts(package_id, version):
|
|
419
|
+
"""Repository URL and licence from the nuspec (catalog often lacks both)."""
|
|
420
|
+
url = f"https://api.nuget.org/v3-flatcontainer/{package_id.lower()}/{version.lower()}/{package_id.lower()}.nuspec"
|
|
421
|
+
try:
|
|
422
|
+
with open_https(url, headers={"User-Agent": "health-gate-checker/1.0"}, timeout=30) as resp:
|
|
423
|
+
xml = resp.read().decode("utf-8", "replace")
|
|
424
|
+
except Exception:
|
|
425
|
+
return {}
|
|
426
|
+
facts = {}
|
|
427
|
+
# Tempered token: the prefix cannot consume whitespace starting the
|
|
428
|
+
# url attribute, so the partition is forced and matching stays linear
|
|
429
|
+
# (no [^>]* / url= overlap). The whitespace requirement also keeps
|
|
430
|
+
# url=" inside a longer attribute name (e.g. x-url=) from matching.
|
|
431
|
+
m = re.search(r'<repository(?:[^>\s]|\s(?!url="))*\surl="([^"]+)"', xml)
|
|
432
|
+
if m:
|
|
433
|
+
facts["repository"] = m.group(1)
|
|
434
|
+
m = re.search(r'<license type="expression">([^<]+)</license>', xml)
|
|
435
|
+
if m:
|
|
436
|
+
facts["licence"] = m.group(1).strip()
|
|
437
|
+
elif "<license type=" in xml:
|
|
438
|
+
facts["licence"] = "file"
|
|
439
|
+
return facts
|
|
440
|
+
|
|
441
|
+
|
|
442
|
+
def check_nuget_package(package_id, version, today, exemptions):
|
|
443
|
+
entries = fetch_nuget(package_id)
|
|
444
|
+
latest = [e for e in entries if is_stable(e["version"])][-1]
|
|
445
|
+
nuspec = fetch_nuspec_facts(package_id, latest["version"])
|
|
446
|
+
if nuspec.get("licence") and not latest.get("licenseExpression"):
|
|
447
|
+
latest["licenseExpression"] = "" if nuspec["licence"] == "file" else nuspec["licence"]
|
|
448
|
+
repo = parse_github_repo(nuspec.get("repository") or (latest.get("repository") or {}).get("url") or latest.get("projectUrl"))
|
|
449
|
+
github = fetch_github(*repo) if repo else None
|
|
450
|
+
build_only = bool(exemptions.get(package_id, {}).get("buildOnly"))
|
|
451
|
+
vulns = fetch_osv("NuGet", package_id, version or latest["version"])
|
|
452
|
+
verdict, reasons, facts = grade_nuget(version, entries, github, today, build_only, vulns=vulns)
|
|
453
|
+
verdict, reasons = apply_bypass(package_id, verdict, reasons, exemptions, today)
|
|
454
|
+
return package_id, version or facts.get("latest"), verdict, reasons, facts
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _parse_args(argv):
|
|
458
|
+
ap = argparse.ArgumentParser(description="Grade packages against the style-guide health gate.")
|
|
459
|
+
ap.add_argument("--props", help="Directory.Packages.props to check")
|
|
460
|
+
ap.add_argument("--package", action="append", default=[], help="NuGet package, optionally Name@Version")
|
|
461
|
+
ap.add_argument("--npm", help="package.json to check")
|
|
462
|
+
ap.add_argument("--write-evidence", action="store_true", help="write checked-date evidence comments into the props file")
|
|
463
|
+
ap.add_argument("--today", help="override today's date (YYYY-MM-DD)")
|
|
464
|
+
return ap.parse_args(argv)
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def _collect_props_results(args, today, exemptions, results):
|
|
468
|
+
if not args.props:
|
|
469
|
+
return
|
|
470
|
+
text = pathlib.Path(args.props).expanduser().read_text(encoding="utf-8")
|
|
471
|
+
for package_id, version in parse_props(text):
|
|
472
|
+
if package_id.startswith("ZhEaIsNsAaBn."):
|
|
473
|
+
print(f"SKIP {package_id} (house package)")
|
|
474
|
+
continue
|
|
475
|
+
results.append(check_nuget_package(package_id, version, today, exemptions))
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def _collect_package_results(args, today, exemptions, results):
|
|
479
|
+
for spec in args.package:
|
|
480
|
+
package_id, _, version = spec.partition("@")
|
|
481
|
+
results.append(check_nuget_package(package_id, version or None, today, exemptions))
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def _npm_pinned_version(spec):
|
|
485
|
+
return re.sub(r"^[\^~>=<\s]+", "", str(spec)).split(" ")[0] or None
|
|
486
|
+
|
|
487
|
+
|
|
488
|
+
def _npm_vulns(name, pinned):
|
|
489
|
+
if pinned and re.match(r"^\d+\.\d+\.\d+", pinned):
|
|
490
|
+
return fetch_osv("npm", name, pinned)
|
|
491
|
+
return None
|
|
492
|
+
|
|
493
|
+
|
|
494
|
+
def _check_npm_dependency(name, spec, today, exemptions):
|
|
495
|
+
registry, _ = http_json(f"https://registry.npmjs.org/{name.replace('/', '%2F')}")
|
|
496
|
+
repo = parse_github_repo((registry.get("repository") or {}).get("url", ""))
|
|
497
|
+
github = fetch_github(*repo) if repo else None
|
|
498
|
+
pinned = _npm_pinned_version(spec)
|
|
499
|
+
vulns = _npm_vulns(name, pinned)
|
|
500
|
+
verdict, reasons, facts = grade_npm(registry, github, today, pinned_version=pinned, vulns=vulns)
|
|
501
|
+
verdict, reasons = apply_bypass(name, verdict, reasons, exemptions, today)
|
|
502
|
+
return name, facts.get("latest"), verdict, reasons, facts
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def _collect_npm_results(args, today, exemptions, results):
|
|
506
|
+
if not args.npm:
|
|
507
|
+
return
|
|
508
|
+
pkg = json.loads(pathlib.Path(args.npm).expanduser().read_text(encoding="utf-8"))
|
|
509
|
+
deps = {**pkg.get("dependencies", {}), **pkg.get("devDependencies", {})}
|
|
510
|
+
for name, spec in deps.items():
|
|
511
|
+
results.append(_check_npm_dependency(name, spec, today, exemptions))
|
|
512
|
+
|
|
513
|
+
|
|
514
|
+
def _print_result(package_id, version, verdict, reasons, facts):
|
|
515
|
+
print(f"{verdict:4} {package_id} {version} (latest {facts.get('latest')}, released {facts.get('last_release')}, "
|
|
516
|
+
f"last commit {facts.get('last_commit', '?')}, licence {facts.get('licence')}, vulns {facts.get('vulns', '?')})")
|
|
517
|
+
for reason in reasons:
|
|
518
|
+
print(f" - {reason}")
|
|
519
|
+
|
|
520
|
+
|
|
521
|
+
def _report_results(results):
|
|
522
|
+
any_fail = False
|
|
523
|
+
evidence = []
|
|
524
|
+
for package_id, version, verdict, reasons, facts in results:
|
|
525
|
+
any_fail = any_fail or verdict == "FAIL"
|
|
526
|
+
_print_result(package_id, version, verdict, reasons, facts)
|
|
527
|
+
evidence.append((package_id, version, verdict, facts))
|
|
528
|
+
return any_fail, evidence
|
|
529
|
+
|
|
530
|
+
|
|
531
|
+
def _write_evidence_if_requested(args, evidence, today):
|
|
532
|
+
if not args.write_evidence:
|
|
533
|
+
return
|
|
534
|
+
if not args.props:
|
|
535
|
+
return
|
|
536
|
+
write_evidence(args.props, evidence, today)
|
|
537
|
+
print(f"Evidence comments written to {args.props}")
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def main(argv=None):
|
|
541
|
+
args = _parse_args(argv)
|
|
542
|
+
today = datetime.date.fromisoformat(args.today) if args.today else datetime.date.today()
|
|
543
|
+
exemptions = load_exemptions(args.props or args.npm)
|
|
544
|
+
results = []
|
|
545
|
+
_collect_props_results(args, today, exemptions, results)
|
|
546
|
+
_collect_package_results(args, today, exemptions, results)
|
|
547
|
+
_collect_npm_results(args, today, exemptions, results)
|
|
548
|
+
any_fail, evidence = _report_results(results)
|
|
549
|
+
_write_evidence_if_requested(args, evidence, today)
|
|
550
|
+
return 1 if any_fail else 0
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
if __name__ == "__main__":
|
|
554
|
+
raise SystemExit(main())
|