test_growth_bundle.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. # SPDX-License-Identifier: Apache-2.0
  2. """The growth chart bundle (issue #294): hostile input, and the publish script.
  3. The render job hands a bundle (snapshot JSON + PNG) to the publish job as an
  4. artifact. The publish job holds contents: write, so it re-validates the bundle
  5. offline before anything is pushed. What is proved here:
  6. - a good bundle passes, and every hostile variation fails with a message: extra
  7. file, symlink, oversized snapshot or PNG, bad PNG signature, metadata chunk,
  8. hash mismatch, wrong repository, a stale or future time stamp, a login-like
  9. field, duplicate keys, nesting bombs, absurd counts;
  10. - the publish script creates the orphan metrics branch on a first run, pushes
  11. only the three expected files, skips the push when the picture is unchanged,
  12. and refuses to overwrite a branch that moved under it (force-with-lease).
  13. Everything is offline: the remote is a bare repository in a temporary directory.
  14. """
  15. import copy
  16. import datetime
  17. import json
  18. import os
  19. import shutil
  20. import subprocess
  21. import sys
  22. from pathlib import Path
  23. import pytest
  24. from test_repo_metrics import fixture, png_bytes
  25. ROOT = Path(__file__).resolve().parent.parent
  26. sys.path.insert(0, str(ROOT / "scripts"))
  27. import gen_repo_metrics as grm
  28. PUBLISH = ROOT / "scripts" / "publish_metrics_branch.sh"
  29. NOW = datetime.datetime(2026, 10, 25, 6, 0, 0, tzinfo=datetime.UTC)
  30. REPO = "Example/Repo"
  31. def make_bundle(path: Path, snap=None, png=None, fetched="2026-10-25T05:30:00Z") -> Path:
  32. snap = copy.deepcopy(snap or fixture())
  33. snap["fetched_at"] = fetched
  34. snap["stars"] = {"2026-10-10": 2, "2026-10-12": 5}
  35. snap["forks"] = {"2026-10-13": 1}
  36. snap["merged_prs"] = {"2026-10-11": 3}
  37. snap["closed_issues"] = {"2026-10-13": 1}
  38. if "star_ledger" not in snap:
  39. snap["stars_as_of"] = "2026-10-20"
  40. snap["star_ledger"] = {fetched[:10]: 8}
  41. path.mkdir(parents=True, exist_ok=True)
  42. (path / grm.BUNDLE_PNG).write_bytes(png if png is not None else png_bytes())
  43. snap["source_sha256"] = grm.source_digest(snap)
  44. snap["png_sha256"] = grm.file_digest(path / grm.BUNDLE_PNG)
  45. (path / grm.BUNDLE_SNAPSHOT).write_text(json.dumps(snap, indent=1, sort_keys=True) + "\n")
  46. return path
  47. def problems(bundle: Path, **kw):
  48. kw.setdefault("expect_repo", REPO)
  49. kw.setdefault("now", NOW)
  50. kw.setdefault("max_age_hours", 6)
  51. return grm.verify_bundle(bundle, **kw)
  52. def rewrite_snapshot(bundle: Path, mutate, rehash=True):
  53. p = bundle / grm.BUNDLE_SNAPSHOT
  54. snap = json.loads(p.read_text())
  55. mutate(snap)
  56. if rehash:
  57. snap["source_sha256"] = grm.source_digest(snap)
  58. p.write_text(json.dumps(snap, indent=1, sort_keys=True) + "\n")
  59. def test_a_good_bundle_passes(tmp_path):
  60. assert problems(make_bundle(tmp_path / "b")) == []
  61. def test_an_extra_file_fails(tmp_path):
  62. b = make_bundle(tmp_path / "b")
  63. (b / "payload.sh").write_text("echo hi\n")
  64. assert any("unexpected" in p for p in problems(b))
  65. def test_a_missing_file_fails(tmp_path):
  66. b = make_bundle(tmp_path / "b")
  67. (b / grm.BUNDLE_PNG).unlink()
  68. assert problems(b)
  69. def test_a_symlink_fails(tmp_path):
  70. b = make_bundle(tmp_path / "b")
  71. target = tmp_path / "elsewhere.png"
  72. shutil.move(b / grm.BUNDLE_PNG, target)
  73. os.symlink(target, b / grm.BUNDLE_PNG)
  74. assert any("regular file" in p for p in problems(b))
  75. def test_a_subdirectory_fails(tmp_path):
  76. b = make_bundle(tmp_path / "b")
  77. (b / "sub").mkdir()
  78. assert any("unexpected" in p for p in problems(b))
  79. def test_an_oversized_png_fails(tmp_path):
  80. b = make_bundle(tmp_path / "b")
  81. with (b / grm.BUNDLE_PNG).open("ab") as f:
  82. f.write(b"\0" * (grm.MAX_PNG_BYTES + 1))
  83. assert any("larger than" in p for p in problems(b))
  84. def test_an_oversized_snapshot_fails(tmp_path):
  85. b = make_bundle(tmp_path / "b")
  86. with (b / grm.BUNDLE_SNAPSHOT).open("a") as f:
  87. f.write(" " * (grm.MAX_SNAPSHOT_BYTES + 1))
  88. assert any("larger than" in p for p in problems(b))
  89. def test_a_png_with_a_bad_signature_fails(tmp_path):
  90. b = make_bundle(tmp_path / "b", png=b"GIF89a" + b"\0" * 40)
  91. assert any("PNG" in p for p in problems(b))
  92. def test_a_png_that_is_a_script_fails(tmp_path):
  93. b = make_bundle(tmp_path / "b", png=b"#!/bin/sh\nrm -rf /\n")
  94. assert problems(b)
  95. def test_a_png_that_does_not_match_its_hash_fails(tmp_path):
  96. b = make_bundle(tmp_path / "b")
  97. (b / grm.BUNDLE_PNG).write_bytes(png_bytes(color=9))
  98. assert any("png_sha256" in p for p in problems(b))
  99. def test_a_hand_edited_snapshot_fails(tmp_path):
  100. b = make_bundle(tmp_path / "b")
  101. rewrite_snapshot(b, lambda s: s["forks"].update({"2026-10-13": 99999}), rehash=False)
  102. assert any("source_sha256" in p for p in problems(b))
  103. def test_the_wrong_repository_fails(tmp_path):
  104. b = make_bundle(tmp_path / "b")
  105. assert any("repo" in p for p in problems(b, expect_repo="Other/Thing"))
  106. @pytest.mark.parametrize("field", ["login", "stargazers", "email"])
  107. def test_a_login_like_field_fails(tmp_path, field):
  108. b = make_bundle(tmp_path / "b")
  109. rewrite_snapshot(b, lambda s: s.update({field: ["someone"]}))
  110. assert any("unknown field" in p for p in problems(b))
  111. def test_a_stale_bundle_fails(tmp_path):
  112. b = make_bundle(tmp_path / "b")
  113. later = NOW + datetime.timedelta(hours=7)
  114. assert any("old" in p for p in problems(b, now=later))
  115. def test_a_bundle_from_the_future_fails(tmp_path):
  116. b = make_bundle(tmp_path / "b")
  117. earlier = NOW - datetime.timedelta(hours=3)
  118. assert any("future" in p for p in problems(b, now=earlier))
  119. def test_no_age_limit_when_none_is_given(tmp_path):
  120. b = make_bundle(tmp_path / "b")
  121. assert problems(b, now=NOW + datetime.timedelta(days=400), max_age_hours=None) == []
  122. def test_an_absurd_count_fails(tmp_path):
  123. b = make_bundle(tmp_path / "b")
  124. rewrite_snapshot(b, lambda s: s["merged_prs"].update({"2026-10-11": grm.MAX_DAY_COUNT + 1}))
  125. assert any("too large" in p for p in problems(b))
  126. def test_duplicate_keys_fail(tmp_path):
  127. b = make_bundle(tmp_path / "b")
  128. p = b / grm.BUNDLE_SNAPSHOT
  129. text = p.read_text().replace('"repo": "Example/Repo",', '"repo": "Example/Repo", "repo": "Other/Thing",')
  130. p.write_text(text)
  131. assert any("duplicate" in x for x in problems(b))
  132. def test_a_nesting_bomb_fails_without_crashing(tmp_path):
  133. b = make_bundle(tmp_path / "b")
  134. (b / grm.BUNDLE_SNAPSHOT).write_text("[" * 50000 + "]" * 50000)
  135. out = problems(b)
  136. assert out
  137. @pytest.mark.parametrize("text", ["NaN", "[1, 2", "", "null", '{"schema": 1e999}'])
  138. def test_garbage_snapshots_fail(tmp_path, text):
  139. b = make_bundle(tmp_path / "b")
  140. (b / grm.BUNDLE_SNAPSHOT).write_text(text)
  141. assert problems(b)
  142. def test_the_cli_verifies_and_prints_the_as_of_stamp(tmp_path):
  143. b = make_bundle(tmp_path / "b")
  144. run = lambda *a: subprocess.run([sys.executable, "-I", str(ROOT / "scripts" / "gen_repo_metrics.py"), *a], check=False, capture_output=True, text=True)
  145. ok = run("--verify-bundle", str(b), "--expect-repo", REPO, "--print-as-of")
  146. assert ok.returncode == 0 and ok.stdout.strip() == "2026-10-25T05:30:00Z", ok.stderr
  147. (b / "extra").write_text("x")
  148. bad = run("--verify-bundle", str(b), "--expect-repo", REPO)
  149. assert bad.returncode == 1 and "unexpected" in bad.stderr
  150. # -- the publish script ---------------------------------------------------------------
  151. def git(*args, cwd=None, check=True):
  152. env = {**os.environ, "GIT_CONFIG_GLOBAL": "/dev/null", "GIT_CONFIG_SYSTEM": "/dev/null"}
  153. return subprocess.run(["git", *args], cwd=cwd, check=check, capture_output=True, text=True, env=env)
  154. @pytest.fixture
  155. def remote(tmp_path):
  156. r = tmp_path / "remote.git"
  157. git("init", "-q", "--bare", "-b", "main", str(r))
  158. return r
  159. AUTO = object()
  160. def remote_tip(remote):
  161. out = git("rev-parse", "--verify", "-q", "refs/heads/metrics", cwd=remote, check=False).stdout.strip()
  162. return out
  163. def baseline_beside(bundle):
  164. """A committed baseline for this bundle: same identity, no ledger, valid hashes."""
  165. snap = json.loads((bundle / grm.BUNDLE_SNAPSHOT).read_text())
  166. snap.pop("star_ledger", None)
  167. snap["source_sha256"] = grm.source_digest(snap)
  168. path = bundle.parent / f"{bundle.name}.baseline.json"
  169. path.write_text(json.dumps(snap))
  170. return path
  171. def publish(bundle, remote, tip=AUTO, **extra):
  172. expected = remote_tip(remote) if tip is AUTO else tip
  173. env = {
  174. **os.environ,
  175. "GIT_CONFIG_GLOBAL": "/dev/null",
  176. "GIT_CONFIG_SYSTEM": "/dev/null",
  177. "METRICS_REMOTE": str(remote),
  178. "METRICS_EXPECT_REPO": REPO,
  179. "METRICS_MAX_AGE_HOURS": "0",
  180. "METRICS_BASELINE": str(baseline_beside(bundle)),
  181. "METRICS_EXPECTED_TIP": expected,
  182. **extra,
  183. }
  184. return subprocess.run(["bash", str(PUBLISH), str(bundle)], check=False, capture_output=True, text=True, env=env)
  185. def branch_files(remote):
  186. return sorted(git("ls-tree", "-r", "--name-only", "metrics", cwd=remote).stdout.split())
  187. def test_first_run_creates_an_orphan_branch_with_three_files(tmp_path, remote):
  188. out = publish(make_bundle(tmp_path / "b"), remote)
  189. assert out.returncode == 0, out.stderr
  190. assert branch_files(remote) == ["as-of.txt", "metrics-snapshot.json", "repo-growth.png"]
  191. assert git("rev-list", "--count", "metrics", cwd=remote).stdout.strip() == "1"
  192. assert git("rev-list", "--max-parents=0", "metrics", cwd=remote).stdout.strip() == git("rev-parse", "metrics", cwd=remote).stdout.strip()
  193. assert git("show", "metrics:as-of.txt", cwd=remote).stdout == "2026-10-25T05:30:00Z\n"
  194. assert "main" not in git("branch", "--list", cwd=remote).stdout
  195. def test_an_unchanged_picture_is_not_pushed_again(tmp_path, remote):
  196. b = make_bundle(tmp_path / "b")
  197. assert publish(b, remote).returncode == 0
  198. first = git("rev-parse", "metrics", cwd=remote).stdout
  199. again = publish(b, remote)
  200. assert again.returncode == 0 and "unchanged" in again.stdout
  201. assert git("rev-parse", "metrics", cwd=remote).stdout == first
  202. def test_a_changed_picture_replaces_the_branch(tmp_path, remote):
  203. assert publish(make_bundle(tmp_path / "b"), remote).returncode == 0
  204. first = git("rev-parse", "metrics", cwd=remote).stdout
  205. assert publish(make_bundle(tmp_path / "c", png=png_bytes(color=7)), remote).returncode == 0
  206. assert git("rev-parse", "metrics", cwd=remote).stdout != first
  207. # history is kept: the new commit is a child of the old tip, never a rewrite
  208. assert git("rev-list", "--count", "metrics", cwd=remote).stdout.strip() == "2"
  209. assert git("rev-parse", "metrics~1", cwd=remote).stdout == first
  210. def test_a_hostile_bundle_is_not_pushed(tmp_path, remote):
  211. b = make_bundle(tmp_path / "b")
  212. (b / "extra.sh").write_text("x")
  213. out = publish(b, remote)
  214. assert out.returncode != 0
  215. assert git("branch", "--list", "metrics", cwd=remote).stdout.strip() == ""
  216. def test_a_branch_that_moved_under_the_publish_is_not_overwritten(tmp_path, remote):
  217. assert publish(make_bundle(tmp_path / "b"), remote).returncode == 0
  218. # A second writer lands a commit on the branch after the script read the old
  219. # value and before it pushes: a git shim moves the remote ref, then pushes.
  220. other = tmp_path / "other"
  221. git("clone", "-q", "-b", "metrics", str(remote), str(other))
  222. (other / "note.txt").write_text("someone else\n")
  223. git("-C", str(other), "add", "note.txt")
  224. git("-C", str(other), "-c", "user.name=t", "-c", "user.email=t@example.invalid", "commit", "-q", "-m", "x")
  225. git("-C", str(other), "push", "-q", "origin", "HEAD:refs/heads/side")
  226. moved = git("rev-parse", "side", cwd=remote).stdout.strip()
  227. real = shutil.which("git")
  228. shim = tmp_path / "shim"
  229. shim.mkdir()
  230. (shim / "git").write_text(
  231. "#!/bin/bash\n"
  232. 'for a in "$@"; do\n'
  233. f' if [ "$a" = push ]; then {real} --git-dir={remote} update-ref refs/heads/metrics {moved}; break; fi\n'
  234. "done\n"
  235. f'exec {real} "$@"\n'
  236. )
  237. (shim / "git").chmod(0o755)
  238. out = publish(make_bundle(tmp_path / "c", png=png_bytes(color=3)), remote, PATH=f"{shim}:{os.environ['PATH']}")
  239. assert out.returncode != 0
  240. assert git("rev-parse", "metrics", cwd=remote).stdout.strip() == moved
  241. def test_the_script_has_no_force_except_the_exact_lease():
  242. import re
  243. text = PUBLISH.read_text()
  244. forces = re.findall(r"--force\S*", text)
  245. assert forces, "the exact lease must be there"
  246. # every use is the lease pinned to refs/heads/metrics; header prose uses the same spelling
  247. assert all(re.match(r'--force-with-lease="?refs/heads/metrics:', f) for f in forces), forces
  248. assert not re.search(r"push\s+(-\w*f\b|\+)", text)
  249. assert not re.search(r"\bpush\b[^\n]*\s\+\S", text)
  250. assert not re.search(r"\bpush\b[^\n]*\s-\w*f\b", text)
  251. assert text.count("push -q") == 2 # one child push, one first-run push, both leased
  252. def test_a_changed_snapshot_is_pushed_even_when_the_picture_is_identical(tmp_path, remote):
  253. assert publish(make_bundle(tmp_path / "b"), remote).returncode == 0
  254. first = git("rev-parse", "metrics", cwd=remote).stdout
  255. newer = make_bundle(tmp_path / "c", fetched="2026-10-25T05:45:00Z")
  256. assert (newer / grm.BUNDLE_PNG).read_bytes() == (tmp_path / "b" / grm.BUNDLE_PNG).read_bytes()
  257. out = publish(newer, remote)
  258. assert out.returncode == 0 and "pushed" in out.stdout
  259. assert git("rev-parse", "metrics", cwd=remote).stdout != first
  260. assert git("show", "metrics:as-of.txt", cwd=remote).stdout == "2026-10-25T05:45:00Z\n"
  261. assert json.loads(git("show", "metrics:metrics-snapshot.json", cwd=remote).stdout)["fetched_at"] == "2026-10-25T05:45:00Z"
  262. def test_a_remote_branch_with_an_extra_file_is_replaced_not_skipped(tmp_path, remote):
  263. b = make_bundle(tmp_path / "b")
  264. assert publish(b, remote).returncode == 0
  265. other = tmp_path / "other"
  266. git("clone", "-q", "-b", "metrics", str(remote), str(other))
  267. (other / "extra.txt").write_text("x\n")
  268. git("-C", str(other), "add", "extra.txt")
  269. git("-C", str(other), "-c", "user.name=t", "-c", "user.email=t@example.invalid", "commit", "-q", "-m", "x")
  270. git("-C", str(other), "push", "-q", "origin", "metrics")
  271. assert publish(b, remote).returncode == 0
  272. assert branch_files(remote) == ["as-of.txt", "metrics-snapshot.json", "repo-growth.png"]
  273. @pytest.mark.parametrize("branch", ["main", "master", "metrics:main", "refs/heads/main", "../metrics", "metrics ", "-f", "", "metrics2", "HEAD"])
  274. def test_the_script_refuses_to_push_to_any_ref_but_metrics(tmp_path, remote, branch):
  275. git("-C", str(remote), "symbolic-ref", "HEAD", "refs/heads/main")
  276. out = publish(make_bundle(tmp_path / "b"), remote, METRICS_BRANCH=branch)
  277. assert out.returncode != 0
  278. assert "refs/heads/metrics" in out.stderr
  279. assert git("branch", "--list", cwd=remote).stdout.strip() == ""
  280. def test_the_push_refspec_is_spelled_out_in_the_script():
  281. text = PUBLISH.read_text()
  282. assert "HEAD:refs/heads/metrics" in text
  283. assert "refs/heads/metrics" in text.split("push")[-1]
  284. TOKEN = f"fixture-credential-{6 * 7}" # built at run time: a fake with no literal for a secret scanner to flag
  285. def shimmed_publish(tmp_path, remote, bundle):
  286. """Run the script with a git shim that logs, per call, the credential env and the work repo's config."""
  287. import base64
  288. real = shutil.which("git")
  289. log = tmp_path / "gitcalls.log"
  290. shim = tmp_path / "shim"
  291. shim.mkdir()
  292. (shim / "git").write_text(
  293. "#!/bin/bash\n"
  294. 'sub=""; dir=""\n'
  295. 'args=("$@")\n'
  296. 'if [ "${args[0]}" = -C ]; then dir=${args[1]}; sub=${args[2]}; else sub=${args[0]}; fi\n'
  297. f'{{ echo "CALL $sub count=${{GIT_CONFIG_COUNT:-}} key=${{GIT_CONFIG_KEY_0:-}} hasval=$([ -n "${{GIT_CONFIG_VALUE_0:-}}" ] && echo y || echo n) token=$([ -n "${{GH_TOKEN:-}}" ] && echo y || echo n)"; '
  298. f'[ -n "$dir" ] && [ -f "$dir/.git/config" ] && sed "s/^/CONFIG /" "$dir/.git/config"; }} >> {log}\n'
  299. f'exec {real} "$@"\n'
  300. )
  301. (shim / "git").chmod(0o755)
  302. out = publish(bundle, remote, GH_TOKEN=TOKEN, PATH=f"{shim}:{os.environ['PATH']}")
  303. return out, log.read_text(), base64.b64encode(f"x-access-token:{TOKEN}".encode()).decode()
  304. def test_the_token_header_is_scoped_to_the_remote_url_and_only_remote_commands(tmp_path, remote):
  305. out, calls, _ = shimmed_publish(tmp_path, remote, make_bundle(tmp_path / "b"))
  306. assert out.returncode == 0, out.stderr
  307. remote_calls = [ln for ln in calls.splitlines() if ln.startswith("CALL ") and "hasval=y" in ln]
  308. assert remote_calls, "the header was never sent"
  309. for ln in remote_calls:
  310. assert ln.split()[1] in {"ls-remote", "fetch", "push"}, ln
  311. assert f"key=http.{remote}.extraheader" in ln, ln
  312. assert "count=1" in ln
  313. local = [ln for ln in calls.splitlines() if ln.startswith("CALL ") and ln.split()[1] in {"init", "remote", "add", "commit", "show"}]
  314. assert local and all("hasval=n" in ln and "count= " in ln for ln in local), local
  315. def test_no_file_and_no_output_ever_holds_the_token(tmp_path, remote):
  316. out, calls, b64 = shimmed_publish(tmp_path, remote, make_bundle(tmp_path / "b"))
  317. assert out.returncode == 0
  318. for secret in (TOKEN, b64):
  319. assert secret not in calls # the work repo's .git/config, as seen at every call
  320. assert secret not in out.stdout + out.stderr
  321. for path in tmp_path.rglob("*"):
  322. if path.is_file() and not path.is_symlink() and path != tmp_path / "gitcalls.log":
  323. assert secret.encode() not in path.read_bytes(), path
  324. def test_the_python_validator_does_not_see_the_token(tmp_path, remote):
  325. real = shutil.which("python3")
  326. shim = tmp_path / "pyshim"
  327. shim.mkdir()
  328. seen = tmp_path / "py-env.log"
  329. (shim / "python3").write_text(f'#!/bin/bash\necho "GH_TOKEN=${{GH_TOKEN:-unset}} GITHUB_TOKEN=${{GITHUB_TOKEN:-unset}}" >> {seen}\nexec {real} "$@"\n')
  330. (shim / "python3").chmod(0o755)
  331. out = publish(make_bundle(tmp_path / "b"), remote, GH_TOKEN=TOKEN, GITHUB_TOKEN=TOKEN, PATH=f"{shim}:{os.environ['PATH']}")
  332. assert out.returncode == 0, out.stderr
  333. assert seen.read_text().strip() == "GH_TOKEN=unset GITHUB_TOKEN=unset"
  334. assert "export GIT_CONFIG" not in PUBLISH.read_text()
  335. # -- fast-forward only: the metrics branch is mutable and never authoritative -------------
  336. def test_the_expected_tip_must_match_the_remote_tip(tmp_path, remote):
  337. assert publish(make_bundle(tmp_path / "b"), remote).returncode == 0
  338. stale = git("rev-parse", "metrics", cwd=remote).stdout.strip()
  339. assert publish(make_bundle(tmp_path / "c", png=png_bytes(color=5)), remote).returncode == 0
  340. moved = git("rev-parse", "metrics", cwd=remote).stdout.strip()
  341. out = publish(make_bundle(tmp_path / "d", png=png_bytes(color=6)), remote, tip=stale)
  342. assert out.returncode != 0 and "moved" in out.stderr
  343. assert git("rev-parse", "metrics", cwd=remote).stdout.strip() == moved
  344. def test_an_empty_expected_tip_refuses_when_the_branch_exists(tmp_path, remote):
  345. assert publish(make_bundle(tmp_path / "b"), remote).returncode == 0
  346. tip = git("rev-parse", "metrics", cwd=remote).stdout.strip()
  347. out = publish(make_bundle(tmp_path / "c", png=png_bytes(color=5)), remote, tip="")
  348. assert out.returncode != 0 and "exists" in out.stderr
  349. assert git("rev-parse", "metrics", cwd=remote).stdout.strip() == tip
  350. def test_an_expected_tip_with_no_branch_is_refused(tmp_path, remote):
  351. out = publish(make_bundle(tmp_path / "b"), remote, tip="0123456789abcdef0123456789abcdef01234567")
  352. assert out.returncode != 0
  353. assert git("branch", "--list", "metrics", cwd=remote).stdout.strip() == ""
  354. @pytest.mark.parametrize("tip", ["main", "HEAD", "abc", "0123456789ABCDEF0123456789ABCDEF01234567", "g" * 40, "x; rm -rf /"])
  355. def test_a_malformed_expected_tip_is_refused(tmp_path, remote, tip):
  356. out = publish(make_bundle(tmp_path / "b"), remote, tip=tip)
  357. assert out.returncode != 0 and "expected tip" in out.stderr
  358. def test_the_expected_tip_must_be_set_at_all(tmp_path, remote):
  359. b = make_bundle(tmp_path / "b")
  360. env = {**os.environ, "METRICS_REMOTE": str(remote), "METRICS_EXPECT_REPO": REPO, "METRICS_MAX_AGE_HOURS": "0", "METRICS_BASELINE": str(baseline_beside(b))}
  361. env.pop("METRICS_EXPECTED_TIP", None)
  362. out = subprocess.run(["bash", str(PUBLISH), str(b)], check=False, capture_output=True, text=True, env=env)
  363. assert out.returncode != 0 and "METRICS_EXPECTED_TIP" in out.stderr
  364. def ledger_bundle(tmp_path, name, ledger, day, color=0):
  365. snap = fixture()
  366. snap["stars_as_of"] = "2026-10-20"
  367. snap["star_ledger"] = ledger
  368. return make_bundle(tmp_path / name, snap=snap, png=png_bytes(color=color), fetched=f"2026-10-{day}T05:30:00Z")
  369. def two_days(tmp_path, remote):
  370. assert publish(ledger_bundle(tmp_path, "d1", {"2026-10-23": 6}, 23), remote).returncode == 0
  371. out = publish(ledger_bundle(tmp_path, "d2", {"2026-10-23": 6, "2026-10-24": 7}, 24, color=2), remote)
  372. assert out.returncode == 0, out.stderr
  373. return git("rev-parse", "metrics", cwd=remote).stdout.strip()
  374. def test_a_ledger_that_loses_an_earlier_point_is_not_pushed(tmp_path, remote):
  375. tip = two_days(tmp_path, remote)
  376. out = publish(ledger_bundle(tmp_path, "d3", {"2026-10-24": 7, "2026-10-25": 9}, 25, color=4), remote)
  377. assert out.returncode != 0 and "ledger" in out.stderr
  378. assert git("rev-parse", "metrics", cwd=remote).stdout.strip() == tip
  379. def test_a_ledger_that_changes_an_earlier_point_is_not_pushed(tmp_path, remote):
  380. tip = two_days(tmp_path, remote)
  381. out = publish(ledger_bundle(tmp_path, "d3", {"2026-10-23": 7, "2026-10-24": 7, "2026-10-25": 9}, 25, color=4), remote)
  382. assert out.returncode != 0
  383. assert git("rev-parse", "metrics", cwd=remote).stdout.strip() == tip
  384. def test_a_ledger_that_extends_with_todays_point_is_pushed_as_a_child(tmp_path, remote):
  385. tip = two_days(tmp_path, remote)
  386. out = publish(ledger_bundle(tmp_path, "d3", {"2026-10-23": 6, "2026-10-24": 7, "2026-10-25": 9}, 25, color=4), remote)
  387. assert out.returncode == 0, out.stderr
  388. assert git("rev-parse", "metrics~1", cwd=remote).stdout.strip() == tip
  389. assert git("rev-list", "--count", "metrics", cwd=remote).stdout.strip() == "3"
  390. assert list(json.loads(git("show", "metrics:metrics-snapshot.json", cwd=remote).stdout)["star_ledger"]) == ["2026-10-23", "2026-10-24", "2026-10-25"]
  391. def test_the_first_run_ledger_may_hold_only_todays_point(tmp_path, remote):
  392. out = publish(ledger_bundle(tmp_path, "d1", {"2026-10-22": 6, "2026-10-23": 7}, 23), remote)
  393. assert out.returncode != 0 and "ledger" in out.stderr
  394. # -- the push is an exact compare-and-swap ------------------------------------------------
  395. def push_shim(tmp_path, remote, action):
  396. """A git shim that runs `action` (shell, on the remote) right before the real push."""
  397. real = shutil.which("git")
  398. shim = tmp_path / "pushshim"
  399. shim.mkdir(exist_ok=True)
  400. (shim / "git").write_text(
  401. "#!/bin/bash\n"
  402. 'for a in "$@"; do\n'
  403. f' if [ "$a" = push ]; then g() {{ {real} --git-dir={remote} "$@"; }}; {action}; break; fi\n'
  404. "done\n"
  405. f'exec {real} "$@"\n'
  406. )
  407. (shim / "git").chmod(0o755)
  408. return f"{shim}:{os.environ['PATH']}"
  409. def test_a_remote_rewound_to_an_ancestor_before_the_push_fails(tmp_path, remote):
  410. two_days(tmp_path, remote)
  411. ancestor = git("rev-parse", "metrics~1", cwd=remote).stdout.strip()
  412. path = push_shim(tmp_path, remote, f"g update-ref refs/heads/metrics {ancestor}")
  413. out = publish(ledger_bundle(tmp_path, "d3", {"2026-10-23": 6, "2026-10-24": 7, "2026-10-25": 9}, 25, color=4), remote, PATH=path)
  414. assert out.returncode != 0
  415. assert git("rev-parse", "metrics", cwd=remote).stdout.strip() == ancestor # untouched, not fast-forwarded
  416. def test_a_branch_deleted_before_the_push_fails(tmp_path, remote):
  417. two_days(tmp_path, remote)
  418. path = push_shim(tmp_path, remote, "g update-ref -d refs/heads/metrics")
  419. out = publish(ledger_bundle(tmp_path, "d3", {"2026-10-23": 6, "2026-10-24": 7, "2026-10-25": 9}, 25, color=4), remote, PATH=path)
  420. assert out.returncode != 0
  421. assert git("branch", "--list", "metrics", cwd=remote).stdout.strip() == ""
  422. def test_a_first_run_where_the_branch_appears_meanwhile_fails(tmp_path, remote):
  423. other = tmp_path / "other"
  424. git("init", "-q", "-b", "metrics", str(other))
  425. (other / "note.txt").write_text("someone else\n")
  426. git("-C", str(other), "add", "note.txt")
  427. git("-C", str(other), "-c", "user.name=t", "-c", "user.email=t@example.invalid", "commit", "-q", "-m", "x")
  428. git("-C", str(other), "push", "-q", str(remote), "HEAD:refs/heads/side")
  429. side = git("rev-parse", "side", cwd=remote).stdout.strip()
  430. path = push_shim(tmp_path, remote, f"g update-ref refs/heads/metrics {side}")
  431. out = publish(make_bundle(tmp_path / "b"), remote, PATH=path)
  432. assert out.returncode != 0
  433. assert git("rev-parse", "metrics", cwd=remote).stdout.strip() == side
  434. def test_the_normal_fast_forward_path_still_passes_through_the_shim(tmp_path, remote):
  435. two_days(tmp_path, remote)
  436. tip = git("rev-parse", "metrics", cwd=remote).stdout.strip()
  437. path = push_shim(tmp_path, remote, "true")
  438. out = publish(ledger_bundle(tmp_path, "d3", {"2026-10-23": 6, "2026-10-24": 7, "2026-10-25": 9}, 25, color=4), remote, PATH=path)
  439. assert out.returncode == 0, out.stderr
  440. assert git("rev-parse", "metrics~1", cwd=remote).stdout.strip() == tip
  441. def test_the_new_commit_has_exactly_the_expected_tip_as_its_only_parent(tmp_path, remote):
  442. tip = two_days(tmp_path, remote)
  443. assert publish(ledger_bundle(tmp_path, "d3", {"2026-10-23": 6, "2026-10-24": 7, "2026-10-25": 9}, 25, color=4), remote).returncode == 0
  444. assert git("rev-list", "--parents", "-n1", "metrics", cwd=remote).stdout.split()[1:] == [tip]
  445. first = git("rev-list", "--max-parents=0", "metrics", cwd=remote).stdout.split()
  446. assert len(first) == 1 # one orphan root, ever
  447. def test_the_script_proves_the_parent_before_pushing():
  448. text = PUBLISH.read_text()
  449. assert 'rev-parse "HEAD^@"' in text and '[ "$parents" = "$expected_tip" ]' in text