From 4421e851dd11d2451934d862c60e377867506cd4 Mon Sep 17 00:00:00 2001 From: Kurt Himebauch <136133082+xXJSONDeruloXx@users.noreply.github.com> Date: Thu, 22 Oct 2026 11:12:41 -0400 Subject: [PATCH] Enforce human authorship with automatic trailer scrubbing (#1325) Install commit and push hooks that remove bot co-author trailers, preserve human credits, and reject bot primary authors. Add a trusted default-branch CI checker and publish its required status on the exact proposed commit. Validate main pushes as well. Ten regression tests pass, including real Git hook tests and the --no-verify case. --- .github/workflows/authorship.yml | 58 +++++++++++++++ .github/workflows/build.yml | 23 +++--- tools/release/authorship_hook.py | 43 +++++++++++ tools/release/check_authorship.py | 87 +++++++++++++++++++++++ tools/release/install_authorship_hooks.py | 36 ++++++++++ tools/tests/test_authorship.py | 83 +++++++++++++++++++++ 6 files changed, 321 insertions(+), 9 deletions(-) create mode 100644 .github/workflows/authorship.yml create mode 100644 tools/release/authorship_hook.py create mode 100644 tools/release/check_authorship.py create mode 100644 tools/release/install_authorship_hooks.py create mode 100644 tools/tests/test_authorship.py diff --git a/.github/workflows/authorship.yml b/.github/workflows/authorship.yml new file mode 100644 index 000000000..4bbefa414 --- /dev/null +++ b/.github/workflows/authorship.yml @@ -0,0 +1,58 @@ +name: Human authorship + +on: + pull_request_target: + types: [opened, synchronize, reopened, edited, ready_for_review] + push: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + pull-requests: read + statuses: write + +jobs: + authorship: + name: Validate human authorship + runs-on: ubuntu-24.04 + timeout-minutes: 5 + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.repository.default_branch }} + fetch-depth: 0 + persist-credentials: false + - name: Check the proposed or merged history + id: validate + env: + GH_TOKEN: ${{ github.token }} + EVENT_NAME: ${{ github.event_name }} + PR_NUMBER: ${{ github.event.pull_request.number }} + BEFORE: ${{ github.event.before }} + AFTER: ${{ github.sha }} + PR_HEAD: ${{ github.event.pull_request.head.sha }} + run: | + set -euo pipefail + if [ "$EVENT_NAME" = pull_request_target ]; then + gh auth setup-git + git fetch --no-tags origin "refs/pull/$PR_NUMBER/head" + test "$(git rev-parse FETCH_HEAD)" = "$PR_HEAD" + base=$(git merge-base HEAD FETCH_HEAD) + python3 tools/release/check_authorship.py "$base..FETCH_HEAD" --event "$GITHUB_EVENT_PATH" + elif [ "$EVENT_NAME" = push ] && [ "$BEFORE" != 0000000000000000000000000000000000000000 ]; then + python3 tools/release/check_authorship.py "$BEFORE..$AFTER" + else + python3 tools/release/check_authorship.py HEAD + fi + - name: Publish the required result on the actual proposed commit + if: always() + env: + GH_TOKEN: ${{ github.token }} + TARGET_SHA: ${{ github.event.pull_request.head.sha || github.sha }} + RESULT: ${{ steps.validate.outcome == 'success' && 'success' || 'failure' }} + RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + run: | + gh api --method POST "repos/$GITHUB_REPOSITORY/statuses/$TARGET_SHA" \ + -f context='Human authorship' -f state="$RESULT" -f target_url="$RUN_URL" \ + -f description='Bot authors and bot co-author trailers are forbidden' diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 0dc1289e5..32ea61e34 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -100,17 +100,22 @@ jobs: fetch-depth: 0 persist-credentials: false - - name: Check co-authors - if: github.event_name == 'pull_request' + - name: Check human authorship + env: + EVENT_NAME: ${{ github.event_name }} + BEFORE: ${{ github.event.before }} run: | set -euo pipefail - git fetch --no-tags origin main - base=$(git merge-base origin/main HEAD) - messages=$(git log --format=%B "$base..HEAD") - messages+=$'\n'"$(jq -r '.pull_request.title, (.pull_request.body // "")' "$GITHUB_EVENT_PATH")" - if grep -Eiq '^[[:space:]]*Co-authored-by:.*(Claude|Anthropic|OpenAI|ChatGPT|GPT|Copilot|Cursor|Gemini|Codex|Devin|Windsurf|Codeium|Amazon Q|Tabnine|Cody|\[bot\])' <<<"$messages"; then - echo "::error::AI and bot identities cannot be co-authors; remove the Co-authored-by trailer." - exit 1 + if [ "$EVENT_NAME" = pull_request ]; then + git fetch --no-tags origin main + base=$(git merge-base origin/main HEAD) + checker="$RUNNER_TEMP/droiddeck-check-authorship.py" + git show origin/main:tools/release/check_authorship.py > "$checker" + python3 "$checker" "$base..HEAD" --event "$GITHUB_EVENT_PATH" + elif [ "$EVENT_NAME" = push ] && [ "$BEFORE" != 0000000000000000000000000000000000000000 ]; then + python3 tools/release/check_authorship.py "$BEFORE..HEAD" + else + python3 tools/release/check_authorship.py HEAD fi - name: The packages a signed build ships as diff --git a/tools/release/authorship_hook.py b/tools/release/authorship_hook.py new file mode 100644 index 000000000..3129f7615 --- /dev/null +++ b/tools/release/authorship_hook.py @@ -0,0 +1,43 @@ +#!/usr/bin/env python3 +import os +from pathlib import Path +import subprocess +import sys + +from check_authorship import BOT, COAUTHOR, check_revision + + +def main(): + hook, *args = sys.argv[1:] + payload = sys.stdin.buffer.read() if hook == "pre-push" else None + if hook == "pre-push": + checked = set() + for line in payload.decode().splitlines(): + local_ref, local_sha, _, _ = line.split() + if local_sha == "0" * 40 or local_sha in checked: + continue + checked.add(local_sha) + _, errors = check_revision(local_sha) + if errors: + print("\n".join(errors), file=sys.stderr) + return 1 + else: + identity = subprocess.check_output(["git", "var", "GIT_AUTHOR_IDENT"], text=True) + if BOT.search(identity): + print("Bot commit author is forbidden: " + identity.strip(), file=sys.stderr) + return 1 + message = Path(args[0]) + original = message.read_text(encoding="utf-8") + cleaned = "".join(line for line in original.splitlines(keepends=True) + if not (COAUTHOR.match(line) and BOT.search(line))) + if cleaned != original: + message.write_text(cleaned, encoding="utf-8") + print("Removed bot co-author trailers; human credits preserved.", file=sys.stderr) + legacy = Path(__file__).with_name("legacy-" + hook) + if legacy.exists() and os.access(legacy, os.X_OK): + return subprocess.run([str(legacy), *args], input=payload).returncode + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/release/check_authorship.py b/tools/release/check_authorship.py new file mode 100644 index 000000000..9d952acc0 --- /dev/null +++ b/tools/release/check_authorship.py @@ -0,0 +1,87 @@ +#!/usr/bin/env python3 +"""Reject bot authors and bot co-author trailers without executing reviewed code.""" +import argparse +import json +import re +import subprocess +import sys + +BOT = re.compile( + r"Claude|Anthropic|OpenAI|ChatGPT|GPT|Copilot|Cursor|Gemini|Codex|Devin|" + r"Windsurf|Codeium|Amazon Q|Tabnine|Cody|\[bot\]|github-actions|" + r"dependabot|renovate(?:\[bot\])?", + re.IGNORECASE, +) +COAUTHOR = re.compile(r"^\s*Co-authored-by\s*:", re.IGNORECASE) + + +def commit_violations(commit, raw): + header, separator, message = raw.partition(b"\n\n") + if not separator: + return [f"{commit}: invalid commit object"] + authors = [line[7:] for line in header.splitlines() if line.startswith(b"author ")] + if len(authors) != 1: + return [f"{commit}: expected one author"] + identity = authors[0].decode("utf-8", errors="replace") + errors = [] + if BOT.search(identity): + errors.append(f"{commit}: bot author: {identity}") + for line in message.decode("utf-8", errors="replace").splitlines(): + if COAUTHOR.match(line) and BOT.search(line): + errors.append(f"{commit}: bot co-author: {line.strip()}") + return errors + + +def event_violations(event): + pr = event.get("pull_request", {}) + user = pr.get("user", {}) + errors = [] + if user.get("type") == "Bot" or BOT.search(user.get("login", "")): + errors.append("pull request: bot authorship is forbidden") + for field in ("title", "body"): + for line in (pr.get(field) or "").splitlines(): + if COAUTHOR.match(line) and BOT.search(line): + errors.append(f"pull request {field}: bot co-author trailer") + return errors + + +def check_revision(revision): + commits = subprocess.check_output(["git", "rev-list", revision], text=True).splitlines() + errors = [] + with subprocess.Popen(["git", "cat-file", "--batch"], stdin=subprocess.PIPE, stdout=subprocess.PIPE) as process: + for commit in commits: + process.stdin.write((commit + "\n").encode("ascii")) + process.stdin.flush() + descriptor = process.stdout.readline().split() + if len(descriptor) != 3 or descriptor[1] != b"commit": + raise RuntimeError(f"Cannot read commit {commit}") + size = int(descriptor[2]) + raw = process.stdout.read(size) + if len(raw) != size or process.stdout.read(1) != b"\n": + raise RuntimeError(f"Truncated commit {commit}") + errors.extend(commit_violations(commit, raw)) + process.stdin.close() + if process.wait() != 0: + raise RuntimeError("git cat-file failed") + return commits, errors + + +def main(): + parser = argparse.ArgumentParser() + parser.add_argument("revision") + parser.add_argument("--event") + args = parser.parse_args() + commits, errors = check_revision(args.revision) + if args.event: + with open(args.event, encoding="utf-8") as source: + errors.extend(event_violations(json.load(source))) + for error in errors: + print(f"::error::{error}", file=sys.stderr) + if errors: + return 1 + print(f"Human authorship verified for {len(commits)} commits.") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/release/install_authorship_hooks.py b/tools/release/install_authorship_hooks.py new file mode 100644 index 000000000..dae4eb517 --- /dev/null +++ b/tools/release/install_authorship_hooks.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +"""Install shared worktree hooks while preserving existing executable hooks.""" +from pathlib import Path +import shutil +import subprocess + +MARKER = "# DroidDeck human authorship hook" + + +def install(): + common = Path(subprocess.check_output(["git", "rev-parse", "--git-common-dir"], text=True).strip()).resolve() + configured = subprocess.run(["git", "config", "--get", "core.hooksPath"], capture_output=True, text=True) + hooks = Path(configured.stdout.strip()).resolve() if configured.returncode == 0 else common / "hooks" + target = common / "authorship-hooks" + hooks.mkdir(parents=True, exist_ok=True) + target.mkdir(parents=True, exist_ok=True) + for name in ("check_authorship.py", "authorship_hook.py"): + shutil.copyfile(Path(__file__).with_name(name), target / name) + for name in ("prepare-commit-msg", "commit-msg", "pre-push"): + path = hooks / name + if path.exists() and MARKER not in path.read_text(errors="replace"): + legacy = target / ("legacy-" + name) + if legacy.exists(): + raise RuntimeError(f"Refusing to replace existing saved hook: {legacy}") + shutil.copy2(path, legacy) + path.write_text( + '#!/bin/sh\n' + MARKER + '\n' + 'exec python3 "$(git rev-parse --git-common-dir)/authorship-hooks/authorship_hook.py" ' + + name + ' "$@"\n' + ) + path.chmod(0o755) + print(f"Human authorship hooks installed in {hooks}") + + +if __name__ == "__main__": + install() diff --git a/tools/tests/test_authorship.py b/tools/tests/test_authorship.py new file mode 100644 index 000000000..03d0003b0 --- /dev/null +++ b/tools/tests/test_authorship.py @@ -0,0 +1,83 @@ +import importlib.util +from pathlib import Path +import subprocess +import sys +import tempfile +import unittest + +path = Path(__file__).resolve().parents[1] / "release/check_authorship.py" +spec = importlib.util.spec_from_file_location("check_authorship", path) +check = importlib.util.module_from_spec(spec) +spec.loader.exec_module(check) + + +class AuthorshipTest(unittest.TestCase): + def commit(self, author="Human Contributor ", message="Fix a bug\n"): + return (f"tree {'0' * 40}\nauthor {author} 1 +0000\n" + "committer GitHub 1 +0000\n\n" + message).encode() + + def test_bot_primary_author_is_rejected_without_a_trailer(self): + for author in ("OpenAI Codex ", "Claude ", + "github-actions[bot] "): + with self.subTest(author=author): + self.assertTrue(check.commit_violations("abc", self.commit(author=author))) + + def test_bot_trailers_are_rejected_even_after_human_trailers(self): + message = "Fix\n\nCo-authored-by: Resul Övür \nco-AUTHORED-by: OpenAI Codex \n" + self.assertEqual(1, len(check.commit_violations("abc", self.commit(message=message)))) + + def test_human_authors_and_human_coauthors_are_preserved(self): + message = "Fix the Codex configuration\n\nCo-authored-by: Resul Övür \n" + self.assertEqual([], check.commit_violations("abc", self.commit(message=message))) + + def test_record_separator_in_message_does_not_hide_a_bot_trailer(self): + self.assertTrue(check.commit_violations("abc", self.commit(message="Fix\x1e\nCo-authored-by: Claude \n"))) + + def test_pr_metadata_cannot_add_a_bot_to_the_squash_message(self): + for field in ("title", "body"): + self.assertTrue(check.event_violations({"pull_request": {field: "Co-authored-by: Copilot "}})) + + def test_bot_pr_author_is_rejected(self): + self.assertTrue(check.event_violations({"pull_request": {"user": {"login": "service", "type": "Bot"}}})) + + def test_missing_author_fails_closed(self): + self.assertTrue(check.commit_violations("abc", b"tree 000\n\nmessage\n")) + + +class InstalledHooksTest(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.repo = Path(self.directory.name) + self.git("init", "-q") + self.git("config", "user.name", "Human Contributor") + self.git("config", "user.email", "human@example.com") + installer = path.with_name("install_authorship_hooks.py") + subprocess.run([sys.executable, str(installer)], cwd=self.repo, check=True, capture_output=True) + (self.repo / "file").write_text("content") + self.git("add", "file") + + def tearDown(self): + self.directory.cleanup() + + def git(self, *args): + return subprocess.run(["git", *args], cwd=self.repo, text=True, capture_output=True) + + def test_explicit_bot_author_override_is_blocked(self): + result = self.git("commit", "--author=OpenAI Codex ", "-m", "Fix") + self.assertNotEqual(0, result.returncode, result.stdout + result.stderr) + self.assertIn("Bot commit author is forbidden", result.stderr) + + def test_no_verify_does_not_skip_automatic_trailer_scrubbing(self): + result = self.git("commit", "--no-verify", "-m", "Fix\n\nCo-authored-by: Another Human \nCo-authored-by: Claude ") + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + message = self.git("log", "-1", "--format=%B").stdout + self.assertNotIn("noreply@anthropic.com", message) + self.assertIn("Co-authored-by: Another Human ", message) + + def test_human_commit_and_human_coauthor_are_allowed(self): + result = self.git("commit", "-m", "Fix\n\nCo-authored-by: Another Human ") + self.assertEqual(0, result.returncode, result.stdout + result.stderr) + + +if __name__ == "__main__": + unittest.main()