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
67 changes: 67 additions & 0 deletions infra/github-backup/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
# github-backup

Mirrors of Drew's GitHub estate, kept on the laptop, updatable forever,
with a dedicated GitHub App for rate limits and webhook freshness.

**This directory is the canonical home of the whole system** — scripts,
systemd units, the webhook Worker source, the config schema, and the
docs. Nothing load-bearing lives only on a machine: a fresh laptop plus
this repo plus Bitwarden rebuilds everything (see `docs/RUNBOOK.md`).

## Layout of the backup tree (`~/backups/github` on the laptop)

```
<owner>/<repo>.git bare mirrors (git clone --mirror: all branches+tags)
plan.json generated by reconcile.py from config.json + GitHub
MANIFEST.json generated: what exists, sizes, HEADs, last fetch
FAMILIES.md generated: fork-family anchors (alternates pool)
state.json generated: fetch/drain bookkeeping
clone-status.jsonl clone pass log (append-only)
fetch.log fetch failures (append-only)
reconcile-YYYY-MM-DD.md weekly sweep reports
```

## Design

- **Scope (config.json):** all non-fork repos + forks under 500 MB across
17 owners, plus force-includes; 7 passive giants are excluded by Drew's
ruling 2026-10-31 (upstream is their backup). Edsebooks (HTTP 451) and
vertexinc (SAML) are recorded gaps, not silent misses.
- **Pool/dedupe:** forks sharing an upstream are cloned with git
alternates against a family anchor, so e.g. the three nixpkgs copies
store one shared history plus deltas. Members are NOT self-contained —
the tree is the unit. Cold copies use `git bundle` (materializes
objects), never a bare tar of a member `.git`.
- **Freshness:** a dedicated GitHub App (`hatch-repo-backup`,
metadata:read + contents:read, push+repository events) sends webhooks
to the Cloudflare Worker in `worker/`; the Worker verifies the HMAC
and queues events in KV; the laptop drains the queue every 5 min
(per-repo coalescing 15 min) and fetches just those mirrors.
- **Correctness floor:** a weekly reconciliation sweep re-inventories
GitHub, diffs against the tree, clones new repos matching the tier
rules, and flags new giant forks as `pending-drew-review` instead of
cloning them. Webhooks may be missed; the sweep may not.
- **Daily fetch:** every mirror is fetched daily regardless (12 h
coalescing), so even total webhook loss degrades to daily freshness.
- **Rate limits:** the App's installation tokens have their own pool
(5,000/hr base, scaling with installed repos toward 12,500/hr),
separate from Drew's personal token that the fleet uses.
- **Secrets:** by name only, in Bitwarden Secrets Manager — see
`config.json` → `app.bitwarden_secret_names`. Values never enter this
repo, the backup tree, or chat.

## Components

| Path | What |
|---|---|
| `config.json` | owners, tier rules, exclusions, gaps, App/Worker names |
| `bin/ghb_common.py` | shared inventory + plan builder |
| `bin/clone_all.py` | resumable parallel initial clone (from plan.json) |
| `bin/fetch_mirrors.py` | daily fetch / targeted fetch of named repos |
| `bin/reconcile.py` | weekly sweep: inventory → plan → clone new → report |
| `bin/manifest.py` | regenerate MANIFEST.json + FAMILIES.md |
| `bin/drain_queue.py` | drain Worker queue, fetch pushed repos |
| `bin/app_setup.py` | App manifest flow, credential storage, install report |
| `worker/` | Cloudflare Worker webhook receiver (wrangler) |
| `systemd/` | laptop user units + timers + installer |
| `docs/RUNBOOK.md` | copy-paste operations: install, add org, upgrade, DR |
170 changes: 170 additions & 0 deletions infra/github-backup/bin/app_setup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
#!/usr/bin/env python3
"""app_setup.py — GitHub App (hatch-repo-backup) lifecycle helper.

Subcommands:
manifest Print the App Manifest JSON + the exact click-path to create
the App (GitHub requires a human to submit the manifest form;
everything after the redirect is automated here).
convert CODE
Exchange the manifest-flow temporary code for the App's
credentials (POST /app-manifests/<code>/conversions) and store
them in Bitwarden Secrets Manager BY NAME (see config.json
app.bitwarden_secret_names). Values are never printed or
written to disk.
install-report
Using the App private key from Bitwarden (via bws env), mint a
JWT and list installations (GET /app/installations) so the
runbook's install checklist can be verified.
webhook-secret
Generate a webhook secret and store it in Bitwarden by name;
the same value must then be set on the App (GitHub UI) and on
the Worker (`wrangler secret put GITHUB_WEBHOOK_SECRET`).
Prints only the Bitwarden secret name, never the value.

Bitwarden access goes through `bws` with BWS_ACCESS_TOKEN from the
environment (source ~/tools/bws-env.sh first). bws project: the one
~/tools/bws-env.sh defaults to.
"""
import json, os, secrets as secrets_mod, subprocess, sys, time

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from ghb_common import load_config

CFG = load_config()
NAMES = CFG["app"]["bitwarden_secret_names"]


def app_manifest(worker_url):
return {
"name": CFG["app"]["name"],
"url": "https://github.com/developing-today/code/tree/main/infra/github-backup",
"hook_attributes": {"url": worker_url.rstrip("/") + CFG["worker"]["webhook_path"]},
"redirect_url": "http://localhost:8765/callback",
"public": False,
"default_permissions": {"metadata": "read", "contents": "read"},
"default_events": CFG["app"]["events"],
}


def _bws_list():
r = subprocess.run(["bws", "secret", "list"], capture_output=True, text=True,
env=dict(os.environ))
if r.returncode != 0:
raise RuntimeError(f"bws secret list failed: {r.stderr[:200]}")
return json.loads(r.stdout or "[]")


def _project_id():
if os.environ.get("GHB_BWS_PROJECT_ID"):
return os.environ["GHB_BWS_PROJECT_ID"]
r = subprocess.run(["bws", "project", "list"], capture_output=True, text=True,
env=dict(os.environ))
projects = json.loads(r.stdout or "[]")
if not projects:
raise RuntimeError("no Bitwarden projects visible to this token")
return projects[0]["id"]


def bws_set(name, value):
"""Create-or-update a Bitwarden secret by name."""
sid = next((s["id"] for s in _bws_list() if s.get("key") == name), None)
if sid:
r = subprocess.run(["bws", "secret", "edit", sid, "--value", value],
capture_output=True, text=True, env=dict(os.environ))
else:
r = subprocess.run(["bws", "secret", "create", name, value, _project_id()],
capture_output=True, text=True, env=dict(os.environ))
if r.returncode != 0:
raise RuntimeError(f"bws store failed for {name}: {r.stderr[:200]}")


def bws_get(name):
sid = next((s["id"] for s in _bws_list() if s.get("key") == name), None)
if not sid:
raise KeyError(name)
r = subprocess.run(["bws", "secret", "get", sid],
capture_output=True, text=True, env=dict(os.environ))
return json.loads(r.stdout)["value"]


def cmd_manifest():
worker_url = os.environ.get("GHB_WORKER_URL", "https://<worker-host>")
m = app_manifest(worker_url)
print(json.dumps(m, indent=2))
print("""
CLICK PATH (one human step — GitHub requires it):
1. Set GHB_WORKER_URL to the deployed Worker URL and re-run to bake it in.
2. Open https://github.com/settings/apps/new as dezren39 and submit this
manifest via the manifest-flow form (the RUNBOOK §App has the exact
HTML snippet), OR paste it using GitHub's manifest flow page.
3. GitHub redirects to the redirect_url with ?code=XXXX.
4. Run: python3 app_setup.py convert XXXX
-> stores app id / client id / client secret / private key in
Bitwarden under the names in config.json. Nothing is printed.
""", file=sys.stderr)


def cmd_convert(code):
import urllib.request
req = urllib.request.Request(
f"https://api.github.com/app-manifests/{code}/conversions",
data=b"", method="POST")
req.add_header("Accept", "application/vnd.github+json")
with urllib.request.urlopen(req, timeout=60) as r:
conv = json.loads(r.read())
bws_set(NAMES["app_id"], str(conv["id"]))
bws_set(NAMES["client_id"], conv["client_id"])
bws_set(NAMES["client_secret"], conv["client_secret"])
bws_set(NAMES["private_key"], conv["pem"])
print(f"App created: id={conv['id']} slug={conv['slug']} — credentials stored "
f"in Bitwarden by name ({', '.join(NAMES.values())}).")
print("Next: app_setup.py webhook-secret, then install the App per RUNBOOK §App.")


def cmd_webhook_secret():
value = secrets_mod.token_hex(32)
bws_set(NAMES["webhook_secret"], value)
print(f"Stored under Bitwarden name {NAMES['webhook_secret']}. "
"Set the same value on the App (GitHub UI > App settings > Webhook secret) "
"and on the Worker: wrangler secret put GITHUB_WEBHOOK_SECRET.")


def cmd_install_report():
# JWT minting needs a JOSE lib; use PyJWT if present, else cryptography.
try:
import jwt as pyjwt
except ImportError:
print("PyJWT not installed (pip install pyjwt cryptography) — cannot mint App JWT here.")
return 1
import urllib.request
app_id = bws_get(NAMES["app_id"])
pem = bws_get(NAMES["private_key"])
now = int(time.time())
token = pyjwt.encode({"iat": now - 60, "exp": now + 540, "iss": app_id},
pem, algorithm="RS256")
req = urllib.request.Request("https://api.github.com/app/installations")
req.add_header("Authorization", "Bearer " + token)
req.add_header("Accept", "application/vnd.github+json")
with urllib.request.urlopen(req, timeout=60) as r:
installs = json.loads(r.read())
for i in installs:
acct = i["account"]["login"]
print(f"installed: {acct} (installation {i['id']}, repos: "
f"{i.get('repository_selection')})")
print(f"total installations: {len(installs)}")
return 0


if __name__ == "__main__":
cmd = sys.argv[1] if len(sys.argv) > 1 else ""
if cmd == "manifest":
cmd_manifest()
elif cmd == "convert" and len(sys.argv) == 3:
cmd_convert(sys.argv[2])
elif cmd == "webhook-secret":
cmd_webhook_secret()
elif cmd == "install-report":
sys.exit(cmd_install_report())
else:
print(__doc__)
sys.exit(2)
111 changes: 111 additions & 0 deletions infra/github-backup/bin/clone_all.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
#!/usr/bin/env python3
"""clone_all.py — resumable parallel mirror-clone driver.

Reads plan.json from the backup tree (build it with reconcile.py --plan-only
or copy from a previous run). Mirrors land at <root>/<owner>/<repo>.git.
Repos with a `reference` wait for their anchor; if the anchor failed they
fall back to a full clone. Status is appended to clone-status.jsonl;
re-running skips verified mirrors.
"""
import json, os, subprocess, sys, time
from concurrent.futures import ThreadPoolExecutor

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from ghb_common import load_config, backup_root, mirror_path, valid_mirror, disk_kb

PAR = 4
TIMEOUT = 5400


def main():
cfg = load_config()
root = backup_root(cfg)
plan = json.load(open(os.path.join(root, "plan.json")))
status_path = os.path.join(root, "clone-status.jsonl")

def log_status(rec):
rec["ts"] = time.strftime("%Y-%m-%dT%H:%M:%S%z")
with open(status_path, "a") as f:
f.write(json.dumps(rec) + "\n")

ok_prev = set()
if os.path.exists(status_path):
for line in open(status_path):
try:
r = json.loads(line)
if r.get("status") == "ok":
ok_prev.add(r["repo"])
except Exception:
pass

def clone_one(item, ref_ok):
repo = item["repo"]
dest = mirror_path(root, repo)
if valid_mirror(dest):
return {"repo": repo, "status": "ok", "note": "already-present",
"disk_kb": disk_kb(dest)}
os.makedirs(os.path.dirname(dest), exist_ok=True)
cmd = ["git", "clone", "--mirror"]
ref = item.get("reference")
if ref and ref_ok and valid_mirror(mirror_path(root, ref)):
cmd += ["--reference", mirror_path(root, ref)]
cmd += [f"https://github.com/{repo}.git", dest]
t0 = time.time()
env = dict(os.environ, GIT_TERMINAL_PROMPT="0")
try:
r = subprocess.run(cmd, capture_output=True, text=True,
timeout=TIMEOUT, env=env)
except subprocess.TimeoutExpired:
return {"repo": repo, "status": "fail", "error": "timeout",
"seconds": round(time.time() - t0)}
dt = round(time.time() - t0)
if r.returncode == 0 and valid_mirror(dest):
return {"repo": repo, "status": "ok", "seconds": dt,
"disk_kb": disk_kb(dest),
"reference_used": ref if (ref and ref_ok) else None}
return {"repo": repo, "status": "fail", "seconds": dt,
"error": (r.stderr or r.stdout)[-400:]}

state = {}
for p in plan:
if p["repo"] in ok_prev and valid_mirror(mirror_path(root, p["repo"])):
state[p["repo"]] = "ok"
pending = [p for p in plan if state.get(p["repo"]) != "ok"]
print(f"plan={len(plan)} already-ok={len(plan)-len(pending)} pending={len(pending)}", flush=True)
inflight = {}
with ThreadPoolExecutor(max_workers=PAR) as ex:
while pending or inflight:
for p in list(pending):
ref = p.get("reference")
if ref and state.get(ref) is None and any(q["repo"] == ref for q in pending):
continue
if len(inflight) >= PAR:
break
inflight[ex.submit(clone_one, p, state.get(ref) == "ok")] = p
pending.remove(p)
if not inflight:
if pending:
p = pending.pop(0)
inflight[ex.submit(clone_one, p, False)] = p
else:
break
done = [f for f in list(inflight) if f.done()]
if not done:
time.sleep(2)
continue
for f in done:
p = inflight.pop(f)
try:
rec = f.result()
except Exception as e:
rec = {"repo": p["repo"], "status": "fail", "error": str(e)[:300]}
state[p["repo"]] = "ok" if rec["status"] == "ok" else "fail"
log_status(rec)
print(rec["repo"], rec["status"], rec.get("seconds", ""), flush=True)
ok = sum(1 for s in state.values() if s == "ok")
print(f"DONE ok={ok} fail={len(state)-ok} of {len(plan)}", flush=True)
return 0 if ok == len(plan) else 1


if __name__ == "__main__":
sys.exit(main())
Loading