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
84 changes: 84 additions & 0 deletions .github/workflows/authorize-privileged-workflow.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
name: Authorize privileged workflow

on:
workflow_call:
outputs:
attempt:
description: Run attempt that passed authorization
value: ${{ jobs.authorize.outputs.attempt }}

permissions:
actions: read

jobs:
authorize:
runs-on: ubuntu-latest
outputs:
attempt: ${{ steps.authorize.outputs.attempt }}
steps:
- name: Check repository, account and current permissions
id: authorize
env:
GH_TOKEN: ${{ github.token }}
ACTOR_ID: ${{ github.actor_id }}
COMMENT_AUTHOR_ID: ${{ github.event.comment.user.id }}
run: |
set -euo pipefail

if [[ "$GITHUB_REPOSITORY" != pingcap/docs || "$GITHUB_REF" != refs/heads/master ]]; then
echo "::error::Privileged workflows require pingcap/docs master."
exit 1
fi

# Scheduled first attempts do not have a human requester.
if [[ "$GITHUB_EVENT_NAME" == schedule && "$GITHUB_RUN_ATTEMPT" == 1 ]]; then
echo "attempt=$GITHUB_RUN_ATTEMPT" >> "$GITHUB_OUTPUT"
exit 0
fi

check_permission() {
local login="$1" account_id="$2"
# GitHub account IDs for lilin90, qiancai, and seominjea1942.
case "$account_id" in
30922556|79440533|47792576) ;;
*)
echo "::error::The account is outside the privileged workflow allowlist."
return 1
;;
esac

# Verify the login still belongs to that account and still has write access.
gh api "repos/${GITHUB_REPOSITORY}/collaborators/${login}/permission" |
jq -e --arg id "$account_id" '
(.user.id | tostring) == $id and
(.permission == "write" or .permission == "maintain" or .permission == "admin")
' > /dev/null
}

case "$GITHUB_EVENT_NAME" in
issue_comment)
if [[ "$COMMENT_AUTHOR_ID" != "$ACTOR_ID" ]]; then
echo "::error::The PR comment author must match the original actor."
exit 1
fi
check_permission "$GITHUB_ACTOR" "$ACTOR_ID"
;;
workflow_dispatch|repository_dispatch)
check_permission "$GITHUB_ACTOR" "$ACTOR_ID"
;;
schedule)
;;
*)
exit 1
;;
esac

if [[ "$GITHUB_RUN_ATTEMPT" != 1 ]]; then
# The workflow context exposes only the rerun initiator's login.
attempt=$(gh api "repos/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}/attempts/${GITHUB_RUN_ATTEMPT}")
login=$(jq -er '.triggering_actor.login | select(type == "string" and length > 0)' <<< "$attempt")
account_id=$(jq -er '.triggering_actor.id | select(type == "number")' <<< "$attempt")
check_permission "$login" "$account_id"
fi

echo "attempt=$GITHUB_RUN_ATTEMPT" >> "$GITHUB_OUTPUT"
1 change: 1 addition & 0 deletions .github/workflows/ci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ jobs:
run: |
python3 -m pip install --disable-pip-version-check --no-deps PyYAML==6.0.3
python3 scripts/test-media-workflow.py
python3 scripts/test-privileged-workflow-actors.py

internal-links-files:
runs-on: ubuntu-latest
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/keywords.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ permissions:

jobs:
check-keywords:
if: github.repository == 'pingcap/docs'
if: github.repository == 'pingcap/docs' && github.ref == 'refs/heads/master'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
Expand Down
9 changes: 8 additions & 1 deletion .github/workflows/link.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,15 @@ permissions:
issues: write

jobs:
authorize:
uses: ./.github/workflows/authorize-privileged-workflow.yml
permissions:
actions: read

linkChecker:
if: github.repository == 'pingcap/docs'
needs: authorize
# A partial rerun must pass authorization for the current attempt.
if: needs.authorize.outputs.attempt == github.run_attempt
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6
Expand Down
12 changes: 8 additions & 4 deletions .github/workflows/sync-doc-pr-zh-to-en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,16 @@ env:
PRODUCT: TiDB

jobs:
authorize:
uses: ./.github/workflows/authorize-privileged-workflow.yml
permissions:
actions: read

sync-docs:
runs-on: ubuntu-latest
if: >
github.repository == 'pingcap/docs' &&
contains(fromJson('["lilin90","qiancai","seominjea1942"]'), github.actor) &&
contains(fromJson('["lilin90","qiancai","seominjea1942"]'), github.triggering_actor)
needs: authorize
# A partial rerun must pass authorization for the current attempt.
if: needs.authorize.outputs.attempt == github.run_attempt

steps:
- name: Checkout current repository
Expand Down
172 changes: 172 additions & 0 deletions scripts/test-privileged-workflow-actors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
"""Test actor guards on write-privileged workflows that consume secrets."""

import os
import re
from pathlib import Path
import subprocess
from tempfile import TemporaryDirectory
import unittest

import yaml


ROOT = Path(__file__).resolve().parents[1]


def load_workflow(workflow_name):
"""Load a workflow without evaluating any GitHub expressions."""
workflow_path = ROOT / ".github/workflows" / workflow_name
return yaml.safe_load(workflow_path.read_text())


def load_job(workflow_name, job_name):
"""Load a job definition from a workflow."""
return load_workflow(workflow_name)["jobs"][job_name]


class PrivilegedWorkflowActorTest(unittest.TestCase):
def test_shared_authorization_allowlists_exactly_the_expected_accounts(self):
step = load_job("authorize-privileged-workflow.yml", "authorize")["steps"][0]
allowed_ids = re.findall(r"^\s+([0-9]+(?:\|[0-9]+)*)\) ;;$", step["run"], re.MULTILINE)
self.assertEqual(len(allowed_ids), 1)
self.assertCountEqual(allowed_ids[0].split("|"), ["30922556", "79440533", "47792576"])

def test_gate_checks_current_permission_and_rerun_initiator(self):
gate = load_job("authorize-privileged-workflow.yml", "authorize")["steps"][0]
mock_api = """
gh() {
case "$2" in
*/attempts/2)
printf '{"triggering_actor":{"login":"rerunner","id":%s}}' "$RERUN_ID"
;;
*/collaborators/renamed/permission)
printf '{"user":{"id":%s},"permission":"%s"}' "$API_ID" "$ROLE"
;;
*/collaborators/rerunner/permission)
printf '{"user":{"id":%s},"permission":"%s"}' "$RERUN_ID" "$RERUN_ROLE"
;;
*) return 1 ;;
esac
}
"""
cases = (
("authorized renamed commenter", {}, True),
("authorized manual dispatch", {"GITHUB_EVENT_NAME": "workflow_dispatch"}, True),
("authorized repository dispatch", {"GITHUB_EVENT_NAME": "repository_dispatch"}, True),
("unauthorized manual dispatch", {
"GITHUB_EVENT_NAME": "workflow_dispatch", "ACTOR_ID": "42",
}, False),
("unauthorized repository dispatch", {
"GITHUB_EVENT_NAME": "repository_dispatch", "ACTOR_ID": "42",
}, False),
("read-only repository dispatcher", {
"GITHUB_EVENT_NAME": "repository_dispatch", "ROLE": "read",
}, False),
("fork manual dispatch", {
"GITHUB_EVENT_NAME": "workflow_dispatch", "GITHUB_REPOSITORY": "fork/docs-cn",
}, False),
("fork repository dispatch", {
"GITHUB_EVENT_NAME": "repository_dispatch", "GITHUB_REPOSITORY": "fork/docs-cn",
}, False),
("fork scheduled run", {
"GITHUB_EVENT_NAME": "schedule", "GITHUB_REPOSITORY": "fork/docs-cn",
}, False),
("public commenter", {"ACTOR_ID": "42", "COMMENT_AUTHOR_ID": "42"}, False),
("read-only allowlisted account", {
"ACTOR_ID": "47792576", "COMMENT_AUTHOR_ID": "47792576",
"API_ID": "47792576", "ROLE": "read",
}, False),
("reassigned login", {"API_ID": "42"}, False),
("different comment author", {"COMMENT_AUTHOR_ID": "42"}, False),
("non-master dispatch", {
"GITHUB_EVENT_NAME": "workflow_dispatch", "GITHUB_REF": "refs/heads/test",
}, False),
("first scheduled run", {"GITHUB_EVENT_NAME": "schedule", "ACTOR_ID": "42"}, True),
("non-master scheduled run", {
"GITHUB_EVENT_NAME": "schedule", "GITHUB_REF": "refs/heads/test",
}, False),
("non-master repository dispatch", {
"GITHUB_EVENT_NAME": "repository_dispatch", "GITHUB_REF": "refs/heads/test",
}, False),
("tag dispatch", {
"GITHUB_EVENT_NAME": "workflow_dispatch", "GITHUB_REF": "refs/tags/master",
}, False),
("unexpected event", {"GITHUB_EVENT_NAME": "push"}, False),
("authorized rerun", {"GITHUB_RUN_ATTEMPT": "2"}, True),
("unauthorized rerun", {"GITHUB_RUN_ATTEMPT": "2", "RERUN_ROLE": "read"}, False),
("original actor loses access", {"GITHUB_RUN_ATTEMPT": "2", "ROLE": "read"}, False),
("unauthorized scheduled rerun", {
"GITHUB_EVENT_NAME": "schedule", "GITHUB_RUN_ATTEMPT": "2", "RERUN_ID": "42",
}, False),
("unauthorized repository dispatch rerun", {
"GITHUB_EVENT_NAME": "repository_dispatch", "GITHUB_RUN_ATTEMPT": "2",
"RERUN_ID": "42",
}, False),
)
with TemporaryDirectory() as directory:
output = Path(directory) / "output"
for name, overrides, allowed in cases:
with self.subTest(case=name):
output.write_text("")
env = {
**os.environ,
"GITHUB_REPOSITORY": "pingcap/docs",
"GITHUB_REF": "refs/heads/master",
"GITHUB_EVENT_NAME": "issue_comment",
"GITHUB_ACTOR": "renamed",
"GITHUB_RUN_ID": "123",
"GITHUB_RUN_ATTEMPT": "1",
"GITHUB_OUTPUT": str(output),
"ACTOR_ID": "30922556",
"COMMENT_AUTHOR_ID": "30922556",
"API_ID": "30922556",
"ROLE": "admin",
"RERUN_ID": "79440533",
"RERUN_ROLE": "write",
**overrides,
}
result = subprocess.run(
["bash", "-c", mock_api + gate["run"]],
env=env,
capture_output=True,
text=True,
timeout=5,
)
self.assertEqual(result.returncode == 0, allowed, result.stderr)
expected = f"attempt={env['GITHUB_RUN_ATTEMPT']}\n" if allowed else ""
self.assertEqual(output.read_text(), expected)

def test_privileged_jobs_require_the_shared_authorization_workflow(self):
for filename, job_name in (
("sync-doc-pr-zh-to-en.yml", "sync-docs"),
("link.yaml", "linkChecker"),
):
with self.subTest(workflow=filename):
workflow = load_workflow(filename)
gate = workflow["jobs"]["authorize"]
self.assertEqual(
gate["uses"],
"./.github/workflows/authorize-privileged-workflow.yml",
)
self.assertEqual(gate["permissions"], {"actions": "read"})
self.assertNotIn("secrets", gate)
self.assertEqual(workflow["jobs"][job_name]["needs"], "authorize")
self.assertEqual(
workflow["jobs"][job_name]["if"],
"needs.authorize.outputs.attempt == github.run_attempt",
)

def test_keywords_requires_upstream_master(self):
job = load_job("keywords.yaml", "check-keywords")
self.assertEqual(
job["if"],
"github.repository == 'pingcap/docs' && github.ref == 'refs/heads/master'",
)

def test_ci_uses_read_only_repository_permissions(self):
permissions = load_workflow("ci.yaml")["permissions"]
self.assertEqual(permissions, {"contents": "read"})


if __name__ == "__main__":
unittest.main()
Loading