diff --git a/cli/contributing/update/README.md b/cli/contributing/update/README.md index 1950be4b8e..7c508a8e15 100644 --- a/cli/contributing/update/README.md +++ b/cli/contributing/update/README.md @@ -136,8 +136,10 @@ 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`: +`python -m cli.contributing.update.apps --repo infinito-nexus/core --updater-slug infinito-nexus-updater --translate-slug infinito-nexus-translator --downloads ~/Downloads` +walks the operator through the browser steps and stores the results with `gh`. +It names each menu entry to click, waits for Enter after every browser step and +offers the `.pem` that appeared in `--downloads` during that step: 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 diff --git a/cli/contributing/update/apps/__main__.py b/cli/contributing/update/apps/__main__.py index e070212389..9e1d6e8ab8 100755 --- a/cli/contributing/update/apps/__main__.py +++ b/cli/contributing/update/apps/__main__.py @@ -5,6 +5,7 @@ import argparse import re import subprocess import sys +import time from pathlib import Path from typing import TYPE_CHECKING from urllib.parse import urlencode @@ -121,8 +122,11 @@ def read_private_key(path: Path) -> bytes: 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() +def ask_client_id(ask: Ask, say: Say, app: str) -> str: + say( + f" In the left menu of {app} open 'General'; under 'About' copy the 'Client ID'." + ) + value = ask(" Client ID (starts with Iv): ").strip() if not _CLIENT_ID.fullmatch(value): raise SystemExit(f"{value!r} is no GitHub App Client ID; it starts with Iv") return value @@ -133,6 +137,43 @@ def confirm(ask: Ask, question: str) -> None: raise SystemExit("stopped; run again once that step is done") +def wait(ask: Ask, what: str) -> None: + ask(f" {what} Press Enter when done.") + + +def newest_pem(downloads: Path, since: float) -> Path | None: + """ + Args: + downloads: the directory the browser saves into. + since: epoch seconds; older files are ignored. + + Returns: + the most recently modified ``*.pem`` saved at or after *since*, or + ``None`` when there is none. + """ + fresh = [p for p in downloads.glob("*.pem") if p.stat().st_mtime >= since] + return max(fresh, key=lambda p: p.stat().st_mtime) if fresh else None + + +def ask_pem(ask: Ask, say: Say, downloads: Path | None, since: float) -> Path: + found = newest_pem(downloads, since) if downloads is not None else None + if found is None: + return Path(ask(" Path of the downloaded .pem: ").strip()).expanduser() + say(f" Found the new key {found}") + typed = ask(" Press Enter to use it, or type another path: ").strip() + return Path(typed).expanduser() if typed else found + + +def generate_key(ask: Ask, say: Say, page: str) -> float: + since = time.time() + say(f" Open {page}") + say( + " In the left menu open 'Credentials', tab 'Key pairs', press 'Generate a private key'." + ) + wait(ask, "The browser downloads a .pem file.") + return since + + def set_secret( gh: Gh, repo: str, name: str, value: bytes, environment: str | None ) -> None: @@ -166,37 +207,45 @@ def new_app_url(org: str, repo: str, name: str) -> str: 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: +def rotate_updater_key( + gh: Gh, repo: str, slug: str, downloads: Path | None, 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() + say(f"\nStep 1 of 4: new key for the updater App {slug}") + since = generate_key(ask, say, app_page(org, slug)) + pem = ask_pem(ask, say, downloads, since) key = read_private_key(pem) + client_id = ask_client_id(ask, say, slug) set_secret(gh, repo, UPDATER_NAMES[0], client_id.encode(), UPDATER_ENVIRONMENT) set_secret(gh, repo, UPDATER_NAMES[1], key, UPDATER_ENVIRONMENT) say(f" stored {', '.join(UPDATER_NAMES)} in environment {UPDATER_ENVIRONMENT}") - say( - f" Now delete every OLDER key on {app_page(org, slug)}; keep only the one just made." - ) + say(" Back in 'Credentials', tab 'Key pairs': delete every key except the newest") + say(" one (the one created just now, see its date).") 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: +def create_translate_app( + gh: Gh, repo: str, slug: str, downloads: Path | None, ask: Ask, say: Say +) -> Path: org = repo.split("/", maxsplit=1)[0] - say(f"\n2. Translation App: open {new_app_url(org, repo, slug)}") + say(f"\nStep 2 of 4: create the translation App {slug}") + say(f" Open {new_app_url(org, repo, slug)}") say( - " The form is prefilled (no webhook, Contents and Pull requests write); press 'Create GitHub App'." + " The form is prefilled: no webhook, Contents and Pull requests read and write." ) - 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() + wait(ask, "Scroll down and press 'Create GitHub App'.") + since = generate_key(ask, say, app_page(org, slug)) + pem = ask_pem(ask, say, downloads, since) key = read_private_key(pem) + client_id = ask_client_id(ask, say, slug) + say( + " In the left menu open 'Install App', press 'Install' next to the organization," + ) + say( + f" choose 'Only select repositories', pick {repo.split('/', maxsplit=1)[1]}, press 'Install'." + ) + confirm(ask, f" {slug} is installed on {repo} alone?") set_secret(gh, repo, TRANSLATE_NAMES[0], client_id.encode(), None) set_secret(gh, repo, TRANSLATE_NAMES[1], key, None) say( @@ -243,17 +292,30 @@ def main(argv: Sequence[str] | None, gh: Gh, ask: Ask, say: Say) -> int: parser.add_argument( "--skip-updater", action="store_true", help="Updater key already rotated" ) + parser.add_argument( + "--downloads", + type=Path, + help="Directory the browser saves into; the newest .pem there is offered", + ) 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") + pems.append( + rotate_updater_key( + gh, args.repo, args.updater_slug, args.downloads, ask, say + ) + ) + pems.append( + create_translate_app( + gh, args.repo, args.translate_slug, args.downloads, ask, say + ) + ) + say("\nStep 3 of 4: repository copies of the updater key") drop_repository_copies(gh, args.repo, say) - say("\n4. Downloaded keys") + say("\nStep 4 of 4: downloaded keys") for pem in pems: if ask(f" Delete {pem}? [y/N] ").strip().lower() == "y": pem.unlink() diff --git a/docs/contributing/tools/github/actions/secrets.md b/docs/contributing/tools/github/actions/secrets.md index 8bf830b217..a96e3396d1 100644 --- a/docs/contributing/tools/github/actions/secrets.md +++ b/docs/contributing/tools/github/actions/secrets.md @@ -93,7 +93,7 @@ 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: +`python -m cli.contributing.update.apps --repo infinito-nexus/core --updater-slug infinito-nexus-updater --translate-slug infinito-nexus-translator --downloads ~/Downloads` 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`. diff --git a/tests/unit/python/cli/contributing/update/apps/test_main.py b/tests/unit/python/cli/contributing/update/apps/test_main.py index 7acd3b6aea..130521f468 100644 --- a/tests/unit/python/cli/contributing/update/apps/test_main.py +++ b/tests/unit/python/cli/contributing/update/apps/test_main.py @@ -1,5 +1,6 @@ from __future__ import annotations +import os import tempfile import unittest from pathlib import Path @@ -67,12 +68,15 @@ class AppsMainTest(unittest.TestCase): def full_answers(self): return [ - UPDATER_ID, + "", str(self.updater_pem), + UPDATER_ID, "y", - "y", - TRANSLATE_ID, + "", + "", str(self.translate_pem), + TRANSLATE_ID, + "y", "y", "y", ] @@ -117,7 +121,7 @@ class AppsMainTest(unittest.TestCase): 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"] + answers = ["", str(self.updater_pem), UPDATER_ID, "n"] with self.assertRaises(SystemExit): self.run_main(gh, answers) self.assertEqual( @@ -127,7 +131,7 @@ class AppsMainTest(unittest.TestCase): 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"] + answers = ["", "", str(self.translate_pem), TRANSLATE_ID, "y", "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"]) @@ -136,9 +140,45 @@ class AppsMainTest(unittest.TestCase): 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.run_main(gh, ["", str(self.updater_pem), "12345"]) self.assertEqual(gh.secrets_set(), []) + def test_downloads_offers_only_the_key_generated_during_the_step(self) -> None: + downloads = self.tmp / "downloads" + downloads.mkdir() + stale = downloads / "old.pem" + stale.write_bytes(b"stale") + os.utime(stale, (1, 1)) + fresh = downloads / "infinito-nexus-updater.private-key.pem" + replies = iter(["", UPDATER_ID, "n"]) + prompts: list[str] = [] + + def ask(prompt: str) -> str: + prompts.append(prompt) + if "Press Enter when done" in prompt: + fresh.write_bytes(KEY) + return next(replies) + + gh = FakeGh("updater\n", "main\n", "") + with self.assertRaises(SystemExit): + apps.main( + [ + "--repo", + REPO, + "--updater-slug", + "infinito-nexus-updater", + "--translate-slug", + "infinito-nexus-translator", + "--downloads", + str(downloads), + ], + gh=gh, + ask=lambda p: "" if "use it" in p else ask(p), + say=self.said.append, + ) + self.assertIn(f" Found the new key {fresh}", self.said) + self.assertEqual(gh.secrets_set()[1], ("BOT_APP_PRIVATE_KEY", "updater", KEY)) + if __name__ == "__main__": unittest.main()