diff --git a/cli/contributing/update/README.md b/cli/contributing/update/README.md index 0b933bf733..1950be4b8e 100644 --- a/cli/contributing/update/README.md +++ b/cli/contributing/update/README.md @@ -133,3 +133,14 @@ fails `tests/lint/ansible/services/test_version_keys.py`. Run `python -m cli.contributing.update.source --dry-run` to list pending bumps; the `update-version-sources` job of `.github/workflows/cron-update.yml` opens the PRs, and `tests/external/update/source/` warns about them. + +## App credentials + +`python -m cli.contributing.update.apps --repo infinito-nexus/core --updater-slug infinito-nexus-updater --translate-slug infinito-nexus-translator` +walks the operator through the browser steps and stores the results with `gh`: +it creates the `updater` environment restricted to `main` when it is missing, +stores a freshly generated updater key there, waits until the older keys are +deleted, prefills the form for the separate translation App and stores its +key as a repository secret. Keys go to `gh` on stdin and are never printed; +`--skip-updater` resumes after the updater step. See +[secrets.md](../../../docs/contributing/tools/github/actions/secrets.md). diff --git a/cli/contributing/update/apps/__init__.py b/cli/contributing/update/apps/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/cli/contributing/update/apps/__main__.py b/cli/contributing/update/apps/__main__.py new file mode 100755 index 0000000000..d9230e07c8 --- /dev/null +++ b/cli/contributing/update/apps/__main__.py @@ -0,0 +1,271 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import re +import subprocess +import sys +from pathlib import Path +from typing import TYPE_CHECKING +from urllib.parse import urlencode + +if TYPE_CHECKING: + from collections.abc import Callable, Sequence + + Gh = Callable[[Sequence[str], bytes | None], bytes] + Ask = Callable[[str], str] + Say = Callable[[str], None] + +GH_TIMEOUT_SECONDS = 120 +UPDATER_ENVIRONMENT = "updater" +UPDATER_BRANCH = "main" +UPDATER_SECRETS = ("BOT_APP_CLIENT_ID", "BOT_APP_PRIVATE_KEY") +TRANSLATE_SECRETS = ("TRANSLATE_APP_CLIENT_ID", "TRANSLATE_APP_PRIVATE_KEY") +_CLIENT_ID = re.compile(r"Iv[0-9A-Za-z.]{8,}") + + +def run_gh(args: Sequence[str], stdin: bytes | None) -> bytes: + return subprocess.run( + ["gh", *args], + input=stdin, + capture_output=True, + check=True, + timeout=GH_TIMEOUT_SECONDS, + ).stdout + + +def lines(out: bytes) -> list[str]: + return [line for line in out.decode("utf-8").splitlines() if line.strip()] + + +def ensure_environment(gh: Gh, repo: str, say: Say) -> None: + """ + Args: + gh: runs ``gh`` with the given arguments and stdin, returns its stdout. + repo: ``owner/name``. + say: prints one line to the operator. + + Raises: + SystemExit: the environment exists with other deployment branches. + """ + path = f"repos/{repo}/environments/{UPDATER_ENVIRONMENT}" + names = lines( + gh(["api", f"repos/{repo}/environments", "--jq", ".environments[].name"], None) + ) + if UPDATER_ENVIRONMENT not in names: + gh( + [ + "api", + "--method", + "PUT", + path, + "-F", + "deployment_branch_policy[protected_branches]=false", + "-F", + "deployment_branch_policy[custom_branch_policies]=true", + ], + None, + ) + gh( + [ + "api", + "--method", + "POST", + f"{path}/deployment-branch-policies", + "-f", + f"name={UPDATER_BRANCH}", + "-f", + "type=branch", + ], + None, + ) + say( + f"created environment {UPDATER_ENVIRONMENT}, restricted to {UPDATER_BRANCH}" + ) + return + policies = lines( + gh( + [ + "api", + f"{path}/deployment-branch-policies", + "--jq", + ".branch_policies[].name", + ], + None, + ) + ) + if policies != [UPDATER_BRANCH]: + raise SystemExit( + f"environment {UPDATER_ENVIRONMENT} allows {policies or 'every branch'}, " + f"not only {UPDATER_BRANCH}: fix it under https://github.com/{repo}/settings/environments" + ) + say(f"environment {UPDATER_ENVIRONMENT} exists, restricted to {UPDATER_BRANCH}") + + +def read_private_key(path: Path) -> bytes: + """ + Args: + path: the file the App's settings page downloaded. + + Returns: + the file's bytes, never printed. + + Raises: + SystemExit: the file is missing or holds no PEM private key. + """ + if not path.is_file(): + raise SystemExit(f"no file at {path}") + data = path.read_bytes() # nocheck: cache-read + if b"-----BEGIN" not in data or b"PRIVATE KEY-----" not in data: + raise SystemExit(f"{path} holds no PEM private key") + return data + + +def ask_client_id(ask: Ask, app: str) -> str: + value = ask(f"Client ID of {app} (Iv..., on the App's General page): ").strip() + if not _CLIENT_ID.fullmatch(value): + raise SystemExit(f"{value!r} is no GitHub App Client ID; it starts with Iv") + return value + + +def confirm(ask: Ask, question: str) -> None: + if ask(f"{question} [y/N] ").strip().lower() != "y": + raise SystemExit("stopped; run again once that step is done") + + +def set_secret( + gh: Gh, repo: str, name: str, value: bytes, environment: str | None +) -> None: + """ + Args: + gh: runs ``gh`` with the given arguments and stdin. + repo: ``owner/name``. + name: the secret's name. + value: the secret's bytes. + environment: the environment holding it, ``None`` for a repository secret. + """ + scope = ["--env", environment] if environment is not None else [] + gh(["secret", "set", name, "--repo", repo, *scope], value) + + +def app_page(org: str, slug: str) -> str: + return f"https://github.com/organizations/{org}/settings/apps/{slug}" + + +def new_app_url(org: str, repo: str, name: str) -> str: + query = urlencode( + { + "name": name, + "url": f"https://github.com/{repo}", + "public": "false", + "webhook_active": "false", + "contents": "write", + "pull_requests": "write", + } + ) + return f"https://github.com/organizations/{org}/settings/apps/new?{query}" + + +def rotate_updater_key(gh: Gh, repo: str, slug: str, ask: Ask, say: Say) -> Path: + org = repo.split("/", maxsplit=1)[0] + say(f"\n1. Updater App: open {app_page(org, slug)}") + say( + " Under 'Private keys' press 'Generate a private key'; the browser downloads a .pem." + ) + client_id = ask_client_id(ask, slug) + pem = Path(ask("Path of the downloaded .pem: ").strip()).expanduser() + key = read_private_key(pem) + set_secret(gh, repo, UPDATER_SECRETS[0], client_id.encode(), UPDATER_ENVIRONMENT) + set_secret(gh, repo, UPDATER_SECRETS[1], key, UPDATER_ENVIRONMENT) + say(f" stored {', '.join(UPDATER_SECRETS)} in environment {UPDATER_ENVIRONMENT}") + say( + f" Now delete every OLDER key on {app_page(org, slug)}; keep only the one just made." + ) + confirm(ask, " Only the new updater key is left?") + return pem + + +def create_translate_app(gh: Gh, repo: str, slug: str, ask: Ask, say: Say) -> Path: + org = repo.split("/", maxsplit=1)[0] + say(f"\n2. Translation App: open {new_app_url(org, repo, slug)}") + say( + " The form is prefilled (no webhook, Contents and Pull requests write); press 'Create GitHub App'." + ) + say(" Then 'Generate a private key', and install it on the core repository only:") + say(f" https://github.com/apps/{slug}/installations/new") + confirm(ask, f" {slug} is created and installed on {repo} alone?") + client_id = ask_client_id(ask, slug) + pem = Path(ask("Path of the downloaded .pem: ").strip()).expanduser() + key = read_private_key(pem) + set_secret(gh, repo, TRANSLATE_SECRETS[0], client_id.encode(), None) + set_secret(gh, repo, TRANSLATE_SECRETS[1], key, None) + say( + f" stored {', '.join(TRANSLATE_SECRETS)} as repository secrets; never add {slug} to a bypass list" + ) + return pem + + +def drop_repository_copies(gh: Gh, repo: str, say: Say) -> None: + names = lines( + gh( + ["secret", "list", "--repo", repo, "--json", "name", "--jq", ".[].name"], + None, + ) + ) + for name in UPDATER_SECRETS: + if name in names: + gh(["secret", "delete", name, "--repo", repo], None) + say(f" deleted repository secret {name}; pull_request runs could read it") + + +def main(argv: Sequence[str] | None, gh: Gh, ask: Ask, say: Say) -> int: + """ + Args: + argv: command-line arguments; ``None`` reads ``sys.argv``. + gh: runs ``gh`` with the given arguments and stdin, returns its stdout. + ask: reads one answer from the operator. + say: prints one line to the operator. + + Returns: + 0 once every secret is in place. + """ + parser = argparse.ArgumentParser( + description=( + "Rotate the updater App key into the main-only updater environment and " + "set up the separate translation App, through gh and the browser." + ) + ) + parser.add_argument("--repo", required=True, help="owner/name") + parser.add_argument("--updater-slug", required=True, help="Slug of the updater App") + parser.add_argument( + "--translate-slug", required=True, help="Slug for the translation App" + ) + parser.add_argument( + "--skip-updater", action="store_true", help="Updater key already rotated" + ) + args = parser.parse_args(argv) + + gh(["auth", "status"], None) + ensure_environment(gh, args.repo, say) + pems = [] + if not args.skip_updater: + pems.append(rotate_updater_key(gh, args.repo, args.updater_slug, ask, say)) + pems.append(create_translate_app(gh, args.repo, args.translate_slug, ask, say)) + say("\n3. Repository copies of the updater key") + drop_repository_copies(gh, args.repo, say) + say("\n4. Downloaded keys") + for pem in pems: + if ask(f" Delete {pem}? [y/N] ").strip().lower() == "y": + pem.unlink() + say(f" deleted {pem}") + say( + "\nDone. Merge the pull request that moves the workflows to these secrets next;" + ) + say( + "the merge App joins the Main bypass list only after its prerequisites in secrets.md hold." + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main(None, run_gh, input, print)) diff --git a/docs/contributing/tools/github/actions/secrets.md b/docs/contributing/tools/github/actions/secrets.md index a15f42158d..8bf830b217 100644 --- a/docs/contributing/tools/github/actions/secrets.md +++ b/docs/contributing/tools/github/actions/secrets.md @@ -93,6 +93,8 @@ A classic personal access token MAY be used as a fallback for unrelated automati ### How to hand the credentials to CI 📥 +`python -m cli.contributing.update.apps --repo infinito-nexus/core --updater-slug infinito-nexus-updater --translate-slug infinito-nexus-translator` walks through the steps below and the [translation App](#translate_app_client_id-and-translate_app_private_key-) through `gh`, passing every key on stdin. Done by hand: + 1. Open the repository on GitHub. 2. Go to **Settings → Environments → New environment**, name it `updater`, and under **Deployment branches and tags** choose **Selected branches and tags** with the single rule `main`. 3. Under **Environment secrets**, add `BOT_APP_CLIENT_ID` with the App's Client ID (shown on the App's General page under **About**, in the `Iv…` format, *not* the numeric App ID). diff --git a/tests/unit/python/cli/contributing/update/apps/__init__.py b/tests/unit/python/cli/contributing/update/apps/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/tests/unit/python/cli/contributing/update/apps/test_main.py b/tests/unit/python/cli/contributing/update/apps/test_main.py new file mode 100644 index 0000000000..7acd3b6aea --- /dev/null +++ b/tests/unit/python/cli/contributing/update/apps/test_main.py @@ -0,0 +1,144 @@ +from __future__ import annotations + +import tempfile +import unittest +from pathlib import Path + +import cli.contributing.update.apps.__main__ as apps + +REPO = "infinito-nexus/core" +KEY = b"-----BEGIN RSA PRIVATE KEY-----\nabc\n-----END RSA PRIVATE KEY-----\n" +UPDATER_ID = "Iv23liUpdater01" +TRANSLATE_ID = "Iv23liTranslate1" + + +class FakeGh: + def __init__(self, environments: str, policies: str, repo_secrets: str) -> None: + self.calls: list[tuple[list[str], bytes | None]] = [] + self.outputs = { + f"repos/{REPO}/environments": environments, + f"repos/{REPO}/environments/updater/deployment-branch-policies": policies, + } + self.repo_secrets = repo_secrets + + def __call__(self, args, stdin): + self.calls.append((list(args), stdin)) + if args[:2] == ["secret", "list"]: + return self.repo_secrets.encode() + if args[0] == "api" and len(args) > 1: + return self.outputs.get(args[1], "").encode() + return b"" + + def secrets_set(self): + return [ + (a[2], a[a.index("--env") + 1] if "--env" in a else None, s) + for a, s in self.calls + if a[:2] == ["secret", "set"] + ] + + +class AppsMainTest(unittest.TestCase): + def setUp(self) -> None: + holder = tempfile.TemporaryDirectory() + self.addCleanup(holder.cleanup) + self.tmp = Path(holder.name) + self.updater_pem = self.tmp / "updater.pem" + self.translate_pem = self.tmp / "translate.pem" + self.updater_pem.write_bytes(KEY) + self.translate_pem.write_bytes(KEY) + self.said: list[str] = [] + + def run_main(self, gh, answers, *extra): + replies = iter(answers) + return apps.main( + [ + "--repo", + REPO, + "--updater-slug", + "infinito-nexus-updater", + "--translate-slug", + "infinito-nexus-translator", + *extra, + ], + gh=gh, + ask=lambda _prompt: next(replies), + say=self.said.append, + ) + + def full_answers(self): + return [ + UPDATER_ID, + str(self.updater_pem), + "y", + "y", + TRANSLATE_ID, + str(self.translate_pem), + "y", + "y", + ] + + def test_keys_reach_gh_through_stdin_only(self) -> None: + gh = FakeGh("updater\n", "main\n", "") + self.assertEqual(self.run_main(gh, self.full_answers()), 0) + self.assertEqual( + gh.secrets_set(), + [ + ("BOT_APP_CLIENT_ID", "updater", UPDATER_ID.encode()), + ("BOT_APP_PRIVATE_KEY", "updater", KEY), + ("TRANSLATE_APP_CLIENT_ID", None, TRANSLATE_ID.encode()), + ("TRANSLATE_APP_PRIVATE_KEY", None, KEY), + ], + ) + for args, _stdin in gh.calls: + self.assertNotIn(KEY.decode(), " ".join(args)) + self.assertNotIn(KEY.decode(), "\n".join(self.said)) + self.assertFalse(self.updater_pem.exists()) + self.assertFalse(self.translate_pem.exists()) + + def test_missing_environment_is_created_main_only(self) -> None: + gh = FakeGh("auto-merge\n", "", "") + self.run_main(gh, self.full_answers()) + api = [a for a, _ in gh.calls if a[0] == "api" and "--method" in a] + self.assertEqual(api[0][2:4], ["PUT", f"repos/{REPO}/environments/updater"]) + self.assertIn("name=main", api[1]) + + def test_environment_open_to_other_branches_stops_before_any_secret(self) -> None: + gh = FakeGh("updater\n", "main\nfeature/*\n", "") + with self.assertRaises(SystemExit): + self.run_main(gh, self.full_answers()) + self.assertEqual(gh.secrets_set(), []) + + def test_file_without_private_key_stops_before_any_secret(self) -> None: + self.updater_pem.write_bytes(b"not a key") + gh = FakeGh("updater\n", "main\n", "") + with self.assertRaises(SystemExit): + self.run_main(gh, self.full_answers()) + self.assertEqual(gh.secrets_set(), []) + + def test_unconfirmed_old_key_deletion_stops_before_translation(self) -> None: + gh = FakeGh("updater\n", "main\n", "") + answers = [UPDATER_ID, str(self.updater_pem), "n"] + with self.assertRaises(SystemExit): + self.run_main(gh, answers) + self.assertEqual( + [n for n, _, _ in gh.secrets_set()], + ["BOT_APP_CLIENT_ID", "BOT_APP_PRIVATE_KEY"], + ) + + def test_repository_copies_of_the_updater_key_are_deleted(self) -> None: + gh = FakeGh("updater\n", "main\n", "BOT_APP_PRIVATE_KEY\nDOCKERHUB_TOKEN\n") + answers = ["y", TRANSLATE_ID, str(self.translate_pem), "n"] + self.run_main(gh, answers, "--skip-updater") + deleted = [a[2] for a, _ in gh.calls if a[:2] == ["secret", "delete"]] + self.assertEqual(deleted, ["BOT_APP_PRIVATE_KEY"]) + self.assertTrue(self.translate_pem.exists()) + + def test_client_id_must_be_an_app_client_id(self) -> None: + gh = FakeGh("updater\n", "main\n", "") + with self.assertRaises(SystemExit): + self.run_main(gh, ["12345", str(self.updater_pem)]) + self.assertEqual(gh.secrets_set(), []) + + +if __name__ == "__main__": + unittest.main()