Skip to content
pi-c Artifact [dc6ab0e163]
Login

Artifact [dc6ab0e163]

Artifact dc6ab0e163f99f9d9ecbf0bde7b995859ad613638d899be259b6dd061047a9b5:


#!/bin/sh
# End-to-end MCP OAuth tests against a self-contained fake OAuth + Streamable HTTP MCP server:
# 401 discovery (RFC 9728 PRM + RFC 8414 AS), DCR (RFC 7591), pre-registered client
# (client_secret_basic & client_secret_post), authServerMetadataUrl, localhost callbackUrl,
# S256 PKCE loopback + --no-browser paste, RFC 9207 iss validation, proactive & reactive 401
# refresh, concurrent lockfile refresh with rotating refresh tokens, 403 insufficient_scope
# step-up, invalid_grant / invalid_client recovery, --mcp-config login/logout, pic mcp logout,
# and secret non-leakage.
set -eu
PIC=${PIC:?set PIC to the pic binary}
SQLITE3=${SQLITE3:-sqlite3}
PYTHON=${PYTHON:-python3}
T=$(mktemp -d "${TMPDIR:-/tmp}/pic-mcp-oauth.XXXXXX")
T=$(cd "$T" && pwd -P)
spid=
cleanup() { [ -n "$spid" ] && kill "$spid" 2>/dev/null || :; rm -rf -- "$T"; }
trap cleanup EXIT HUP INT TERM
fail() { printf 'FAIL: %s\n' "$*" >&2; exit 1; }

mkdir "$T/ws" "$T/home"
for v in $(env | sed -nE 's/^([A-Za-z0-9_]*_(API_KEY|TOKEN))=.*/\1/p'); do unset "$v"; done
export HOME="$T/home" PIC_MODEL_CATALOG=offline PIC_PI_EXPORT=0 PIC_NO_KEY_CHECKS=1
pic() { "$PIC" --db "$T/j" --workspace "$T/ws" "$@"; }

cat > "$T/fake_server.py" <<'PYEOF'
import base64, hashlib, json, os, sys, threading, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import parse_qs, urlencode, urlparse

port_file = sys.argv[1]
state_file = sys.argv[2]
deadline = time.time() + int(sys.argv[3])

lock = threading.Lock()
STATE = {
    "dcr_count": 0,
    "refresh_count": 0,
    "token_seq": 0,
    "clients": {
        "pre-basic": {"secret": "BASIC_SECRET_XYZ", "auth": "client_secret_basic"},
        "pre-post": {"secret": "POST_SECRET_XYZ", "auth": "client_secret_post"},
    },
    "codes": {},          # code -> {challenge, redirect_uri, client_id, scope, resource}
    "tokens": {},         # access -> {scope, client_id, active}
    "refreshes": {},      # refresh -> {client_id, scope, used}
    "last_authorize": {},
    "last_token_auth": "",
    "last_dcr": {},
    "mode": {
        "expires_in": 3600,
        "omit_refresh_on_refresh": False,
        "rotate_refresh": True,
        "refresh_delay": 0.0,
        "force_token_error": "",     # invalid_grant | invalid_client
        "echo_secret_in_error": False,
        "big_auth_methods": False,
        "require_write_scope": True,
        "bad_iss": False,
    },
}

def dump_state():
    with open(state_file + ".tmp", "w") as f:
        json.dump({
            "dcr_count": STATE["dcr_count"],
            "refresh_count": STATE["refresh_count"],
            "last_authorize": STATE["last_authorize"],
            "last_token_auth": STATE["last_token_auth"],
            "last_dcr": STATE["last_dcr"],
        }, f)
    os.replace(state_file + ".tmp", state_file)

def pkce_s256(verifier):
    d = hashlib.sha256(verifier.encode("ascii")).digest()
    return base64.urlsafe_b64encode(d).rstrip(b"=").decode("ascii")

class Handler(BaseHTTPRequestHandler):
    def log_message(self, fmt, *args):
        pass

    def send_json(self, code, obj, headers=None):
        body = json.dumps(obj).encode("utf-8")
        self.send_response(code)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        if headers:
            for k, v in headers.items():
                self.send_header(k, v)
        self.end_headers()
        self.wfile.write(body)

    def base_url(self):
        return f"http://127.0.0.1:{self.server.server_address[1]}"

    def do_GET(self):
        p = urlparse(self.path)
        base = self.base_url()
        if p.path == "/.well-known/oauth-protected-resource/mcp":
            if "application/json" not in self.headers.get("Accept", ""):
                return self.send_json(406, {"error": "missing Accept"})
            if not self.headers.get("MCP-Protocol-Version"):
                return self.send_json(400, {"error": "missing MCP-Protocol-Version"})
            return self.send_json(200, {
                "resource": f"{base}/mcp",
                "authorization_servers": [f"{base}/auth"],
                "scopes_supported": ["mcp:read"],
            })
        if p.path == "/.well-known/oauth-authorization-server/auth":
            with lock:
                big_am = STATE["mode"]["big_auth_methods"]
            methods = ["none", "client_secret_basic"]
            if big_am:
                methods = [f"custom_auth_method_padding_name_{i:02d}" for i in range(18)] + methods
            return self.send_json(200, {
                "issuer": f"{base}/auth",
                "authorization_endpoint": f"{base}/authorize",
                "token_endpoint": f"{base}/token",
                "registration_endpoint": f"{base}/register",
                "response_types_supported": ["code"],
                "code_challenge_methods_supported": ["S256"],
                "token_endpoint_auth_methods_supported": methods,
                "authorization_response_iss_parameter_supported": True,
            })
        if p.path == "/custom-meta":
            return self.send_json(200, {
                "issuer": f"{base}/custom-as",
                "authorization_endpoint": f"{base}/authorize-custom",
                "token_endpoint": f"{base}/token",
                "registration_endpoint": f"{base}/register",
                "response_types_supported": ["code"],
                "code_challenge_methods_supported": ["S256"],
                "token_endpoint_auth_methods_supported": ["client_secret_post"],
                "authorization_response_iss_parameter_supported": True,
            })
        if p.path in ("/authorize", "/authorize-custom"):
            qs = parse_qs(p.query)
            q1 = {k: v[0] for k, v in qs.items()}
            if q1.get("response_type") != "code" or q1.get("code_challenge_method") != "S256":
                return self.send_json(400, {"error": "invalid_request"})
            with lock:
                STATE["last_authorize"] = q1
                STATE["token_seq"] += 1
                code = f"code_{STATE['token_seq']}"
                STATE["codes"][code] = {
                    "challenge": q1.get("code_challenge", ""),
                    "redirect_uri": q1.get("redirect_uri", ""),
                    "client_id": q1.get("client_id", ""),
                    "scope": q1.get("scope", "mcp:read"),
                    "resource": q1.get("resource", ""),
                }
                bad_iss = STATE["mode"]["bad_iss"]
                dump_state()
            iss = f"{base}/wrong-issuer" if bad_iss else (f"{base}/custom-as" if p.path == "/authorize-custom" else f"{base}/auth")
            redir = q1["redirect_uri"] + "?" + urlencode({
                "code": code,
                "state": q1.get("state", ""),
                "iss": iss,
            })
            self.send_response(302)
            self.send_header("Location", redir)
            self.send_header("Content-Length", "0")
            self.end_headers()
            return
        self.send_json(404, {"error": "not_found"})

    def do_POST(self):
        p = urlparse(self.path)
        n = int(self.headers.get("Content-Length", "0"))
        raw = self.rfile.read(n).decode("utf-8") if n else ""
        base = self.base_url()

        # Test control endpoint
        if p.path == "/_control":
            cmd = json.loads(raw)
            with lock:
                if "mode" in cmd:
                    STATE["mode"].update(cmd["mode"])
                if cmd.get("revoke_access"):
                    for t in STATE["tokens"].values():
                        t["active"] = False
                if cmd.get("reset_counts"):
                    STATE["refresh_count"] = 0
                dump_state()
            return self.send_json(200, {"ok": True})

        if p.path == "/register":
            req = json.loads(raw)
            if req.get("application_type") != "native" or not req.get("redirect_uris"):
                return self.send_json(400, {"error": "invalid_client_metadata"})
            with lock:
                STATE["dcr_count"] += 1
                cid = f"dcr-client-{STATE['dcr_count']}"
                STATE["clients"][cid] = {"secret": None, "auth": "none"}
                STATE["last_dcr"] = req
                dump_state()
            return self.send_json(201, {
                "client_id": cid,
                "redirect_uris": req["redirect_uris"],
                "token_endpoint_auth_method": "none",
            })

        if p.path == "/token":
            qs = {k: v[0] for k, v in parse_qs(raw).items()}
            auth_hdr = self.headers.get("Authorization", "")
            cid = qs.get("client_id", "")
            csec = qs.get("client_secret", "")
            auth_used = "none"
            if auth_hdr.startswith("Basic "):
                dec = base64.b64decode(auth_hdr[6:]).decode("utf-8")
                cid, csec = dec.split(":", 1)
                auth_used = "client_secret_basic"
            elif csec:
                auth_used = "client_secret_post"
            with lock:
                STATE["last_token_auth"] = auth_used
                force_err = STATE["mode"]["force_token_error"]
                delay = STATE["mode"]["refresh_delay"]
                client = STATE["clients"].get(cid)
            if not client:
                return self.send_json(401, {"error": "invalid_client", "error_description": "unknown client"})
            if client["secret"] is not None:
                if csec != client["secret"] or auth_used != client["auth"]:
                    return self.send_json(401, {"error": "invalid_client", "error_description": f"bad auth {auth_used}"})
            grant = qs.get("grant_type")
            if grant == "authorization_code":
                code = qs.get("code", "")
                with lock:
                    rec = STATE["codes"].pop(code, None)
                if not rec or rec["client_id"] != cid or rec["redirect_uri"] != qs.get("redirect_uri", ""):
                    return self.send_json(400, {"error": "invalid_grant", "error_description": "bad code"})
                if pkce_s256(qs.get("code_verifier", "")) != rec["challenge"]:
                    return self.send_json(400, {"error": "invalid_grant", "error_description": "pkce mismatch"})
                with lock:
                    STATE["token_seq"] += 1
                    tok = f"tok_{STATE['token_seq']}"
                    ref = f"ref_tok_{STATE['token_seq']:06d}"
                    exp = STATE["mode"]["expires_in"]
                    STATE["tokens"][tok] = {"scope": rec["scope"], "client_id": cid, "active": True}
                    STATE["refreshes"][ref] = {"client_id": cid, "scope": rec["scope"], "used": False}
                    dump_state()
                return self.send_json(200, {
                    "access_token": tok,
                    "token_type": "Bearer",
                    "expires_in": exp,
                    "refresh_token": ref,
                    "scope": rec["scope"],
                })
            if grant == "refresh_token":
                if delay > 0:
                    time.sleep(delay)
                rt = qs.get("refresh_token", "")
                if force_err:
                    desc = f"forced error echoing {csec or ''} and {rt}" if STATE["mode"]["echo_secret_in_error"] else "forced error"
                    return self.send_json(400, {"error": force_err, "error_description": desc})
                with lock:
                    rec = STATE["refreshes"].get(rt)
                    if not rec or rec["client_id"] != cid or (STATE["mode"]["rotate_refresh"] and rec["used"]):
                        return self.send_json(400, {"error": "invalid_grant", "error_description": "stale refresh"})
                    rec["used"] = True
                    STATE["refresh_count"] += 1
                    STATE["token_seq"] += 1
                    tok = f"tok_{STATE['token_seq']}"
                    STATE["tokens"][tok] = {"scope": rec["scope"], "client_id": cid, "active": True}
                    resp = {
                        "access_token": tok,
                        "token_type": "Bearer",
                        "expires_in": STATE["mode"]["expires_in"],
                    }
                    if not STATE["mode"]["omit_refresh_on_refresh"]:
                        new_ref = f"ref_tok_{STATE['token_seq']:06d}"
                        STATE["refreshes"][new_ref] = {"client_id": cid, "scope": rec["scope"], "used": False}
                        resp["refresh_token"] = new_ref
                    else:
                        rec["used"] = False  # server kept same refresh_token
                    dump_state()
                return self.send_json(200, resp)
            return self.send_json(400, {"error": "unsupported_grant_type"})

        if p.path == "/mcp":
            auth = self.headers.get("Authorization", "")
            tok = auth[7:] if auth.startswith("Bearer ") else ""
            with lock:
                tinfo = STATE["tokens"].get(tok)
                req_write = STATE["mode"]["require_write_scope"]
            if not tinfo or not tinfo["active"]:
                hdr = f'Bearer resource_metadata="{base}/.well-known/oauth-protected-resource/mcp", scope="mcp:read"'
                return self.send_json(401, {"error": "unauthorized"}, {"WWW-Authenticate": hdr})
            msg = json.loads(raw)
            mid = msg.get("id")
            method = msg.get("method", "")
            if method == "server/discover":
                return self.send_json(200, {
                    "jsonrpc": "2.0", "id": mid,
                    "result": {
                        "resultType": "complete",
                        "supportedVersions": ["2026-07-28"],
                        "capabilities": {"tools": {}},
                        "_meta": {"io.modelcontextprotocol/serverInfo": {"name": "fake-oauth-mcp", "version": "1"}},
                    },
                })
            if method == "tools/list":
                return self.send_json(200, {
                    "jsonrpc": "2.0", "id": mid,
                    "result": {
                        "resultType": "complete",
                        "tools": [
                            {"name": "echo", "description": "Echo", "inputSchema": {"type": "object"}, "annotations": {"readOnlyHint": True}},
                            {"name": "write_note", "description": "Write", "inputSchema": {"type": "object"}},
                        ],
                    },
                })
            if method == "tools/call":
                tname = msg.get("params", {}).get("name", "")
                targs = msg.get("params", {}).get("arguments", {})
                if tname == "write_note" and req_write and "mcp:write" not in tinfo["scope"].split():
                    hdr = 'Bearer error="insufficient_scope", scope="mcp:write"'
                    return self.send_json(403, {"error": "insufficient_scope"}, {"WWW-Authenticate": hdr})
                return self.send_json(200, {
                    "jsonrpc": "2.0", "id": mid,
                    "result": {"resultType": "complete", "content": [{"type": "text", "text": f"{tname}: {json.dumps(targs)}"}]},
                })
            return self.send_json(200, {"jsonrpc": "2.0", "id": mid, "error": {"code": -32601, "message": "not found"}})

        self.send_json(404, {"error": "not_found"})

srv = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
srv.timeout = 0.2
with open(port_file + ".tmp", "w") as f:
    f.write(str(srv.server_address[1]) + "\n")
os.replace(port_file + ".tmp", port_file)
dump_state()

def watchdog():
    while time.time() < deadline:
        time.sleep(0.5)
    os._exit(0)

threading.Thread(target=watchdog, daemon=True).start()
srv.serve_forever()
PYEOF

"$PYTHON" -u "$T/fake_server.py" "$T/port" "$T/state.json" 120 &
spid=$!
i=0
while [ ! -s "$T/port" ]; do i=$((i + 1)); [ "$i" -lt 200 ] || fail "fake server did not start"; sleep 0.05; done
PORT=$(cat "$T/port")
BASE="http://127.0.0.1:$PORT"
URL="$BASE/mcp"

ctrl() {
    "$PYTHON" -c 'import urllib.request, sys; req = urllib.request.Request(sys.argv[1], data=sys.argv[2].encode(), headers={"Content-Type":"application/json"}); urllib.request.urlopen(req).read()' "$BASE/_control" "$1"
}

# Helper: runs pic mcp login NAME --no-browser, captures auth URL, and completes either via
# loopback HTTP redirect (mode=loopback) or pasted URL on stdin (mode=paste).
do_login() {
    mode=$1; shift
    outf="$T/login.out"; errf="$T/login.err"; fifo="$T/login.in"
    rm -f "$outf" "$errf" "$fifo"
    mkfifo "$fifo"
    "$PIC" --db "$T/j" --workspace "$T/ws" "$@" < "$fifo" > "$outf" 2> "$errf" &
    lpid=$!
    exec 3> "$fifo"
    # Wait for auth URL on stdout
    url=""
    j=0
    while [ "$j" -lt 200 ]; do
        url=$(sed -n 's/^  \(http[^ ]*\)$/\1/p' "$outf" 2>/dev/null | head -1 || true)
        [ -n "$url" ] && break
        kill -0 "$lpid" 2>/dev/null || break
        j=$((j + 1))
        sleep 0.05
    done
    if [ -n "$url" ]; then
        if [ "$mode" = loopback ]; then
            # Follow redirect from /authorize -> loopback listener on 127.0.0.1
            "$PYTHON" -c 'import urllib.request, sys; urllib.request.urlopen(sys.argv[1], timeout=10).read()' "$url" >/dev/null 2>&1 || true
        else
            # Capture Location header without following redirect, paste into stdin
            redir=$("$PYTHON" -c '
import urllib.request, sys
class NoRedir(urllib.request.HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl): return None
op = urllib.request.build_opener(NoRedir)
try:
    op.open(sys.argv[1], timeout=10)
except urllib.error.HTTPError as e:
    print(e.headers.get("Location", ""))
' "$url")
            printf '%s\n' "$redir" >&3
        fi
    fi
    exec 3>&-
    rc=0
    wait "$lpid" || rc=$?
    return "$rc"
}

# 1. pic mcp add on 401 server saves cleanly with hint naming pic mcp login
pic mcp add dcr "$URL" > "$T/add.out" 2> "$T/add.err" || fail "add 401 should exit 0: $(cat "$T/add.err")"
grep -q "pic mcp login dcr" "$T/add.out" || fail "missing login hint: $(cat "$T/add.out")"
printf 'PASS: pic mcp add on 401 saves cleanly with pic mcp login hint\n'

# 2. Full 401 discovery + DCR + S256 PKCE loopback sign-in + tool call
do_login loopback mcp login dcr --no-browser || fail "dcr login failed: $(cat "$T/login.err")"
grep -q "Signed in to dcr" "$T/login.out" || fail "login output: $(cat "$T/login.out")"
grep -q "2 tools" "$T/login.out" || fail "tool count missing: $(cat "$T/login.out")"
grep -q "MCP 2026-07-28" "$T/login.out" || fail "era missing: $(cat "$T/login.out")"
pic mcp list > "$T/list.out" 2>&1 || fail "pic mcp list after login: $(cat "$T/list.out")"
grep -q "connected" "$T/list.out" || fail "list not connected: $(cat "$T/list.out")"
pic mcp call dcr echo '{"text":"hello"}' > "$T/call.out" 2>&1 || fail "call echo: $(cat "$T/call.out")"
grep -q 'echo: {"text": "hello"}' "$T/call.out" || fail "unexpected echo: $(cat "$T/call.out")"
printf 'PASS: 401 discovery, DCR, S256 PKCE loopback sign-in, list and call\n'

# 3. 403 insufficient_scope step-up (never opens browser on call; login unions existing + challenged)
pic mcp call dcr write_note '{"note":"x"}' > "$T/w1.out" 2>&1 && fail "write_note should fail with 403 insufficient_scope"
grep -q "pic mcp login dcr" "$T/w1.out" || fail "403 error should name pic mcp login dcr: $(cat "$T/w1.out")"
do_login loopback mcp login dcr --no-browser || fail "step-up login failed: $(cat "$T/login.err")"
"$PYTHON" -c 'import json, sys; s = json.load(open(sys.argv[1]))["last_authorize"].get("scope", ""); assert "mcp:read" in s.split() and "mcp:write" in s.split(), s' "$T/state.json" ||
    fail "step-up scope union missing: $(cat "$T/state.json")"
pic mcp call dcr write_note '{"note":"ok"}' > "$T/w2.out" 2>&1 || fail "write_note after step-up: $(cat "$T/w2.out")"
grep -q 'write_note:' "$T/w2.out" || fail "write_note output: $(cat "$T/w2.out")"
printf 'PASS: HTTP 403 insufficient_scope step-up union\n'

# 4. Pre-registered client with client_secret_basic, callbackPort, offline_access -> prompt=consent
CBPORT=$("$PYTHON" -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1]); s.close()')
pic mcp add basic "$URL" --oauth-client-id pre-basic --oauth-client-secret BASIC_SECRET_XYZ \
    --oauth-callback-port "$CBPORT" --oauth-scope "mcp:read offline_access" > "$T/b.out" 2>&1 || fail "add basic: $(cat "$T/b.out")"
do_login loopback mcp login basic --no-browser || fail "basic login failed: $(cat "$T/login.err")"
"$PYTHON" -c 'import json, sys; d = json.load(open(sys.argv[1])); assert d["last_token_auth"] == "client_secret_basic", d; assert d["last_authorize"].get("prompt") == "consent", d; assert ":" + sys.argv[2] + "/callback" in d["last_authorize"].get("redirect_uri", ""), d' "$T/state.json" "$CBPORT" ||
    fail "basic auth / prompt=consent / callbackPort check failed: $(cat "$T/state.json")"
printf 'PASS: pre-registered client_secret_basic, callbackPort and prompt=consent\n'

# 5. add-json oauth object: client_secret_post, localhost callbackUrl, authServerMetadataUrl, --no-browser paste
pic mcp add-json post "{\"type\":\"http\",\"url\":\"$URL\",\"oauth\":{\"clientId\":\"pre-post\",\"clientSecret\":\"POST_SECRET_XYZ\",\"callbackUrl\":\"http://localhost/custom-cb\",\"authServerMetadataUrl\":\"$BASE/custom-meta\"}}" > "$T/p.out" 2>&1 || fail "add-json post: $(cat "$T/p.out")"
# First verify RFC 9207 iss mismatch is rejected on paste
ctrl '{"mode":{"bad_iss":true}}'
do_login paste mcp login post --no-browser && fail "mismatched iss should fail"
grep -qi "issuer mismatch" "$T/login.err" || fail "expected issuer mismatch: $(cat "$T/login.err")"
ctrl '{"mode":{"bad_iss":false}}'
# Now valid paste flow
do_login paste mcp login post --no-browser || fail "post paste login failed: $(cat "$T/login.err")"
"$PYTHON" -c 'import json, sys; d = json.load(open(sys.argv[1])); assert d["last_token_auth"] == "client_secret_post", d; assert d["last_authorize"].get("redirect_uri", "").startswith("http://localhost:"), d' "$T/state.json" ||
    fail "client_secret_post / localhost callback check failed: $(cat "$T/state.json")"
pic mcp call post echo '{"k":"v"}' > "$T/pc.out" 2>&1 || fail "post call: $(cat "$T/pc.out")"
printf 'PASS: add-json oauth, authServerMetadataUrl, client_secret_post, localhost callback, paste & RFC 9207 iss\n'

# 6. Proactive refresh (expires_in=5 within 30s skew) preserving refresh_token when omitted
ctrl '{"mode":{"expires_in":5,"omit_refresh_on_refresh":true},"reset_counts":true}'
do_login loopback mcp login dcr --no-browser || fail "short-lived login: $(cat "$T/login.err")"
# Reset after login's own tool-list refresh so we count only the calls below.
ctrl '{"reset_counts":true}'
pic mcp call dcr echo '{"p":1}' > "$T/pr1.out" 2>&1 || fail "proactive call 1: $(cat "$T/pr1.out")"
"$PYTHON" -c 'import json, sys; assert json.load(open(sys.argv[1]))["refresh_count"] == 1' "$T/state.json" ||
    fail "expected 1 proactive refresh: $(cat "$T/state.json")"
# Second proactive call proves original refresh_token was preserved when omitted by server
pic mcp call dcr echo '{"p":2}' > "$T/pr2.out" 2>&1 || fail "proactive call 2: $(cat "$T/pr2.out")"
"$PYTHON" -c 'import json, sys; assert json.load(open(sys.argv[1]))["refresh_count"] == 2' "$T/state.json" ||
    fail "expected preserved refresh_token to allow 2nd refresh: $(cat "$T/state.json")"
# Refreshing into a 3600s token stops proactive refreshes on subsequent calls
ctrl '{"mode":{"expires_in":3600}}'
pic mcp call dcr echo '{"p":3}' > "$T/pr3.out" 2>&1 || fail "proactive call 3: $(cat "$T/pr3.out")"
pic mcp call dcr echo '{"p":4}' > "$T/pr4.out" 2>&1 || fail "proactive call 4: $(cat "$T/pr4.out")"
"$PYTHON" -c 'import json, sys; assert json.load(open(sys.argv[1]))["refresh_count"] == 3' "$T/state.json" ||
    fail "unexpected extra refresh for fresh 3600s token: $(cat "$T/state.json")"
printf 'PASS: proactive refresh within 30s skew preserves omitted refresh_token\n'

# 7. Reactive 401 refresh + concurrent cross-process lockfile refresh with rotating refresh tokens
ctrl '{"mode":{"expires_in":3600,"omit_refresh_on_refresh":false,"rotate_refresh":true,"refresh_delay":0.25},"reset_counts":true}'
do_login loopback mcp login dcr --no-browser || fail "fresh login for concurrent test: $(cat "$T/login.err")"
ctrl '{"revoke_access":true,"reset_counts":true}'
pic mcp call dcr echo '{"c":1}' > "$T/c1.out" 2>&1 &
p1=$!
pic mcp call dcr echo '{"c":2}' > "$T/c2.out" 2>&1 &
p2=$!
rc1=0; rc2=0
wait "$p1" || rc1=$?
wait "$p2" || rc2=$?
[ "$rc1" = 0 ] && [ "$rc2" = 0 ] || fail "concurrent 401 refresh failed: rc1=$rc1 ($(cat "$T/c1.out")) rc2=$rc2 ($(cat "$T/c2.out"))"
"$PYTHON" -c 'import json, sys; rc = json.load(open(sys.argv[1]))["refresh_count"]; assert rc == 1, f"expected 1 refresh, got {rc}"' "$T/state.json" ||
    fail "concurrent refresh double-spent refresh_token: $(cat "$T/state.json")"
printf 'PASS: reactive 401 refresh + concurrent cross-process lockfile prevents double-spend\n'

# 8. Self-healing invalidation on invalid_grant and invalid_client
ctrl '{"mode":{"refresh_delay":0.0,"force_token_error":"invalid_grant"},"revoke_access":true}'
pic mcp call dcr echo '{"g":1}' > "$T/ig.out" 2>&1 && fail "invalid_grant should fail"
grep -q "pic mcp login dcr" "$T/ig.out" || fail "invalid_grant error: $(cat "$T/ig.out")"
ctrl '{"mode":{"force_token_error":""}}'
do_login loopback mcp login dcr --no-browser || fail "recovery after invalid_grant: $(cat "$T/login.err")"
pic mcp call dcr echo '{"g":2}' > "$T/ig2.out" 2>&1 || fail "call after invalid_grant recovery: $(cat "$T/ig2.out")"

dcr_before=$("$PYTHON" -c 'import json, sys; print(json.load(open(sys.argv[1]))["dcr_count"])' "$T/state.json")
ctrl '{"mode":{"force_token_error":"invalid_client"},"revoke_access":true}'
pic mcp call dcr echo '{"ic":1}' > "$T/ic.out" 2>&1 && fail "invalid_client should fail"
ctrl '{"mode":{"force_token_error":""}}'
do_login loopback mcp login dcr --no-browser || fail "recovery after invalid_client: $(cat "$T/login.err")"
dcr_after=$("$PYTHON" -c 'import json, sys; print(json.load(open(sys.argv[1]))["dcr_count"])' "$T/state.json")
[ "$dcr_after" -gt "$dcr_before" ] || fail "invalid_client did not invalidate cached DCR client ($dcr_before -> $dcr_after)"
printf 'PASS: self-healing invalidation on invalid_grant and invalid_client\n'

# 9. Secret non-leakage in get, list, RPC, and raw pic.sqlite
pic mcp get basic > "$T/get_basic.out" 2>&1 || fail "get basic"
pic mcp get post > "$T/get_post.out" 2>&1 || fail "get post"
printf '{"id":"1","type":"get_mcp_servers"}\n' | pic --mode rpc > "$T/rpc.out" 2>&1 || fail "rpc get_mcp_servers"
grep -q '"auth":"signed_in"' "$T/rpc.out" || fail "rpc missing signed_in: $(cat "$T/rpc.out")"
for pat in BASIC_SECRET_XYZ POST_SECRET_XYZ tok_ ref_; do
    grep -qF "$pat" "$T/get_basic.out" && fail "secret $pat leaked in pic mcp get basic"
    grep -qF "$pat" "$T/get_post.out" && fail "secret $pat leaked in pic mcp get post"
    grep -qF "$pat" "$T/rpc.out" && fail "secret $pat leaked in RPC get_mcp_servers"
done
"$PYTHON" -c '
import sys
raw = open(sys.argv[1], "rb").read()
for pat in (b"BASIC_SECRET_XYZ", b"POST_SECRET_XYZ", b"tok_", b"ref_"):
    assert pat not in raw, f"secret {pat!r} found in plaintext in pic.sqlite"
' "$HOME/.pic/pic.sqlite" || fail "plaintext secret found in pic.sqlite"
printf 'PASS: no clientSecret or OAuth tokens leak in CLI, RPC or pic.sqlite\n'

# 10. --mcp-config login & logout + pic mcp logout
cfg="{\"mcpServers\":{\"cfgsrv\":{\"type\":\"http\",\"url\":\"$URL\"}}}"
do_login loopback --mcp-config "$cfg" mcp login cfgsrv --no-browser || fail "mcp-config login: $(cat "$T/login.err")"
pic --mcp-config "$cfg" mcp call cfgsrv echo '{"cfg":1}' > "$T/cfgc.out" 2>&1 || fail "mcp-config call: $(cat "$T/cfgc.out")"
pic --mcp-config "$cfg" mcp logout cfgsrv > "$T/cfgo.out" 2>&1 || fail "mcp-config logout: $(cat "$T/cfgo.out")"
grep -q "Signed out of cfgsrv" "$T/cfgo.out" || fail "mcp-config logout text: $(cat "$T/cfgo.out")"

pic mcp logout dcr > "$T/lo.out" 2>&1 || fail "logout dcr: $(cat "$T/lo.out")"
grep -q "Signed out of dcr" "$T/lo.out" || fail "logout output: $(cat "$T/lo.out")"
pic mcp call dcr echo '{"after":"logout"}' > "$T/al.out" 2>&1 && fail "call after logout should fail with 401"
grep -q "pic mcp login dcr" "$T/al.out" || fail "post-logout error: $(cat "$T/al.out")"
printf 'PASS: pic mcp logout and --mcp-config login/logout\n'

# 11. Hardening regressions: huge expires_in (UBSan), >255-byte auth_methods_supported, error secret scrubbing
ctrl '{"mode":{"expires_in":1e20,"big_auth_methods":true,"force_token_error":"","echo_secret_in_error":false},"reset_counts":true}'
do_login loopback mcp login basic --no-browser || fail "hardening login failed: $(cat "$T/login.err")"
pic mcp call basic echo '{"h":1}' > "$T/h1.out" 2>&1 || fail "call after huge expires_in + big auth_methods: $(cat "$T/h1.out")"
# Reactive 401 refresh proves filtered auth_methods_supported sealed valid JSON and kept client_secret_basic
ctrl '{"mode":{"expires_in":3600},"revoke_access":true,"reset_counts":true}'
pic mcp call basic echo '{"h":2}' > "$T/h2.out" 2>&1 || fail "reactive refresh after big auth_methods: $(cat "$T/h2.out")"
"$PYTHON" -c 'import json, sys; d = json.load(open(sys.argv[1])); assert d["refresh_count"] == 1 and d["last_token_auth"] == "client_secret_basic", d' "$T/state.json" ||
    fail "expected client_secret_basic refresh after big auth_methods: $(cat "$T/state.json")"
# Error description echoing client_secret and refresh_token must be scrubbed from output and DB
ctrl '{"mode":{"force_token_error":"invalid_grant","echo_secret_in_error":true},"revoke_access":true}'
pic mcp call basic echo '{"h":3}' > "$T/h3.out" 2>&1 && fail "echoed-secret refresh error should fail"
grep -qF "BASIC_SECRET_XYZ" "$T/h3.out" && fail "client_secret leaked in token error: $(cat "$T/h3.out")"
grep -qF "ref_" "$T/h3.out" && fail "refresh_token leaked in token error: $(cat "$T/h3.out")"
printf 'PASS: huge expires_in, oversized auth_methods_supported, and token error secret scrubbing\n'