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.
Files changed (44) hide show
  1. slopthreshold/__init__.py +1 -0
  2. slopthreshold/guide/STYLE_GUIDE.md +495 -0
  3. slopthreshold/packs/editorconfig-pack/.editorconfig +899 -0
  4. slopthreshold/packs/editorconfig-pack/Directory.Build.props +47 -0
  5. slopthreshold/packs/editorconfig-pack/Directory.Build.targets +16 -0
  6. slopthreshold/packs/editorconfig-pack/Directory.Packages.props +29 -0
  7. slopthreshold/packs/editorconfig-pack/README.md +141 -0
  8. slopthreshold/packs/editorconfig-pack/global.json +7 -0
  9. slopthreshold/packs/editorconfig-pack/nuget.config +19 -0
  10. slopthreshold/packs/editorconfig-pack/ruff.toml +29 -0
  11. slopthreshold/packs/editorconfig-pack/sonar-drift-allowlist.json +10 -0
  12. slopthreshold/packs/frontend-lint-pack/.prettierrc.json +7 -0
  13. slopthreshold/packs/frontend-lint-pack/.stylelintrc.json +64 -0
  14. slopthreshold/packs/frontend-lint-pack/README.md +64 -0
  15. slopthreshold/packs/frontend-lint-pack/eslint.config.mjs +108 -0
  16. slopthreshold/packs/frontend-lint-pack/package.json +23 -0
  17. slopthreshold/packs/frontend-lint-pack/tsconfig.app.json +17 -0
  18. slopthreshold/packs/frontend-lint-pack/tsconfig.base.json +20 -0
  19. slopthreshold/packs/frontend-lint-pack/tsconfig.json +4 -0
  20. slopthreshold/packs/frontend-lint-pack/tsconfig.spec.json +8 -0
  21. slopthreshold/packs/project-guide-starters/app-STYLE_GUIDE.md +35 -0
  22. slopthreshold/packs/project-guide-starters/frontend-STYLE_GUIDE.md +33 -0
  23. slopthreshold/packs/project-guide-starters/library-STYLE_GUIDE.md +36 -0
  24. slopthreshold/packs/three-layer-wiring/.githooks/commit-msg +13 -0
  25. slopthreshold/packs/three-layer-wiring/.githooks/post-merge +8 -0
  26. slopthreshold/packs/three-layer-wiring/.githooks/pre-commit +10 -0
  27. slopthreshold/packs/three-layer-wiring/.githooks/pre-push +14 -0
  28. slopthreshold/packs/three-layer-wiring/.github/actionlint.yaml +3 -0
  29. slopthreshold/packs/three-layer-wiring/.github/workflows/quality.yml +164 -0
  30. slopthreshold/packs/three-layer-wiring/.gitleaks.toml +16 -0
  31. slopthreshold/packs/three-layer-wiring/.hadolint.yaml +6 -0
  32. slopthreshold/packs/three-layer-wiring/README.md +62 -0
  33. slopthreshold/packs/three-layer-wiring/budget.json +14 -0
  34. slopthreshold/tools/check_characters.py +104 -0
  35. slopthreshold/tools/check_ci_config.py +405 -0
  36. slopthreshold/tools/check_package_health.py +554 -0
  37. slopthreshold/tools/check_sonar_drift.py +1123 -0
  38. slopthreshold/tools/mine_sonar_metrics.py +1259 -0
  39. slopthreshold/tools/validate_guide_tags.py +795 -0
  40. slopthreshold/zh.py +973 -0
  41. slopthreshold-2.1.0.dev22.dist-info/METADATA +49 -0
  42. slopthreshold-2.1.0.dev22.dist-info/RECORD +44 -0
  43. slopthreshold-2.1.0.dev22.dist-info/WHEEL +4 -0
  44. slopthreshold-2.1.0.dev22.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,405 @@
1
+ #!/usr/bin/env python3
2
+ """Enforce ST-SEC-15 and ST-CI-01..05: CI YAML hygiene.
3
+
4
+ Scans workflow files and composite action files (.github/actions/*/action.yml)
5
+ for inline Sonar project keys, Sonar host URLs and token literals. Values
6
+ coming from ${{ vars.* }} / ${{ secrets.* }} or environment references pass;
7
+ literal values fail.
8
+
9
+ Usage: check_ci_config.py [PATH ...]
10
+ With no PATH, scans .github/workflows and .github/actions under the current
11
+ directory.
12
+ Exit 1 when anything is flagged.
13
+ """
14
+ import argparse
15
+ import json
16
+ import os
17
+ import pathlib
18
+ import re
19
+ import sys
20
+ import urllib.error
21
+
22
+ sys.path.insert(0, str(pathlib.Path(__file__).resolve().parent))
23
+ from http_util import open_https # noqa: E402
24
+
25
+ SHA_PIN = re.compile(r"uses:\s*([^\s#]+)")
26
+ # owner/repo[/path...]@<40-hex>: plain actions, subpath actions
27
+ # (owner/repo/path@sha) and reusable workflows
28
+ # (owner/repo/.github/workflows/x.yml@sha) all share this shape.
29
+ PIN_REF = re.compile(
30
+ r"^([A-Za-z0-9_.-]+)/([A-Za-z0-9_.-]+)"
31
+ r"((?:/(?!\.{1,2}(?:/|@))[A-Za-z0-9_.-]+)*)@([0-9a-f]{40})$")
32
+ PINNED = PIN_REF
33
+
34
+ GITHUB_DIR = ".github"
35
+
36
+ PATTERNS = [
37
+ (re.compile(r"sonar\.projectKey\s*=\s*(?!\$\{\{)([^\s\"']+)"),
38
+ "hardcoded Sonar project key (use vars.SONAR_PROJECT_KEY)"),
39
+ (re.compile(r"sonarscanner\s+begin[^#\n]*/k:\s*\"?(?!\$\{\{)([A-Za-z0-9_.-]+)"),
40
+ "hardcoded Sonar project key in sonarscanner /k: (use vars.SONAR_PROJECT_KEY)"),
41
+ (re.compile(r"sonar\.host\.url\s*=\s*\"?(https?://[^\s\"']+)"),
42
+ "hardcoded Sonar host URL (use vars.SONAR_HOST_URL)"),
43
+ (re.compile(r"sonar\.token\s*=\s*\"?(?!\$\{\{)([^\s\"']+)"),
44
+ "hardcoded Sonar token (use secrets.SONAR_TOKEN)"),
45
+ (re.compile(r"SONAR_TOKEN\s*:\s*(?!\$\{\{)([^\s\"']+)"),
46
+ "hardcoded SONAR_TOKEN value (use secrets.SONAR_TOKEN)"),
47
+ (re.compile(r"SONAR_HOST_URL\s*:\s*(https?://[^\s\"']+)"),
48
+ "hardcoded SONAR_HOST_URL value (use vars.SONAR_HOST_URL)"),
49
+ ]
50
+
51
+
52
+ def is_action_file(path):
53
+ """True for composite action files (.github/actions/*/action.yml).
54
+
55
+ Composite actions have no top-level permissions, no jobs and no
56
+ timeout-minutes, so the workflow-only checks (ST-CI-02/03/05) must not
57
+ apply to them. Pin, Sonar-literal and download-and-execute checks do.
58
+ """
59
+ p = pathlib.Path(path)
60
+ parts = p.parts
61
+ for i in range(len(parts) - 1):
62
+ if parts[i] == GITHUB_DIR and parts[i + 1] == "workflows":
63
+ return False
64
+ if parts[i] == GITHUB_DIR and parts[i + 1] == "actions":
65
+ return True
66
+ return p.name in ("action.yml", "action.yaml")
67
+
68
+
69
+ def _normalized_key_line(line):
70
+ """Return (indent, stripped, is_list_item), or None to skip the line.
71
+
72
+ Blank lines and comment lines carry no mapping key and are skipped.
73
+ A list item ("- ...") counts as two extra columns of indent and its
74
+ marker is removed, matching how the nested mapping aligns.
75
+ """
76
+ if not line.strip():
77
+ return None
78
+ if line.strip().startswith("#"):
79
+ return None
80
+ indent = len(line) - len(line.lstrip())
81
+ stripped = line.strip()
82
+ if stripped.startswith("- "):
83
+ return (indent + 2, stripped[2:], True)
84
+ return (indent, stripped, False)
85
+
86
+
87
+ def _reset_for_list_item(stack, indent, is_list_item):
88
+ """Start a fresh mapping context for a list item, in place.
89
+
90
+ Runs before the key test, exactly like the original inline code: a
91
+ list item opens a new context even when its text holds no key.
92
+ """
93
+ if not is_list_item:
94
+ return
95
+ stack[:] = [(i, s) for i, s in stack if i < indent]
96
+ stack.append((indent, {}))
97
+
98
+
99
+ def _key_context(stack, indent):
100
+ """Return the mapping context dict for a key at this indent.
101
+
102
+ Contexts deeper than the key are closed; a new context opens when
103
+ the key sits deeper than every open context. Runs only for lines
104
+ that actually hold a key.
105
+ """
106
+ stack[:] = [(i, s) for i, s in stack if i <= indent]
107
+ if not stack or stack[-1][0] < indent:
108
+ stack.append((indent, {}))
109
+ return stack[-1][1]
110
+
111
+
112
+ def _duplicate_key_findings(path, lines):
113
+ """Flag duplicate keys within one mapping (GitHub rejects the workflow).
114
+
115
+ Mapping contexts are tracked by indent; list items start a fresh
116
+ context.
117
+ """
118
+ findings = []
119
+ stack = [] # (indent, {key: first_line})
120
+ for lineno, line in enumerate(lines, 1):
121
+ normalized = _normalized_key_line(line)
122
+ if normalized is None:
123
+ continue
124
+ indent, stripped, is_list_item = normalized
125
+ _reset_for_list_item(stack, indent, is_list_item)
126
+ m = re.match(r"^([A-Za-z0-9_-]+):", stripped)
127
+ if not m:
128
+ continue
129
+ ctx = _key_context(stack, indent)
130
+ key = m.group(1)
131
+ if key in ctx:
132
+ findings.append((str(path), lineno, f"ERROR duplicate YAML key '{key}' (first at line {ctx[key]}) - GitHub rejects the workflow"))
133
+ ctx[key] = lineno
134
+ return findings
135
+
136
+
137
+ def _workflow_only_findings(path, text):
138
+ """ST-CI-02/03 checks; composite action files are exempt."""
139
+ if is_action_file(path):
140
+ return []
141
+ findings = []
142
+ if "permissions:" not in text:
143
+ findings.append((str(path), 1, "ERROR ST-CI-02: no top-level permissions declared (least-privilege token)"))
144
+ if "write-all" in text:
145
+ findings.append((str(path), 1, "ERROR ST-CI-02: permissions write-all is forbidden"))
146
+ if "pull_request_target" in text and "pull_request.head" in text:
147
+ findings.append((str(path), 1, "ERROR ST-CI-03: pull_request_target with PR head checkout runs untrusted code with secrets"))
148
+ return findings
149
+
150
+
151
+ def _pattern_findings(path, lineno, line):
152
+ """Sonar literal findings (ST-SEC-15) for one line, in PATTERNS order."""
153
+ findings = []
154
+ for pattern, message in PATTERNS:
155
+ if pattern.search(line):
156
+ findings.append((str(path), lineno, "ERROR " + message))
157
+ return findings
158
+
159
+
160
+ def _pin_finding(path, lineno, line):
161
+ """ST-CI-01 finding when a uses: ref is not pinned by full SHA."""
162
+ m = SHA_PIN.search(line)
163
+ if not m:
164
+ return None
165
+ ref = m.group(1).strip("\"'")
166
+ if ref.startswith(("./", "docker://")):
167
+ return None
168
+ if PINNED.match(ref):
169
+ return None
170
+ return (str(path), lineno, f"ERROR ST-CI-01: action not pinned by full SHA: {ref}")
171
+
172
+
173
+ def _is_download_execute(line):
174
+ """True when the line pipes a curl/wget download into a shell."""
175
+ if re.search(r"curl[^|\n]*\|\s*(sudo\s+)?(bash|sh)\b", line):
176
+ return True
177
+ return re.search(r"wget[^|\n]*\|\s*(sudo\s+)?(bash|sh)\b", line) is not None
178
+
179
+
180
+ def _line_findings(path, lines):
181
+ """Per-line findings: Sonar literals, pin check, download-and-execute."""
182
+ findings = []
183
+ for lineno, line in enumerate(lines, 1):
184
+ if line.strip().startswith("#"):
185
+ continue
186
+ findings.extend(_pattern_findings(path, lineno, line))
187
+ pin = _pin_finding(path, lineno, line)
188
+ if pin is not None:
189
+ findings.append(pin)
190
+ if _is_download_execute(line):
191
+ findings.append((str(path), lineno, "ERROR ST-CI-04: download-and-execute in pipeline"))
192
+ return findings
193
+
194
+
195
+ def _job_start_lines(lines):
196
+ """Line numbers where jobs start, inside the top-level jobs: mapping."""
197
+ in_jobs = False
198
+ jobs = []
199
+ for i, ln in enumerate(lines, 1):
200
+ if re.match(r"^jobs:\s*$", ln):
201
+ in_jobs = True
202
+ continue
203
+ if in_jobs and re.match(r"^\S", ln):
204
+ in_jobs = False
205
+ if in_jobs and re.match(r"^ {2}[A-Za-z0-9_-]+:\s*$", ln):
206
+ jobs.append(i)
207
+ return jobs
208
+
209
+
210
+ def _timeout_finding(path, lines, text):
211
+ """ST-CI-05 warning when fewer timeout-minutes than jobs; else None."""
212
+ jobs = _job_start_lines(lines)
213
+ if not jobs:
214
+ return None
215
+ if is_action_file(path):
216
+ return None
217
+ timeouts = text.count("timeout-minutes:")
218
+ if timeouts >= len(jobs):
219
+ return None
220
+ return (str(path), 1, f"WARN ST-CI-05: {len(jobs) - timeouts} job(s) without timeout-minutes")
221
+
222
+
223
+ def check_file(path):
224
+ try:
225
+ lines = path.read_text(encoding="utf-8").splitlines()
226
+ except OSError as exc:
227
+ return [(str(path), 0, f"unreadable: {exc}")]
228
+ text = "\n".join(lines)
229
+ findings = []
230
+ findings.extend(_duplicate_key_findings(path, lines))
231
+ findings.extend(_workflow_only_findings(path, text))
232
+ findings.extend(_line_findings(path, lines))
233
+ timeout = _timeout_finding(path, lines, text)
234
+ if timeout is not None:
235
+ findings.append(timeout)
236
+ return findings
237
+
238
+
239
+ def _candidates_for_root(p):
240
+ """Workflow and action files under one root path, in scan order."""
241
+ if p.is_file():
242
+ return [p]
243
+ wf = p / GITHUB_DIR / "workflows"
244
+ if not wf.is_dir():
245
+ return sorted(p.rglob("*.y*ml"))
246
+ candidates = sorted(wf.rglob("*.y*ml"))
247
+ actions = p / GITHUB_DIR / "actions"
248
+ if actions.is_dir():
249
+ candidates += sorted(actions.glob("*/action.y*ml"))
250
+ return candidates
251
+
252
+
253
+ def iter_workflows(roots):
254
+ seen = set()
255
+ for root in roots:
256
+ for f in _candidates_for_root(pathlib.Path(root)):
257
+ key = str(f)
258
+ if key in seen:
259
+ continue
260
+ seen.add(key)
261
+ yield f
262
+
263
+
264
+ def _read_lines_replace(path):
265
+ """File lines with undecodable bytes replaced, or None if unreadable."""
266
+ try:
267
+ return path.read_text(encoding="utf-8", errors="replace").splitlines()
268
+ except OSError:
269
+ return None # check_file already reports unreadable files
270
+
271
+
272
+ def _pin_ref_from_line(line):
273
+ """Return (ref, PIN_REF match) for a verifiable pin, else None.
274
+
275
+ Comment lines, lines without uses:, local/docker refs and unpinned
276
+ refs yield None; unpinned refs are check_file's ST-CI-01 finding.
277
+ """
278
+ if line.strip().startswith("#"):
279
+ return None
280
+ raw = SHA_PIN.search(line)
281
+ if not raw:
282
+ return None
283
+ ref = raw.group(1).strip("\"'")
284
+ if ref.startswith(("./", "docker://")):
285
+ return None
286
+ m = PIN_REF.match(ref)
287
+ if not m:
288
+ return None
289
+ return (ref, m)
290
+
291
+
292
+ def _build_pin_request(owner, repo, sha):
293
+ """GitHub commit URL + headers for a pin, plus the explicit GH_TOKEN.
294
+
295
+ GH_TOKEN wins over GITHUB_TOKEN; the explicit value is returned
296
+ because a same-organization 404 is an error again when it is set.
297
+ """
298
+ url = f"https://api.github.com/repos/{owner}/{repo}/commits/{sha}"
299
+ headers = {"User-Agent": "Mozilla/5.0", "Accept": "application/vnd.github+json"}
300
+ explicit_token = os.environ.get("GH_TOKEN", "")
301
+ token = explicit_token or os.environ.get("GITHUB_TOKEN", "")
302
+ if token:
303
+ headers["Authorization"] = f"Bearer {token}"
304
+ return (url, headers, explicit_token)
305
+
306
+
307
+ def _is_private_same_org_404(exc, owner, explicit_token):
308
+ """True for a 404 that only means a private same-organization repo."""
309
+ if exc.code != 404:
310
+ return False
311
+ if explicit_token:
312
+ return False
313
+ return os.environ.get("GITHUB_REPOSITORY_OWNER", "").lower() == owner.lower()
314
+
315
+
316
+ def _resolve_pin(path, lineno, ref, owner, repo, sha):
317
+ """Finding when a pinned SHA does not resolve on GitHub, else None."""
318
+ url, headers, explicit_token = _build_pin_request(owner, repo, sha)
319
+ try:
320
+ with open_https(url, headers=headers, timeout=20) as resp:
321
+ json.loads(resp.read().decode("utf-8"))
322
+ return None
323
+ except urllib.error.HTTPError as exc:
324
+ if _is_private_same_org_404(exc, owner, explicit_token):
325
+ return (str(path), lineno, f"WARN pinned action {ref} is in a private same-organization repository and cannot be verified from here (ST-CI-01); set GH_TOKEN to verify it fully")
326
+ if exc.code == 404:
327
+ return (str(path), lineno, f"ERROR pinned action {ref} does not resolve to a commit on GitHub (ST-CI-01)")
328
+ # 403/429/5xx: the API could not answer (rate limit or outage).
329
+ # That is not evidence the pin is wrong; warn, do not fail.
330
+ return (str(path), lineno, f"WARN could not verify pinned action {ref}: GitHub API returned HTTP {exc.code} (ST-CI-01); set GH_TOKEN to raise the rate limit")
331
+ except Exception as exc:
332
+ return (str(path), lineno, f"WARN could not verify pinned action {ref}: {type(exc).__name__} (ST-CI-01); network or API unavailable")
333
+
334
+
335
+ def _verify_pin_line(path, lineno, line, seen):
336
+ """Finding for one line's pin, deduplicated through the seen set."""
337
+ pin = _pin_ref_from_line(line)
338
+ if pin is None:
339
+ return None
340
+ ref, m = pin
341
+ owner, repo, _subpath, sha = m.groups()
342
+ if (owner, repo, sha) in seen:
343
+ return None
344
+ seen.add((owner, repo, sha))
345
+ return _resolve_pin(path, lineno, ref, owner, repo, sha)
346
+
347
+
348
+ def _verify_pins_in_file(path, seen):
349
+ """Pin-resolution findings for one file; unreadable files yield none."""
350
+ lines = _read_lines_replace(path)
351
+ if lines is None:
352
+ return []
353
+ findings = []
354
+ for lineno, line in enumerate(lines, 1):
355
+ finding = _verify_pin_line(path, lineno, line, seen)
356
+ if finding is not None:
357
+ findings.append(finding)
358
+ return findings
359
+
360
+
361
+ def verify_pins(files):
362
+ """Resolve pinned action SHAs against the GitHub API (ST-CI-01 evidence).
363
+
364
+ Subpath action refs (owner/repo/path@sha) and reusable workflow refs
365
+ (owner/repo/.github/workflows/x.yml@sha) resolve against the owner/repo
366
+ commit, exactly like plain owner/repo@sha refs. Skipping them would
367
+ leave first-party pins silently unverified.
368
+
369
+ A pin into a private repository of the same organization answers 404
370
+ to unauthenticated calls and to the caller-scoped GITHUB_TOKEN, which
371
+ cannot read other repositories. That 404 is a warning, not an error:
372
+ the pin is covered by the publisher repository's own CI and by the
373
+ Actions access gate that lets the workflow download it at all. Set
374
+ GH_TOKEN to a token that can read the organization repositories to
375
+ verify private pins fully; with GH_TOKEN set, a 404 is an error again.
376
+ """
377
+ findings = []
378
+ seen = set()
379
+ for path in files:
380
+ findings.extend(_verify_pins_in_file(path, seen))
381
+ return findings
382
+
383
+
384
+ def main(argv=None):
385
+ ap = argparse.ArgumentParser(description="ST-SEC-15 CI config check")
386
+ ap.add_argument("paths", nargs="*", default=["."])
387
+ ap.add_argument("--verify-pins", action="store_true", help="Also verify each pinned action SHA resolves to a real commit on GitHub (network)")
388
+ args = ap.parse_args(argv)
389
+ findings = []
390
+ checked = 0
391
+ files = list(iter_workflows(args.paths))
392
+ for f in files:
393
+ checked += 1
394
+ findings.extend(check_file(f))
395
+ if args.verify_pins:
396
+ findings.extend(verify_pins(files))
397
+ for path, line, msg in findings:
398
+ print(f"{path}:{line}: {msg}")
399
+ errors = [f for f in findings if "ERROR" in f[2]]
400
+ print(f"checked {checked} CI file(s), {len(errors)} error(s), {len(findings) - len(errors)} warning(s)")
401
+ return 1 if errors else 0
402
+
403
+
404
+ if __name__ == "__main__":
405
+ sys.exit(main())