Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions .github/workflows/policy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,6 @@ on:
description: Newline-separated allowed product names
type: string
default: ''
dependabot-exception:
description: Allow the exact signoff on an authenticated Dependabot commit
type: boolean
default: false
permissions: {}
jobs:
policy:
Expand Down Expand Up @@ -38,7 +34,6 @@ jobs:
env:
GH_TOKEN: ${{ github.token }}
ALLOW_TERMS: ${{ inputs.allow-terms }}
DEPENDABOT_EXCEPTION: ${{ inputs.dependabot-exception }}
run: python3 ../.shared/scripts/check-policy.py
- if: hashFiles('member/.github/release.json') != ''
run: python3 .shared/scripts/validate-version --root member
1 change: 0 additions & 1 deletion .github/workflows/source-policy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,3 @@ jobs:
Cursor

Claude'
dependabot-exception: true
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

## Unreleased

- `policy.yml` checks pull requests by their title, added lines and paths only. Commit verification, committer identity, Conventional Commit subjects and attribution trailers are checked on each new default-branch commit and on the commit selected for manual dispatch, so merge commits that update a pull request and external contributors' commits pass.
- **Breaking:** `policy.yml` no longer takes the `dependabot-exception` input. Pull requests are not checked commit by commit, and default-branch commits carry no trailers. Remove the input from callers.

## 0.1.1

- `policy.yml` accepts the agents CLI's tracked instruction files: `.agent/instructions/`, `.agent/agents.json` and `.agent/agents.resolved`. Other `.agent/` paths, including private directories nested under the units, stay private execution files. The declaration and lock may name agent IDs such as `codex` without an allowed product term.
Expand Down
17 changes: 11 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ for Swift packages, and publication of a package template. Required member check
| `demo` | Builds the release executable and checks a fresh terminal recording through the presentation action's recording-only mode. |
| `commands` | Runs each repository command in its own job in the member checkout. |
| `result` | Requires every declared job to succeed. Only undeclared optional jobs may be skipped; failures and cancellation fail the aggregate. |
| `policy.yml` / `policy` | Checks commit verification/identity, Conventional Commit messages and PR title, attribution, added lines, private paths and permitted product terms. Validates version declarations when `.github/release.json` exists. |
| `policy.yml` / `policy` | On pull requests, checks the PR title, added lines, private paths and permitted product terms. On default-branch pushes, also checks each new commit's verification, committer identity, Conventional Commit subject and attribution; manual dispatch checks only those for the selected commit. Validates version declarations when `.github/release.json` exists. |
| `swift-package-release.yml` / `verify`, `publish` | Verifies the accepted commit and signed annotated tag; validates version/changelog; publishes notes without assets. Only `publish` writes contents. |
| `organization.yml` / `organization` | Compares catalog membership, About descriptions and, in online mode, declared repository settings. All API requests are reads. |

Expand Down Expand Up @@ -108,14 +108,19 @@ jobs:
uses: swift-library/github-workflows/.github/workflows/policy.yml@<full-sha> # vX.Y.Z
with:
allow-terms: ''
dependabot-exception: false
```

`allow-terms` is a newline-separated, case-insensitive product-name allowlist.
It does not exempt attribution or private execution paths. The optional
Dependabot exception permits only its exact signoff after GitHub authenticates
the verified bot author and web-flow signer. Policy retains the family owner
identity `10173746+showxu@users.noreply.github.com` and GitHub's web committer.
It does not exempt attribution or private execution paths.

Pull-request policy checks the title, added content and added or modified file
paths, not individual commits. Callers must allow only squash merges with the
PR title as the subject and an empty body; default-branch push policy then
checks the resulting commit: GitHub verification, a committer that is GitHub's
web committer or the family owner identity
`10173746+showxu@users.noreply.github.com`, a Conventional Commit subject and
no attribution trailer. It does not restrict the original author. Manual
dispatch checks only the selected commit's verification, committer and message.

## Calling release

Expand Down
56 changes: 12 additions & 44 deletions scripts/check-policy.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
import re
import subprocess
import sys
from urllib.request import Request, urlopen


TYPES = "build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test"
Expand All @@ -17,7 +16,6 @@
r"^\s*(?:Co-authored-by|Signed-off-by|Generated-by|Generated-with|"
r"Made-with|Assisted-by|Powered-by):", re.IGNORECASE | re.MULTILINE
)
DEPENDABOT_SIGNOFF = "Signed-off-by: dependabot[bot] <support@github.com>"
CONFLICT = re.compile(r"^(?:<{7}(?: |$)|={7}$|>{7}(?: |$)|\|{7}(?: |$))")
ZERO = "0" * 40
OWNER_EMAIL = "10173746+showxu@users.noreply.github.com"
Expand Down Expand Up @@ -105,48 +103,16 @@ def push_base(event):
return None


def message_findings(label, message, *, dependabot=False):
def message_findings(label, message):
subject = message.split("\n", 1)[0]
findings = []
if not SUBJECT.fullmatch(subject) or subject != subject.rstrip():
findings.append(f"{label}: expected a Conventional Commit subject ({TYPES})")
if any(ATTRIBUTION.search(line) and not (dependabot and line == DEPENDABOT_SIGNOFF)
for line in message.split("\n")):
if any(ATTRIBUTION.search(line) for line in message.split("\n")):
findings.append(f"{label}: forbidden attribution trailer")
return findings


def authenticated_dependabot_commit(repository, commit):
"""Require GitHub's verified bot identity, not a spoofable Git author field."""
if not re.fullmatch(r"[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+", repository):
raise ValueError("invalid repository for commit authentication")
request = Request(
f"https://api.github.com/repos/{repository}/commits/{commit}",
headers={"Accept": "application/vnd.github+json",
"Authorization": "Bearer " + os.environ["GH_TOKEN"],
"X-GitHub-Api-Version": "2022-11-28"},
method="GET",
)
with urlopen(request, timeout=30) as response:
observed = json.load(response)
if not isinstance(observed, dict):
return False
author = observed.get("author") or {}
committer = observed.get("committer") or {}
details = observed.get("commit") or {}
if not all(isinstance(value, dict) for value in (author, committer, details)):
return False
verification = details.get("verification") or {}
if not isinstance(verification, dict):
return False
# A verified signature by a different contributor does not authenticate
# a claimed bot author. Dependabot commits use GitHub's web-flow signer.
return (observed.get("sha") == commit
and author.get("login") == "dependabot[bot]" and author.get("type") == "Bot"
and committer.get("login") == "web-flow"
and verification.get("verified") is True and verification.get("reason") == "valid")


def added_findings(patch, *, trailing_blank_start=None, allow_terms=frozenset()):
"""Inspect hunk additions, including additions whose text starts with '++'."""
findings = []
Expand Down Expand Up @@ -195,7 +161,7 @@ def source_range(event, event_name):
return base, head


def check(event, event_name, *, allow_terms=frozenset(), dependabot_exception=False, verify_commits=False):
def check(event, event_name, *, allow_terms=frozenset(), verify_commits=False):
if event_name == "push" and event.get("deleted"):
print("::notice::Policy skipped branch deletion push")
return []
Expand All @@ -219,23 +185,25 @@ def check(event, event_name, *, allow_terms=frozenset(), dependabot_exception=Fa
comparison = base
else:
comparison = base
commits = [head] if base is None else git("rev-list", "--reverse", base + ".." + head).splitlines()
if event_name == "pull_request":
# Members squash-merge with the PR title as the subject and an empty
# body, so pull-request commits never reach the default branch. The
# default-branch push checks the squash commit's message and identity.
commits = []
else:
commits = [head] if base is None else git("rev-list", "--reverse", base + ".." + head).splitlines()
if event_name == "push":
if base is None:
print(f"::notice::Policy push: validating only {head}; previous default-branch tip unavailable or absent")
else:
print(f"::notice::Policy push: validating {len(commits)} commits in {base}..{head}")
for commit in commits:
# Preserve carriage returns: newline normalization would broaden the
# exact signoff exception to differently spelled trailer lines.
message = subprocess.check_output(
["git", "show", "-s", "--format=%B", commit], stdin=subprocess.DEVNULL
).decode("utf-8", errors="replace")
if verify_commits:
findings.extend(commit_findings(commit, api_commit(event["repository"]["full_name"], commit)))
dependabot = (dependabot_exception and DEPENDABOT_SIGNOFF in message.split("\n")
and authenticated_dependabot_commit(event["repository"]["full_name"], commit))
findings.extend(message_findings(commit, message, dependabot=dependabot))
findings.extend(message_findings(commit, message))
if comparison is None:
# Dispatch supplies a selected commit but no new-change range.
return findings
Expand Down Expand Up @@ -267,7 +235,7 @@ def main():
event = json.loads(Path(os.environ["GITHUB_EVENT_PATH"]).read_text())
findings = check(event, os.environ["GITHUB_EVENT_NAME"],
allow_terms={term.strip().lower() for term in os.environ.get("ALLOW_TERMS", "").splitlines() if term.strip()},
dependabot_exception=os.environ.get("DEPENDABOT_EXCEPTION") == "true", verify_commits=True)
verify_commits=True)
# Avoid interpreting source-controlled text as workflow commands.
for finding in findings:
print("FAIL " + finding.replace("\n", " | "))
Expand Down
Loading
Loading