Repository navigation
Add Phase-2 registration-delegation connect flow, per II instance (beta on, prod on v1) - #41
Merged
Merged
Conversation
…ide) Implement the MCP-server side of the registration-delegation design: instead of Internet Identity binding a session key it was merely shown (fetched from our callback), II mints a single-use, canister-signed delegation P_reg -> X and delivers it to a pinned callback page as a URL fragment; the backend redeems it by signing one mcp_register_v2 call as X, binding the long-lived session key S to the anchor. Server pieces (all behind the MCP_REGISTRATION_DELEGATION flag, OFF by default): - identities.rs: a per-connect registration keypair X bound to the session (priv(X) never leaves the backend); registration_pubkey_b64() to carry pub(X) outbound; redeem_registration_delegation() building a DelegatedIdentity from priv(X) + the delegation and calling mcp_register_v2, then recording the grant expiration + read-only level (reusing the v1 require_write guard). - auth.rs: the v2 II link carrying pub(X); GET /oauth/connect/callback pinned page (sole fragment reader, strict CSP with a per-response script nonce, no reflection); POST /oauth/connect/redeem (initiator-cookie check, delegation redemption as consenter + registration proof, PKCE code minting). The fragment-delivered delegation subsumes finish_secret; synchronous registration removes the grant_is_live probe and finishing_page poll. - main.rs: route the GET callback page and the redeem endpoint. Gated OFF by default: mcp_register_v2 and the delegation-minting II methods (prepare_/get_mcp_registration_delegation, the mcp-registration seed) do not exist on Internet Identity yet, and the II frontend that produces the fragment isn't written. The fragment wire shape (RegDelegationDto), the link params (regkey, flow), and the mcp_register_v2 candid are marked PROVISIONAL and must be reconciled against II's published .did before the flag is flipped. When off, the v1 flow is unchanged (the GET callback page and redeem route 404). Unit tests cover the registration-key mint (idempotent, distinct from S), the redemption guards (missing key, empty chain, wrong delegate), the strict-CSP non-reflecting page (nonce match), the v2 link params, and the fragment decode (round-trip + malformed/unknown-permission rejection). Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_014T9N8USDfNK5yzznPGg7Ym
There was a problem hiding this comment.
Pull request overview
Adds a flag-gated (“OFF by default”) Phase-2 registration-delegation connect flow on the MCP server, introducing a pinned callback page + redeem endpoint and a per-connect registration keypair to eliminate the “II binds a key it was merely shown” weakness in the v1 flow.
Changes:
- Adds a Phase-2 connect path behind
MCP_REGISTRATION_DELEGATION, including a GET callback page (sole fragment reader) and a POST redeem endpoint. - Introduces a per-connect registration keypair
Xstored server-side and redemption logic to call provisionalmcp_register_v2asXwhile registering the long-lived session keyS. - Documents the Phase-2 flow and its II dependency/provisional wire types in README and module docs.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 2 comments.
| File | Description |
|---|---|
| src/main.rs | Routes Phase-2 callback GET and redeem POST (while retaining v1 POST callback). |
| src/identities.rs | Stores per-connect registration keypair and implements delegation redemption via mcp_register_v2 (provisional contract). |
| src/auth.rs | Adds feature flag, v2 II link builder, pinned callback page (CSP), fragment decoding, and redeem handler that mints auth codes. |
| README.md | Documents the Phase-2 registration-delegation design and its flag-gated/II-dependent status. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
- The pinned page's CSP nonce now uses the STANDARD base64 alphabet: CSP3's grammar admits base64url, but CSP2's does not, and a strict parser dropping the nonce source would block the inline script and break the callback page. - Redemption is now single-flight per connect: an atomic claim (a `redeeming` marker on the pending connect) serializes the mcp_register_v2 attempt, so a page double-submit can't fire two concurrent redemptions. A failed attempt releases the claim (retry proceeds); a finished one leaves the code, which later requests get back idempotently. II's idempotency-on-S would tolerate the race, but one deterministic attempt is strictly better. - Tests: nonce alphabet, the claim state machine (win / in-progress / release / existing-code / vanished), and a regression proving both Phase-2 routes 404 with the flag off. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_014T9N8USDfNK5yzznPGg7Ym
Turn the global MCP_REGISTRATION_DELEGATION switch into a per-instance
setting on IiInstance, so the server runs both connect protocols side by
side:
- beta / staging (/mcp, beta.id.ai): Phase-2 registration delegation ON by
default (MCP_REGISTRATION_DELEGATION=0 to disable). Enabling is
outbound-compatible with v1 — the II link gains the regkey/flow params and
the pinned-callback/redeem routes turn on, while every v1 handler (the
callback POSTs, /oauth/finish) stays live — so beta keeps completing
connects via v1 until beta II ships the new frontend + canister methods,
and switches over when it does.
- production (/mcp-prod, id.ai): pinned to v1 by default
(MCP_REGISTRATION_DELEGATION_PROD=1 to opt in later). Its link, callback,
and finish flow are exactly the existing protocol; Phase-2 routes 404.
/version now reports registration_delegation: {beta, prod} so operators can
confirm which instance runs which flow, and startup logs name the protocol
per instance.
Tests: per-instance route gating (v1-pinned 404s vs Phase-2 page + live
redeem), v1 key request still served on a Phase-2 instance (the
outbound-compatibility property), and the beta-on/prod-off defaults.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_014T9N8USDfNK5yzznPGg7Ym
Cap the redeem body's user_key (4 KB) and delegation (64 KB) base64 text lengths, checked before any base64 decode / JSON parse, so oversized attacker-controlled input is rejected without large allocations (CWE-770, same posture as the discovery-buffering bound). Legitimate values are far smaller (a DER canister-sig key ~100 bytes; a delegation with its canister signature a few KB), and axum's 2 MB default body limit plus the initiator cookie gate already bound exposure — this adds an explicit tight guard at the parse chokepoint. Test covers over-cap rejection for both fields and that at-cap input passes the size check. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_014T9N8USDfNK5yzznPGg7Ym
Internet Identity is moving to pin the /mcp connect flow to a fixed path on the trusted origin (dfinity/internet-identity#4091) instead of taking the callback path from the attacker-craftable link fragment. Serve that path now so this server keeps connecting when the pinning ships — the path carries no instance prefix, so one route serves BOTH II instances: - POST: II's v1 connect POSTs (key request / completion), dispatched to the instance whose store owns the connect state (session ids are per-store UUIDs, so at most one matches); an unknown state falls through to ordinary 403/204 semantics. - GET: the Phase-2 pinned page, generalized to carry every Phase-2-enabled instance's redeem endpoint — the instance is only knowable from the fragment, which the server never sees, so the page tries each same-origin redeem in order; the wrong instance rejects the state and each instance's path-scoped connect cookie only rides to its own redeem path. 404 when no instance runs Phase 2. The per-instance {prefix}/oauth/connect/callback routes remain for pre-pinning II frontends, which use the link's callback verbatim. Tests: dispatch-by-state at the pinned POST (owning store claimed, other store untouched, unknown state 403), the GET gating on Phase 2 with the enabled instance's redeem URL, and the multi-instance page embedding both redeem endpoints in order. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_014T9N8USDfNK5yzznPGg7Ym
Internet Identity's implementation is now written (dfinity/internet-identity
PRs #4091, #4092, #4093), so replace the provisional wire shapes with the
real ones:
- Callback allow-list, not a fixed path (#4091 switched approach after
review): drop the /.well-known/ii-mcp-connect route and instead serve
GET /.well-known/ii-auth-callbacks — {"callbacks": [<absolute URL>, ...]}
declaring both instances' connect callbacks. II fetches it (redirect:
"error", no credentials, no-store, 8 KB cap, application/json) and
requires the link's callback to be EXACTLY one of the entries,
fail-closed — so serving this document is mandatory once #4091 ships.
The document and the II links build the callback URL from one helper
(connect_callback_url) so they cannot drift; a test locks the verbatim
match in. The per-instance callback routes keep working unchanged (the
allow-list validates them rather than replacing them), so the pinned
page reverts to single-instance form.
- Link param (#4093): registration_key = base64url(DER(pub(X))); its
presence selects the flow, so the provisional regkey/flow params go away.
- Fragment shape (#4093): II navigates back with
#delegation=<JSON.stringify(DelegationChain.toJSON())>&state=…
(percent-encoded by URLSearchParams, not base64url). The parser now
consumes agent-js DelegationChain JSON — hex byte fields, HEX-string
expiration (BigInt.toString(16)), principal-text targets, top-level
publicKey = der(P_reg) — with deny_unknown_fields so a field this parser
doesn't carry (every delegation field is signature-covered) fails fast
instead of silently dropping and resurfacing the #40 "sig not found"
class of error. The single 64 KB size cap still applies before parsing.
- mcp_register_v2 reply (#4092): McpRegistrationV2 = record { expiration :
Timestamp; permissions : Permissions } with Permissions = variant
{ queries; all } — a NON-optional named variant (unlike the Delegation
record's opt text field), so decode it as a variant and thread the level
into the same read-only guard as before.
II's PRs are not merged yet; the shapes are marked to be re-verified against
the published .did and frontend when they land. Until deployed II ships
them, a Phase-2 instance keeps completing connects via v1 as before.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_014T9N8USDfNK5yzznPGg7Ym
Guide-driven fixes (cross-validation against the II MCP server guide rev2): - Never issue a token that outlives the grant: the access-token TTL is now the earlier of the standard 1h and the grant's expiration (authoritative from mcp_register_v2, best-effort from v1's completion POST; unknown falls back to the default). The user can shorten the grant to 10 minutes on II's consent screen, so the fixed TTL alone could overshoot — leaving the client hitting opaque tool errors on a live-looking token instead of the 401 invalid_token challenge that prompts an inline re-auth. - DCR grant types per the guide's RFC 7591 reading: requested grant_types are intersected with the supported set and the result returned (authoritative response — a client that asked for refresh_token sees it wasn't granted), an empty request defaults to authorization_code, and a request whose intersection LOSES authorization_code is refused with invalid_client_metadata before anything is stored, instead of registering a client that could never complete any flow. - invalid_client (not invalid_request) for an unknown client_id/redirect_uri at /oauth/authorize. - Refresh stale module docs: identities.rs now describes both connect protocols (v1 fetched-key and the Phase-2 registration delegation) instead of presenting v1 as the only model, and auth.rs no longer cites a docs/mcp-server-guide.md path that does not exist in this repo. Flaky test fix (was failing CI on unchanged code): oisy's main bundle chunks have grown to ~3 MiB, and the 2 MiB per-file discovery cap silently truncated the labelled backend id away — whether the test passed depended on which chunk survived a mid-stream error (read_capped is deliberately best-effort). Raise the per-file cap to 4 MiB (memory stays bounded by the 8 MiB aggregate cap, which sizes every read to the remaining room) and retry the live-network test up to 3 times so it asserts the mining logic rather than one fetch's luck. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_014T9N8USDfNK5yzznPGg7Ym
- /.well-known/ii-auth-callbacks now sends Cache-Control: no-store. II's own fetch is no-store client-side, but an intermediary (CDN/proxy) could still cache our response — and a stale copy of fail-closed, exact-match infrastructure would break every connect after a callback-path change. - The pinned callback page adds frame-ancestors 'none' to its CSP (plus X-Frame-Options: DENY for pre-CSP2 browsers): II reaches it only by top-level navigation, so framing is never legitimate, and the delegation-bearing page must not be embeddable for UI redress. Tests assert both headers. Co-Authored-By: Claude Opus 4.8 <[email protected]> Claude-Session: https://claude.ai/code/session_014T9N8USDfNK5yzznPGg7Ym
Comment on lines
+117
to
+123
| /// Whether THIS instance runs the **Phase-2 registration-delegation** | ||
| /// connect flow (see `crate::auth`'s "Phase 2" module docs). Per-instance so | ||
| /// the server supports BOTH protocols side by side: staging II (beta) on the | ||
| /// new flow while production II stays on v1. Enabling is outbound-compatible: | ||
| /// it only adds the `regkey`/`flow` params to the II link and turns on the | ||
| /// pinned callback page + redeem endpoint — an II frontend that doesn't know | ||
| /// the new flow ignores the params and completes v1, which the server always |
Comment on lines
+176
to
+184
| /// A boolean flag from the environment, with a default when unset. A SET value | ||
| /// is truthy only for `1`/`true`/`yes`/`on` (case-insensitive) — so an explicit | ||
| /// `VAR=0` turns a default-on flag off. | ||
| fn env_flag(var: &str, default: bool) -> bool { | ||
| match std::env::var(var) { | ||
| Ok(v) => matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes" | "on"), | ||
| Err(_) => default, | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Implements the MCP-server side of the registration delegation design (rev2), with the connect protocol selected per II instance so the server runs both flows side by side:
/mcp, beta.id.ai) — Phase 2 on by default (MCP_REGISTRATION_DELEGATION=0to disable)./mcp-prod, id.ai) — pinned to v1 by default (MCP_REGISTRATION_DELEGATION_PROD=1to opt in later). Its link, callback, and finish flow are exactly the existing protocol; the Phase-2 routes404.In today's v1 flow, Internet Identity binds a session key it was merely shown — fetched from our callback — so any path on the trusted origin that can echo an attacker's key lets II bind it. Phase 2 replaces the fetched key with a single-use, canister-signed delegation
P_reg → Xthat II mints under the user's own authentication and delivers to a pinned callback page as a URL fragment; the backend redeems it by signing onemcp_register_v2call asX, binding the long-lived session keySto the anchor. II never again binds a bare key it was shown.Enabling Phase 2 for an instance is outbound-compatible with v1: the II link gains the
registration_keyparam and the pinned-callback/redeem routes turn on, while every v1 handler (the callback POSTs,/oauth/finish) stays live — an II frontend that doesn't know the new flow ignores the extra param and completes v1 unchanged. So beta keeps connecting via v1 until beta II ships the new protocol, and switches over when it does.Wire shapes are reconciled against II's implementation PRs (dfinity/internet-identity#4091, #4092, #4093), and the implementation is cross-validated against the II MCP server guide (rev2).
Changes
identities.rsIiInstance.registration_delegation— per-instance protocol selection (beta default on, prod default off).Xbound to the session;priv(X)never leaves the backend.registration_pubkey_b64()exposes onlypub(X).redeem_registration_delegation(): builds aDelegatedIdentityfrompriv(X)+ the delegation, callsmcp_register_v2(pub(S)), and records the grant expiration + read-only level (feeding the samerequire_writeguard as v1's completion POST). Rejects a delegation that doesn't terminate atXbefore any network call. Reply candid per #4092:McpRegistrationV2 = record { expiration : Timestamp; permissions : Permissions }withPermissions = variant { queries; all }— a non-optional named variant (unlike theDelegationrecord'sopt textfield from the Fix read-only sessions: decode II delegation permissions as opt text #40 outage).auth.rsGET /.well-known/ii-auth-callbacks— the callback allow-list (#4091):{"callbacks": [<absolute URL>, ...]}declaring both instances' connect callbacks; fail-closed at II, so serving this is mandatory once #4091 ships. Built from the sameconnect_callback_urlhelper as the II links, with a test locking in the verbatim match.registration_key= base64url(DER(pub(X))) (#4093).GET /oauth/connect/callback— the pinned callback page: sole reader of the returned fragment (#delegation=<DelegationChain JSON>&state=…per #4093), strict CSP, zero reflection.POST /oauth/connect/redeem— initiator-cookie check, size-capped parse (CWE-770) of agent-jsDelegationChain.toJSON()(deny_unknown_fieldsper the Fix read-only sessions: decode II delegation permissions as opt text #40 lesson), single-flight redemption claim, then PKCE-bound code minting.grant_typesare intersected with the supported set and a request whose intersection losesauthorization_codeis refused withinvalid_client_metadatabefore anything is stored; unknownclient_id/redirect_uriat/oauth/authorizenow answersinvalid_client.discover.rs— fix the flaky live-network test that was failing CI on unchanged code: oisy's bundle chunks grew to ~3 MiB and the 2 MiB per-file cap silently truncated the labelled backend id away; the per-file cap is now 4 MiB (memory stays bounded by the 8 MiB aggregate cap) and the test retries up to 3× so it asserts the mining logic rather than one fetch's luck.main.rs— routes the callback page, the redeem endpoint, and the allow-list;/versionreportsregistration_delegation: {beta, prod}.README.md— "Registration delegation (Phase 2 — per-instance)" subsection incl. the allow-list.mcp_register_v2and the delegation-minting methods are not on deployed II yet — until they ship, a Phase-2 instance simply continues to complete connects via v1 (see outbound-compatibility above). The wire shapes match II PRs #4091/#4092/#4093, which are not merged yet — re-verify against II's published.didand frontend when they land. Retiring v1 on a Phase-2 instance (the guide describes only the end state, with no v1) is a separate, later step. Phase 2's security precondition is Phase 1 (the #4091 callback allow-list validation), whose server-side counterpart this PR includes.Testing
cargo test— 74 pass. Unit tests cover the registration-key mint, the redemption guards, the input size cap, the single-flight claim state machine, the strict-CSP non-reflecting page, the v2 link param, theDelegationChainJSON decode (round-trip + fail-fast on unknown fields), the allow-list ↔ II-link verbatim-match invariant, per-instance route gating, v1 compatibility on a Phase-2 instance, the beta-on/prod-off defaults, the grant-capped token TTL, and the DCR grant-type intersection/refusal. No new build or clippy warnings. The end-to-end round trip still needs deployed II endpoints.🤖 Generated with Claude Code
https://claude.ai/code/session_014T9N8USDfNK5yzznPGg7Ym