approval-gate-demo/gate_demo.py
caelum0x e4523b2c7c feat(SCR-BRD): approval gate demo, one script against the live API, transcript and video
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-30 20:58:37 +03:00

415 lines
17 KiB
Python

#!/usr/bin/env python3
"""Scribase production approver gate, end to end, against the live hosted API.
An agent token without admin scope tries `DROP TABLE` on a production
environment. Scribase answers `202 approval_required`, emails the named
approver, and runs the stored request only after that person approves.
Every step is a real HTTP call to console.scribase.com / api.scribase.com.
The script makes a throwaway mail.tm inbox, signs up with it, and deletes
the account at the end. Nothing is mocked and every response printed is the
unedited server response (the agent token is the only thing redacted).
1. Sign up with a throwaway inbox, verify by magic link.
2. Create an org, a project and a production environment.
3. Name the inbox as the project's production approver.
4. Mint an agent token: project write + sql read/write, no admin.
5. With that token: create a table, then DROP it.
no confirm -> 200 confirmation_required, nothing runs
confirm: true -> 202 approval_required, nothing runs
6. Read the approval email, take the decision link from it.
7. Approve (what clicking Approve in the email does).
8. Poll the approval until state=executed; the table is gone only now.
9. Revoke the token; its next call is a 401.
10. Delete the account.
Docs: https://docs.scribase.com/docs/agents/prod-approver
Usage: python3 gate_demo.py [--keep] (Python 3.9+, standard library only)
"""
import argparse
import http.cookiejar
import json
import os
import random
import re
import shutil
import string
import sys
import tempfile
import time
import urllib.error
import urllib.request
CONSOLE = "https://console.scribase.com"
CONTROL = CONSOLE + "/api/control/v1"
API = "https://api.scribase.com/v1"
MAILTM = "https://api.mail.tm"
READY_TIMEOUT_S = 240
MAIL_TIMEOUT_S = 120
def rand(n: int) -> str:
return "".join(random.choice(string.ascii_lowercase + string.digits) for _ in range(n))
def banner(text: str) -> None:
print()
print(f"# {text}")
def show(method: str, url: str, status: int, body) -> None:
print(f"$ {method} {url}")
pretty = json.dumps(body, indent=2) if isinstance(body, (dict, list)) else str(body)
print(f"-> {status}")
print(pretty)
class Client:
"""Cookie-session HTTP client for the console's same-origin control-plane proxy."""
def __init__(self) -> None:
self.jar = http.cookiejar.CookieJar()
self.opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.jar))
def csrf(self):
for cookie in self.jar:
if cookie.name in ("__Host-scb_csrf", "scb_csrf"):
return cookie.value
return None
def call(self, method, url, body=None, headers=None, idempotent=False):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, method=method)
req.add_header("Content-Type", "application/json")
req.add_header("Accept", "application/json")
req.add_header("Origin", CONSOLE)
req.add_header("User-Agent", "scribase-approval-gate-demo/1.0")
token = self.csrf()
if token and method != "GET":
req.add_header("x-scribase-csrf", token)
if idempotent:
req.add_header("Idempotency-Key", "qa-" + rand(16))
for key, value in (headers or {}).items():
req.add_header(key, value)
try:
with self.opener.open(req, timeout=30) as resp:
text = resp.read().decode()
return resp.status, (json.loads(text) if text else None)
except urllib.error.HTTPError as err:
text = err.read().decode()
try:
return err.code, json.loads(text)
except ValueError:
return err.code, {"raw": text[:500]}
def direct_call(method, url, body=None, bearer=None, idempotent=False):
"""A plain call against api.scribase.com, no cookie session -- exactly
what a CLI/agent/CI token does."""
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, method=method)
req.add_header("Content-Type", "application/json")
req.add_header("Accept", "application/json")
req.add_header("User-Agent", "scribase-approval-gate-demo/1.0")
if bearer:
req.add_header("Authorization", f"Bearer {bearer}")
if idempotent:
req.add_header("Idempotency-Key", "qa-" + rand(16))
try:
with urllib.request.urlopen(req, timeout=30) as resp:
text = resp.read().decode()
return resp.status, (json.loads(text) if text else None)
except urllib.error.HTTPError as err:
text = err.read().decode()
try:
return err.code, json.loads(text)
except ValueError:
return err.code, {"raw": text[:500]}
def redact_token(minted):
"""A copy of the mint response that is safe to print: the secret is cut
from both the `token` field and the `agent_message` sentence."""
safe = dict(minted or {})
secret = safe.get("token")
if secret:
for key, value in safe.items():
if isinstance(value, str) and secret in value:
safe[key] = value.replace(secret, secret[:38] + "***redacted***")
safe["token"] = "scb_agt_***redacted***"
return safe
def mailtm_inbox():
plain = Client()
_, domains = plain.call("GET", MAILTM + "/domains")
items = domains if isinstance(domains, list) else domains["hydra:member"]
domain = items[0]["domain"]
address = f"scribaseqa{rand(10)}@{domain}" # this prefix keeps demo runs out of Scribase usage counts
password = rand(20)
status, _ = plain.call("POST", MAILTM + "/accounts", {"address": address, "password": password})
if status not in (200, 201):
sys.exit(f"mail.tm account failed: {status}")
_, tok = plain.call("POST", MAILTM + "/token", {"address": address, "password": password})
return address, tok["token"]
def wait_for_pattern(mail_token, pattern, label, seen_ids=None):
plain = Client()
auth = {"Authorization": f"Bearer {mail_token}"}
deadline = time.time() + MAIL_TIMEOUT_S
seen_ids = seen_ids if seen_ids is not None else set()
while time.time() < deadline:
_, msgs = plain.call("GET", MAILTM + "/messages", headers=auth)
items = msgs if isinstance(msgs, list) else (msgs or {}).get("hydra:member", [])
for msg in items:
if msg["id"] in seen_ids:
continue
_, full = plain.call("GET", MAILTM + "/messages/" + msg["id"], headers=auth)
text = (full or {}).get("text") or ""
match = re.search(pattern, text)
if match:
seen_ids.add(msg["id"])
return match, text
time.sleep(2)
sys.exit(f"no {label} email arrived in mail.tm within {MAIL_TIMEOUT_S}s")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("--keep", action="store_true", help="skip account deletion cleanup")
args = parser.parse_args()
address, mail_token = mailtm_inbox()
print(f"$ mail.tm inbox: {address}")
seen = set()
c = Client()
t0 = time.time()
marks = []
def mark(name):
marks.append((name, round(time.time() - t0, 1)))
banner("1. sign up -- zero-human account creation, mail.tm address")
password = "Qa-" + rand(18) + "!9"
status, body = c.call("POST", CONSOLE + "/api/auth/signup", {"email": address, "password": password})
show("POST", CONSOLE + "/api/auth/signup", status, body)
if status >= 300:
sys.exit(f"signup failed {status}: {body}")
mark("signup")
c.call("POST", CONSOLE + "/api/auth/magic-link/request", {"email": address})
match, _ = wait_for_pattern(mail_token, r"token=(scb_mgl_[A-Za-z0-9]+)", "magic-link", seen)
link_token = match.group(1)
status, body = c.call("POST", CONSOLE + "/api/auth/magic-link/verify", {"token": link_token})
show("POST", CONSOLE + "/api/auth/magic-link/verify", status, {"verified": status < 300})
if status >= 300:
sys.exit(f"verify failed {status}: {body}")
mark("email_verified")
banner("2. create org, project, production environment")
org = "proof-" + rand(8)
project = "approver-proof"
status, body = c.call("PUT", f"{CONTROL}/organizations/{org}", {"display_name": "Approval proof"})
show("PUT", f"{CONTROL}/organizations/{org}", status, body)
if status >= 300:
sys.exit(f"org failed {status}: {body}")
mark("org")
status, body = c.call(
"PUT", f"{CONTROL}/organizations/{org}/projects/{project}",
{"region": "eu-frankfurt", "postgres_major": 17},
)
show("PUT", f"{CONTROL}/organizations/{org}/projects/{project}", status, body)
if status >= 300:
sys.exit(f"project failed {status}: {body}")
mark("project")
env_submit = time.time()
status, body = c.call(
"POST", f"{CONTROL}/environments",
{
"organization_id": org, "project_id": project, "environment_id": "production",
"kind": "production", "data_mode": "schema_only", "region": "eu-frankfurt", "postgres_major": 17,
},
idempotent=True,
)
show("POST", f"{CONTROL}/environments", status, body)
if status >= 300:
sys.exit(f"environment failed {status}: {body}")
mark("env_requested")
phase = None
while time.time() - env_submit < READY_TIMEOUT_S:
_, env = c.call("GET", f"{CONTROL}/organizations/{org}/projects/{project}/environments/production")
phase = (env or {}).get("phase") or ((env or {}).get("status") or {}).get("phase")
if str(phase).lower() == "ready":
break
time.sleep(1)
elapsed = round(time.time() - env_submit, 1)
print(f"production environment ready in {elapsed}s")
mark("env_ready")
if str(phase).lower() != "ready":
sys.exit(f"environment never became ready (last phase: {phase})")
banner("3. name a production approver -- the human in the loop")
approver_url = f"{CONTROL}/organizations/{org}/projects/{project}/prod-approver"
status, body = c.call("PUT", approver_url, {"email": address})
show("PUT", approver_url, status, body)
if status >= 300:
sys.exit(f"setting the production approver failed {status}: {body}")
mark("approver_set")
banner("4. mint a NON-admin agent token -- no project:*:admin scope")
scopes = [f"project:{project}:write", "sql:read", "sql:write"]
status, minted = c.call(
"POST", f"{CONTROL}/account/tokens",
{"name": "ci-agent-non-admin", "organization_id": org, "scopes": scopes, "ttl": "2h"},
idempotent=True,
)
show("POST", f"{CONTROL}/account/tokens", status, redact_token(minted))
if status >= 300:
sys.exit(f"minting an agent token failed {status}: {minted}")
agent_token = minted["token"]
token_id = minted.get("id")
print(f"token scopes: {', '.join(scopes)} (no admin)")
mark("token_minted")
execute_url = f"{API}/organizations/{org}/projects/{project}/environments/production/database/execute"
banner("5a. CREATE a real table -- non-destructive, runs immediately")
status, body = direct_call(
"POST", execute_url,
{
"query": (
"create table public.proof_widgets (id bigint generated always as identity primary key, note text not null);\n"
"alter table public.proof_widgets enable row level security;\n"
"create policy proof_widgets_read on public.proof_widgets for select using (auth.uid() is not null);"
)
},
bearer=agent_token,
)
show("POST", execute_url, status, body)
if status >= 300:
sys.exit(f"create table failed unexpectedly {status}: {body}")
mark("table_created")
banner("5b. DROP the table, no confirm -- the SQL editor lists it back, nothing runs")
drop_body = {"query": "drop table public.proof_widgets;"}
status, body = direct_call("POST", execute_url, drop_body, bearer=agent_token)
show("POST", execute_url, status, body)
mark("drop_listed_unconfirmed")
banner("5c. same DROP, confirm: true -- destructive + production + non-admin token")
status, body = direct_call("POST", execute_url, {**drop_body, "confirm": True}, bearer=agent_token)
show("POST", execute_url, status, body)
if status != 202 or not isinstance(body, dict) or body.get("status") != "approval_required":
sys.exit(
"CRITICAL FINDING: the production approver gate did not behave as documented -- "
f"expected 202 approval_required, got {status}: {body}"
)
approval_id = body["approval_id"]
status_url = API.rsplit("/v1", 1)[0] + body["status_url"]
print(f"BLOCKED: the DROP did not run. approval_id={approval_id}")
mark("approval_required")
banner("5d. confirm the table is still there -- nothing ran")
status, body = direct_call(
"POST", f"{API}/organizations/{org}/projects/{project}/environments/production/database/query",
{"query": "select to_regclass('public.proof_widgets') is not null as still_there"},
bearer=agent_token,
)
show("POST", f"{API}/organizations/{org}/projects/{project}/environments/production/database/query", status, body)
mark("confirmed_still_there")
banner("6. the approval-request email -- the real decision link")
match, raw = wait_for_pattern(
mail_token, r"/approve\?id=(apr_[a-f0-9]+)&t=([A-Za-z0-9]+)&d=approve", "approval-request", seen
)
mail_approval_id, decision_token = match.group(1), match.group(2)
print(f"email received, decision link carries approval_id={mail_approval_id}")
print(f"matches the approval_id from step 5c: {mail_approval_id == approval_id}")
mark("approval_email_received")
if mail_approval_id != approval_id:
sys.exit("CRITICAL FINDING: the emailed approval id does not match the API's approval_id")
banner("7. approve -- the one human action, as a click on the email link would do")
decision_url = f"{API}/prod-approvals/{approval_id}/decision"
status, body = direct_call("POST", decision_url, {"token": decision_token, "decision": "approve"})
show("POST", decision_url, status, body)
if status >= 300:
sys.exit(f"the decision call failed {status}: {body}")
mark("approved")
banner("8. poll the status url until the stored DROP has actually run")
state = None
deadline = time.time() + 60
while time.time() < deadline:
status, body = direct_call("GET", status_url + "?wait=25", bearer=agent_token)
state = (body or {}).get("state")
print(f"state={state}")
if state in ("executed", "failed", "denied", "expired"):
show("GET", status_url + "?wait=25", status, body)
break
mark("final_state_" + str(state))
if state != "executed":
sys.exit(f"CRITICAL FINDING: expected state=executed after approval, got {state}: {body}")
status, body = direct_call(
"POST", f"{API}/organizations/{org}/projects/{project}/environments/production/database/query",
{"query": "select to_regclass('public.proof_widgets') is not null as still_there"},
bearer=agent_token,
)
show("POST", f"{API}/organizations/{org}/projects/{project}/environments/production/database/query", status, body)
rows = (body or {}).get("rows") or (body or {}).get("statements", [{}])[0].get("rows", [])
still_there = rows[0].get("still_there") if rows else None
print(f"table gone (only now, after approval): {still_there is False}")
mark("confirmed_dropped")
if still_there is not False:
sys.exit("CRITICAL FINDING: the table was not actually dropped after approval")
banner("9. revoke the agent token, verify the next call is a real 401")
revoke_url = f"{CONTROL}/account/tokens/{token_id}"
status, body = c.call("DELETE", revoke_url, idempotent=True)
show("DELETE", revoke_url, status, body)
mark("token_revoked")
status, body = direct_call(
"POST", f"{API}/organizations/{org}/projects/{project}/environments/production/database/query",
{"query": "select 1"},
bearer=agent_token,
)
show("POST (revoked token)", f"{API}/organizations/{org}/projects/{project}/environments/production/database/query", status, body)
mark("revoked_token_rejected_" + str(status))
if status != 401:
sys.exit(f"CRITICAL FINDING: a revoked agent token was not rejected with 401 (got {status})")
banner("10. clean up -- delete the demo account")
if not args.keep:
status, body = c.call(
"POST", CONSOLE + "/api/control/v1/account/deletion",
{"confirm_email": address, "refund_unused": True, "reason": "approval-gate-demo cleanup"},
idempotent=True,
)
show("POST", CONSOLE + "/api/control/v1/account/deletion", status, body)
mark("account_deleted")
print()
print("=== SUMMARY ===")
print(json.dumps({
"mail": address,
"org": org,
"project": project,
"approval_id": approval_id,
"steps": dict(marks),
"total_s": round(time.time() - t0, 1),
"result": "the named production approver gate blocked a non-admin agent token's "
"destructive DROP TABLE on production, required a real human approval, "
"then ran it exactly once after approval, and a revoked token was rejected",
}, indent=2))
if __name__ == "__main__":
main()