Skip to main content

Platform Token Issuer (MCP trust root)

Issue #1954 · resolves the #1864 trust-root gap · ADR-0022 · milestone 24.

What it is​

The platform-owned MCP token issuer is UpsQuad's OWN authorization server for the governed-MCP path. It lets us mint the short-TTL, agent-scoped bearer that a worker presents at /mcp/team/{unit} and have the gateway validate it against a key set we control — closing the gap where the dev stack could only validate tokens from fake-jwt-issuer / Clerk, neither of which we can mint with.

Two PUBLIC routes on the gateway (cmd/context-engine, HTTP mux):

RoutePurpose
GET /.well-known/jwks.jsonPublic half of the platform signing key (JWK Set, RS256).
GET /.well-known/oauth-authorization-serverRFC 8414 AS metadata (issuer, jwks_uri, token_endpoint).
POST /oauth/tokenClient-credentials token endpoint for external / BYO agents (PR-4, #1957).

token_endpoint (/oauth/token) was advertised from PR-1 and is now IMPLEMENTED in PR-4 (#1957); PR-2 (#1955) wires the orchestrator minter and repoints MCP_GATEWAY_JWKS_URL at /.well-known/jwks.json.

Single-key custody (finding 2 — the one decision the founder signed off)​

There is exactly ONE platform signing key. Two processes load it from the same secret-backend source:

  • Gateway (context-engine) loads it to SERVE the public half (this PR).
  • Orchestrator (agent-orchestrator) loads it to MINT tokens (PR-2, #1955).

Env contract (identical in both processes):

VarMeaning
PLATFORM_SIGNING_KEY_FILEPath to the PEM (secret-backend mount).
PLATFORM_SIGNING_KEYInline PEM alternative (tests/CI).
PLATFORM_SIGNING_KEY_IDJWS kid — must match between served JWKS and minted token.
PLATFORM_ISSUERiss claim / AS issuer identifier.

There is deliberately no second custody path: a worker only ever RECEIVES a finished token and can never re-sign it.

Fail-safe​

No key material ⇒ LoadSigningKey returns (nil, nil), the issuer routes are not mounted, and mint stays OFF. The trust root is wholly present or wholly absent — never half-open. Material present but malformed / missing kid/issuer is a fatal startup error (loud, never silent).

Dev stack​

bash scripts/dev-secrets/gen-platform-signing-key.sh # seeds .env + PEM
docker compose -f docker-compose.dev.yml up -d context-engine agent-orchestrator
curl -s http://127.0.0.1:8083/.well-known/jwks.json | jq
curl -s http://127.0.0.1:8083/.well-known/oauth-authorization-server | jq

The generated PEM lives OUTSIDE the repo, in the directory .env records as PLATFORM_SIGNING_KEY_HOST_DIR (first run: $PLATFORM_SIGNING_KEY_DIR, else /opt/upsquad-secrets/platform-issuer/). The generator creates the key at mode 0600 in a 0700 directory, and refuses to run against one that is not (below). It is a dev-only key, never used in GCP.

Key custody on a shared host (#4237)​

Anyone who can read this key can mint a token for every audience the issuer signs. On beta-dev it was found at 0644 in a 2755 directory. Every account on the devbox could read it.

The rule. The key is 0600 and its directory is 0700. Both are owned by the uid the two containers run as: 65532 on Linux (the root Dockerfile's USER nonroot:nonroot). Measure it with stat -c %u /proc/$(docker inspect -f '{{.State.Pid}}' upsquad-context-engine). Never loosen the mode to let a container read the key. Hand the key to the container's uid instead. That loosening is how beta-dev's key became 0644.

What the generator enforces. On every run, --rotate included, the generator refuses (exit 1) and writes nothing if the key or its directory has any group/other bit. It prints the mode and the exact chown/chmod/--rotate commands. A directory it cannot search exits 2. For a non-root user that is the secured state, so re-run it as root.

What a failed run leaves behind. A run changes two files, the key and .env, and it prepares both before it changes either:

  1. The new key is generated beside the live one and given the directory's owner.
  2. The complete new .env is written to a private staging file beside the live one (.env.platform-signing-key.*). A second tool (awk) must agree with it line for line. Then it is given the live file's owner, group and mode. On beta-dev those are vb:dev 0660, and the reconciler reads .env as vb.
  3. Two renames publish them, the key first. A rename never leaves a partial file, so a reader sees the old .env or the new one, never anything in between.

The failure boundary, exactly:

  • Any failure in steps 1 and 2 exits 2, with the key and .env exactly as found. That covers a read or write error, a short copy, no room for the staging file, an owner this user cannot give, and a key that does not generate or parse. A first run may leave an empty key directory behind.
  • The key rename fails: exit 2, both files as found.
  • The .env rename fails after the key went live: the old key is renamed back (a first key is removed again), then exit 2 with both files as found.
  • That rollback fails too: exit 3. The new key is live and .env still names the old kid. The run keeps the staging file and the old key, and prints a finish: line, which completes the rotation, and a revert: line, which restores the old pair. Run one of them, as root, before anything restarts the containers.
  • Interrupted: INT, TERM and HUP are ignored while the run publishes. A SIGKILL or power loss before the first rename leaves only temp files beside the two live files, and both are as found. Only a SIGKILL or power loss between the renames leaves the new key under the old kid. Re-run with --rotate, then delete the leftover .env.platform-signing-key.* and .platform-signing-key.pem.prev.*.
  • A non-root run against someone else's .env: the replacement must keep the live owner, and a user who cannot give it that owner gets exit 2 before anything changes. A non-root run against beta-dev's vb:dev .env is this case, so re-run as root.

Not covered: the directories above the key. This boundary is open and pending the founder. The generator checks only the key file and its own directory. Both ancestors on beta-dev are group-writable: /opt/upsquad is 2775 vb:dev and /opt/upsquad/dev-secrets is 2775 ashik:dev (measured 2026-10-21; re-measure with stat -c '%a %U:%G %n' /opt/upsquad /opt/upsquad/dev-secrets). So any member of dev can rename the 0700 key directory aside and put a directory holding a key of their own in its place. uid 65532 can read that key, both containers load it at their next restart, and the generator accepts it on its next run if its modes are private. The #4244 review confirmed this in a network-less scratch container: a second uid with write access to the parent's group could not read the original 0600/65532 key, but it could rename the 0700 directory aside and plant a replacement that uid 65532 read and parsed. Tightening only /opt/upsquad/dev-secrets does not close the gap, because /opt/upsquad above it is group-writable too. Today this is an existing trusted-operator boundary: every dev member is trusted not to substitute the key. The founder decides whether to keep that boundary or to move the key under parents that no shared group can write (#4237). Until then, do not describe the key's custody as isolated from dev members.

When a change takes effect. Both consumers read the key once, at startup: cmd/context-engine/main.go and cmd/agent-orchestrator/main.go call oauth.LoadSigningKey in run(), which does the only os.ReadFile of the file (internal/auth/oauth/signing_key.go). An unreadable file is a fatal startup error. The kid is the env var PLATFORM_SIGNING_KEY_ID, which is fixed when the container is created. So:

  • A permission change does nothing to running containers. It takes effect at the next restart, and on beta-dev any */15 reconcile can be that restart. Change the owner before you tighten the mode. Never run a bare chmod 600.
  • A rotation is live only once both containers are recreated. On beta-dev the reconcile does this on its own, because the kid in .env changed. Until then both keep signing and serving the old key, so they stay consistent.
  • Validators re-fetch the JWKS when they see an unknown kid (jwks_validator.go, Validate), so tokens with the new kid validate at once. A validator's cached JWKS (jwksTTL, 5 min) keeps accepting old-kid tokens for at most that long after the restart.

Tools that read the key. scripts/dev-seed-first-party-mcp.sh --smoke runs as context-engine's own user. The deterministic part of scripts/smoke-mcp-trust-root.sh reads no key. Its live mode (MCP_LIVE_SMOKE=1) reads PLATFORM_SIGNING_KEY_FILE on the host, so on a secured host it must run as root.

Operator checklist: secure and rotate (beta-dev)​

Run these from the shared checkout, after a Deploy Dev Stack run that ships this script. Steps 2 and 3 need root.

  1. Baseline: stat -c '%a %U:%G %n' /opt/upsquad/dev-secrets/platform-issuer /opt/upsquad/dev-secrets/platform-issuer/platform-signing-key.pem, curl -s http://127.0.0.1:8083/.well-known/jwks.json | jq -r '.keys[].kid', and the container uid from the measurement above (expect 65532).
  2. Change the owner first, then the mode. This needs no restart, and a restart in between still reads the key: sudo chown 65532:65532 /opt/upsquad/dev-secrets/platform-issuer /opt/upsquad/dev-secrets/platform-issuer/platform-signing-key.pem, then sudo chmod 700 /opt/upsquad/dev-secrets/platform-issuer and sudo chmod 600 /opt/upsquad/dev-secrets/platform-issuer/platform-signing-key.pem. Prove that uid 65532 reads the key through a bind mount and that you do not. Neither check prints the key: docker run --rm --network none --user 65532:65532 -v /opt/upsquad/dev-secrets/platform-issuer:/k:ro --entrypoint test "$(docker inspect -f '{{.Image}}' upsquad-postgres)" -r /k/platform-signing-key.pem && echo READABLE-BY-65532 and test -r /opt/upsquad/dev-secrets/platform-issuer/platform-signing-key.pem || echo DENIED.
  3. Rotate. A key that was readable must be treated as copied: sudo env PLATFORM_SIGNING_KEY_DIR=/opt/upsquad/dev-secrets/platform-issuer bash scripts/dev-secrets/gen-platform-signing-key.sh --rotate. It must print owner uid 65532 and no NOTE: line. Do not pass PLATFORM_ISSUER. Exit 2 means nothing changed: read the message. Exit 3 means the new key is live but .env is not. Run the printed finish: line before anything restarts.
  4. Recreate both consumers. Either dispatch the reconcile (gh api -X POST repos/upsquad-ai/upsquad-core/actions/workflows/dev-deploy.yml/dispatches -f ref=main) or wait for the */15 run (up to 15 min plus schedule delay). Do not hand-run dev-reconcile.sh. When it finishes, the JWKS kid must equal the new PLATFORM_SIGNING_KEY_ID in .env, both containers must carry it, and neither log may contain fatal startup error.
  5. Smoke: bash scripts/smoke-mcp-trust-root.sh (deterministic), then bash scripts/dev-seed-first-party-mcp.sh --smoke "$AGENT" (live, with the new key).

Rollback. Step 2 reverses with chown ashik:dev / chmod 2755 / chmod 644, which restores the exposure. Use it only if step 2's READABLE-BY-65532 probe fails. Step 3 has no reverse by design: the old key is compromised and has been renamed over. If a container then fails with read platform signing key file: … permission denied, the forward fix is sudo chown 65532:65532 <key> && sudo chmod 600 <key>, then dispatch the reconcile again (not the */15 sweep). That fits inside the five-minute tenet.

GCP​

Same env contract, satisfied by a mounted K8s secret / Workload-Identity-fronted secret. Key rotation is a redeploy: publish the new public key in the JWKS (advertise both kids during overlap), then flip the minter to the new kid.

POST /oauth/token — external / BYO agent client credentials (PR-4, #1957)​

A registered external agent (external_agent_clients, migration 155; RegisterExternalAgent RPC, #1956) presents its client credential here and receives the same agent-scoped gateway token an internal orchestrator mint produces: agent_id / org_id / unit_id claims, aud = <base>/mcp/team/{unit}, ~10m TTL, azp = agent-runtime (finding 1), plus runtime = external provenance (finding 3/5). It reuses RS256AgentTokenMinter.Mint UNCHANGED (finding 3), so the terminator needs zero changes (finding 5). grant_type=client_credentials only; no refresh tokens — the agent re-grants to refresh.

Two client-authentication methods (the two the AS metadata advertises):

  • private_key_jwt (RFC 7523, PREFERRED) — the customer holds the private key; we store only the public JWK. The client signs a short-lived assertion (iss = sub = client_id, aud = this token endpoint, jti, exp ≤ 5m); we verify the signature against the stored public key, the audience, expiry, and a jti single-use replay guard.
  • client_secret_post (FALLBACK) — bcrypt compare against hashed_secret.

Enable gate (Decision-D, #1864)​

The endpoint mirrors the orchestrator's env gate. It is NOT mounted (404s) until armed, and even when mounted refuses a resolved org that is not enabled:

VarMeaning
MCP_GATEWAY_ENABLEDGlobal on/off (default false).
MCP_GATEWAY_TENANTSCSV of org_ids allowed even when global is off.

Set the SAME values on context-engine (issue side) as on agent-orchestrator (mint side) so both flip together.

Governed-MCP enablement checklist (#1981)​

Governed MCP for internal agents is inert unless the session-snapshot freeze derives the agent's MCP set from the v2.4 inheritance resolver. That path is gated by orgv24.multiparent_resolver — so this flag sits at the same tier as the signing key and the MCP_GATEWAY_ENABLED gate. Miss it and the gateway edge is correct but every agent runs on an EMPTY snapshot and "has no tool to see" (#1981 root cause).

To turn governed MCP on for an environment, ALL of the following must hold:

RequirementWhereNote
PLATFORM_SIGNING_KEY_FILE (or _KEY) + _ID armedorchestrator + context-engineMints/verifies the agent-gateway token (#1955).
MCP_GATEWAY_ENABLED=true or org in MCP_GATEWAY_TENANTSorchestrator + context-engineDecision-D enable gate (#1864).
orgv24.multiparent_resolver = trueplatform_feature_flags row (global)Gates the snapshot MCP freeze (#1981). Seeded ON by migration 161; compile default is also ON post-GA. Set the row to false to kill-switch back to v2.3.

Fail-loud coupling: the orchestrator now REFUSES TO START (startup fatal, not a WARN) when the MCP trust root is armed (signing key + enable gate) but orgv24.multiparent_resolver resolves OFF — the contradictory state that silently produced empty snapshots is now impossible to boot into (cmd/agent-orchestrator/main.go, guard tagged #1981).

Persistence: migration 161 seeds orgv24.multiparent_resolver=true via ON CONFLICT DO UPDATE, so a DB reset that re-runs migrations restores the ON posture — an environment (e.g. beta-dev) no longer silently reverts to a hand-inserted SQL row. The .down.sql restores the false kill-switch posture.

Hardening (public trust-root surface)​

  • Uniform failure: unknown client, revoked client, wrong secret/signature, expired/replayed assertion, wrong audience, and a disabled tenant ALL return the identical 401 invalid_client body — no client-enumeration oracle. The secret path always runs a bcrypt compare (dummy hash for unknown clients) so timing does not distinguish unknown from known-wrong.
  • Rate limit + lockout: per-IP and per-client_id token buckets plus a consecutive-failure exponential backoff (429 slow_down), enforced before any DB work.
  • Audit: every issuance (external_token_issued) and every failed attempt (external_token_denied) writes an audit row (migration 157). The assertion, the secret, and the minted token are NEVER logged or placed in a detail.
  • Bootstrap resolve: the org is unknown until the credential resolves, so the lookup goes through the resolve_external_agent_client SECURITY DEFINER function (migration 156) — the one sanctioned cross-tenant read, production-safe under the NOBYPASSRLS app_rw role (#1908). A miss returns zero rows.

External-agent usage​

# 1. private_key_jwt — build a client assertion (aud = the token endpoint):
# claims: {iss, sub = client_id, aud = "<BASE>/oauth/token", jti, exp}
# signed with the client's PRIVATE key (RS256/ES256/PS256).
ASSERTION=$(build_client_assertion) # your runtime signs this

curl -s -X POST "$BASE/oauth/token" \
-d grant_type=client_credentials \
-d client_assertion_type=urn:ietf:params:oauth:client-assertion-type:jwt-bearer \
-d "client_assertion=$ASSERTION"
# => {"access_token":"<jwt>","token_type":"Bearer","expires_in":600}

# 2. client_secret_post fallback:
curl -s -X POST "$BASE/oauth/token" \
-d grant_type=client_credentials \
-d "client_id=$CLIENT_ID" \
-d "client_secret=$CLIENT_SECRET"

# 3. Use the token at the governed team gateway (same as an internal agent):
curl -s -X POST "$BASE/mcp/team/$UNIT" \
-H "Authorization: Bearer $ACCESS_TOKEN" \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'