|
| 1 | +#!/usr/bin/env bash |
| 2 | +# gatekeeper-approve.sh — "Gatekeeper" GitHub App auto-approver bridge (MCP-1249). |
| 3 | +# |
| 4 | +# Purpose: turn a Paperclip Codex review verdict of ACCEPT into a real GitHub |
| 5 | +# *approving review* posted by a branded GitHub App identity, so the repo's |
| 6 | +# "1 approving review by a reviewer with write access" branch-protection rule is |
| 7 | +# satisfied WITHOUT an admin override and WITHOUT the PR author approving their |
| 8 | +# own PR (author != approver). Once the App approval lands, GitHub auto-merge |
| 9 | +# (squash) completes the merge with zero admin — full "Model B". |
| 10 | +# |
| 11 | +# This is the missing piece of MCP-1249. It pairs with arm-auto-merge.sh. |
| 12 | +# |
| 13 | +# Verdict source of record = the Paperclip review comment (the review bots do NOT |
| 14 | +# post to GitHub). This script reads that verdict and, only on ACCEPT, posts the |
| 15 | +# GitHub approval as the App. |
| 16 | +# |
| 17 | +# ───────────────────────────────────────────────────────────────────────────── |
| 18 | +# Configuration (env, or sourced from a gitignored file — NEVER commit secrets): |
| 19 | +# GATEKEEPER_APP_ID GitHub App ID (integer) |
| 20 | +# GATEKEEPER_INSTALLATION_ID Installation ID for smart-mcp-proxy/mcpproxy-go |
| 21 | +# GATEKEEPER_PRIVATE_KEY Path to the App private key .pem |
| 22 | +# GATEKEEPER_REPO (optional) owner/repo, default smart-mcp-proxy/mcpproxy-go |
| 23 | +# PAPERCLIP_API_URL (optional) default http://localhost:3100 |
| 24 | +# PAPERCLIP_COMPANY_ID (optional) default 16edd8ed-8691-4a89-aa30-74ab6b931663 |
| 25 | +# CODEX_REVIEWER_AGENT_ID (optional) default 5b94562c-524f-4c29-bc24-3524c1acd8e9 |
| 26 | +# A convenient place: ~/.mcpproxy-gatekeeper/env (chmod 600, gitignored). |
| 27 | +# |
| 28 | +# Usage: |
| 29 | +# gatekeeper-approve.sh --pr <N> [--verdict accept|request_changes] |
| 30 | +# [--reviewed-sha <sha>] [--dry-run] |
| 31 | +# |
| 32 | +# --pr <N> (required) PR number to act on. |
| 33 | +# --verdict <v> override the Paperclip verdict lookup (testing/manual). |
| 34 | +# --reviewed-sha <s> override the reviewed SHA (pairs with --verdict; required |
| 35 | +# to approve via the manual override path — fail-closed). |
| 36 | +# --dry-run do everything except POST the review (and print the plan). |
| 37 | +# |
| 38 | +# Safe to run repeatedly (idempotent): no-ops if the PR is closed/merged, if the |
| 39 | +# verdict isn't ACCEPT, or if the Gatekeeper already approved the current head. |
| 40 | +# |
| 41 | +# FAIL-CLOSED SHA GUARD (MCP-1249 Codex REQUEST_CHANGES): the script approves the |
| 42 | +# PR's CURRENT head ONLY when it can resolve a reviewed SHA that EQUALS that head. |
| 43 | +# If no reviewed SHA can be resolved, it REFUSES (never approves blind) so a |
| 44 | +# post-review force-push of unreviewed code cannot inherit an old ACCEPT. The |
| 45 | +# manual --verdict accept override is held to the same requirement. |
| 46 | +# |
| 47 | +# Exit codes: 0 ok/approved/dry-run/no-op; 2 not configured; 3 verdict not accept; |
| 48 | +# 5 GitHub/API error; 6 stale verdict (reviewed SHA != head); |
| 49 | +# 7 no reviewed SHA resolvable (fail-closed refusal). |
| 50 | +# ───────────────────────────────────────────────────────────────────────────── |
| 51 | +set -euo pipefail |
| 52 | + |
| 53 | +REPO="${GATEKEEPER_REPO:-smart-mcp-proxy/mcpproxy-go}" |
| 54 | +PAPERCLIP_API_URL="${PAPERCLIP_API_URL:-http://localhost:3100}" |
| 55 | +PAPERCLIP_COMPANY_ID="${PAPERCLIP_COMPANY_ID:-16edd8ed-8691-4a89-aa30-74ab6b931663}" |
| 56 | +CODEX_REVIEWER_AGENT_ID="${CODEX_REVIEWER_AGENT_ID:-5b94562c-524f-4c29-bc24-3524c1acd8e9}" |
| 57 | + |
| 58 | +# Optional config file |
| 59 | +[[ -f "${HOME}/.mcpproxy-gatekeeper/env" ]] && source "${HOME}/.mcpproxy-gatekeeper/env" |
| 60 | + |
| 61 | +PR=""; VERDICT_OVERRIDE=""; REVIEWED_SHA_OVERRIDE=""; DRY_RUN=0 |
| 62 | +while [[ $# -gt 0 ]]; do |
| 63 | + case "$1" in |
| 64 | + --pr) PR="$2"; shift 2;; |
| 65 | + --verdict) VERDICT_OVERRIDE="$2"; shift 2;; |
| 66 | + --reviewed-sha) REVIEWED_SHA_OVERRIDE="$2"; shift 2;; |
| 67 | + --dry-run) DRY_RUN=1; shift;; |
| 68 | + -h|--help) grep '^#' "$0" | sed 's/^# \{0,1\}//'; exit 0;; |
| 69 | + *) echo "unknown arg: $1" >&2; exit 1;; |
| 70 | + esac |
| 71 | +done |
| 72 | +[[ -z "$PR" ]] && { echo "ERROR: --pr <N> required" >&2; exit 1; } |
| 73 | + |
| 74 | +log() { echo "[gatekeeper] $*" >&2; } |
| 75 | + |
| 76 | +# ── 1. Resolve the Codex review verdict (+reviewed SHA) from Paperclip ─────── |
| 77 | +# Emits "<verdict> <reviewed_sha_or_empty>". |
| 78 | +resolve_verdict() { |
| 79 | + if [[ -n "$VERDICT_OVERRIDE" ]]; then echo "$VERDICT_OVERRIDE ${REVIEWED_SHA_OVERRIDE:-}"; return; fi |
| 80 | + # Reads are fine unauthenticated against the local instance. |
| 81 | + curl -fsS -m 15 "${PAPERCLIP_API_URL}/api/companies/${PAPERCLIP_COMPANY_ID}/issues?q=Review%20PR%20%23${PR}" 2>/dev/null \ |
| 82 | + | PR="$PR" CODEX="$CODEX_REVIEWER_AGENT_ID" BASE="$PAPERCLIP_API_URL" python3 -c ' |
| 83 | +import sys, json, os, re, urllib.request |
| 84 | +pr, codex, base = os.environ["PR"], os.environ["CODEX"], os.environ["BASE"] |
| 85 | +iss = json.load(sys.stdin) |
| 86 | +iss = iss if isinstance(iss, list) else iss.get("issues", iss.get("data", [])) |
| 87 | +# Codex review tasks for this PR (title references "PR #<n>"), assigned to the |
| 88 | +# Codex reviewer, newest first (round-2 supersedes round-1). |
| 89 | +needle = "PR #%s" % pr |
| 90 | +revs = [i for i in iss |
| 91 | + if needle in (i.get("title") or "") and i.get("assigneeAgentId") == codex] |
| 92 | +revs.sort(key=lambda x: x.get("createdAt", ""), reverse=True) |
| 93 | +verdict, sha = "unknown", "" |
| 94 | +for i in revs: |
| 95 | + url = "%s/api/issues/%s/comments" % (base, i.get("id")) |
| 96 | + try: |
| 97 | + c = json.load(urllib.request.urlopen(url, timeout=15)) |
| 98 | + except Exception: |
| 99 | + continue |
| 100 | + c = c if isinstance(c, list) else c.get("comments", c.get("data", [])) |
| 101 | + for cm in reversed(c): |
| 102 | + body = cm.get("body") or "" |
| 103 | + b = body.lower() |
| 104 | + if "verdict:" not in b: |
| 105 | + continue |
| 106 | + tail = b.split("verdict:", 1)[1][:40] |
| 107 | + shas = re.findall(r"\b[0-9a-f]{40}\b", body) # SHA the reviewer pinned |
| 108 | + sha = shas[-1] if shas else "" |
| 109 | + if "accept" in tail: |
| 110 | + verdict = "accept"; break |
| 111 | + if "request_changes" in tail or "request changes" in tail: |
| 112 | + verdict = "request_changes"; break |
| 113 | + if verdict != "unknown": |
| 114 | + break |
| 115 | +print(verdict, sha) |
| 116 | +' |
| 117 | +} |
| 118 | + |
| 119 | +# ── 2. Mint a GitHub App installation access token (RS256 JWT via openssl) ──── |
| 120 | +mint_installation_token() { |
| 121 | + local app_id="$1" install_id="$2" pem="$3" |
| 122 | + local now exp header payload b64 signing sig jwt |
| 123 | + now=$(date +%s); exp=$((now + 540)) # 9-min window (max 10) |
| 124 | + b64() { openssl base64 -A | tr '+/' '-_' | tr -d '='; } |
| 125 | + header=$(printf '{"alg":"RS256","typ":"JWT"}' | b64) |
| 126 | + payload=$(printf '{"iat":%d,"exp":%d,"iss":"%s"}' "$((now-60))" "$exp" "$app_id" | b64) |
| 127 | + signing="${header}.${payload}" |
| 128 | + sig=$(printf '%s' "$signing" | openssl dgst -sha256 -sign "$pem" -binary | b64) |
| 129 | + jwt="${signing}.${sig}" |
| 130 | + curl -fsS -m 20 -X POST \ |
| 131 | + -H "Authorization: Bearer ${jwt}" \ |
| 132 | + -H "Accept: application/vnd.github+json" \ |
| 133 | + "https://api.github.com/app/installations/${install_id}/access_tokens" \ |
| 134 | + | python3 -c 'import sys,json; print(json.load(sys.stdin)["token"])' |
| 135 | +} |
| 136 | + |
| 137 | +# ── main ──────────────────────────────────────────────────────────────────── |
| 138 | +read -r VERDICT REVIEWED_SHA <<<"$(resolve_verdict || echo 'unknown ')" |
| 139 | +log "PR #${PR} Codex verdict = ${VERDICT}${REVIEWED_SHA:+ (reviewed ${REVIEWED_SHA:0:9})}" |
| 140 | + |
| 141 | +if [[ "$VERDICT" != "accept" ]]; then |
| 142 | + log "verdict is not 'accept' — NOT approving (no-op). request_changes/unknown must not auto-approve." |
| 143 | + exit 3 |
| 144 | +fi |
| 145 | + |
| 146 | +# Current PR head + author (one API read). |
| 147 | +read -r HEAD AUTHOR PR_STATE <<<"$(gh pr view "$PR" --repo "$REPO" --json headRefOid,author,state \ |
| 148 | + -q '"\(.headRefOid) \(.author.login) \(.state)"' 2>/dev/null || echo '? ? ?')" |
| 149 | +log "PR #${PR} state=${PR_STATE} head=${HEAD:0:9} author=${AUTHOR} (App approves as a distinct identity)" |
| 150 | + |
| 151 | +# Don't act on already-closed/merged PRs. |
| 152 | +if [[ "$PR_STATE" != "OPEN" ]]; then |
| 153 | + log "PR is ${PR_STATE} — nothing to do." |
| 154 | + exit 0 |
| 155 | +fi |
| 156 | + |
| 157 | +# Fail-closed stale-verdict guard (MCP-1249 Codex REQUEST_CHANGES): we approve |
| 158 | +# ONLY the exact SHA the reviewer reviewed. The checks below are UNCONDITIONAL — |
| 159 | +# a missing or non-matching reviewed SHA must REFUSE, never approve blind. This |
| 160 | +# closes the hole where an old ACCEPT (or a verdict that pinned no SHA) would |
| 161 | +# auto-approve the current head after a post-review force-push of unreviewed code. |
| 162 | +if [[ -z "$HEAD" ]]; then |
| 163 | + log "REFUSING: could not resolve the PR head SHA — fail-closed (will not approve)." |
| 164 | + exit 5 |
| 165 | +fi |
| 166 | +if [[ -z "$REVIEWED_SHA" ]]; then |
| 167 | + log "REFUSING: no reviewed SHA could be resolved from the ACCEPT verdict — fail-closed (will not approve blind)." |
| 168 | + log " The reviewer must pin the reviewed commit SHA in the verdict comment; for a manual override pass --reviewed-sha <sha>." |
| 169 | + exit 7 |
| 170 | +fi |
| 171 | +if [[ "$REVIEWED_SHA" != "$HEAD" ]]; then |
| 172 | + log "STALE: reviewer reviewed ${REVIEWED_SHA:0:9} but head is ${HEAD:0:9} — NOT approving (re-review needed)." |
| 173 | + exit 6 |
| 174 | +fi |
| 175 | + |
| 176 | +# Idempotency: skip if the Gatekeeper already has an APPROVED review at this head. |
| 177 | +ALREADY="$(gh api "repos/${REPO}/pulls/${PR}/reviews" 2>/dev/null \ |
| 178 | + | HEAD="$HEAD" python3 -c ' |
| 179 | +import sys, json, os |
| 180 | +head = os.environ.get("HEAD","") |
| 181 | +try: revs = json.load(sys.stdin) |
| 182 | +except Exception: revs = [] |
| 183 | +for r in revs: |
| 184 | + u = (r.get("user") or {}) |
| 185 | + if u.get("type") == "Bot" and "gatekeeper" in (u.get("login","").lower()) \ |
| 186 | + and r.get("state") == "APPROVED" and (not head or r.get("commit_id") == head): |
| 187 | + print("yes"); break |
| 188 | +' 2>/dev/null)" |
| 189 | +if [[ "$ALREADY" == "yes" ]]; then |
| 190 | + log "already approved by Gatekeeper at head ${HEAD:0:9} — no-op (idempotent)." |
| 191 | + exit 0 |
| 192 | +fi |
| 193 | + |
| 194 | +if [[ -z "${GATEKEEPER_APP_ID:-}" || -z "${GATEKEEPER_INSTALLATION_ID:-}" || -z "${GATEKEEPER_PRIVATE_KEY:-}" ]]; then |
| 195 | + log "NOT CONFIGURED: set GATEKEEPER_APP_ID, GATEKEEPER_INSTALLATION_ID, GATEKEEPER_PRIVATE_KEY" |
| 196 | + log "(register the 'MCPProxy Gatekeeper' App, install on ${REPO}, drop creds in ~/.mcpproxy-gatekeeper/env)" |
| 197 | + exit 2 |
| 198 | +fi |
| 199 | +[[ -f "$GATEKEEPER_PRIVATE_KEY" ]] || { log "private key not found: $GATEKEEPER_PRIVATE_KEY"; exit 2; } |
| 200 | + |
| 201 | +BODY="✅ **Gatekeeper approval** — Codex review verdict: ACCEPT. |
| 202 | +
|
| 203 | +This approval is posted automatically by the MCPProxy Gatekeeper App on behalf of the Codex reviewer (verdict of record lives in the Paperclip review thread). Author≠approver satisfied; QA + CI gates enforced separately. |
| 204 | +
|
| 205 | +_Auto-approved per Model B (MCP-1249)._" |
| 206 | + |
| 207 | +if [[ "$DRY_RUN" == "1" ]]; then |
| 208 | + log "DRY-RUN: would mint installation token (app=${GATEKEEPER_APP_ID} install=${GATEKEEPER_INSTALLATION_ID}) and POST APPROVE review on ${REPO}#${PR}." |
| 209 | + exit 0 |
| 210 | +fi |
| 211 | + |
| 212 | +log "minting installation token…" |
| 213 | +TOKEN="$(mint_installation_token "$GATEKEEPER_APP_ID" "$GATEKEEPER_INSTALLATION_ID" "$GATEKEEPER_PRIVATE_KEY")" \ |
| 214 | + || { log "failed to mint installation token"; exit 5; } |
| 215 | + |
| 216 | +log "posting APPROVE review on ${REPO}#${PR}…" |
| 217 | +HTTP=$(curl -s -o /tmp/gatekeeper-resp.json -w '%{http_code}' -m 20 -X POST \ |
| 218 | + -H "Authorization: token ${TOKEN}" \ |
| 219 | + -H "Accept: application/vnd.github+json" \ |
| 220 | + "https://api.github.com/repos/${REPO}/pulls/${PR}/reviews" \ |
| 221 | + --data "$(python3 -c 'import json,sys; print(json.dumps({"event":"APPROVE","body":sys.argv[1]}))' "$BODY")") |
| 222 | + |
| 223 | +if [[ "$HTTP" == "200" ]]; then |
| 224 | + log "✅ approved ${REPO}#${PR} as Gatekeeper." |
| 225 | + exit 0 |
| 226 | +else |
| 227 | + log "❌ GitHub review POST failed (HTTP ${HTTP}):"; cat /tmp/gatekeeper-resp.json >&2; echo >&2 |
| 228 | + exit 5 |
| 229 | +fi |
0 commit comments