From 532f3c8e8b44d3dcbb8ae9ac84024f8680044f74 Mon Sep 17 00:00:00 2001 From: Aditya Mukhopadhyay Date: Thu, 3 Dec 2026 18:02:39 +0530 Subject: [PATCH] ci: preflight generated release bodies before publishing Validate the rendered release body through the existing release gate and add an early PR preflight with boundary and configuration tests. Use one audited cargo-dist version policy in both workflows. Surface warnings as safe Actions annotations and support lower character budgets. Incorporate review feedback while retaining the existing branch filters. --- .github/release/check_release_body.py | 238 +++++++++++ .github/release/test_release_body.py | 414 ++++++++++++++++++++ .github/release/test_release_body_config.py | 187 +++++++++ .github/workflows/release-body.yml | 74 ++++ .github/workflows/release-gate.yml | 19 + 5 files changed, 932 insertions(+) create mode 100644 .github/release/check_release_body.py create mode 100644 .github/release/test_release_body.py create mode 100644 .github/release/test_release_body_config.py create mode 100644 .github/workflows/release-body.yml diff --git a/.github/release/check_release_body.py b/.github/release/check_release_body.py new file mode 100644 index 0000000000..777c261dab --- /dev/null +++ b/.github/release/check_release_body.py @@ -0,0 +1,238 @@ +#!/usr/bin/env python3 +"""Read-only preflight for a decoded cargo-dist announcement or final notes file. + +Exit 0: pass/warning; 1: a size policy fails; 2: input/configuration error. +GitHub reports a 125,000-character maximum, without documenting its Unicode +unit. Code points are this check's explicit character-counting policy. The +optional UTF-8 budget is a conservative project policy, not an API byte limit. +No text is trimmed, normalized, truncated, published, or written by this tool. +Configuration checks require Python 3.11+; --check-dist-config prints the audited +version instead of a body report, for use by the installer step. +""" + +import argparse +import hashlib +import json +import os +from pathlib import Path +import sys + +GITHUB_MAX_CHARS = 125_000 +DEFAULT_WARN_AT = 120_000 +# Audit notes-file transport and release-job ordering before changing this pin. +AUDITED_DIST_VERSION = "0.31.0" +ENV_OVERHEAD = len(b"ANNOUNCEMENT_BODY=") + 1 # Include the terminating NUL. + + +def diagnostic(level, message): + if os.environ.get("GITHUB_ACTIONS") == "true": + # Keep untrusted paths/JSON diagnostics inside one workflow command. + message = message.replace("%", "%25").replace("\r", "%0D").replace("\n", "%0A") + print(f"::{level}::{message}", file=sys.stderr) + else: + print(f"{level.upper()}: {message}", file=sys.stderr) + + +class PreflightParser(argparse.ArgumentParser): + def error(self, message): + self.print_usage(sys.stderr) + diagnostic("error", message) + self.exit(2) + + +def audited_dist_version(path): + try: + import tomllib + except ImportError as exc: + raise ValueError("cargo-dist configuration checks require Python 3.11+") from exc + config = tomllib.loads(path.read_bytes().decode("utf-8", errors="strict")) + dist = config.get("dist") + if not isinstance(dist, dict) or dist.get("cargo-dist-version") != AUDITED_DIST_VERSION: + raise ValueError("configured cargo-dist version must match audited version " + + AUDITED_DIST_VERSION + + "; review the notes transport before upgrading the audit pin") + return AUDITED_DIST_VERSION + + +def unique_object(pairs): + result = {} + for key, value in pairs: + if key in result: + raise ValueError("duplicate JSON key: " + json.dumps(key)) + result[key] = value + return result + + +def reject_constant(value): + raise ValueError("non-standard JSON constant: " + value) + + +def read_input(args): + source = args.manifest or args.notes_file + # read_text() would translate CRLF and could undercount a notes file. + raw = source.read_bytes().decode("utf-8", errors="strict") + metadata = {} + if args.manifest: + doc = json.loads(raw, object_pairs_hook=unique_object, + parse_constant=reject_constant) + if not isinstance(doc, dict): + raise ValueError("manifest must be a JSON object") + body = doc.get("announcement_github_body") + if args.require_changelog: + changelog = doc.get("announcement_changelog") + if not isinstance(changelog, str) or not changelog.strip(): + raise ValueError("manifest must contain a nonempty changelog") + for key, expected in (("announcement_tag", args.expected_tag), + ("dist_version", args.expected_dist_version)): + if expected is not None and doc.get(key) != expected: + raise ValueError(key + " does not match the expected value") + if key in doc: + if not isinstance(doc[key], str) or not doc[key]: + raise ValueError(key + " must be a nonempty string") + metadata[key] = doc[key] + else: + body = raw + if not isinstance(body, str) or not body.strip(): + raise ValueError("release body must be a nonempty, non-whitespace string") + if "\x00" in body: + raise ValueError("release body contains NUL, unsupported by the transport") + # json.loads permits lone escaped surrogates; valid UTF-8 does not. + body.encode("utf-8", errors="strict") + return body, metadata + + +def check(body, args, metadata): + submitted = body + ("\n" if args.append_final_lf else "") + encoded = submitted.encode("utf-8") + counts = { + "announcement_code_points": len(body), + "submitted_code_points": len(submitted), + "submitted_utf8_bytes": len(encoded), + "submitted_utf16_units": len(submitted.encode("utf-16-le")) // 2, + "submitted_sha256": hashlib.sha256(encoded).hexdigest(), + "headroom_code_points": args.max_chars - len(submitted), + } + if args.manifest: + counts["announcement_env_entry_bytes"] = ( + len(body.encode("utf-8")) + ENV_OVERHEAD + ) + errors = [] + warnings = [] + if len(submitted) > args.max_chars: + errors.append(f"Submitted body has {len(submitted):,} code points; " + f"maximum {args.max_chars:,}; remove at least " + f"{len(submitted) - args.max_chars:,} code points.") + if args.max_utf8_bytes is not None and len(encoded) > args.max_utf8_bytes: + errors.append(f"Submitted body has {len(encoded):,} UTF-8 bytes; " + f"project byte budget {args.max_utf8_bytes:,}.") + if args.max_env_bytes is not None: + env_size = counts["announcement_env_entry_bytes"] + if env_size > args.max_env_bytes: + errors.append(f"ANNOUNCEMENT_BODY environment entry is {env_size:,} " + f"bytes including name and NUL; transport maximum " + f"{args.max_env_bytes:,}.") + if not errors: + if len(submitted) >= args.warn_at: + warnings.append(f"Submitted body reached warning threshold " + f"{args.warn_at:,} code points; " + f"{counts['headroom_code_points']:,} remain.") + if (args.max_utf8_bytes is not None and len(encoded) >= args.warn_at): + warnings.append(f"Submitted body reached {args.warn_at:,} UTF-8 " + f"bytes; project byte-budget headroom is " + f"{args.max_utf8_bytes - len(encoded):,} bytes.") + return { + "status": "fail" if errors else "warn" if warnings else "pass", + "metadata": metadata, + "measurements": counts, + "policy": { + "max_code_points": args.max_chars, + "warn_at": args.warn_at, + "max_utf8_bytes": args.max_utf8_bytes, + "max_env_bytes": args.max_env_bytes, + "append_final_lf": args.append_final_lf, + }, + "errors": errors, + "warnings": warnings, + } + + +def main(argv=None): + parser = PreflightParser(description=__doc__) + source = parser.add_mutually_exclusive_group(required=True) + source.add_argument("--manifest", type=Path) + source.add_argument("--notes-file", type=Path) + source.add_argument("--check-dist-config", type=Path, + help="validate TOML against the audit pin and print its version") + parser.add_argument("--expected-tag") + parser.add_argument("--expected-dist-version") + parser.add_argument("--audited-dist-config", type=Path, + help="validate TOML and manifest against the shared audit pin") + parser.add_argument("--require-changelog", action="store_true", + help="reject an announcement containing only downloads") + parser.add_argument("--append-final-lf", action="store_true", + help="model the LF added by cargo-dist's audited echo transport") + parser.add_argument("--max-chars", type=int, + help="character ceiling (default: 125000)") + parser.add_argument("--warn-at", type=int, + help="warning threshold (default: min(120000, --max-chars))") + parser.add_argument("--max-utf8-bytes", type=int, + help="optional conservative project byte budget") + parser.add_argument("--max-env-bytes", type=int, + help="target Linux per-env-string cap, including NUL") + args = parser.parse_args(argv) + if args.check_dist_config: + if (args.expected_tag is not None or args.expected_dist_version is not None + or args.audited_dist_config is not None or args.require_changelog + or args.append_final_lf or args.max_chars is not None + or args.warn_at is not None or args.max_utf8_bytes is not None + or args.max_env_bytes is not None): + parser.error("--check-dist-config must be used without body-check options") + try: + print(audited_dist_version(args.check_dist_config)) + except (OSError, ValueError, UnicodeError) as exc: + diagnostic("error", "release-body preflight input error: " + str(exc)) + return 2 + return 0 + if args.max_chars is None: + args.max_chars = GITHUB_MAX_CHARS + if not 0 < args.max_chars <= GITHUB_MAX_CHARS: + parser.error("--max-chars must be between 1 and 125000") + if args.warn_at is None: + args.warn_at = min(DEFAULT_WARN_AT, args.max_chars) + if not 0 < args.warn_at <= args.max_chars: + parser.error("--warn-at must be positive and no greater than --max-chars") + for value in (args.max_utf8_bytes, args.max_env_bytes): + if value is not None and value <= 0: + parser.error("byte budgets must be positive") + if args.notes_file and (args.expected_tag is not None + or args.expected_dist_version is not None + or args.audited_dist_config is not None + or args.require_changelog + or args.append_final_lf + or args.max_env_bytes is not None): + parser.error("metadata, LF and environment options require --manifest") + if args.audited_dist_config is not None and args.expected_dist_version is not None: + parser.error("choose --audited-dist-config or --expected-dist-version, not both") + try: + if args.audited_dist_config is not None: + args.expected_dist_version = audited_dist_version(args.audited_dist_config) + body, metadata = read_input(args) + report = check(body, args, metadata) + except (OSError, ValueError, UnicodeError) as exc: + diagnostic("error", "release-body preflight input error: " + str(exc)) + return 2 + print(json.dumps(report, indent=2, ensure_ascii=True)) + counts = report["measurements"] + print(f"release-body preflight {report['status']}: " + f"{counts['submitted_code_points']:,}/{args.max_chars:,} code points, " + f"{counts['submitted_utf8_bytes']:,} UTF-8 bytes, " + f"{counts['headroom_code_points']:,} code-point headroom", file=sys.stderr) + for message in report["errors"]: + diagnostic("error", message) + for message in report["warnings"]: + diagnostic("warning", message) + return 1 if report["errors"] else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/.github/release/test_release_body.py b/.github/release/test_release_body.py new file mode 100644 index 0000000000..0a41e7be1f --- /dev/null +++ b/.github/release/test_release_body.py @@ -0,0 +1,414 @@ +#!/usr/bin/env python3 +"""CLI contract tests for the release-body preflight (no network).""" + +import hashlib +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +CHECKER = Path(__file__).with_name("check_release_body.py") + + +class ReleaseBodyTests(unittest.TestCase): + def invoke(self, raw, *, mode="manifest", args=(), expected=0, env_overrides=None): + """Run a real CLI process and verify that it never edits its input.""" + with tempfile.TemporaryDirectory(prefix="release-body-test-") as tmp: + root = Path(tmp) + path = root / ("input.json" if mode == "manifest" else "notes.md") + path.write_bytes(raw) + argv = [sys.executable, str(CHECKER)] + if mode is not None: + argv.extend(["--" + mode, str(path)]) + argv.extend(str(path) if arg == "{input}" else arg for arg in args) + env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1", PYTHONUTF8="1", + GITHUB_ACTIONS="false") + for key, value in (env_overrides or {}).items(): + if value is None: + env.pop(key, None) + else: + env[key] = value + result = subprocess.run( + argv, cwd=root, env=env, capture_output=True, timeout=10, + check=False, + ) + stdout = result.stdout.decode("utf-8") + stderr = result.stderr.decode("utf-8") + self.assertEqual(result.returncode, expected, (stdout, stderr)) + self.assertEqual(path.read_bytes(), raw, "Preflight modified its input") + self.assertEqual( + sorted(p.name for p in root.iterdir()), [path.name], + "Preflight created an unexpected file", + ) + if expected == 2: + self.assertTrue(stderr.strip(), "Invalid input needs a diagnostic") + return None, stdout, stderr + report = json.loads(stdout) + self.assertIsInstance(report, dict) + self.assertIn(report["status"], ("pass", "warn", "fail")) + self.assertIsInstance(report["errors"], list) + self.assertIsInstance(report["warnings"], list) + self.assertIsInstance(report["measurements"], dict) + if expected == 1: + self.assertEqual(report["status"], "fail") + self.assertTrue(report["errors"]) + else: + self.assertNotEqual(report["status"], "fail") + self.assertFalse(report["errors"]) + if report["status"] == "warn": + self.assertTrue(report["warnings"]) + return report, stdout, stderr + + @staticmethod + def manifest(body, **overrides): + value = { + "announcement_github_body": body, + "announcement_tag": "v3.0.0-alpha.1", + "dist_version": "0.31.0", + } + value.update(overrides) + return json.dumps(value, ensure_ascii=True).encode("utf-8") + + def check_counts(self, report, submitted, *, announcement=None, limit=125_000): + counts = report["measurements"] + self.assertEqual(counts["submitted_code_points"], len(submitted)) + self.assertEqual(counts["submitted_utf8_bytes"], len(submitted.encode("utf-8"))) + self.assertEqual( + counts["submitted_utf16_units"], len(submitted.encode("utf-16-le")) // 2, + ) + self.assertEqual( + counts["submitted_sha256"], hashlib.sha256(submitted.encode("utf-8")).hexdigest(), + ) + self.assertEqual(counts["headroom_code_points"], limit - len(submitted)) + if announcement is not None: + self.assertEqual(counts["announcement_code_points"], len(announcement)) + self.assertEqual( + counts["announcement_env_entry_bytes"], + len(b"ANNOUNCEMENT_BODY=") + len(announcement.encode("utf-8")) + 1, + ) + + def test_ascii_notes_boundaries(self): + for length, code in ((124_999, 0), (125_000, 0), (125_001, 1)): + with self.subTest(length=length): + body = "a" * length + report, _, _ = self.invoke(body.encode(), mode="notes-file", expected=code) + self.check_counts(report, body) + + def test_manifest_without_append_preserves_exact_limit(self): + body = "a" * 125_000 + report, _, _ = self.invoke(self.manifest(body)) + self.check_counts(report, body, announcement=body) + + def test_manifest_appended_lf_boundary(self): + for length, code in ((124_999, 0), (125_000, 1)): + with self.subTest(length=length): + body = "a" * length + report, _, _ = self.invoke( + self.manifest(body), args=["--append-final-lf"], expected=code, + ) + self.check_counts(report, body + "\n", announcement=body) + + def test_existing_trailing_newlines_are_not_stripped(self): + body = "release\n\n" + report, _, _ = self.invoke(self.manifest(body), args=["--append-final-lf"]) + self.check_counts(report, body + "\n", announcement=body) + report, _, _ = self.invoke(body.encode(), mode="notes-file") + self.check_counts(report, body) + + def test_notes_crlf_is_not_normalized(self): + body = "first\r\nsecond\r\n" + report, _, _ = self.invoke(body.encode(), mode="notes-file") + self.check_counts(report, body) + + def test_unicode_codepoints_bytes_and_utf16_are_distinct(self): + body = "é😀e\u0301" + self.assertEqual((len(body), len(body.encode("utf-8"))), (4, 9)) + report, _, _ = self.invoke(self.manifest(body)) + self.check_counts(report, body, announcement=body) + + def test_json_escapes_are_decoded_before_counting(self): + value = {"announcement_github_body": "é😀\r\nquoted: \"ok\"\\"} + reports = [] + for ensure_ascii in (True, False): + with self.subTest(ensure_ascii=ensure_ascii): + raw = json.dumps(value, ensure_ascii=ensure_ascii).encode("utf-8") + report, _, _ = self.invoke(raw) + self.check_counts(report, value["announcement_github_body"], + announcement=value["announcement_github_body"]) + reports.append(report["measurements"]) + for key in ("submitted_code_points", "submitted_utf8_bytes", "submitted_sha256"): + self.assertEqual(reports[0][key], reports[1][key]) + + def test_default_does_not_impose_a_125000_byte_limit(self): + for body in ("é" * 62_501, "😀" * 31_251): + with self.subTest(character=body[0]): + self.assertGreater(len(body.encode("utf-8")), 125_000) + report, _, _ = self.invoke(body.encode("utf-8"), mode="notes-file") + self.check_counts(report, body) + + def test_optional_utf8_budget_boundary(self): + for suffix, code in (("", 0), ("a", 1)): + with self.subTest(suffix=suffix): + body = "é" * 62_500 + suffix + report, _, _ = self.invoke( + body.encode("utf-8"), mode="notes-file", + args=["--max-utf8-bytes", "125000"], expected=code, + ) + self.check_counts(report, body) + + def test_optional_byte_budget_counts_appended_lf(self): + for length, code in ((9, 0), (10, 1)): + with self.subTest(length=length): + body = "a" * length + report, _, _ = self.invoke( + self.manifest(body), + args=["--append-final-lf", "--max-utf8-bytes", "10"], expected=code, + ) + self.check_counts(report, body + "\n", announcement=body) + + def test_env_boundary_includes_name_equals_and_nul(self): + for suffix, code in (("a", 0), ("aa", 1)): + with self.subTest(suffix=suffix): + body = "é" * 65_526 + suffix + report, _, _ = self.invoke( + self.manifest(body), args=["--max-env-bytes", "131072"], expected=code, + ) + self.check_counts(report, body, announcement=body) + + def test_env_boundary_excludes_lf_added_to_notes_file(self): + body = "é" * 65_526 + "a" + report, _, _ = self.invoke( + self.manifest(body), args=["--max-env-bytes", "131072", "--append-final-lf"], + ) + self.check_counts(report, body + "\n", announcement=body) + + def test_warning_threshold(self): + for length, status in ((119_999, "pass"), (120_000, "warn")): + with self.subTest(length=length): + report, _, _ = self.invoke(("a" * length).encode(), mode="notes-file") + self.assertEqual(report["status"], status) + + def test_smaller_project_character_budget(self): + for length, code in ((10, 0), (11, 1)): + with self.subTest(length=length): + body = "a" * length + report, _, _ = self.invoke( + body.encode(), mode="notes-file", + args=["--max-chars", "10", "--warn-at", "8"], expected=code, + ) + self.check_counts(report, body, limit=10) + + def test_max_chars_alone_derives_warning_threshold(self): + for length, code, status in ((99_999, 0, "pass"), (100_000, 0, "warn"), + (100_001, 1, "fail")): + with self.subTest(length=length): + body = "a" * length + report, _, _ = self.invoke( + body.encode(), mode="notes-file", args=["--max-chars", "100000"], + expected=code, + ) + self.assertEqual(report["status"], status) + self.check_counts(report, body, limit=100_000) + + def assert_annotation(self, stderr, severity): + annotations = [line for line in stderr.splitlines() + if line.startswith(("::warning::", "::error::"))] + self.assertEqual(len(annotations), 1, stderr) + self.assertTrue(annotations[0].startswith("::" + severity + "::"), stderr) + self.assertNotIn("\r", stderr) + return annotations[0] + + def test_actions_warning_annotation(self): + report, stdout, stderr = self.invoke( + b"a" * 120_000, mode="notes-file", env_overrides={"GITHUB_ACTIONS": "true"}, + ) + self.assertEqual(report["status"], "warn") + self.assert_annotation(stderr, "warning") + self.assertNotIn("::warning::", stdout) + + def test_actions_size_failure_annotation(self): + report, stdout, stderr = self.invoke( + b"a" * 125_001, mode="notes-file", expected=1, + env_overrides={"GITHUB_ACTIONS": "true"}, + ) + self.assertEqual(report["status"], "fail") + self.assert_annotation(stderr, "error") + self.assertNotIn("::error::", stdout) + + def test_actions_input_failure_annotation(self): + _, stdout, stderr = self.invoke( + b"{", expected=2, env_overrides={"GITHUB_ACTIONS": "true"}, + ) + self.assert_annotation(stderr, "error") + self.assertNotIn("::error::", stdout) + + def test_plain_diagnostics_outside_github_actions(self): + for value in (None, "false", "TRUE"): + for raw, code, label in ((b"a" * 120_000, 0, "WARNING:"), + (b"a" * 125_001, 1, "ERROR:")): + with self.subTest(github_actions=value, expected=code): + _, _, stderr = self.invoke( + raw, mode="notes-file", expected=code, + env_overrides={"GITHUB_ACTIONS": value}, + ) + self.assertIn(label, stderr) + self.assertNotIn("::warning::", stderr) + self.assertNotIn("::error::", stderr) + + def test_actions_duplicate_key_cannot_inject_a_workflow_command(self): + key = json.dumps("duplicate%0A\r\n::warning::INJECTED_KEY") + raw = ('{"announcement_github_body":"valid",' + key + ':1,' + key + ':2}').encode() + _, _, stderr = self.invoke( + raw, expected=2, env_overrides={"GITHUB_ACTIONS": "true"}, + ) + annotation = self.assert_annotation(stderr, "error") + self.assertIn("%250A", annotation) + self.assertFalse(any(line.startswith("::warning::") for line in stderr.splitlines())) + + def test_actions_missing_path_cannot_inject_a_workflow_command(self): + path = "missing%0D\r\n::warning::INJECTED_PATH.json" + _, _, stderr = self.invoke( + b"unused", mode=None, args=["--manifest", path], expected=2, + env_overrides={"GITHUB_ACTIONS": "true"}, + ) + annotation = self.assert_annotation(stderr, "error") + self.assertIn("%250D", annotation) + self.assertFalse(any(line.startswith("::warning::") for line in stderr.splitlines())) + + def test_actions_parser_error_escapes_percent_cr_and_lf(self): + argument = "--unknown%0A\r\n::warning::INJECTED_ARGUMENT" + _, _, stderr = self.invoke( + self.manifest("release"), args=[argument], expected=2, + env_overrides={"GITHUB_ACTIONS": "true"}, + ) + annotation = self.assert_annotation(stderr, "error") + self.assertIn("--unknown%250A%0D%0A::warning::INJECTED_ARGUMENT", annotation) + self.assertFalse(any(line.startswith("::warning::") for line in stderr.splitlines())) + + def test_matching_tag_and_dist_version(self): + report, _, _ = self.invoke( + self.manifest("release"), + args=["--expected-tag", "v3.0.0-alpha.1", "--expected-dist-version", "0.31.0"], + ) + self.check_counts(report, "release", announcement="release") + + def test_mismatching_tag_or_dist_version(self): + for flag, expected in (("--expected-tag", "v9.0.0"), + ("--expected-dist-version", "0.0.1")): + with self.subTest(flag=flag): + self.invoke(self.manifest("release"), args=[flag, expected], expected=2) + + def test_missing_or_invalid_expected_metadata(self): + for key, flag in (("announcement_tag", "--expected-tag"), + ("dist_version", "--expected-dist-version")): + for value in (None, 31, "missing"): + with self.subTest(key=key, value=value): + data = {"announcement_github_body": "release"} + if value != "missing": + data[key] = value + self.invoke(json.dumps(data).encode(), args=[flag, "expected"], expected=2) + + def test_malformed_json(self): + for raw in (b"{", b"not-json", b'{"announcement_github_body":"ok"} garbage'): + with self.subTest(raw=raw): + self.invoke(raw, expected=2) + + def test_require_changelog_accepts_nonempty_notes(self): + report, _, _ = self.invoke( + self.manifest("generated body", announcement_changelog="Release changes"), + args=["--require-changelog"], + ) + self.assertEqual(report["status"], "pass") + + def test_require_changelog_rejects_missing_or_invalid_notes(self): + self.invoke(self.manifest("downloads only"), args=["--require-changelog"], expected=2) + for changelog in (None, "", " \r\n", 1, []): + with self.subTest(changelog=changelog): + self.invoke( + self.manifest("downloads only", announcement_changelog=changelog), + args=["--require-changelog"], expected=2, + ) + + def test_invalid_manifest_shapes_and_body_types(self): + values = [None, [], "release", {}, {"unrelated": "text"}] + values.extend({"announcement_github_body": value} + for value in (None, 0, False, [], {})) + for value in values: + with self.subTest(value=value): + self.invoke(json.dumps(value).encode(), expected=2) + + def test_empty_or_whitespace_only_body(self): + for body in ("", " \t\r\n", "\u2003\u00a0"): + for mode in ("manifest", "notes-file"): + with self.subTest(body=repr(body), mode=mode): + raw = self.manifest(body) if mode == "manifest" else body.encode("utf-8") + self.invoke(raw, mode=mode, expected=2) + + def test_invalid_utf8(self): + for mode, raw in (("manifest", b'{"announcement_github_body":"\xff"}'), + ("notes-file", b"release\xff"), + ("notes-file", b"\xed\xa0\x80")): + with self.subTest(mode=mode, raw=raw): + self.invoke(raw, mode=mode, expected=2) + + def test_escaped_lone_surrogates(self): + for body in ("\ud800", "\udfff", "prefix\ud800suffix"): + with self.subTest(body=repr(body)): + self.invoke(self.manifest(body), expected=2) + + def test_embedded_nul_is_rejected(self): + self.invoke(self.manifest("a\0b"), expected=2) + self.invoke(b"a\0b", mode="notes-file", expected=2) + + def test_duplicate_json_keys_are_rejected(self): + for raw in ( + b'{"announcement_github_body":"first","announcement_github_body":"second"}', + b'{"announcement_github_body":"ok","dist_version":"1","dist_version":"1"}', + b'{"announcement_github_body":"ok","other":{"x":1,"x":2}}', + ): + with self.subTest(raw=raw): + self.invoke(raw, expected=2) + + def test_input_selector_and_missing_file_errors(self): + self.invoke(b"unused", mode=None, expected=2) + self.invoke(self.manifest("ok"), args=["--notes-file", "{input}"], expected=2) + self.invoke(b"unused", mode=None, args=["--manifest", "missing.json"], expected=2) + + def test_manifest_only_options_rejected_for_notes_file(self): + for args in (["--append-final-lf"], ["--expected-tag", "v1"], + ["--expected-dist-version", "0.31.0"], ["--max-env-bytes", "131072"], + ["--require-changelog"]): + with self.subTest(args=args): + self.invoke(b"release", mode="notes-file", args=args, expected=2) + + def test_invalid_numeric_configuration(self): + cases = [ + ["--max-chars", "0"], ["--max-chars", "-1"], + ["--max-chars", "125001"], ["--max-chars", "abc"], + ["--warn-at", "0"], ["--warn-at", "-1"], ["--warn-at", "125001"], + ["--max-chars", "100", "--warn-at", "101"], + ["--max-utf8-bytes", "0"], ["--max-utf8-bytes", "-1"], + ["--max-env-bytes", "0"], ["--max-env-bytes", "-1"], + ] + for args in cases: + with self.subTest(args=args): + self.invoke(self.manifest("release"), args=args, expected=2) + + def test_report_and_diagnostics_do_not_expose_the_body(self): + sentinel = "PRIVATE_RELEASE_BODY_CONTENT_DO_NOT_PRINT_5a71f0" + for mode in ("manifest", "notes-file"): + for excess, code in ((0, 0), (125_001, 1)): + with self.subTest(mode=mode, excess=excess): + body = sentinel + "a" * excess + raw = self.manifest(body) if mode == "manifest" else body.encode() + _, stdout, stderr = self.invoke(raw, mode=mode, expected=code) + self.assertNotIn(sentinel, stdout) + self.assertNotIn(sentinel, stderr) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/release/test_release_body_config.py b/.github/release/test_release_body_config.py new file mode 100644 index 0000000000..4c0ad934b6 --- /dev/null +++ b/.github/release/test_release_body_config.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python3 +"""CLI tests for the shared cargo-dist transport audit (no network).""" + +import json +import os +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + + +CHECKER = Path(__file__).with_name("check_release_body.py") +# These fixtures describe the reviewed transport, not a second production pin. +AUDITED_VERSION = "0.31.0" +UNAUDITED_VERSION = "0.32.0" +CONFIG = "dist-workspace.toml" +MANIFEST = "manifest.json" + + +class ReleaseBodyConfigTests(unittest.TestCase): + def invoke(self, args, files, *, expected=0): + """Exercise the real CLI and require every supplied file to stay intact.""" + with tempfile.TemporaryDirectory(prefix="release-body-config-test-") as tmp: + root = Path(tmp) + for name, content in files.items(): + (root / name).write_bytes(content) + env = dict(os.environ, PYTHONDONTWRITEBYTECODE="1", PYTHONUTF8="1") + result = subprocess.run( + [sys.executable, "-B", str(CHECKER), *args], + cwd=root, env=env, capture_output=True, timeout=10, check=False, + ) + stdout = result.stdout.decode("utf-8") + stderr = result.stderr.decode("utf-8") + self.assertEqual(result.returncode, expected, (stdout, stderr)) + self.assertEqual( + sorted(p.name for p in root.iterdir()), sorted(files), + "Configuration validation created an unexpected file", + ) + for name, content in files.items(): + self.assertEqual((root / name).read_bytes(), content, + "Configuration validation changed " + name) + if expected == 2: + self.assertEqual(stdout, "", "An invalid config must not yield a usable version") + self.assertTrue(stderr.strip(), "Invalid input needs a diagnostic") + return stdout, stderr + + @staticmethod + def config(version=AUDITED_VERSION): + return ( + '[workspace]\nmembers = ["cargo:."]\n\n' + '[dist]\n# Version whose notes transport was audited.\n' + f'cargo-dist-version = "{version}"\nci = "github"\n' + ).encode("utf-8") + + @staticmethod + def manifest(version=AUDITED_VERSION, *, omit_version=False): + doc = { + "announcement_github_body": "Release body\n", + "announcement_changelog": "Release changes", + "announcement_tag": "v3.0.0-alpha", + } + if not omit_version: + doc["dist_version"] = version + return json.dumps(doc).encode("utf-8") + + def test_config_only_prints_exact_validated_version(self): + stdout, stderr = self.invoke( + ["--check-dist-config", CONFIG], {CONFIG: self.config()}, + ) + self.assertEqual(stdout, AUDITED_VERSION + "\n") + self.assertEqual(stderr, "") + + def test_config_upgrade_is_rejected_before_providing_installer_version(self): + self.invoke( + ["--check-dist-config", CONFIG], + {CONFIG: self.config(UNAUDITED_VERSION)}, expected=2, + ) + + def test_missing_config_file_is_rejected(self): + self.invoke(["--check-dist-config", CONFIG], {}, expected=2) + + def test_malformed_or_invalid_utf8_config_is_rejected(self): + for config in (b'[dist\ncargo-dist-version = "0.31.0"\n', + b'[dist]\ncargo-dist-version = "\xff"\n'): + with self.subTest(config=config): + self.invoke(["--check-dist-config", CONFIG], {CONFIG: config}, expected=2) + + def test_missing_config_version_or_dist_table_is_rejected(self): + for config in (b"", b"[dist]\nci = 'github'\n", + b"[other]\ncargo-dist-version = '0.31.0'\n", + b"dist = 'not a table'\n"): + with self.subTest(config=config): + self.invoke(["--check-dist-config", CONFIG], {CONFIG: config}, expected=2) + + def test_nonstring_config_versions_are_rejected(self): + for value in ("31", "31.0", "true", '["0.31.0"]', '{value = "0.31.0"}'): + with self.subTest(value=value): + config = f"[dist]\ncargo-dist-version = {value}\n".encode("utf-8") + self.invoke(["--check-dist-config", CONFIG], {CONFIG: config}, expected=2) + + def test_empty_or_semver_range_config_is_not_an_audited_exact_version(self): + for version in ("", "^0.31.0", ">=0.31.0", "0.31", "v0.31.0"): + with self.subTest(version=version): + self.invoke( + ["--check-dist-config", CONFIG], + {CONFIG: self.config(version)}, expected=2, + ) + + def test_audited_manifest_uses_shared_version_policy(self): + stdout, _ = self.invoke( + ["--manifest", MANIFEST, "--audited-dist-config", CONFIG, + "--expected-tag", "v3.0.0-alpha", "--require-changelog", "--append-final-lf"], + {CONFIG: self.config(), MANIFEST: self.manifest()}, + ) + report = json.loads(stdout) + self.assertEqual(report["status"], "pass") + self.assertEqual(report["metadata"]["dist_version"], AUDITED_VERSION) + self.assertEqual(report["measurements"]["submitted_code_points"], + len("Release body\n\n")) + + def test_stale_or_unaudited_manifest_version_is_rejected(self): + for version in ("0.30.0", UNAUDITED_VERSION): + with self.subTest(version=version): + self.invoke( + ["--manifest", MANIFEST, "--audited-dist-config", CONFIG], + {CONFIG: self.config(), MANIFEST: self.manifest(version)}, expected=2, + ) + + def test_synchronized_config_and_manifest_upgrade_still_needs_transport_audit(self): + self.invoke( + ["--manifest", MANIFEST, "--audited-dist-config", CONFIG], + {CONFIG: self.config(UNAUDITED_VERSION), + MANIFEST: self.manifest(UNAUDITED_VERSION)}, expected=2, + ) + + def test_missing_or_invalid_manifest_version_is_rejected(self): + manifests = [self.manifest(omit_version=True)] + manifests.extend(self.manifest(value) for value in (None, "", 31, True, [], {})) + for manifest in manifests: + with self.subTest(manifest=manifest): + self.invoke( + ["--manifest", MANIFEST, "--audited-dist-config", CONFIG], + {CONFIG: self.config(), MANIFEST: manifest}, expected=2, + ) + + def test_manifest_audit_also_requires_config_to_exist_and_match(self): + for files in ({MANIFEST: self.manifest()}, + {CONFIG: self.config(UNAUDITED_VERSION), MANIFEST: self.manifest()}): + with self.subTest(files=files): + self.invoke( + ["--manifest", MANIFEST, "--audited-dist-config", CONFIG], + files, expected=2, + ) + + def test_explicit_version_cannot_override_or_duplicate_audit_policy(self): + for version in (AUDITED_VERSION, UNAUDITED_VERSION): + with self.subTest(version=version): + self.invoke( + ["--manifest", MANIFEST, "--audited-dist-config", CONFIG, + "--expected-dist-version", version], + {CONFIG: self.config(), MANIFEST: self.manifest()}, expected=2, + ) + + def test_audit_config_requires_a_manifest(self): + self.invoke( + ["--notes-file", "notes.md", "--audited-dist-config", CONFIG], + {CONFIG: self.config(), "notes.md": b"Release body\n"}, expected=2, + ) + + def test_config_only_rejects_body_and_manifest_options(self): + files = {CONFIG: self.config(), MANIFEST: self.manifest(), "notes.md": b"Release body\n"} + body_options = ( + ["--manifest", MANIFEST], ["--notes-file", "notes.md"], + ["--audited-dist-config", CONFIG], ["--expected-tag", "v3.0.0-alpha"], + ["--expected-dist-version", AUDITED_VERSION], ["--require-changelog"], + ["--append-final-lf"], ["--max-chars", "125000"], + ["--warn-at", "120000"], ["--max-utf8-bytes", "125000"], + ["--max-env-bytes", "131072"], + ) + for options in body_options: + with self.subTest(options=options): + self.invoke(["--check-dist-config", CONFIG, *options], files, expected=2) + + +if __name__ == "__main__": + unittest.main() diff --git a/.github/workflows/release-body.yml b/.github/workflows/release-body.yml new file mode 100644 index 0000000000..b90b7c3394 --- /dev/null +++ b/.github/workflows/release-body.yml @@ -0,0 +1,74 @@ +name: Release Body Preflight + +# The generated release workflow is tag-only (pr-run-mode = "skip"). +# This independent check measures the version declared by the checked-out crate. +# Repeat after staging the final changelog and version bump. +# A PR stacked onto release/* is intentionally excluded. Its parent PR to main +# must pass this workflow after the changes are integrated, before tagging. +on: + pull_request: + branches: ["main", "v[0-9]*"] + push: + branches: ["main", "v[0-9]*"] + +permissions: + contents: read + +jobs: + check: + name: Generated release body + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + with: + persist-credentials: false + submodules: recursive + - name: Test the preflight checker + run: python3 -B -m unittest discover -s .github/release -p 'test_release_body*.py' -v + - name: Verify the audited cargo-dist configuration + id: dist-version + shell: bash + run: | + version=$(python3 -B .github/release/check_release_body.py \ + --check-dist-config dist-workspace.toml) + printf 'version=%s\n' "$version" >> "$GITHUB_OUTPUT" + - name: Install the pinned cargo-dist + shell: bash + env: + AUDITED_DIST_VERSION: ${{ steps.dist-version.outputs.version }} + run: | + curl --proto '=https' --tlsv1.2 -LsSf \ + "https://github.com/axodotdev/cargo-dist/releases/download/v${AUDITED_DIST_VERSION}/cargo-dist-installer.sh" | sh + "$HOME/.cargo/bin/dist" --version + - name: Determine the prospective release tag + id: version + shell: bash + run: | + cargo metadata --format-version=1 --no-deps > "$RUNNER_TEMP/release-body-cargo-metadata.json" + tag=$(jq -er '. as $workspace | .packages[] | + select(.manifest_path == ($workspace.workspace_root + "/Cargo.toml")) | + "v" + .version' "$RUNNER_TEMP/release-body-cargo-metadata.json") + printf 'tag=%s\n' "$tag" >> "$GITHUB_OUTPUT" + - name: Check generated workflow freshness + run: | + "$HOME/.cargo/bin/dist" generate --mode ci --check + - name: Plan and check the release body + shell: bash + env: + RELEASE_TAG: ${{ steps.version.outputs.tag }} + run: | + # Run in the checkout; only output files go to RUNNER_TEMP. + # Planning performs no builds, hosting, release creation or publishing. + "$HOME/.cargo/bin/dist" plan --tag="$RELEASE_TAG" --output-format=json \ + > "$RUNNER_TEMP/release-body-plan.json" + # The UTF-8 budget is project policy; GitHub reports a character limit. + # The environment cap is a backstop if that byte budget is raised. + python3 -B .github/release/check_release_body.py \ + --manifest "$RUNNER_TEMP/release-body-plan.json" \ + --expected-tag "$RELEASE_TAG" \ + --audited-dist-config dist-workspace.toml \ + --require-changelog \ + --append-final-lf \ + --max-utf8-bytes 125000 \ + --max-env-bytes 131072 diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.yml index 9d0ef213fb..ddb785a486 100644 --- a/.github/workflows/release-gate.yml +++ b/.github/workflows/release-gate.yml @@ -22,6 +22,25 @@ jobs: persist-credentials: false - name: Test release validation run: python3 -B -m unittest discover -s .github/release -v + - name: Download the generated release plan + uses: actions/download-artifact@v7 + with: + name: artifacts-plan-dist-manifest + path: ${{ runner.temp }}/release-body-preflight + - name: Check the generated release body + shell: bash + run: | + # Use the same audited version/configuration policy as the PR check. + # The UTF-8 budget is project policy; GitHub reports a character limit. + # The environment cap is a backstop if that byte budget is raised. + python3 -B .github/release/check_release_body.py \ + --manifest "$RUNNER_TEMP/release-body-preflight/plan-dist-manifest.json" \ + --expected-tag "$GITHUB_REF_NAME" \ + --audited-dist-config dist-workspace.toml \ + --require-changelog \ + --append-final-lf \ + --max-utf8-bytes 125000 \ + --max-env-bytes 131072 - name: Require successful CI on the tagged commit env: GH_TOKEN: ${{ github.token }}