From 500b524ef50110ac8963146175abdc126127ca23 Mon Sep 17 00:00:00 2001 From: mojomast <76818041+mojomast@users.noreply.github.com> Date: Fri, 27 Nov 2026 15:09:15 -0500 Subject: [PATCH] docs: reproducible GitHub App identities (reviewer + coordinator) with setup scripts --- .gitignore | 4 + README.md | 2 + docs/github-apps.md | 228 ++++++++++++++++++ docs/profiles.md | 4 + tests/test_github_apps.py | 111 +++++++++ tools/github-apps/README.md | 22 ++ tools/github-apps/convert.sh | 124 ++++++++++ tools/github-apps/fingerprint.sh | 16 ++ tools/github-apps/make_submit_page.py | 124 ++++++++++ .../coordinator.manifest.template.json | 21 ++ .../manifests/reviewer.manifest.template.json | 17 ++ tools/github-apps/verify.sh | 138 +++++++++++ 12 files changed, 811 insertions(+) create mode 100644 docs/github-apps.md create mode 100644 tests/test_github_apps.py create mode 100644 tools/github-apps/README.md create mode 100755 tools/github-apps/convert.sh create mode 100755 tools/github-apps/fingerprint.sh create mode 100755 tools/github-apps/make_submit_page.py create mode 100644 tools/github-apps/manifests/coordinator.manifest.template.json create mode 100644 tools/github-apps/manifests/reviewer.manifest.template.json create mode 100755 tools/github-apps/verify.sh diff --git a/.gitignore b/.gitignore index ce3742e..c5453c6 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,7 @@ __pycache__/ *.pyc # machine-local private-name patterns for codemap --verify-docs (never commit) scripts/codemap/private-names.local +# GitHub App setup output (tools/github-apps): never commit keys, records or state files +*.pem +out-*/ +*.state.json diff --git a/README.md b/README.md index 19b0b20..4db82ca 100644 --- a/README.md +++ b/README.md @@ -93,6 +93,8 @@ This repository is the map. Each component has its own implementation, setup ins The contracts are the connection points. A coordinator can speak Hyvv’s `/v1` API without running Orbit; a team can adopt Workflow’s contracts without running any workers. To integrate another tool, start with the [protocol map](docs/protocol.md) and [agent extension guide](docs/adding-an-agent.md). +To run the stack on your own repositories, give the orchestrator and the reviewer their own GitHub identities. [docs/github-apps.md](docs/github-apps.md) sets up the two GitHub Apps, `rizzstack-coordinator` (builds and merges) and `rizzstack-reviewer` (posts reviews only), while your own account keeps the deciding vote. + ## How it was built [Kyle Durepos](https://github.com/mojomast) developed rizzstack while working with agents on games, creative tools, and Hermes plugins. The [project history](https://github.com/mojomast/workflow/blob/main/docs/07-projects.md) traces those builds. Kyle directed the work; coordinator agents broke it into briefs, and coding agents worked in disposable sandboxes. Some of the most useful parts of the stack came from runs that went wrong. diff --git a/docs/github-apps.md b/docs/github-apps.md new file mode 100644 index 0000000..421d016 --- /dev/null +++ b/docs/github-apps.md @@ -0,0 +1,228 @@ +# GitHub App identities: reviewer and coordinator + +rizzstack splits the GitHub work across three identities so that each repository's gate can eventually tell who did what from the GitHub login, not from the text of a comment. This guide sets the split up for your own account or organization from start to finish. The scripts it uses are in [`tools/github-apps/`](../tools/github-apps/). + +| Identity | Who uses it | Job | +|---|---|---| +| **Owner** (your own GitHub account) | you, a human | Decide: owner approvals, typed yeses, settings, rulesets, creating and installing the apps | +| **Coordinator app** (`rizzstack-coordinator[bot]`) | the orchestrator (for example a Hermes agent running the BundleBees coordinator) and its scheduled lanes | Build and land: push branches, open, update and merge PRs, label and comment, rerun CI | +| **Reviewer app** (`rizzstack-reviewer[bot]`) | the outside-review poster | Review: post PR reviews (approve or request changes) and nothing else | + +Examples use the default names. If you had to fall back to `rizzstack-reviewer-`, the bot login follows the app's slug: `[bot]`. + +## Why split the identities + +If the owner, the orchestrator and its review lanes all act through one personal token, GitHub records every action under the same login. The gate then can't tell an owner approval from an agent's review, or an independent review from one the coordinator wrote about its own work. All it can trust is the wording of a review, and anything holding the token can write those words. + +With three identities: + +- the coordinator can build and merge, but any review it posts counts for nothing; +- the reviewer can review, but it can't push or merge what it reviewed; +- the owner's login is never used by an agent. Once the coordinator's GitHub calls move to the app, the owner's personal token comes off the orchestrator host. + +The split only protects you if each private key is readable only by the process that should use it. See [Key custody](#key-custody). + +## Permissions + +Both apps are private, have no webhook (the hook is inactive, with no events subscribed), and are installed with **Only select repositories** on the rizzstack repositories. Ask for nothing beyond these. + +### Reviewer app + +| Permission | Access | Why | +|---|---|---| +| Pull requests | write | Submit PR reviews (`POST /repos/{owner}/{repo}/pulls/{n}/reviews`) | +| Contents | read | Read the diff, files and commits under review | +| Checks | read | See whether CI passed on the reviewed head | +| Metadata | read | Mandatory for every app | + +GitHub has no "reviews only" permission. Pull requests write also allows PR comments, labels and edits to titles and bodies, so "reviews only" is enforced by the poster that holds the key, which only submits verdicts. The reviewer can't merge (merging needs contents write) and can't push. + +### Coordinator app + +| Permission | Access | Why | +|---|---|---| +| Contents | write | Push feature branches; merge PRs (`PUT /repos/{owner}/{repo}/pulls/{n}/merge`) | +| Pull requests | write | Open, update and close PRs; request reviewers | +| Issues | write | Labels, and comments on PRs (PR comments go through the issues API); open tracking issues | +| Actions | write | Rerun failed jobs (`POST /repos/{owner}/{repo}/actions/runs/{id}/rerun-failed-jobs`) and dispatch workflows | +| Workflows | write | Push commits that change files under `.github/workflows/` (CI changes still land through a PR) | +| Checks | read | Read check runs before merging | +| Statuses | read | Read commit statuses before merging | +| Metadata | read | Mandatory for every app | + +### Deliberately excluded + +- **Administration:** without it the coordinator can't change rulesets, branch protection, collaborators or repository settings, so it can't loosen the gate that checks it. +- **Secrets, Variables, Environments:** it can't read or change CI secrets or deployment environments. +- **Members and any organization permission.** +- **Webhooks and events:** neither app receives deliveries, so there's no endpoint or webhook secret to protect. +- **All repositories:** install only on the repositories you list. + +Never add either app as a ruleset **bypass actor**. Merges still have to satisfy the required checks (`ci-gate`) like any other PR. + +Workflows write is the most powerful of these: a commit can change the CI that gates it. That's why changes under `.github/` and to gate scripts are high-risk in every rizzstack gate and need the owner or an independent reviewer, whoever authors them. + +## What you need + +- A GitHub account (or an organization you own) holding the repositories. +- A browser signed in as that owner. Two steps can only be done there: confirming each app's creation and confirming each installation. +- An always-on orchestrator host with `python3`, `openssl` and `bash`, where the keys will live. +- A copy of this repository (or just `tools/github-apps/`) on that host. + +## 1. Generate the manifests and submit pages + +On the orchestrator host: + +```sh +cd tools/github-apps +python3 make_submit_page.py --role reviewer --owner --out ~/rizzstack-apps-setup +python3 make_submit_page.py --role coordinator --owner --out ~/rizzstack-apps-setup +``` + +Each run writes three files into the output directory (mode 700): + +- `.manifest.json`: the filled-in manifest from `manifests/.manifest.template.json`; +- `.html`: a page with a form that POSTs the manifest to `https://github.com/settings/apps/new?state=`, or to `https://github.com/organizations//settings/apps/new?state=` with `--org`; +- `.state.json` (mode 600): the random state and the manifest. `convert.sh` checks the state GitHub returns against it. + +Options: + +- `--name`: change the app name. App names are unique across all of GitHub, including private apps you can't see, and can be at most 34 characters. If GitHub says the name is taken, rerun with `--name rizzstack-reviewer-` (or `rizzstack-coordinator-`). If that's over 34 characters, shorten the prefix (for example `rs-coordinator-`). The bot login and every later step use the new slug. +- `--homepage`: point the app's homepage somewhere other than `https://github.com//rizzstack`. +- `--redirect-url`: choose where GitHub sends you after creation (the default is the homepage repository). +- `--no-autosubmit`: wait for a button press instead of submitting as soon as the page opens. + +## 2. Create each app (browser) + +GitHub's manifest flow only accepts the manifest as a **form POST** from a page in the owner's browser. A plain link can't carry it. So: + +1. Open `.html` **in a browser on the machine that holds the file** (a `file://` page). If the files are on a headless host, copy the two HTML files to your own computer. They contain only the public manifest and the state. +2. The page submits itself. GitHub shows "Create GitHub App for <owner>" with the name and permissions. **Check them against the tables above**, then click **Create GitHub App**. +3. GitHub redirects to the redirect URL with `?code=…&state=…` appended. Copy the **whole address** from the address bar. + +Notes: + +- **Redirect target.** A listener on `http://127.0.0.1:/callback` only works when the browser runs on the same machine as the listener. A `127.0.0.1` redirect always lands on the computer running the browser. With the default redirect (a repository page) you copy the address instead, and nothing needs to be running. +- **Hosting the page elsewhere is optional.** If you can't open a local file (on a phone, for example), you can serve the page from your own GitHub Pages site. Third-party raw-HTML proxies (githack, htmlpreview and similar) also work, but they are **untrusted**. They never see a secret, but they could serve a modified page with other permissions or another redirect. If you use one, check GitHub's confirmation screen especially carefully. +- **The code is a secret until it's exchanged.** Whoever exchanges it first receives the app's private key. It's single-use and **expires one hour after the app is created**. Paste it only into `convert.sh`, or over a private channel to whoever runs it, and do the next step promptly. +- **State.** The `state` in the returned address must match the one in `.state.json`. A mismatch means the code belongs to a different page or app, and `convert.sh` refuses to exchange it. + +## 3. Exchange the code and store the key + +Run this on the orchestrator host, as the OS user that will use the key (see [Key custody](#key-custody)): + +```sh +./convert.sh ~/rizzstack-apps-setup/rizzstack-reviewer.state.json +# prompts (hidden input) for the full redirect address +./convert.sh ~/rizzstack-apps-setup/rizzstack-coordinator.state.json +``` + +`convert.sh` checks the state, then calls `POST https://api.github.com/app-manifests/{code}/conversions`. The response holds the private key (`pem`), a client secret and a webhook secret. The script then: + +- writes the key to `~/.config/rizzstack-apps/.pem`. The directory is mode 700, and the file is opened with `O_EXCL` at mode 600, so an existing key is never overwritten. Use `--keydir DIR` or `RIZZSTACK_APPS_KEYDIR` to choose another private directory; +- **discards** the client secret and webhook secret without printing them. rizzstack uses neither; +- writes and prints only safe fields to `/.json`: App ID, slug, bot login, Client ID, owner and permissions; +- fails if the app's permissions or events differ from the manifest. + +The key is never printed, logged or passed on the command line. Never commit it, paste it into chat, an issue or a PR, or copy it to another machine you don't need it on. + +### Key custody + +- Keep both keys on the **always-on orchestrator host**, in private directories at mode 600, never in a repository or a synced folder. +- Ideally the **reviewer key belongs to a separate OS user** that runs only the verdict poster, so the coordinator's process can't read it. If one process can read both keys, the coordinator can act as the reviewer, and the split protects nothing. +- The coordinator key belongs to the orchestrator's service user (or its secret store). + +## 4. Install each app (browser) + +There's no API to create an installation, so this is a manual browser step. (Once an installation exists, `PUT /user/installations/{installation_id}/repositories/{repository_id}` can add a repository to it, using a token whose user has admin on that repository. A classic PAT needs the `repo` scope. Whether a given token is accepted varies, so treat the browser as the dependable path.) + +1. Open `https://github.com/apps//installations/new`. +2. Pick the owner account, then **Only select repositories**. +3. Select exactly: `workflow`, `hyvv`, `bundlebees`, `orbitdesktop`, `orbit-control-plane`, `uirizz` and `rizzstack` (or your forks of them). +4. Click **Install**. Never choose "All repositories". + +To add or remove a repository later, go to Settings → Applications → Installed GitHub Apps → Configure, then run `verify.sh` again. + +## 5. Verify + +```sh +REPOS=workflow,hyvv,bundlebees,orbitdesktop,orbit-control-plane,uirizz,rizzstack +./verify.sh rizzstack-reviewer --repos "$REPOS" +./verify.sh rizzstack-coordinator --repos "$REPOS" +``` + +For each app, `verify.sh`: + +1. builds an RS256 JWT (valid for 10 minutes; `iss` = App ID) from the key; +2. calls `GET /app` and checks the name, that the permissions equal the manifest, and that no events are subscribed; +3. calls `GET /app/installations` and checks for exactly one installation, on the owner, with `repository_selection: selected`, whose permissions match; +4. mints an installation token **narrowed to `metadata: read`** (`POST /app/installations/{id}/access_tokens`); +5. calls `GET /installation/repositories` and checks that the list is exactly the repositories you passed; +6. revokes the token (`DELETE /installation/token`) and drops it from memory; +7. prints the key's SHA256 fingerprint. + +It prints only safe fields and exits non-zero if anything differs. + +**Fingerprint check.** On each app's settings page (`https://github.com/settings/apps/`, under **Private keys**), compare the fingerprint GitHub shows with the one `verify.sh` printed, or run: + +```sh +./fingerprint.sh ~/.config/rizzstack-apps/.pem 'SHA256:' +# same as: openssl rsa -in key.pem -pubout -outform DER | openssl dgst -sha256 -binary | openssl base64 +``` + +The App ID, Client ID, installation ID and fingerprint aren't secrets, but they are specific to your setup. Keep them in the orchestrator's private config, not in public docs. + +## How the orchestrator mints installation tokens + +The coordinator never stores a long-lived token. For each batch of GitHub work it: + +1. signs a JWT with its key (`iat` = now − 60 s, `exp` ≤ now + 10 min, `iss` = App ID); +2. calls `POST /app/installations/{installation_id}/access_tokens`, optionally narrowed with `"repositories": ["hyvv"]` and a smaller `"permissions"` map for the task at hand; +3. keeps the returned token **in memory only**. It's valid for one hour, so refresh it a few minutes before `expires_at`; +4. passes it to tools without writing it to disk: `Authorization: Bearer ` for the REST API, `GH_TOKEN` in a child process's environment for `gh`, and a credential helper supplying username `x-access-token` for `git` over HTTPS. Never embed it in a remote URL, which ends up in `.git/config` and process lists; +5. revokes it with `DELETE /installation/token` when the batch ends. + +Commits and PRs made this way show `[bot]` as the author or actor. To make commit authorship match, set the author to `[bot]` with email `+[bot]@users.noreply.github.com`, where the bot's user ID comes from `GET /users/[bot]`. Unlike the Actions `GITHUB_TOKEN`, pushes and PRs made with an installation token **do** trigger workflows, so CI runs as usual. + +The reviewer poster does the same with the reviewer key, narrowed to the one repository it's reviewing. + +## Rotating and revoking keys + +- **Rotate:** on the app's settings page, choose **Generate a private key**. GitHub downloads a new `.pem` to that browser. Move it to the orchestrator host over a private channel, write it to the key directory at mode 600 (for example `install -m 600 new.pem ~/.config/rizzstack-apps/.pem.new`, then `mv` it into place), and run `verify.sh`. Compare the new fingerprint, restart whatever caches the key, then **delete the old key** on the settings page and delete the downloaded copy. +- **Revoke one key:** delete it on the settings page. New JWTs signed with it fail at once. Installation tokens minted earlier may stay valid until they expire (up to one hour). +- **Cut off an app immediately:** suspend or uninstall its installation (Settings → Applications → Installed GitHub Apps → Configure). That also invalidates its outstanding installation tokens. +- **Retire an app:** uninstall it, then delete it from Settings → Developer settings → GitHub Apps → *app* → Advanced. +- If a key may have leaked, revoke first, then rotate, and check the repositories' audit log and recent PR activity for the bot login. + +## Gate by login (planned) + +> **Status: planned, not enforced yet.** Today the gates in each repository still trust review **text**. This section describes the target. + +Once the coordinator's GitHub calls run through its app and review posting runs through the reviewer app: + +- an **independent approval** counts only when the review's `user.login` is the reviewer bot (`rizzstack-reviewer[bot]`) or the owner's login; +- **owner approvals** and relayed owner yeses count only from the owner's login; +- reviews by the coordinator bot count for nothing; +- because PRs will be authored by the coordinator bot, the owner can submit ordinary GitHub **Approve** reviews, and the reviewer can submit real APPROVED / CHANGES REQUESTED states instead of comment-style attestations. + +Migration order: + +1. Create, install and verify both apps (this guide). +2. Move the coordinator's GitHub calls to installation tokens, and confirm that PRs, pushes, merges and job reruns work. +3. Route review posting through the reviewer app. +4. Change each repository's gate to trust logins as above. This is a gate change, so it needs the owner's approval and an independent review. +5. **Remove the owner's personal token from the orchestrator host.** Until this step, the coordinator can still act as the owner. + +## Which identity each repository's automation uses + +| Repository | Coordinator app | Reviewer app | Owner | +|---|---|---|---| +| workflow | coordinator playbook: open, update and merge PRs, rerun CI | outside-review verdicts | owner approvals and decisions | +| bundlebees | coordinator plugin: integrate accepted slices, open and merge PRs | review-bee verdict poster | owner approvals | +| hyvv | PRs and CI reruns opened by the coordinator | review verdicts | owner approvals, deploy yeses | +| orbitdesktop | PRs and CI reruns opened by the coordinator | review verdicts | owner approvals, release yeses | +| orbit-control-plane | PRs and CI reruns opened by the coordinator | review verdicts | owner approvals | +| uirizz | PRs and CI reruns opened by the coordinator | review verdicts | owner approvals, release yeses | +| rizzstack | docs and codemap PRs | review verdicts | owner approvals, ruleset and settings changes | + +Each repository's own docs point back here. diff --git a/docs/profiles.md b/docs/profiles.md index 52f4906..deab3bd 100644 --- a/docs/profiles.md +++ b/docs/profiles.md @@ -2,3 +2,7 @@ full | observer | orchestrator | worker | contracts — each documented with its minimum component set, what it watches/does, and its dependency edges. Spec in progress. + +## GitHub identities (orchestrator profile) + +An orchestrator that opens, merges or reviews PRs needs two GitHub Apps installed on your repositories, and their private keys on the orchestrator host: the **coordinator** app for building and merging, and the **reviewer** app for posting reviews. Your own account stays the owner and decides. Set them up with [github-apps.md](github-apps.md) and the scripts in [`tools/github-apps/`](../tools/github-apps/). Observer, worker and contracts-only profiles need neither. diff --git a/tests/test_github_apps.py b/tests/test_github_apps.py new file mode 100644 index 0000000..b92b24f --- /dev/null +++ b/tests/test_github_apps.py @@ -0,0 +1,111 @@ +"""Contract for tools/github-apps (docs/github-apps.md). + +The manifests ask for exactly the documented permissions and nothing that could +change settings, rulesets or secrets; the generated page POSTs the manifest with a +random state; the state file is private; and the scripts never echo secrets. +""" +import json +import os +import re +import stat +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +TOOLS = ROOT / "tools" / "github-apps" + +REVIEWER = {"pull_requests": "write", "contents": "read", "checks": "read", "metadata": "read"} +COORDINATOR = { + "contents": "write", "pull_requests": "write", "issues": "write", "actions": "write", + "workflows": "write", "checks": "read", "statuses": "read", "metadata": "read", +} +FORBIDDEN = ("administration", "secrets", "members", "environments", "organization_administration", + "repository_hooks", "organization_hooks", "variables") + + +def template(role): + return json.loads((TOOLS / "manifests" / ("%s.manifest.template.json" % role)).read_text()) + + +class ManifestTests(unittest.TestCase): + def test_exact_permissions(self): + self.assertEqual(template("reviewer")["default_permissions"], REVIEWER) + self.assertEqual(template("coordinator")["default_permissions"], COORDINATOR) + + def test_nothing_that_changes_settings_or_secrets(self): + for role in ("reviewer", "coordinator"): + perms = template(role)["default_permissions"] + for name in FORBIDDEN: + self.assertNotIn(name, perms, "%s asks for %s" % (role, name)) + + def test_private_no_events_inactive_hook_placeholders(self): + for role in ("reviewer", "coordinator"): + m = template(role) + self.assertIs(m["public"], False) + self.assertEqual(m["default_events"], []) + self.assertIs(m["hook_attributes"]["active"], False) + self.assertEqual(m["name"], "") + self.assertIn("", m["url"]) + + +class PageTests(unittest.TestCase): + def run_tool(self, out, *extra): + subprocess.run([sys.executable, str(TOOLS / "make_submit_page.py"), "--role", "coordinator", + "--owner", "example-owner", "--out", out, *extra], + check=True, capture_output=True, text=True) + + def test_page_posts_manifest_with_random_state(self): + with tempfile.TemporaryDirectory() as tmp: + out = os.path.join(tmp, "o") + self.run_tool(out) + page = Path(out, "rizzstack-coordinator.html").read_text() + m = re.search(r'
', page) + self.assertIsNotNone(m) + state_path = Path(out, "rizzstack-coordinator.state.json") + st = json.loads(state_path.read_text()) + self.assertEqual(st["state"], m.group(1)) + self.assertEqual(stat.S_IMODE(state_path.stat().st_mode), 0o600) + self.assertEqual(stat.S_IMODE(Path(out).stat().st_mode), 0o700) + manifest = json.loads(Path(out, "rizzstack-coordinator.manifest.json").read_text()) + self.assertEqual(manifest["default_permissions"], COORDINATOR) + self.assertEqual(manifest["url"], "https://github.com/example-owner/rizzstack") + self.assertNotIn("", json.dumps(manifest)) + self.assertIn('name="manifest"', page) + + def test_states_differ_and_org_and_fallback_name(self): + with tempfile.TemporaryDirectory() as tmp: + a, b = os.path.join(tmp, "a"), os.path.join(tmp, "b") + self.run_tool(a) + self.run_tool(b, "--org", "--name", "rizzstack-coordinator-exowner") + sa = json.loads(Path(a, "rizzstack-coordinator.state.json").read_text())["state"] + page = Path(b, "rizzstack-coordinator-exowner.html").read_text() + self.assertIn("https://github.com/organizations/example-owner/settings/apps/new?state=", page) + self.assertNotIn(sa, page) + + +class ScriptTests(unittest.TestCase): + def test_shell_syntax(self): + for name in ("convert.sh", "verify.sh", "fingerprint.sh"): + subprocess.run(["bash", "-n", str(TOOLS / name)], check=True) + + def test_convert_writes_key_exclusively_and_drops_secrets(self): + text = (TOOLS / "convert.sh").read_text() + self.assertIn("os.O_EXCL", text) + self.assertIn("0o600", text) + self.assertIn('data.pop("client_secret"', text) + self.assertIn('data.pop("webhook_secret"', text) + self.assertIn("read -rs", text) + self.assertNotRegex(text, r"print\([^)]*pem\b(?!_)") + + def test_verify_narrows_and_revokes_the_token(self): + text = (TOOLS / "verify.sh").read_text() + self.assertIn('{"permissions": {"metadata": "read"}}', text) + self.assertIn('"DELETE", "/installation/token"', text) + self.assertNotRegex(text, r"print\([^)]*\btok\b") + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/github-apps/README.md b/tools/github-apps/README.md new file mode 100644 index 0000000..331b55c --- /dev/null +++ b/tools/github-apps/README.md @@ -0,0 +1,22 @@ +# tools/github-apps + +Scripts for the reviewer and coordinator GitHub Apps. The full walkthrough, including why the identities are split, the permissions, key custody, rotation and the planned gate by login, is in [docs/github-apps.md](../../docs/github-apps.md). + +| File | What it does | +|---|---| +| `manifests/reviewer.manifest.template.json` | Reviewer app manifest: pull requests write; contents, checks and metadata read. `` and `` are placeholders | +| `manifests/coordinator.manifest.template.json` | Coordinator app manifest: contents, pull requests, issues, actions and workflows write; checks, statuses and metadata read. No administration, secrets, members or environments | +| `make_submit_page.py` | Fills in a manifest and writes the self-submitting HTML page (form POST to `settings/apps/new?state=`) plus a mode-600 state file | +| `convert.sh` | Exchanges the one-hour code (after checking its state), writes the key with `O_EXCL` at mode 600, and discards the client and webhook secrets unprinted | +| `verify.sh` | JWT → `GET /app` → `GET /app/installations` → a metadata-only installation token (revoked after use) → exact repository-set check → key fingerprint | +| `fingerprint.sh` | A key's SHA256 fingerprint, as shown on the app's settings page | + +Requirements: `bash`, `python3` (standard library only) and `openssl`. Nothing here prints a key, code or token. Never commit what these scripts write: keys, records and state files belong in private directories outside any repository. + +```sh +python3 make_submit_page.py --role reviewer --owner --out ~/rizzstack-apps-setup +# open the .html in the owner's browser, confirm, copy the redirect address +./convert.sh ~/rizzstack-apps-setup/rizzstack-reviewer.state.json +# install: https://github.com/apps//installations/new → Only select repositories +./verify.sh rizzstack-reviewer --repos workflow,hyvv,bundlebees,orbitdesktop,orbit-control-plane,uirizz,rizzstack +``` diff --git a/tools/github-apps/convert.sh b/tools/github-apps/convert.sh new file mode 100755 index 0000000..9c534a6 --- /dev/null +++ b/tools/github-apps/convert.sh @@ -0,0 +1,124 @@ +#!/usr/bin/env bash +# Exchange a GitHub App manifest code for the new app's credentials. +# +# Usage: convert.sh .state.json [--keydir DIR] [--skip-state-check] +# +# Run it on the host that will USE the key (the always-on orchestrator host), as +# the OS user that will read it. It prompts (hidden input, nothing in argv or shell +# history) for the full address GitHub redirected to after "Create GitHub App", +# e.g. https://github.com//rizzstack?code=...&state=... +# +# - checks the returned state against the state file written by make_submit_page.py +# - POSTs /app-manifests/{code}/conversions (no auth needed; the code is single-use +# and expires one hour after creation) +# - writes the private key to $KEYDIR/.pem with O_EXCL at mode 600, in a mode +# 700 directory; refuses to overwrite an existing file +# - discards client_secret and webhook_secret without printing them +# - writes and prints only safe fields (id, slug, client_id, owner, permissions) to +# $KEYDIR/.json +# - fails if the created app's permissions or events differ from the manifest +# +# The key is never printed, logged or echoed. Default KEYDIR: ~/.config/rizzstack-apps +set -euo pipefail +umask 077 + +state_file=""; keydir="${RIZZSTACK_APPS_KEYDIR:-$HOME/.config/rizzstack-apps}"; skip_state=0 +while [ $# -gt 0 ]; do + case "$1" in + --keydir) keydir="${2:?--keydir needs a value}"; shift 2;; + --skip-state-check) skip_state=1; shift;; + -h|--help) sed -n '2,23p' "$0"; exit 0;; + *) [ -z "$state_file" ] || { echo "unexpected argument: $1" >&2; exit 2; }; state_file="$1"; shift;; + esac +done +[ -n "$state_file" ] || { echo "usage: convert.sh .state.json [--keydir DIR] [--skip-state-check]" >&2; exit 2; } +[ -r "$state_file" ] || { echo "cannot read $state_file" >&2; exit 2; } +command -v python3 >/dev/null || { echo "python3 is required" >&2; exit 2; } + +read -rs -p "Paste the full redirect address (or the bare code with --skip-state-check): " reply; echo +REPLY_URL="$reply" STATE_FILE="$state_file" KEYDIR="$keydir" SKIP_STATE="$skip_state" \ + nice -n 10 timeout 60 python3 - <<'PY' +import json, os, sys, time, urllib.error, urllib.parse, urllib.request + +reply = os.environ.pop("REPLY_URL").strip() +st = json.load(open(os.environ["STATE_FILE"])) +keydir = os.path.expanduser(os.environ["KEYDIR"]) +skip_state = os.environ["SKIP_STATE"] == "1" + +if "code=" in reply: + q = urllib.parse.parse_qs(urllib.parse.urlsplit(reply).query) + code = (q.get("code") or [""])[0] + state = (q.get("state") or [""])[0] +else: + code, state = reply, "" +del reply +if not code or not all(c.isalnum() or c in "-_" for c in code): + sys.exit("no usable code in what was pasted") +if not skip_state: + if not state: + sys.exit("no state in what was pasted; paste the full address, or pass --skip-state-check") + if state != st["state"]: + sys.exit("state mismatch: this code was not issued for %s; not exchanging it" % st["name"]) +age = time.time() - st.get("created", 0) +if age > 3600: + print("warning: the page was generated %d minutes ago; codes expire one hour after creation" + % (age // 60), file=sys.stderr) + +os.makedirs(keydir, mode=0o700, exist_ok=True) +os.chmod(keydir, 0o700) + +req = urllib.request.Request( + "https://api.github.com/app-manifests/%s/conversions" % urllib.parse.quote(code), + method="POST", data=b"", + headers={"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "rizzstack-github-apps-convert"}) +del code +try: + with urllib.request.urlopen(req, timeout=30) as r: + data = json.load(r) +except urllib.error.HTTPError as e: + try: + msg = json.loads(e.read()).get("message", "") + except Exception: + msg = "" + sys.exit("conversion failed: HTTP %s %s (codes are single-use and expire after an hour)" % (e.code, msg)) + +pem = data.pop("pem") +data.pop("client_secret", None) +data.pop("webhook_secret", None) +slug = data["slug"] +path = os.path.join(keydir, "%s.pem" % slug) +try: + fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) +except FileExistsError: + sys.exit("refusing to overwrite %s; the app exists but its key was NOT saved. " + "Generate a new key on the app's settings page instead." % path) +with os.fdopen(fd, "w") as fh: + fh.write(pem) +os.chmod(path, 0o600) +del pem + +record = { + "role": st["role"], "name": data.get("name"), "slug": slug, "bot_login": "%s[bot]" % slug, + "app_id": data["id"], "client_id": data.get("client_id"), + "owner": (data.get("owner") or {}).get("login"), + "permissions": data.get("permissions"), "events": data.get("events"), + "manifest_permissions": st["manifest"]["default_permissions"], + "pem_path": path, +} +rec_path = os.path.join(keydir, "%s.json" % slug) +with open(rec_path, "w") as fh: + json.dump(record, fh, indent=2) +print(json.dumps(record, indent=2)) + +problems = [] +if record["permissions"] != record["manifest_permissions"]: + problems.append("permissions differ from the manifest") +if record["events"]: + problems.append("app subscribes to events") +if record["name"] != st["name"]: + problems.append("app was created under another name (%s); was the name taken?" % record["name"]) +for p in problems: + print("PROBLEM: " + p, file=sys.stderr) +sys.exit(3 if problems else 0) +PY diff --git a/tools/github-apps/fingerprint.sh b/tools/github-apps/fingerprint.sh new file mode 100755 index 0000000..2153c3a --- /dev/null +++ b/tools/github-apps/fingerprint.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash +# Print a GitHub App private key's SHA256 fingerprint, the same value GitHub shows +# under "Private keys" on the app's settings page. Optionally compare it. +# +# Usage: fingerprint.sh [expected] expected may carry the SHA256: prefix +# +# Only the public half is hashed; the key itself is never printed. +set -euo pipefail +pem="${1:?usage: fingerprint.sh [expected]}" +expected="${2:-}" +fp="$(openssl rsa -in "$pem" -pubout -outform DER 2>/dev/null | openssl dgst -sha256 -binary | openssl base64 -A)" +[ -n "$fp" ] || { echo "could not read a key from $pem" >&2; exit 2; } +echo "SHA256:$fp" +if [ -n "$expected" ]; then + if [ "${expected#SHA256:}" = "$fp" ]; then echo "match"; else echo "MISMATCH (settings page shows ${expected#SHA256:})" >&2; exit 3; fi +fi diff --git a/tools/github-apps/make_submit_page.py b/tools/github-apps/make_submit_page.py new file mode 100755 index 0000000..abb6b79 --- /dev/null +++ b/tools/github-apps/make_submit_page.py @@ -0,0 +1,124 @@ +#!/usr/bin/env python3 +"""Generate a GitHub App manifest and a self-submitting HTML page for it. + +Usage: + python3 make_submit_page.py --role reviewer --owner [--name ] + [--org] [--homepage URL] [--redirect-url URL] [--out DIR] + +Writes three files into --out (default ./out-, created mode 700): + .manifest.json the filled-in manifest (public) + .html a page that POSTs the manifest to GitHub (public) + .state.json the random state + manifest, mode 600; convert.sh + checks the state GitHub returns against it + +The page must be opened in a browser that is signed in as (or as an +org owner with --org). GitHub's manifest flow only accepts the manifest as a +form POST, so a plain link cannot carry it. Nothing in these files is secret; +the state is a one-time CSRF check, not a credential. +""" +import argparse +import html +import json +import os +import re +import secrets +import sys +import time +from pathlib import Path + +HERE = Path(__file__).resolve().parent +ROLES = ("reviewer", "coordinator") +NAME_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9 ._-]{0,33}$") # GitHub app names: 34 chars max +OWNER_RE = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$") + + +def fill(template, owner, name, homepage, redirect): + manifest = json.loads(json.dumps(template).replace("", owner).replace("", name)) + if homepage: + manifest["url"] = homepage + manifest["hook_attributes"]["url"] = homepage + if redirect: + manifest["redirect_url"] = redirect + return manifest + + +def page(manifest, action, role, autosubmit=True): + blob = json.dumps(manifest, indent=2) + esc = html.escape(blob, quote=True) + perms = "".join( + "
  • %s: %s
  • " % (html.escape(k), html.escape(v)) + for k, v in manifest["default_permissions"].items() + ) + return """ + + +Create GitHub App: {name} + + +

    Create GitHub App: {name}

    +

    Role: {role}. This page submits the manifest to GitHub {when}. GitHub then shows a +"Create GitHub App" confirmation; nothing is created until you confirm there.

    +
      {perms}
    +

    No webhook (inactive), no events, private app.

    + + + + +

    Manifest

    +
    {pre}
    +{script} + +""".format(name=html.escape(manifest["name"]), role=html.escape(role), perms=perms, + action=html.escape(action, quote=True), esc=esc, pre=html.escape(blob), + when="automatically (press the button if nothing happens)" if autosubmit else "when you press the button", + script='' if autosubmit else "") + + +def main(argv=None): + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--role", required=True, choices=ROLES) + ap.add_argument("--owner", required=True, help="GitHub user or org that will own the app") + ap.add_argument("--name", help="app name (default rizzstack-; fallback rizzstack--)") + ap.add_argument("--org", action="store_true", help="owner is an organization") + ap.add_argument("--homepage", help="app homepage and (inactive) hook URL; default https://github.com//rizzstack") + ap.add_argument("--redirect-url", help="where GitHub sends ?code=&state= after creation; default the homepage repo") + ap.add_argument("--no-autosubmit", action="store_true", help="wait for a button press instead of submitting on load") + ap.add_argument("--out", help="output directory (default ./out-)") + args = ap.parse_args(argv) + + if not OWNER_RE.match(args.owner): + ap.error("owner looks wrong: %r" % args.owner) + name = args.name or "rizzstack-%s" % args.role + if not NAME_RE.match(name): + ap.error("app name must be 1-34 chars of letters, digits, space, . _ -") + template = json.loads((HERE / "manifests" / ("%s.manifest.template.json" % args.role)).read_text()) + manifest = fill(template, args.owner, name, args.homepage, args.redirect_url) + + state = secrets.token_hex(16) + base = ("https://github.com/organizations/%s/settings/apps/new" % args.owner) if args.org \ + else "https://github.com/settings/apps/new" + action = "%s?state=%s" % (base, state) + + out = Path(args.out or "out-%s" % args.owner) + out.mkdir(mode=0o700, parents=True, exist_ok=True) + (out / ("%s.manifest.json" % name)).write_text(json.dumps(manifest, indent=2) + "\n") + (out / ("%s.html" % name)).write_text(page(manifest, action, args.role, not args.no_autosubmit)) + state_path = out / ("%s.state.json" % name) + if state_path.exists(): + state_path.unlink() + fd = os.open(str(state_path), os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600) + with os.fdopen(fd, "w") as fh: + json.dump({"role": args.role, "owner": args.owner, "org": args.org, "name": name, + "state": state, "created": int(time.time()), "manifest": manifest}, fh, indent=2) + print("wrote %s/%s.{manifest.json,html,state.json}" % (out, name)) + print("open %s in a browser signed in as %s, on the machine that holds the file" % (out / ("%s.html" % name), args.owner)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/github-apps/manifests/coordinator.manifest.template.json b/tools/github-apps/manifests/coordinator.manifest.template.json new file mode 100644 index 0000000..9747dd4 --- /dev/null +++ b/tools/github-apps/manifests/coordinator.manifest.template.json @@ -0,0 +1,21 @@ +{ + "name": "", + "url": "https://github.com//rizzstack", + "hook_attributes": { + "url": "https://github.com//rizzstack", + "active": false + }, + "redirect_url": "https://github.com//rizzstack", + "public": false, + "default_events": [], + "default_permissions": { + "contents": "write", + "pull_requests": "write", + "issues": "write", + "actions": "write", + "workflows": "write", + "checks": "read", + "statuses": "read", + "metadata": "read" + } +} diff --git a/tools/github-apps/manifests/reviewer.manifest.template.json b/tools/github-apps/manifests/reviewer.manifest.template.json new file mode 100644 index 0000000..ae8b8c8 --- /dev/null +++ b/tools/github-apps/manifests/reviewer.manifest.template.json @@ -0,0 +1,17 @@ +{ + "name": "", + "url": "https://github.com//rizzstack", + "hook_attributes": { + "url": "https://github.com//rizzstack", + "active": false + }, + "redirect_url": "https://github.com//rizzstack", + "public": false, + "default_events": [], + "default_permissions": { + "pull_requests": "write", + "contents": "read", + "checks": "read", + "metadata": "read" + } +} diff --git a/tools/github-apps/verify.sh b/tools/github-apps/verify.sh new file mode 100755 index 0000000..10696ea --- /dev/null +++ b/tools/github-apps/verify.sh @@ -0,0 +1,138 @@ +#!/usr/bin/env bash +# Verify a rizzstack GitHub App and its installation without printing any token. +# +# Usage: verify.sh --repos repo1,repo2,... [--owner OWNER] [--keydir DIR] +# +# Reads $KEYDIR/.json (written by convert.sh) and $KEYDIR/.pem, then: +# 1. builds an RS256 JWT (10 min) from the key and the App ID (openssl signs it) +# 2. GET /app name, owner, permissions == manifest, no events +# 3. GET /app/installations exactly one, on OWNER, repository_selection "selected" +# 4. POST /app/installations/{id}/access_tokens narrowed to metadata:read +# 5. GET /installation/repositories must be exactly OWNER/ +# 6. DELETE /installation/token revokes the token straight away +# 7. prints the key's SHA256 fingerprint (compare it with the app's settings page) +# +# Prints safe fields only. Exit 0 when everything matches, 3 when something does not. +# Default KEYDIR: ~/.config/rizzstack-apps. OWNER defaults to the app's owner. +set -euo pipefail +umask 077 + +slug=""; repos=""; owner=""; keydir="${RIZZSTACK_APPS_KEYDIR:-$HOME/.config/rizzstack-apps}" +while [ $# -gt 0 ]; do + case "$1" in + --repos) repos="${2:?--repos needs a value}"; shift 2;; + --owner) owner="${2:?--owner needs a value}"; shift 2;; + --keydir) keydir="${2:?--keydir needs a value}"; shift 2;; + -h|--help) sed -n '2,17p' "$0"; exit 0;; + *) [ -z "$slug" ] || { echo "unexpected argument: $1" >&2; exit 2; }; slug="$1"; shift;; + esac +done +[ -n "$slug" ] && [ -n "$repos" ] || { echo "usage: verify.sh --repos repo1,repo2,... [--owner OWNER] [--keydir DIR]" >&2; exit 2; } +command -v openssl >/dev/null || { echo "openssl is required" >&2; exit 2; } + +SLUG="$slug" REPOS="$repos" OWNER="$owner" KEYDIR="$keydir" nice -n 10 timeout 120 python3 - <<'PY' +import base64, json, os, stat, subprocess, sys, time, urllib.error, urllib.request + +slug = os.environ["SLUG"] +keydir = os.path.expanduser(os.environ["KEYDIR"]) +info = json.load(open(os.path.join(keydir, "%s.json" % slug))) +pem = os.path.join(keydir, "%s.pem" % slug) +owner = os.environ["OWNER"] or info["owner"] +expected = sorted("%s/%s" % (owner, r.strip()) for r in os.environ["REPOS"].split(",") if r.strip()) +problems = [] + +mode = stat.S_IMODE(os.stat(pem).st_mode) +if mode & 0o077: + problems.append("key file mode is %o; it must be 600" % mode) + +def b64(raw): + return base64.urlsafe_b64encode(raw).rstrip(b"=") + +now = int(time.time()) +signing = (b64(json.dumps({"alg": "RS256", "typ": "JWT"}).encode()) + b"." + + b64(json.dumps({"iat": now - 60, "exp": now + 540, "iss": str(info["app_id"])}).encode())) +sig = subprocess.run(["openssl", "dgst", "-sha256", "-sign", pem], input=signing, + capture_output=True, check=True).stdout +jwt = (signing + b"." + b64(sig)).decode() +del sig + +def call(method, path, auth, body=None, ok_empty=False): + req = urllib.request.Request( + "https://api.github.com" + path, method=method, + data=None if body is None else json.dumps(body).encode(), + headers={"Accept": "application/vnd.github+json", "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "rizzstack-github-apps-verify", "Authorization": auth}) + try: + with urllib.request.urlopen(req, timeout=30) as r: + raw = r.read() + return json.loads(raw) if raw else None + except urllib.error.HTTPError as e: + try: + msg = json.loads(e.read()).get("message", "") + except Exception: + msg = "" + sys.exit("%s %s failed: HTTP %s %s" % (method, path.split("?")[0], e.code, msg)) + +out = {"pem_path": pem, "pem_mode": oct(mode)} +app = call("GET", "/app", "Bearer " + jwt) +out.update(name=app["name"], slug=app["slug"], bot_login=app["slug"] + "[bot]", app_id=app["id"], + client_id=app.get("client_id"), owner=app["owner"]["login"], + permissions=app["permissions"], events=app["events"]) +if app["slug"] != slug: + problems.append("key belongs to %s, not %s" % (app["slug"], slug)) +if app["permissions"] != info["manifest_permissions"]: + problems.append("app permissions differ from the manifest") +if app["events"]: + problems.append("app subscribes to events") + +insts = call("GET", "/app/installations", "Bearer " + jwt) +out["installations"] = [{"id": i["id"], "account": i["account"]["login"], + "repository_selection": i["repository_selection"], + "permissions": i["permissions"], "events": i["events"]} for i in insts] +if len(insts) != 1: + problems.append("expected exactly 1 installation, found %d" % len(insts)) +for i in insts: + if i["repository_selection"] != "selected": + problems.append("installation %s can see ALL repositories; choose 'Only select repositories'" % i["id"]) + if i["account"]["login"].lower() != owner.lower(): + problems.append("installation %s is on %s, not %s" % (i["id"], i["account"]["login"], owner)) + if i["permissions"] != info["manifest_permissions"]: + problems.append("installation %s has not accepted the current permissions" % i["id"]) + +if insts: + iid = insts[0]["id"] + out["installation_id"] = iid + tok = call("POST", "/app/installations/%s/access_tokens" % iid, "Bearer " + jwt, + {"permissions": {"metadata": "read"}})["token"] + repos, page = [], 1 + try: + while True: + r = call("GET", "/installation/repositories?per_page=100&page=%d" % page, "token " + tok) + repos += [x["full_name"] for x in r["repositories"]] + if len(repos) >= r["total_count"] or not r["repositories"]: + break + page += 1 + finally: + try: + call("DELETE", "/installation/token", "token " + tok) + out["token_revoked"] = True + except SystemExit: + out["token_revoked"] = False + del tok + out["repositories"] = sorted(repos) + if sorted(r.lower() for r in repos) != [e.lower() for e in expected]: + missing = sorted(set(e.lower() for e in expected) - set(r.lower() for r in repos)) + extra = sorted(set(r.lower() for r in repos) - set(e.lower() for e in expected)) + problems.append("repository set differs (missing: %s; extra: %s)" % (missing, extra)) +del jwt + +der = subprocess.run(["openssl", "rsa", "-in", pem, "-pubout", "-outform", "DER"], + capture_output=True, check=True).stdout +dgst = subprocess.run(["openssl", "dgst", "-sha256", "-binary"], input=der, + capture_output=True, check=True).stdout +out["key_sha256_fingerprint"] = "SHA256:" + base64.b64encode(dgst).decode() +out["problems"] = problems +out["ok"] = not problems +print(json.dumps(out, indent=2)) +sys.exit(0 if not problems else 3) +PY