test_growth_chart_workflow.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266
  1. # SPDX-License-Identifier: Apache-2.0
  2. """Structure of .github/workflows/growth-chart.yml (issue #294).
  3. The growth chart (redrawn every three hours) is rendered in one job that can only read, and published
  4. by a second job that can write but runs nothing it did not validate. These tests
  5. read the workflow as data and pin the properties that make that true: permissions
  6. per job, commit-pinned actions with a version comment, no expression inside a run
  7. script, no secrets in the publish job, no bare force push, a main-only guard, and
  8. hash-pinned plotting dependencies. Each rule is a function over text so a negative
  9. case can prove the rule bites.
  10. """
  11. import re
  12. from pathlib import Path
  13. import pytest
  14. import yaml
  15. ROOT = Path(__file__).resolve().parent.parent
  16. WORKFLOW = ROOT / ".github" / "workflows" / "growth-chart.yml"
  17. REQUIREMENTS = ROOT / "scripts" / "growth-chart-requirements.txt"
  18. PUBLISH = ROOT / "scripts" / "publish_metrics_branch.sh"
  19. IMAGE_URL = "https://raw.githubusercontent.com/ChiefGyk3D/Clouds-Against-Humanity/metrics/repo-growth.png"
  20. USES_RE = re.compile(r"^\s*-?\s*uses:\s*(\S+)(.*)$")
  21. PINNED_RE = re.compile(r"^[\w.-]+/[\w./-]+@[0-9a-f]{40}$")
  22. VERSION_RE = re.compile(r"^\s*#\s*v\d+\.\d+\.\d+\b")
  23. def load(text: str | None = None) -> dict:
  24. return yaml.safe_load(text if text is not None else WORKFLOW.read_text())
  25. def triggers(doc: dict) -> dict:
  26. return doc.get("on", doc.get(True))
  27. def unpinned_uses(text: str) -> list[str]:
  28. bad = []
  29. for line in text.splitlines():
  30. m = USES_RE.match(line)
  31. if m and not (PINNED_RE.match(m.group(1)) and VERSION_RE.match(m.group(2))):
  32. bad.append(line.strip())
  33. return bad
  34. def run_scripts(doc: dict):
  35. for name, job in doc["jobs"].items():
  36. for step in job["steps"]:
  37. if "run" in step:
  38. yield name, step["run"]
  39. def expressions_in_run(doc: dict) -> list[str]:
  40. return [f"{job}: {script}" for job, script in run_scripts(doc) if "${{" in script]
  41. def bare_force(text: str) -> list[str]:
  42. return re.findall(r"--force(?!-with-lease=)\S*|\bpush\b[^\n]*\s-\w*f\b|\bpush\b[^\n]*\s\+\S", text)
  43. @pytest.fixture(scope="module")
  44. def doc():
  45. return load()
  46. def test_the_workflow_exists_and_has_two_jobs(doc):
  47. assert set(doc["jobs"]) == {"render", "publish"}
  48. def test_triggers_are_a_three_hourly_schedule_off_the_hour_and_a_manual_run(doc):
  49. on = triggers(doc)
  50. assert set(on) == {"schedule", "workflow_dispatch"}
  51. crons = [s["cron"] for s in on["schedule"]]
  52. assert len(crons) == 1
  53. minute, hour, dom, month, dow = crons[0].split()
  54. assert minute.isdigit() and minute not in {"0", "00", "30", "15", "45"}
  55. assert hour == "*/3" and (dom, month, dow) == ("*", "*", "*")
  56. def test_workflow_default_permissions_are_empty_and_jobs_name_their_own(doc):
  57. assert doc["permissions"] == {}
  58. assert doc["jobs"]["render"]["permissions"] == {"contents": "read"}
  59. assert doc["jobs"]["publish"]["permissions"] == {"contents": "write"}
  60. def test_publish_waits_for_render(doc):
  61. assert doc["jobs"]["publish"]["needs"] == "render" or doc["jobs"]["publish"]["needs"] == ["render"]
  62. def test_both_jobs_are_guarded_to_main_in_this_repository(doc):
  63. for name in ("render", "publish"):
  64. cond = doc["jobs"][name]["if"]
  65. assert "github.ref == 'refs/heads/main'" in cond, name
  66. assert "github.repository == 'ChiefGyk3D/Clouds-Against-Humanity'" in cond, name
  67. def test_concurrency_group_queues_runs_instead_of_cancelling(doc):
  68. conc = doc["concurrency"]
  69. assert conc["group"] and conc["cancel-in-progress"] is False
  70. def test_every_action_is_pinned_by_commit_with_a_version_comment():
  71. text = WORKFLOW.read_text()
  72. assert "uses:" in text # collect loosely: something must have been collected
  73. assert unpinned_uses(text) == []
  74. @pytest.mark.parametrize(
  75. "line",
  76. [
  77. " - uses: actions/checkout@main",
  78. " - uses: actions/checkout@v7",
  79. " - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1",
  80. " - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b # v7.0.1",
  81. " - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # latest",
  82. ],
  83. )
  84. def test_the_pin_rule_bites(line):
  85. assert unpinned_uses(line)
  86. def test_every_checkout_drops_its_credentials(doc):
  87. seen = 0
  88. for job in doc["jobs"].values():
  89. for step in job["steps"]:
  90. if str(step.get("uses", "")).startswith("actions/checkout@"):
  91. seen += 1
  92. assert step["with"]["persist-credentials"] is False
  93. assert seen == 2
  94. def test_no_expression_inside_a_run_script(doc):
  95. assert expressions_in_run(doc) == []
  96. def test_the_expression_rule_bites():
  97. bad = load("on: push\njobs:\n j:\n runs-on: x\n steps:\n - run: echo ${{ github.head_ref }}\n")
  98. assert expressions_in_run(bad)
  99. def test_publish_has_no_secrets_and_only_the_default_token(doc):
  100. text = WORKFLOW.read_text()
  101. assert not re.search(r"\$\{\{[^}]*\bsecrets\b", text)
  102. assert "secrets:" not in text and "inherit" not in text
  103. publish = doc["jobs"]["publish"]
  104. for step in publish["steps"]:
  105. for value in (step.get("env") or {}).values():
  106. if "${{" in str(value):
  107. assert str(value).replace(" ", "") in {"${{github.token}}", "${{needs.render.outputs.tip}}"}
  108. def test_render_never_pushes_and_publish_never_installs_packages(doc):
  109. render = "\n".join(s for n, s in run_scripts(doc) if n == "render")
  110. publish = "\n".join(s for n, s in run_scripts(doc) if n == "publish")
  111. assert "git push" not in render and "publish_metrics_branch" not in render
  112. assert "pip" not in publish and "matplotlib" not in publish
  113. def test_no_bare_force_push_anywhere():
  114. for path in (WORKFLOW, PUBLISH):
  115. assert bare_force(path.read_text()) == [], path
  116. # history is kept and the push is an exact lease: the only "--force" spelling allowed
  117. forces = re.findall(r"--force\S*", PUBLISH.read_text())
  118. assert forces and all(re.match(r'--force-with-lease="?refs/heads/metrics:', f) for f in forces), forces
  119. @pytest.mark.parametrize("text", ["git push --force origin x", "git push -f origin x", "git push origin +x:y", "git push --force-with-lease origin x"])
  120. def test_the_force_rule_bites(text):
  121. assert bare_force(text)
  122. def test_the_render_job_uploads_a_short_lived_artifact_and_fails_if_empty(doc):
  123. uploads = [s for s in doc["jobs"]["render"]["steps"] if str(s.get("uses", "")).startswith("actions/upload-artifact@")]
  124. assert len(uploads) == 1
  125. w = uploads[0]["with"]
  126. assert w["if-no-files-found"] == "error" and int(w["retention-days"]) <= 3
  127. def test_both_jobs_validate_the_bundle(doc):
  128. for name in ("render", "publish"):
  129. scripts = "\n".join(s for n, s in run_scripts(doc) if n == name)
  130. assert "--verify-bundle" in scripts or "publish_metrics_branch" in scripts, name
  131. def test_dependencies_are_installed_only_with_hashes_from_the_pinned_file(doc):
  132. render = "\n".join(s for n, s in run_scripts(doc) if n == "render")
  133. assert "--require-hashes" in render and "growth-chart-requirements.txt" in render
  134. assert not re.search(r"pip\S*\s+install\s+(?!.*-r)", render.replace("\\\n", " "))
  135. def test_the_requirements_file_pins_every_package_with_hashes():
  136. lines = REQUIREMENTS.read_text().replace("\\\n", " ").splitlines()
  137. pins = [ln for ln in lines if ln.strip() and not ln.strip().startswith("#")]
  138. assert any(ln.startswith("matplotlib==") for ln in pins)
  139. for ln in pins:
  140. assert re.match(r"^[A-Za-z0-9_.-]+==[\w.]+(\s+--hash=sha256:[0-9a-f]{64})+$", ln.strip()), ln
  141. def test_the_job_timeouts_are_set(doc):
  142. for job in doc["jobs"].values():
  143. assert 0 < job["timeout-minutes"] <= 15
  144. # -- the pages point at the metrics branch -----------------------------------------
  145. @pytest.mark.parametrize("page", ["README.md", "docs/wiki/Home.md", "docs/wiki/Repository-Growth.md"])
  146. def test_pages_reference_the_chart_from_the_metrics_branch(page):
  147. text = (ROOT / page).read_text()
  148. refs = re.findall(r"!\[[^\]]*\]\(([^)]*repo-growth\.png)\)", text)
  149. assert refs == [IMAGE_URL], page
  150. def test_publish_runs_only_checkout_download_and_the_verified_script(doc):
  151. steps = doc["jobs"]["publish"]["steps"]
  152. kinds = [s.get("uses", "").split("@")[0] or "run" for s in steps]
  153. assert kinds == ["actions/checkout", "actions/download-artifact", "run"]
  154. assert steps[-1]["run"].strip() == "bash scripts/publish_metrics_branch.sh bundle"
  155. assert set(steps[-1]["env"]) == {"GH_TOKEN", "METRICS_MAX_AGE_HOURS", "METRICS_EXPECTED_TIP"}
  156. assert steps[-1]["env"]["METRICS_EXPECTED_TIP"] == "${{ needs.render.outputs.tip }}"
  157. def test_the_residual_risk_is_documented_in_the_workflow_and_the_page():
  158. text = WORKFLOW.read_text()
  159. assert "repository-wide" in text and "ruleset" in text
  160. page = (ROOT / "docs/wiki/Repository-Growth.md").read_text()
  161. assert "repository-wide" in page and "ruleset" in page and "metrics" in page
  162. def test_render_holds_no_write_permission_and_no_graphql_only_grant(doc):
  163. perms = doc["jobs"]["render"]["permissions"]
  164. assert perms == {"contents": "read"}
  165. assert all(v == "read" for v in perms.values())
  166. def render_script(doc):
  167. return "\n".join(s for n, s in run_scripts(doc) if n == "render")
  168. def test_render_never_asks_for_star_times_and_carries_the_ledger(doc):
  169. script = render_script(doc)
  170. assert "--no-star-times" in script
  171. assert "stargazers" not in script and "graphql" not in script
  172. assert "--baseline docs/wiki/.metrics-snapshot.json" in script
  173. assert "--ledger-from carried/metrics-snapshot.json" in script
  174. def test_the_carry_step_uses_the_script_and_exports_the_tip(doc):
  175. steps = doc["jobs"]["render"]["steps"]
  176. carry = next(st for st in steps if st.get("id") == "carry")
  177. assert "scripts/carry_metrics_snapshot.sh" in carry["run"] and '>> "$GITHUB_OUTPUT"' in carry["run"]
  178. assert doc["jobs"]["render"]["outputs"] == {"tip": "${{ steps.carry.outputs.tip }}"}
  179. def test_the_carry_script_fails_closed_on_every_read_problem():
  180. text = (ROOT / "scripts" / "carry_metrics_snapshot.sh").read_text()
  181. assert "ls-remote --exit-code" in text and '"$rc" -eq 2' in text
  182. assert "|| true" not in text
  183. def test_the_carry_step_runs_before_the_refresh(doc):
  184. names = [s.get("name", "") for s in doc["jobs"]["render"]["steps"]]
  185. carry = next(i for i, n in enumerate(names) if "ledger" in n)
  186. fetch = next(i for i, n in enumerate(names) if n.startswith("Fetch"))
  187. assert carry < fetch