diff --git a/.github/workflows/cron-collection-source.yml b/.github/workflows/cron-collection-source.yml index 877415b27e..ff4cd1e953 100644 --- a/.github/workflows/cron-collection-source.yml +++ b/.github/workflows/cron-collection-source.yml @@ -19,6 +19,7 @@ jobs: name: โš–๏ธ Time Galaxy against the git fallback if: vars.CI_ENABLE_AUTO_UPDATES == 'true' runs-on: ubuntu-26.04 + environment: updater env: HISTORY_PATH: build/collection-source-history.json steps: diff --git a/.github/workflows/cron-update.yml b/.github/workflows/cron-update.yml index e4ae9aebff..4f175076d6 100644 --- a/.github/workflows/cron-update.yml +++ b/.github/workflows/cron-update.yml @@ -22,6 +22,7 @@ jobs: name: ๐Ÿณ Update Docker image versions if: vars.CI_ENABLE_AUTO_UPDATES == 'true' runs-on: ubuntu-26.04 + environment: updater steps: - name: โฌ‡๏ธ Checkout uses: actions/checkout@v7.0.0 @@ -69,6 +70,7 @@ jobs: name: ๐Ÿณ Update compose file image versions if: vars.CI_ENABLE_AUTO_UPDATES == 'true' runs-on: ubuntu-26.04 + environment: updater steps: - name: โฌ‡๏ธ Checkout uses: actions/checkout@v7.0.0 @@ -116,6 +118,7 @@ jobs: name: ๐Ÿ”– Update declared version sources if: vars.CI_ENABLE_AUTO_UPDATES == 'true' runs-on: ubuntu-26.04 + environment: updater steps: - name: โฌ‡๏ธ Checkout uses: actions/checkout@v7.0.0 @@ -163,6 +166,7 @@ jobs: name: ๐Ÿ Update pinned pip requirements if: vars.CI_ENABLE_AUTO_UPDATES == 'true' runs-on: ubuntu-26.04 + environment: updater steps: - name: โฌ‡๏ธ Checkout uses: actions/checkout@v7.0.0 @@ -210,6 +214,7 @@ jobs: name: ๐ŸŒŒ Update pinned Ansible collections if: vars.CI_ENABLE_AUTO_UPDATES == 'true' runs-on: ubuntu-26.04 + environment: updater steps: - name: โฌ‡๏ธ Checkout uses: actions/checkout@v7.0.0 @@ -257,6 +262,7 @@ jobs: name: ๐ŸŒฟ Update repository refs if: vars.CI_ENABLE_AUTO_UPDATES == 'true' runs-on: ubuntu-26.04 + environment: updater steps: - name: โฌ‡๏ธ Checkout uses: actions/checkout@v7.0.0 @@ -304,6 +310,7 @@ jobs: name: ๐Ÿƒ Update GitHub-hosted runner labels if: vars.CI_ENABLE_AUTO_UPDATES == 'true' runs-on: ubuntu-26.04 + environment: updater steps: - name: โฌ‡๏ธ Checkout uses: actions/checkout@v7.0.0 diff --git a/.github/workflows/entry-pr-green-update-merge.yml b/.github/workflows/entry-pr-green-update-merge.yml index 9091ebb92b..57c95027a4 100644 --- a/.github/workflows/entry-pr-green-update-merge.yml +++ b/.github/workflows/entry-pr-green-update-merge.yml @@ -19,6 +19,7 @@ jobs: || startsWith(github.event.workflow_run.head_branch, 'dependabot/')) runs-on: ubuntu-26.04 timeout-minutes: 15 + environment: auto-merge permissions: actions: read checks: read @@ -56,8 +57,11 @@ jobs: id: app-token uses: actions/create-github-app-token@v3 with: - client-id: ${{ secrets.BOT_APP_CLIENT_ID }} - private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }} + client-id: ${{ secrets.MERGE_APP_CLIENT_ID }} + private-key: ${{ secrets.MERGE_APP_PRIVATE_KEY }} + permission-contents: write + permission-pull-requests: write + permission-workflows: write - name: ๐Ÿ”€ Merge the update PR at its tested head if: steps.gate.outputs.merge == 'true' diff --git a/.github/workflows/entry-pr-translate.yml b/.github/workflows/entry-pr-translate.yml index 79654def5f..fe64b9a75e 100644 --- a/.github/workflows/entry-pr-translate.yml +++ b/.github/workflows/entry-pr-translate.yml @@ -126,8 +126,8 @@ jobs: id: app-token uses: actions/create-github-app-token@v3 with: - client-id: ${{ secrets.BOT_APP_CLIENT_ID }} - private-key: ${{ secrets.BOT_APP_PRIVATE_KEY }} + client-id: ${{ secrets.TRANSLATE_APP_CLIENT_ID }} + private-key: ${{ secrets.TRANSLATE_APP_PRIVATE_KEY }} - name: ๐Ÿ“‚ Open PR for the translated catalogs if: steps.diff.outputs.changed == 'true' diff --git a/cli/contributing/update/README.md b/cli/contributing/update/README.md index 0b933bf733..7c508a8e15 100644 --- a/cli/contributing/update/README.md +++ b/cli/contributing/update/README.md @@ -133,3 +133,16 @@ 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 --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 +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..00a4bc9b58 --- /dev/null +++ b/cli/contributing/update/apps/__main__.py @@ -0,0 +1,347 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import argparse +import re +import subprocess +import sys +import time +from pathlib import Path +from typing import TYPE_CHECKING +from urllib.parse import urlencode + +from cryptography.exceptions import UnsupportedAlgorithm +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives.serialization import load_pem_private_key + +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 +INSTALLATION_TOKEN_SECONDS = 3600 +UPDATER_ENVIRONMENT = "updater" +UPDATER_BRANCH = "main" +UPDATER_NAMES = ("BOT_APP_CLIENT_ID", "BOT_APP_PRIVATE_KEY") +TRANSLATE_NAMES = ("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[] | "\\(.type):\\(.name)"', + ], + None, + ) + ) + if policies != [f"branch:{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 unencrypted RSA private key. + """ + if not path.is_file(): + raise SystemExit(f"no file at {path}") + data = path.read_bytes() # nocheck: cache-read + try: + key = load_pem_private_key(data, password=None) + except (ValueError, TypeError, UnsupportedAlgorithm) as exc: + raise SystemExit(f"{path} holds no unencrypted PEM private key") from exc + if not isinstance(key, rsa.RSAPrivateKey): + raise SystemExit(f"{path} holds no RSA private key") + return data + + +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 + + +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 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: + """ + 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, downloads: Path | None, ask: Ask, say: Say +) -> Path: + org = repo.split("/", maxsplit=1)[0] + 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(" 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?") + ready = time.strftime( + "%Y-%m-%d %H:%M", time.localtime(time.time() + INSTALLATION_TOKEN_SECONDS) + ) + say(" Tokens minted with the old keys stay valid up to one hour: delete the") + say(f" pre-rotation update/** and dependabot/** branches after {ready}.") + return pem + + +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"\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 read and write." + ) + 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( + f" stored {', '.join(TRANSLATE_NAMES)} 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_NAMES: + 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" + ) + 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, 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("\nStep 4 of 4: 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/configuration.md b/docs/contributing/tools/github/actions/configuration.md index 4b9e8eb3b7..4eb8a758fc 100644 --- a/docs/contributing/tools/github/actions/configuration.md +++ b/docs/contributing/tools/github/actions/configuration.md @@ -127,7 +127,7 @@ The gate is applied inside [push_ci_policy.sh](../../../../../scripts/meta/resol Controls whether automated update PRs are created. Covers both the workflow-driven jobs in [cron-update.yml](../../../../../.github/workflows/cron-update.yml) (Docker image versions, agent skills) and PRs opened by Dependabot (gated via [entry-pr-open-dependabot-close.yml](../../../../../.github/workflows/entry-pr-open-dependabot-close.yml), which auto-closes them). -The workflow-driven jobs additionally require the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). Without those secrets, runs fail at the token-minting step and no PR is opened. +The workflow-driven jobs additionally require the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` secrets of the `updater` environment, see [secrets.md](secrets.md). Without those secrets, runs fail at the token-minting step and no PR is opened. **Default behaviour (variable not set or set to any value other than `true`):** The `update-docker-image-versions` job is skipped. Dependabot PRs are auto-closed on open with a comment pointing to this variable. @@ -172,7 +172,7 @@ An update PR merges itself only when all of these hold; otherwise the job prints 3. Every latest check run on its head commit completed as `success`, `skipped` or `neutral`, and every commit status is `success`. A check still running counts as not green; no later run retries the merge. 4. Every role under `roles//` the PR changes appears in the `role` column of a `role-runtimes-*` artifact of that run. A PR that changes no role needs no artifact; a missing artifact proves nothing. -The merge goes through `PUT /repos/{owner}/{repo}/pulls/{number}/merge` with `merge_method=merge` and the tested head `sha`, so a commit pushed after the run makes it fail instead of merging untested code. `gh pr merge` is not used because it refuses a PR the ruleset still blocks before the server can apply the App's bypass. The App MUST be a bypass actor of the `Main` ruleset in `pull_request` mode; without that the merge step fails and the PR stays open. +The merge goes through `PUT /repos/{owner}/{repo}/pulls/{number}/merge` with `merge_method=merge` and the tested head `sha`, so a commit pushed after the run makes it fail instead of merging untested code. `gh pr merge` is not used because it refuses a PR the ruleset still blocks before the server can apply the App's bypass. The token comes from the separate merge App in the `auto-merge` environment, which becomes a bypass actor of the `Main` ruleset in `pull_request` mode only once the [prerequisites](secrets.md#prerequisites-for-the-bypass-) hold; until then the merge step fails and the PR stays open for a manual merge. Setup: [secrets.md](secrets.md#merge_app_client_id-and-merge_app_private_key-). ## `INFINITO_PLAYWRIGHT_KEEP` ๐ŸŽฌ diff --git a/docs/contributing/tools/github/actions/secrets.md b/docs/contributing/tools/github/actions/secrets.md index 816df5a001..df30298034 100644 --- a/docs/contributing/tools/github/actions/secrets.md +++ b/docs/contributing/tools/github/actions/secrets.md @@ -2,14 +2,18 @@ This page lists every repository secret that GitHub Actions workflows in this repository consume, and documents the failure mode when a secret is missing. For repository **variables** see [configuration.md](configuration.md). For the workflow catalog see [workflows.md](workflows.md). -Repository secrets MUST be set under **Settings โ†’ Secrets and variables โ†’ Actions โ†’ Secrets**. +Repository secrets MUST be set under **Settings โ†’ Secrets and variables โ†’ Actions โ†’ Secrets**; environment secrets under **Settings โ†’ Environments โ†’ `` โ†’ Environment secrets**. ## Secrets ๐Ÿ“‹ | Secret | Workflow | Purpose | Required when | |---|---|---|---| -| `BOT_APP_CLIENT_ID` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) | GitHub App Client ID (OAuth-style `Ivโ€ฆ` identifier shown on the App's General page) used to mint a short-lived installation token for the update PR and for its automatic merge. | `CI_ENABLE_AUTO_UPDATES == 'true'` | -| `BOT_APP_PRIVATE_KEY` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) | PEM-encoded private key of the same GitHub App. Used to sign the JWT that exchanges for the installation token. | `CI_ENABLE_AUTO_UPDATES == 'true'` | +| `BOT_APP_CLIENT_ID` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [cron-collection-source.yml](../../../../../.github/workflows/cron-collection-source.yml) | GitHub App Client ID (OAuth-style `Ivโ€ฆ` identifier shown on the App's General page) used to mint a short-lived installation token for the update PR. An **environment** secret of `updater`, never a repository secret. | `CI_ENABLE_AUTO_UPDATES == 'true'` | +| `BOT_APP_PRIVATE_KEY` | [cron-update.yml](../../../../../.github/workflows/cron-update.yml), [cron-collection-source.yml](../../../../../.github/workflows/cron-collection-source.yml) | PEM-encoded private key of the same GitHub App. Used to sign the JWT that exchanges for the installation token. An environment secret of `updater`. | `CI_ENABLE_AUTO_UPDATES == 'true'` | +| `TRANSLATE_APP_CLIENT_ID` | [entry-pr-translate.yml](../../../../../.github/workflows/entry-pr-translate.yml) | Client ID of the translation App that opens the machine-translation PRs. A repository secret, readable by same-repository pull requests. | `CI_ENABLE_AUTO_TRANSLATIONS == 'true'` | +| `TRANSLATE_APP_PRIVATE_KEY` | [entry-pr-translate.yml](../../../../../.github/workflows/entry-pr-translate.yml) | PEM private key of the translation App. | `CI_ENABLE_AUTO_TRANSLATIONS == 'true'` | +| `MERGE_APP_CLIENT_ID` | [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) | Client ID of the separate merge App, an **environment** secret of `auto-merge`, never a repository secret. | `CI_ENABLE_AUTO_UPDATES == 'true'` | +| `MERGE_APP_PRIVATE_KEY` | [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) | PEM private key of the merge App, an environment secret of `auto-merge`. | `CI_ENABLE_AUTO_UPDATES == 'true'` | | `API_OPENAI_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Publishes the `openai/*` models on the LiteLLM gateway and lets the CLI test exercise the route. | Never. Unset leaves the route unpublished. | | `API_ANTHROPIC_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Publishes the `anthropic/*` models. | Never. | | `API_OPENROUTER_KEY` | [call-test-deploy.yml](../../../../../.github/workflows/call-test-deploy.yml) | Publishes `openrouter/auto`. | Never. | @@ -89,17 +93,29 @@ 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 --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 โ†’ Secrets and variables โ†’ Actions**. -3. Stay on the **Secrets** tab. -4. Click **New repository secret** and 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). -5. Click **New repository secret** and add `BOT_APP_PRIVATE_KEY` with the complete PEM content, including the `-----BEGIN PRIVATE KEY-----` and `-----END PRIVATE KEY-----` lines. +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). +4. Add `BOT_APP_PRIVATE_KEY` with the complete PEM content, including the `-----BEGIN PRIVATE KEY-----` and `-----END PRIVATE KEY-----` lines. +5. Delete any repository secret of the same names under **Settings โ†’ Secrets and variables โ†’ Actions**; a repository secret would stay readable by `pull_request` runs. ### How the workflow consumes the secrets โš™๏ธ -Each PR-opening job in [cron-update.yml](../../../../../.github/workflows/cron-update.yml) runs an `actions/create-github-app-token@v2` step gated on `steps.diff.outputs.changed == 'true'`, then forwards the minted token as `GH_TOKEN` and the resolved `APP_SLUG` to the subsequent PR step. The job's `permissions:` block keeps the workflow-provided `GITHUB_TOKEN` read-only; write access is provided exclusively by the App token, scoped to the App's repository permissions. +Each PR-opening job in [cron-update.yml](../../../../../.github/workflows/cron-update.yml) and [cron-collection-source.yml](../../../../../.github/workflows/cron-collection-source.yml) declares `environment: updater` and runs an `actions/create-github-app-token@v3` step gated on `steps.diff.outputs.changed == 'true'`, then forwards the minted token as `GH_TOKEN` and the resolved `APP_SLUG` to the subsequent PR step. The job's `permissions:` block keeps the workflow-provided `GITHUB_TOKEN` read-only; write access is provided exclusively by the App token, scoped to the App's repository permissions. -[entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) mints the App token only after its merge gate passed, and uses it for the merge call alone; the gate itself reads with the read-only `GITHUB_TOKEN`. Merging needs the App's `Contents` and `Pull requests` write permissions plus a bypass of the `Main` ruleset; a PR that changes `.github/workflows/` additionally needs `Workflows`: **Read and write**, or its merge fails and it stays open. +These jobs run on `push` to `main`, `schedule` or `workflow_dispatch` and check out `main`; a dispatch on any other branch fails at the environment's branch rule. No job that declares `updater` may check out or execute pull-request code. + +This App MUST NOT be a bypass actor of the `Main` ruleset. It sits on the update-branch ruleset's bypass list beside Dependabot and the admin role, see [Prerequisites for the bypass](#prerequisites-for-the-bypass-). + +## `TRANSLATE_APP_CLIENT_ID` and `TRANSLATE_APP_PRIVATE_KEY` ๐ŸŒ + +[entry-pr-translate.yml](../../../../../.github/workflows/entry-pr-translate.yml) mints its token on `pull_request` after running the pull request's own code, so any same-repository pull request can read this key. It therefore belongs to an App of its own that sits on no bypass list: a leaked key grants what every writer already has, and it opens only `translate/pr-*` branches. + +1. Create the App as in [How to generate the App](#how-to-generate-the-app-), with `Contents` and `Pull requests`: **Read and write**. Install it on the `core` repository only. +2. Add `TRANSLATE_APP_CLIENT_ID` and `TRANSLATE_APP_PRIVATE_KEY` as **repository** secrets. +3. Never add this App to the bypass list of any ruleset. ### Commit identity propagation ๐Ÿชช @@ -119,6 +135,30 @@ A missing secret resolves to an empty string in workflow expressions. The workfl The behaviour is fail-loud by design. Missing or mistyped secret names MUST surface as a failed workflow run rather than as a PR with an unintended author. +## `MERGE_APP_CLIENT_ID` and `MERGE_APP_PRIVATE_KEY` ๐Ÿ”€ + +[entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) merges a proven update PR with a second GitHub App that does nothing else. Once enabled, it is the only bypass actor of the `Main` ruleset besides the admins, so its key MUST be reachable from the default branch alone. + +### How to set it up ๐Ÿ› ๏ธ + +1. Create the App as in [How to generate the App](#how-to-generate-the-app-), with `Contents` and `Pull requests`: **Read and write**, plus `Workflows`: **Read and write** so a PR that changes `.github/workflows/` can merge too. Install it on the `core` repository only. +2. Go to **Settings โ†’ Environments โ†’ New environment**, name it `auto-merge`, and under **Deployment branches and tags** choose **Selected branches and tags** with the single rule `main`. A `pull_request` run, whose ref is the pull request's merge ref, cannot read its secrets. A `pull_request_target` or `workflow_run` job runs with the base branch as its ref and passes this rule, so a job that declares `auto-merge` MUST NOT check out or execute pull-request code; only [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml) declares it, and it runs `main`'s own code. +3. Add `MERGE_APP_CLIENT_ID` (the `Ivโ€ฆ` Client ID) and `MERGE_APP_PRIVATE_KEY` (the full PEM) as **environment secrets** of `auto-merge`, never as repository secrets. +4. Only after every prerequisite below holds: in **Settings โ†’ Rules โ†’ Rulesets โ†’ Main**, add the App under **Bypass list** with **For pull requests only**. Check the live bypass list first; it MUST NOT hold the updater App. + +### Prerequisites for the bypass ๐Ÿ”’ + +The merge gate checks who opened the PR, not who pushed its head commit, so the head of an `update/*` or `dependabot/*` branch MUST be writable by the updater App, Dependabot and admins alone, and the updater key MUST be out of reach of every pull request: + +1. A branch ruleset on `update/**` and `dependabot/**` restricts creation, updates and deletion, with only the updater App, Dependabot and the admin role on its bypass list. The admin role lets a maintainer merge a translation PR or push a fixup onto an update branch; the translation App stays off it. +2. `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` exist only as secrets of the `updater` environment, restricted to `main`, and no longer as repository secrets, so no `pull_request` run can read them; [entry-pr-translate.yml](../../../../../.github/workflows/entry-pr-translate.yml) uses the [translation App](#translate_app_client_id-and-translate_app_private_key-). As with `auto-merge`, a `pull_request_target` or `workflow_run` job passes that branch rule, so no job that declares the environment may check out or execute pull-request code; list every workflow that declares it and confirm this before step 4. +3. The updater App's private key was regenerated after the translation workflow stopped minting from it, the new key is the one in `updater`, and every older key is deleted under **Credentials โ†’ Key pairs** on the App's settings page. Same-repository pull requests could read the old key, and a copy taken then stays valid until it is revoked. Deleting a key stops new installation tokens but does not revoke the ones already minted, which stay valid for up to one hour, so at least one hour passes after the deletion before prerequisite 4 starts. +4. Every `update/**` and `dependabot/**` branch whose head was pushed before that hour ended is deleted, whether its pull request is open, closed or missing, and an open one is closed; the next updater run and Dependabot open fresh ones from heads pushed afterwards. The gate checks who opened a pull request, not who pushed its head, so a head pushed with the old key would otherwise stay mergeable through the bypass, including a closed pull request that a writer reopens. + +With all four in place, and the hour of prerequisite 3 over, pushing a head the gate accepts needs the updater key, which only workflows on `main` can read. Until then the merge App stays off the bypass list, the merge call fails with HTTP 405, and update PRs wait for a manual merge: the ruleset's `update` rule (Restrict updates) lets only bypass actors move `main`, pull-request merges included, whatever reviews the PR holds. + +The job mints the App token only after its merge gate passed, narrowed to `contents`, `pull-requests` and `workflows` write, and uses it for the merge call alone; the gate reads with the read-only `GITHUB_TOKEN`. The job runs on `workflow_run`, which always runs on the default branch, so the environment's branch rule admits it. Without the bypass, the merge call fails with `Repository rule violations found` (HTTP 405) and the PR stays open. + ## Related ๐Ÿ”— - [configuration.md](configuration.md): repository variables that gate the same workflows. diff --git a/docs/contributing/tools/github/actions/workflows.md b/docs/contributing/tools/github/actions/workflows.md index 2f4fcf3352..5b7552dc29 100644 --- a/docs/contributing/tools/github/actions/workflows.md +++ b/docs/contributing/tools/github/actions/workflows.md @@ -83,11 +83,11 @@ Trigger column legend: **auto** = fires automatically (push, pull_request, sched | [call-release-version.yml](../../../../../.github/workflows/call-release-version.yml): `๐Ÿš€ Release: Version Logic` | Releases a specific version tag (build + publish). Called from `entry-push-latest.yml` on tagged pushes. | reusable, manual | `tag` (required, e.g. `v1.2.3`) | | [cron-release-highest.yml](../../../../../.github/workflows/cron-release-highest.yml): `๐Ÿš€ Release missing tag` | Scheduled backfill: finds the highest tag without a release and triggers `call-release-version.yml` for it. | auto (`schedule`: daily 00:00 UTC), manual | none | | [cron-cleanup-stale.yml](../../../../../.github/workflows/cron-cleanup-stale.yml): `๐Ÿงน Prune stale data` | Marks and closes stale issues and PRs, deletes inactive branches, and prunes old GHCR CI image versions. | auto (`schedule`: daily 00:00 UTC), manual | none | -| [cron-update.yml](../../../../../.github/workflows/cron-update.yml): `๐Ÿ”„ Update versions` | Updates Docker image versions and other pinned dependencies; opens an update PR via a GitHub App installation token so PR-lifecycle events fire on the resulting PR. Both jobs are gated behind the `CI_ENABLE_AUTO_UPDATES` repository variable, see [configuration.md](configuration.md). Requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`push` to `main`, `schedule`: daily 00:30 UTC), manual | none | -| [entry-pr-translate.yml](../../../../../.github/workflows/entry-pr-translate.yml): `๐ŸŒ Translate catalogs` | Merges the source strings of the `core` and `docs` domains into `locale/`, then machine-translates what a pull request leaves empty or fuzzy, one runner per language LibreTranslate supports. Each runner opens its own PR against the head branch of the triggering PR. Gated behind the `CI_ENABLE_AUTO_TRANSLATIONS` repository variable, see [configuration.md](configuration.md); pull requests from a fork are skipped. Requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`pull_request` against `main`: opened, synchronize, reopened) | none | +| [cron-update.yml](../../../../../.github/workflows/cron-update.yml): `๐Ÿ”„ Update versions` | Updates Docker image versions and other pinned dependencies; opens an update PR via a GitHub App installation token so PR-lifecycle events fire on the resulting PR. Both jobs are gated behind the `CI_ENABLE_AUTO_UPDATES` repository variable, see [configuration.md](configuration.md). Requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` secrets of the `updater` environment, see [secrets.md](secrets.md). | auto (`push` to `main`, `schedule`: daily 00:30 UTC), manual | none | +| [entry-pr-translate.yml](../../../../../.github/workflows/entry-pr-translate.yml): `๐ŸŒ Translate catalogs` | Merges the source strings of the `core` and `docs` domains into `locale/`, then machine-translates what a pull request leaves empty or fuzzy, one runner per language LibreTranslate supports. Each runner opens its own PR against the head branch of the triggering PR. Gated behind the `CI_ENABLE_AUTO_TRANSLATIONS` repository variable, see [configuration.md](configuration.md); pull requests from a fork are skipped. Requires the `TRANSLATE_APP_CLIENT_ID` and `TRANSLATE_APP_PRIVATE_KEY` repository secrets of a separate App, see [secrets.md](secrets.md). | auto (`pull_request` against `main`: opened, synchronize, reopened) | none | | [entry-pr-open-dependabot-close.yml](../../../../../.github/workflows/entry-pr-open-dependabot-close.yml): `๐Ÿšซ Dependabot: Close while auto-updates disabled` | Auto-closes Dependabot PRs while `CI_ENABLE_AUTO_UPDATES` is not set to `true`, so Dependabot honours the same gate as the workflow-driven update jobs. See [configuration.md](configuration.md). | auto (`pull_request_target`: opened, reopened) | none | | [entry-pr-change-dependabot-label.yml](../../../../../.github/workflows/entry-pr-change-dependabot-label.yml): `๐Ÿ”„ Dependabot: Label update level` | Labels every Dependabot PR `โฌ†๏ธ update` plus exactly one of `๐Ÿ”ด major`, `๐ŸŸก minor` and `๐ŸŸข patch`, read from the `update-type` of `dependabot/fetch-metadata`; a type that names no semver level counts as `major`. Creates a missing label, adds only labels the PR lacks and checks out the base branch only. Gated behind `CI_ENABLE_AUTO_UPDATES`, see [configuration.md](configuration.md). | auto (`pull_request_target`: opened, reopened, synchronize) | none | -| [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml): `๐Ÿ”„ Update: Merge proven PRs` | Runs when a `๐Ÿ”€ Pull Request` run of the `pull_request` event succeeds on an `update/*` or `dependabot/*` branch. [cli.contributing.update.merge](../../../../../cli/contributing/update/merge/__main__.py) merges the PR only when the `infinito-nexus-updater[bot]` App or `dependabot[bot]` opened it, it carries `โฌ†๏ธ update`, every check run and commit status on its head is green, and the run's `role-runtimes-*` artifacts list every role the PR changes. Otherwise it prints why and the PR stays open for a manual merge. The merge pins the tested head and uses the App token, so the App MUST be a bypass actor of the `Main` ruleset. Gated behind `CI_ENABLE_AUTO_UPDATES`, see [configuration.md](configuration.md); requires the `BOT_APP_CLIENT_ID` and `BOT_APP_PRIVATE_KEY` repository secrets, see [secrets.md](secrets.md). | auto (`workflow_run` of `๐Ÿ”€ Pull Request`: completed) | none | +| [entry-pr-green-update-merge.yml](../../../../../.github/workflows/entry-pr-green-update-merge.yml): `๐Ÿ”„ Update: Merge proven PRs` | Runs when a `๐Ÿ”€ Pull Request` run of the `pull_request` event succeeds on an `update/*` or `dependabot/*` branch. [cli.contributing.update.merge](../../../../../cli/contributing/update/merge/__main__.py) merges the PR only when the `infinito-nexus-updater[bot]` App or `dependabot[bot]` opened it, it carries `โฌ†๏ธ update`, every check run and commit status on its head is green, and the run's `role-runtimes-*` artifacts list every role the PR changes. Otherwise it prints why and the PR stays open for a manual merge. The merge pins the tested head and uses the token of a separate merge App, which becomes a bypass actor of the `Main` ruleset only once the prerequisites in [secrets.md](secrets.md#prerequisites-for-the-bypass-) hold; until then the PR waits for a manual merge. Gated behind `CI_ENABLE_AUTO_UPDATES`, see [configuration.md](configuration.md); requires the `MERGE_APP_CLIENT_ID` and `MERGE_APP_PRIVATE_KEY` secrets of the `auto-merge` environment, see [secrets.md](secrets.md). | auto (`workflow_run` of `๐Ÿ”€ Pull Request`: completed) | none | ## Changing workflows โœ๏ธ 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..c10c41766c --- /dev/null +++ b/tests/unit/python/cli/contributing/update/apps/test_main.py @@ -0,0 +1,211 @@ +from __future__ import annotations + +import os +import tempfile +import unittest.mock +from pathlib import Path + +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import ec, rsa + +import cli.contributing.update.apps.__main__ as apps + +REPO = "infinito-nexus/core" +KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048).private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.TraditionalOpenSSL, + serialization.NoEncryption(), +) +TRUNCATED_KEY = b"\n".join([*KEY.splitlines()[:2], KEY.splitlines()[-1]]) + b"\n" +EC_KEY = ec.generate_private_key(ec.SECP256R1()).private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), +) +BRANCH_MAIN = "branch:main\n" +NOW = 1_800_000_000.0 +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 [ + "", + str(self.updater_pem), + UPDATER_ID, + "y", + "", + "", + str(self.translate_pem), + TRANSLATE_ID, + "y", + "y", + "y", + ] + + def test_keys_reach_gh_through_stdin_only(self) -> None: + gh = FakeGh("updater\n", BRANCH_MAIN, "") + 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", "branch:main\nbranch:feature/*\n", "") + with self.assertRaises(SystemExit): + self.run_main(gh, self.full_answers()) + self.assertEqual(gh.secrets_set(), []) + + def test_tag_policy_named_main_stops_before_any_secret(self) -> None: + gh = FakeGh("updater\n", "tag:main\n", "") + with self.assertRaises(SystemExit): + self.run_main(gh, self.full_answers()) + self.assertEqual(gh.secrets_set(), []) + + def test_file_without_usable_rsa_key_stops_before_any_secret(self) -> None: + for body in (b"not a key", TRUNCATED_KEY, EC_KEY): + with self.subTest(body=body[:30]): + self.updater_pem.write_bytes(body) + gh = FakeGh("updater\n", BRANCH_MAIN, "") + 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", BRANCH_MAIN, "") + answers = ["", str(self.updater_pem), UPDATER_ID, "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", BRANCH_MAIN, "BOT_APP_PRIVATE_KEY\nDOCKERHUB_TOKEN\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"]) + self.assertTrue(self.translate_pem.exists()) + + def test_client_id_must_be_an_app_client_id(self) -> None: + gh = FakeGh("updater\n", BRANCH_MAIN, "") + with self.assertRaises(SystemExit): + 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, (NOW - 1, NOW - 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) + os.utime(fresh, (NOW + 1, NOW + 1)) + return next(replies) + + gh = FakeGh("updater\n", BRANCH_MAIN, "") + with ( + unittest.mock.patch.object(apps.time, "time", return_value=NOW), + 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()