Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
228 changes: 228 additions & 0 deletions docs/github-apps.md

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions docs/profiles.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
111 changes: 111 additions & 0 deletions tests/test_github_apps.py
Original file line number Diff line number Diff line change
@@ -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"], "<app-name>")
self.assertIn("<owner>", 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'<form id="f" method="post" action="https://github\.com/settings/apps/new\?state=([0-9a-f]{32})">', 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("<owner>", 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()
22 changes: 22 additions & 0 deletions tools/github-apps/README.md
Original file line number Diff line number Diff line change
@@ -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. `<owner>` and `<app-name>` 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=<random>`) 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 <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/<slug>/installations/new → Only select repositories
./verify.sh rizzstack-reviewer --repos workflow,hyvv,bundlebees,orbitdesktop,orbit-control-plane,uirizz,rizzstack
```
124 changes: 124 additions & 0 deletions tools/github-apps/convert.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
#!/usr/bin/env bash
# Exchange a GitHub App manifest code for the new app's credentials.
#
# Usage: convert.sh <app-name>.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/<owner>/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/<slug>.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/<slug>.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 <app-name>.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
16 changes: 16 additions & 0 deletions tools/github-apps/fingerprint.sh
Original file line number Diff line number Diff line change
@@ -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 <key.pem> [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 <key.pem> [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
Loading