Skip to content

fix(fe): validate the MCP connect callback against a server-declared allow-list - #4091

Merged
aterga merged 5 commits into
mainfrom
claude/mcp-delegation-refactor-x5b6ek
Jul 9, 2026
Merged

aterga merged 5 commits into
mainfrom
claude/mcp-delegation-refactor-x5b6ek

Conversation

@aterga

@aterga aterga commented Jul 8, 2026 •

Copy link
Copy Markdown
Collaborator

Motivation

The /mcp connect flow validates only the origin of the request's callback against the identity's synced trusted-server config (isOriginTrusted); the callback path is taken verbatim from the URL fragment, which is attacker-craftable. An attacker who can serve a chosen response at any path on the trusted origin — a planted file, a reflecting or over-broad static/user-content route — can craft a connect link whose callback points there. II then fetches that response and registers the attacker's public key against the (consenting) victim's anchor, yielding a live MCP session acting as the victim.

This is the "detached key" / planted-JSON phishing vector: II binds a key it merely fetched, at an endpoint path chosen by an untrusted link.

Design (updated after review): an earlier revision of this PR pinned the connect endpoint to an II-dictated fixed path (/.well-known/ii-mcp-connect). Per the review discussion, the destination is now declared by the server instead: II is the sign-in provider and the server is the party being returned to, so the server says where it can be returned to. The link's callback is honoured only when it exact-matches an entry the server declares — the link only ever selects among the server-declared set. The hardening points raised against the allow-list indirection are implemented as part of the mechanism (see below).

Changes

  • New $lib/utils/authCallbacks.ts (deliberately not MCP-specific — a general auth-callback allow-list other II flows can reuse):
    • AUTH_CALLBACKS_PATH = "/.well-known/ii-auth-callbacks" — the server hosts { "callbacks": ["https://server.example/mcp/connect", ...] } there (same origin only; different origins are separate trusted-server entries with their own file).
    • matchDeclaredCallback(origin, requestedCallback) — fetches the allow-list and exact-matches the link's callback against it, strict and fail-closed:
      • the fetch refuses redirects (an open redirect at the well-known path must not let a third party serve the list), carries no credentials, and is never cached (no-store — the match is always against the server's current declaration);
      • the response must be application/json and under a size cap;
      • the matched entry is itself validated: same-origin with the trusted origin (a declared cross-origin callback is rejected rather than honoured) and fragment-free;
      • any failure — including an unreachable allow-list — fails the connect before anything is registered.
  • mcp/+page.svelte: after the origin trust check, the connect flow resolves the callback via matchDeclaredCallback and talks only to that declared callback. An undeclared callback fails closed into the error path (toast + back to the connect screen).
  • mcpConfig.ts: the previous MCP_CONNECT_PATH / connectCallbackUrl pinning is removed.
  • Doc-comment updates in mcp/+page.ts and mcp/utils.ts.

Server contract: an MCP server must (1) host its auth-callback allow-list at /.well-known/ii-auth-callbacks on its trusted origin, served as application/json with CORS headers that let II read it, and (2) list only clean callbacks (no reflecting or open-redirecting endpoints) — the same hygiene the previously pinned page had to satisfy.

Tests

  • Unit (authCallbacks.test.ts): declared match resolves; transport posture (redirect: error, credentials: omit, cache: no-store) is pinned; undeclared / near-miss (prefix, suffix, case, query) callbacks are rejected; declared cross-origin and fragment-carrying entries are rejected; HTTP error, wrong content-type, oversized and malformed documents are rejected; network/redirect failures propagate (fail-closed).
  • e2e (mcp.spec.ts): "An undeclared callback path fails the connect" — with an attacker-chosen path on the trusted origin in the connect link, the connect fails closed with the allow-list error, the attacker path is never contacted, and nothing is registered. The fixture serves the allow-list declaring its callback, as a real server would.
  • npm run check passes (0 errors, pre-existing warnings only); the authCallbacks/mcpConfig/mcp unit tests pass locally. e2e runs in CI.

This is "phase 1" of the design discussed offline: it closes the reported bug now and is the precondition the larger registration-delegation refinement depends on (phase 2 backend: #4092, phase 3 frontend: #4093 — both stacked on this PR).

🤖 Generated with Claude Code

https://claude.ai/code/session_01VbjCCqTjsMn57fczTNGaKf

claude added 2 commits July 8, 2026 16:18
The `/mcp` connect flow validated only the callback's ORIGIN against the
identity's synced trusted-server config; the callback PATH came verbatim from
the attacker-craftable connect link. An attacker who can serve a chosen
response at any path on the trusted origin (a planted file, a reflecting or
over-broad static/user-content route) could make II fetch and register a key
they control against the victim's anchor.

Derive the connect endpoint from the trusted config's origin plus a fixed
well-known path (`connectCallbackUrl` -> `/.well-known/ii-mcp-connect`) and use
that for the key fetch and completion instead of the link's callback. The
link's callback is now used only for its origin (to identify the server and
gate the untrusted screen); its path is dropped, so a crafted link can no
longer point II at an arbitrary path on the trusted origin.

Adds unit coverage for the derivation and an e2e test that a tampered callback
path is ignored (II contacts the pinned endpoint, never the attacker path).

Servers must expose their II connect endpoint at `/.well-known/ii-mcp-connect`.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VbjCCqTjsMn57fczTNGaKf
… race)

"Disabling the master toggle blocks connecting" unchecked the Trusted-MCP-server
switch and immediately navigated to /mcp. handleToggle flips `enabled`
optimistically before awaiting the canister write, so the navigation (and the
connect's readMcpConfig) could race a not-yet-persisted write and read the config
as still enabled, skipping the untrusted screen. Under CI load this lost on all
retries on both the desktop and mobile shards.

Wait for the toggle to re-enable (it is `disabled={saving}` while the write is in
flight) before navigating, mirroring the reliable "Removing the trusted server"
test. Pre-existing race, surfaced by this branch's CI; unrelated to the pinning
change.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VbjCCqTjsMn57fczTNGaKf

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR hardens the /mcp connect flow against attacker-crafted callback paths by deriving the connect endpoint from the trusted server config’s origin plus a fixed well-known path, instead of using the link-provided callback path.

Changes:

  • Introduces a fixed connect endpoint (MCP_CONNECT_PATH) and connectCallbackUrl(config) to pin the connect handshake URL to the trusted origin.
  • Updates the /mcp connect UI flow to fetch/register/report completion using the pinned endpoint rather than the link’s callback path.
  • Adds/updates unit and e2e coverage to ensure a tampered callback path is ignored and to reduce a config-write race in an existing e2e.

Reviewed changes

Copilot reviewed 6 out of 6 changed files in this pull request and generated 1 comment.

Show a summary per file
File Description
src/frontend/src/lib/utils/mcpConfig.ts Adds fixed well-known connect path and helper to derive pinned connect endpoint from trusted config origin.
src/frontend/src/lib/utils/mcpConfig.test.ts Adds unit tests verifying pinned endpoint derivation behavior and edge cases.
src/frontend/src/routes/(new-styling)/mcp/+page.svelte Uses pinned connect endpoint after origin trust check; drops link-provided callback path from network use.
src/frontend/src/routes/(new-styling)/mcp/+page.ts Updates connect-flow documentation to reflect origin-only trust and pinned handshake endpoint.
src/frontend/src/routes/(new-styling)/mcp/utils.ts Updates documentation for the callback parameter to clarify it’s the pinned endpoint (not link-controlled).
src/frontend/tests/e2e-playwright/routes/mcp.spec.ts Adds e2e test ensuring tampered callback path is ignored; adds wait to avoid racing persisted config when disabling.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

…terministic

Addresses a review note: the attacker stub answered no CORS preflight, so a
regression that fetched the attacker path (a cross-origin JSON POST) would stall
on the rejected OPTIONS preflight rather than fail cleanly. Answer OPTIONS with
preflight headers, flip the flag only on the real request, and assert
`attackerPathHit` before awaiting the fixture-resolved completion (which a
regression would misdirect to the attacker path and never resolve) so the
failure mode is a clean assertion, not a timeout.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VbjCCqTjsMn57fczTNGaKf
@aterga
aterga marked this pull request as ready for review July 9, 2026 09:06
@aterga
aterga requested a review from a team as a code owner July 9, 2026 09:06
@aterga
aterga requested a review from sea-snake July 9, 2026 09:06
@zeropath-ai

zeropath-ai Bot commented Jul 9, 2026 •

Copy link
Copy Markdown

✅ No security or compliance issues detected. Reviewed everything up to 1c4cb5a.

Security Overview
Detected Code Changes
Change Type Relevant files
Enhancement ► src/frontend/src/lib/utils/authCallbacks.ts
    Implement server-declared auth callbacks and strict matching logic
► src/frontend/src/routes/(new-styling)/mcp/+page.svelte
    Incorporate matchDeclaredCallback usage and refer to server-declared allow-list
► src/frontend/src/routes/(new-styling)/mcp/+page.ts
    Document and rely on declared server callbacks for connect flow
► src/frontend/src/routes/(new-styling)/mcp/utils.ts
    Adjust types and comments to reflect declared callback handling
► src/frontend/tests/e2e-playwright/fixtures/mcp.ts
    Adapt fixture to expose AUTH_CALLBACKS_PATH for tests
► src/frontend/tests/e2e-playwright/routes/mcp.spec.ts
    Add test for undeclared callback path failing the connect

@sea-snake sea-snake left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pinning the destination is the right fix and closes the reported bug. One design alternative worth weighing before we bake in a hardcoded path:

Instead of II dictating a fixed path, let the server declare its allowed callbacks and have II validate against them.

Today this PR sets callback = origin + MCP_CONNECT_PATH, where MCP_CONNECT_PATH is a constant baked into the II frontend. That inverts the natural relationship: II is the sign-in provider and the server is the party being returned to, so the server is the one that should say where it can be returned to. The alternative:

  • The server hosts /.well-known/ii-auth-callbacks on its origin, listing the callback paths it accepts (same origin — different origins are separate trusted-server entries with their own file):
    {
      "callbacks": [
        "https://server.example/mcp/connect",
        "https://server.example/some-other-flow/callback"
      ]
    }
  • During sign-in the II frontend fetches that file from the (already trusted) origin and exact-matches the link's callback against the list. The link's path is still never trusted on its own — it only selects among the server-declared set.

The name is deliberately not MCP-specific: it's a general auth-callback allowlist that other II flows can reuse — relevant since we're also looking at auth flows initiated by II and/or non-postMessage flows, which need the same callback pinning.

@aterga

aterga commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Pinning the destination is the right fix and closes the reported bug. One design alternative worth weighing before we bake in a hardcoded path:

Instead of II dictating a fixed path, let the server declare its allowed callbacks and have II validate against them.

Today this PR sets callback = origin + MCP_CONNECT_PATH, where MCP_CONNECT_PATH is a constant baked into the II frontend. That inverts the natural relationship: II is the sign-in provider and the server is the party being returned to, so the server is the one that should say where it can be returned to. The alternative:

  • The server hosts /.well-known/ii-auth-callbacks on its origin, listing the callback paths it accepts (same origin — different origins are separate trusted-server entries with their own file):
    {
      "callbacks": [
        "https://server.example/mcp/connect",
        "https://server.example/some-other-flow/callback"
      ]
    }
  • During sign-in the II frontend fetches that file from the (already trusted) origin and exact-matches the link's callback against the list. The link's path is still never trusted on its own — it only selects among the server-declared set.

The name is deliberately not MCP-specific: it's a general auth-callback allowlist that other II flows can reuse — relevant since we're also looking at auth flows initiated by II and/or non-postMessage flows, which need the same callback pinning.

A forged allow-list gives the attacker indirection (it can bless any easier-to-control path, like a user-content route, as a permitted callback), whereas a forged fixed path only exposes that one conventionally server-controlled location. And the allow-list adds surface the fixed path simply doesn't have: the fetch must refuse redirects (or require a same-origin final URL — an open redirect at the well-known path must not let a third party serve the list), entries must be validated as same-origin (not just exact-matched — sea-snake's example uses full URLs, and II must reject a declared cross-origin callback rather than ship fragments off-origin), plus content-type checks, a size cap, a cache/TTL policy, and CORS on the server side. Each is solvable — ii-alternative-origins solves the same set — but it's a mini-spec needing its own review cycle, and one more availability dependency at consent time (well-known fetch fails ⇒ connect fails).

aterga pushed a commit to dfinity/imcp2 that referenced this pull request Jul 9, 2026
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
… allow-list

Replace the II-dictated fixed connect path (MCP_CONNECT_PATH /
connectCallbackUrl) with server-declared callbacks, per review: II is the
sign-in provider and the server is the party being returned to, so the
server declares where it can be returned to. It hosts a JSON allow-list at
/.well-known/ii-auth-callbacks on its origin, and the connect link's
callback is honoured only when it exact-matches a declared entry — the
link only ever selects among the server-declared set, closing the same
crafted-path vector the pinned path did.

The indirection is only as safe as its validation, so the new
matchDeclaredCallback (a general, non-MCP-specific helper) is strict and
fail-closed:
- the fetch refuses redirects (an open redirect at the well-known path
  must not let a third party serve the list), carries no credentials, and
  is never cached (no-store)
- the response must be application/json and under a size cap
- the matched entry is itself validated: same-origin with the trusted
  origin (a declared cross-origin callback is rejected, nothing ships
  off-origin) and fragment-free
- any failure (including an unreachable allow-list) fails the connect
  before anything is registered

The e2e fixture now declares its callback in the well-known document, and
the tampered-path test asserts the new fail-closed semantics: an
undeclared callback path aborts the connect without ever being contacted.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VbjCCqTjsMn57fczTNGaKf
@aterga aterga changed the title fix(fe): pin the MCP connect endpoint to the trusted origin + fixed path fix(fe): validate the MCP connect callback against a server-declared allow-list Jul 9, 2026

aterga commented Jul 9, 2026

Copy link
Copy Markdown
Collaborator Author

Switched to the server-declared allow-list as of 5d744cf, with the hardening points from the discussion above implemented as part of the mechanism rather than left as server hygiene:

  • File: /.well-known/ii-auth-callbacks → { "callbacks": ["<absolute URL>", ...] }, same origin only, served as application/json with CORS.
  • Fetch posture (matchDeclaredCallback in the new, deliberately non-MCP-specific $lib/utils/authCallbacks.ts): redirect: "error" (an open redirect at the well-known path cannot hand the list to a third party), credentials: "omit", cache: "no-store" (the match is always against the server's current declaration).
  • Document validation: content-type must be application/json, size-capped, shape-checked.
  • Match + entry validation: exact string match (the link only selects among declared entries), then the matched entry is itself re-verified same-origin with the trusted origin — a declared cross-origin callback is rejected rather than honoured — and must be fragment-free.
  • Fail-closed: any failure (including an unreachable allow-list) aborts the connect before anything is registered; the e2e test asserts an undeclared path is never contacted.

On the indirection concern: with the registration-delegation model in #4092/#4093, what II delivers to the callback is a single-use P_reg -> X delegation redeemable only by the holder of X's private key, so a blessed-but-attacker-reachable path yields an inert payload rather than a key registration — the allow-list is one layer, not the only one.

#4092 and #4093 are rebased on top; PR descriptions updated accordingly.


Generated by Claude Code

@aterga
aterga requested review from Copilot and sea-snake July 9, 2026 12:46

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Address review: the cap ran only after response.text() had read the whole
body into memory. Reject up front when the server declares an oversize
Content-Length, and otherwise enforce the cap chunk-by-chunk while
streaming, cancelling the read at the limit instead of buffering an
arbitrarily large body first. The cap is now a hard byte cap.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VbjCCqTjsMn57fczTNGaKf
@aterga
aterga enabled auto-merge (squash) July 9, 2026 13:20
@aterga
aterga merged commit 7584c4e into main Jul 9, 2026
46 checks passed
@aterga
aterga deleted the claude/mcp-delegation-refactor-x5b6ek branch July 9, 2026 13:28
aterga added a commit to dfinity/imcp2 that referenced this pull request Jul 9, 2026
…ta on, prod on v1) (#41)

* Add flag-gated Phase-2 registration-delegation connect flow (server side)

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

* Address review: standard-base64 CSP nonce, single-flight redemption

- 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

* Support dual connect protocols, selected per II instance

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

* Address review: bound redeem fragment field sizes before decoding

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

* Serve the pinned connect endpoint /.well-known/ii-mcp-connect (II #4091)

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

* Reconcile Phase 2 with II's implementation PRs (#4091/#4092/#4093)

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

* Align with the MCP server guide; fix the flaky oisy discovery test

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

* Address review: no-store allow-list, frame-ancestors on the pinned page

- /.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

---------

Co-authored-by: Claude <[email protected]>
aterga added a commit that referenced this pull request Jul 10, 2026
)

# Motivation

Phase 2 of the connect-handshake hardening, **stacked on #4091**
(declared-callback validation, now merged). Where phase 1 stops II from
*fetching* a key at an attacker-chosen path (the callback must
exact-match the server's declared allow-list), phase 2 stops II from
binding a key it merely *received* at all: it mints a consent-bound,
short-lived registration delegation and lets the trusted MCP server
redeem it, so the registered session key is one whose holder completed
the ceremony from the consenting browser session.

# Changes

**This PR (backend capability):**
- New `mcp_registration` module. The registration principal `P_reg` is
minted **per connect from a fresh 32-byte random nonce** (the management
canister's `raw_rand`), under a dedicated domain separator
(`b"mcp-registration"`), length-prefixed. Neither the anchor, nor the
consent, nor any key material is in the seed — `P_reg` is an opaque,
per-connect-unique handle. `prepare` returns the resulting `user_key`,
and `get` recovers the seed from it (the `seed` field of the DER
canister-signature key), so the two calls need not re-derive anything
deterministically.
- **The canister-signed hop targets the browser-held `Y`, never a
link-supplied key.** Everything the canister signs transits the IC in
the clear (the `get` query response passes the answering replica and API
boundary nodes), so it must be inert on its own — delegating to a key
from the (attacker-craftable) connect link would let a leaky node hand
an attacker a bearer credential for the consenting anchor. The frontend
(#4093) extends the chain browser-side with a second hop `Y -> X`; the
redeemable `P_reg -> Y -> X` chain is assembled only in the consenting
browser and never transits the IC.
- **The whole consent is stored, and recovered server-side — the server
passes nothing.** The index entry (`StorableMcpRegistration`, memory
index 30) records `P_reg -> {anchor, read_only, grant_ttl_ns,
trusted_url, expiry}`, written under full user authorization at
`prepare`. `mcp_register_v2(session_key)` takes **only** the session
key: it looks the entry up by `caller()` (== `P_reg`) and recovers the
anchor, the read-only choice, and the grant lifetime from it. Because
the server supplies none of these, it can neither name a different
anchor, nor upgrade the access level, nor stretch the TTL — and it never
learns the anchor number, the one identifier II otherwise never hands a
relying party (every later `mcp_*` call recovers the anchor from the
session grant).
- **A config change still invalidates in-flight delegations.**
`register_v2` requires the recorded `trusted_url` to still equal the
anchor's current one, so switching or disabling the trusted server
between consent and redemption breaks redemption — the same guarantee
the earlier derive-and-compare gave, now by comparison of a stored value
rather than re-derivation.
- **Multi-use within the short lifetime, replace-not-add.** No
single-use marker: the entry is redeemable until it expires (a retry
re-binds the same or a different `S`; the recovered consent is identical
each time), retained until a lookup finds it expired, then pruned.
Bounded by declared-callback-only delivery, `priv(X)`, the 5-minute TTL,
and one-session-per-anchor (a re-registration *replaces* the grant).
`register_v2` reports one generic error for missing entry / expired
entry / config mismatch so it can't be an oracle for probing anchors or
their MCP config.
- Registration-delegation TTL: **5 minutes** (browser hops + the IC's
~5-minute permitted clock drift). Explicit `DEFAULT_MCP_GRANT_TTL_NS` (1
hour) when `max_ttl` is omitted; the grant TTL is resolved (defaulted +
clamped to [10 min, 30 days]) at `prepare` and stored, so the entry
holds the effective lifetime; empty registration keys rejected at
`prepare`; `prepare` requires a live trusted-server config.
- Endpoints `prepare_`/`get_mcp_registration_delegation` (`get` now
takes the returned `user_key`, not the consent params) +
`mcp_register_v2(session_key)`; interface types; `internet_identity.did`
+ regenerated bindings; test-api wrappers.
- `mcp_register` (v1) stays alongside; the frontend still uses the
phase-1 flow until #4093.

**Stacked on top:** #4093 rewrites the frontend connect flow (generate
`Y`, mint + extend + fragment-deliver the chain — plus only the `state`
echo, *not* the anchor and *not* any consent value — to the server's
declared callback) and the e2e fixture/spec (server stand-in that
redeems via `mcp_register_v2(session_key)`) — that PR delivers the
end-to-end test path.

# Tests

- PocketIC integration tests (`tests/integration/mcp.rs`): the happy
path (prepare → get → verify the `P_reg -> Y` canister signature →
`register_v2` with the whole consent recovered from the entry → the
grant authorizes the server-facing `mcp_*` methods); a caller with no
entry rejected (cross-anchor protection); config-change and disable
invalidation; multi-use-with-replacement (a same-`S` retry re-binds; a
different `S` replaces the session and the old key loses authorization);
TTL clamp at `prepare`; delegation/entry expiry (register_v2 rejects the
expired entry + the certified signature is pruned);
prepare-without-trusted-server and empty-key rejections; storable
roundtrip.
- Verified locally: full MCP integration suite green (30 tests +
storable roundtrip), `cargo check` (wasm target), `cargo fmt`, `cargo
clippy` clean.

## Design notes (evolution, for reviewers following the threads)
- The seed is a **fresh random nonce**, not derived from the consent,
per [sea-snake's
review](#4092 (comment)):
`prepare` returns the data `get` needs (`user_key`), so neither call has
to be deterministic. This design walked back through two earlier shapes
— a derive-and-compare seed folding the consent (which forced both
methods to re-derive the same principal from clamped values and, when
fully stateless, disclosed the anchor to the server), then a minimal
`{anchor}` record keeping derive-and-compare for read-only/TTL. Storing
the whole consent tuple and keying it by a random `P_reg` is simpler
than both: no re-derivation, the server echoes nothing, and the anchor
stays private.
- `targets` on the registration delegation is left `None`; `P_reg`
authenticates nothing but `mcp_register_v2`.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01VbjCCqTjsMn57fczTNGaKf

---------

Co-authored-by: Claude <[email protected]>
aterga added a commit that referenced this pull request Jul 10, 2026
…2e) (#4093)

# Motivation

Third and final PR of the MCP *registration delegation* refinement,
following
#4092 (phase-2 backend, **now merged**). It migrates the browser `/mcp`
connect
flow — and its e2e coverage — to the new handshake, so the frontend and
the
tests that exercise it land together.

Before, the connect flow fetched the MCP server's session key from a
callback
and called `mcp_register` on the server's behalf, then POSTed a
completion
notification back. That put II in the position of registering a key it
merely
received, and leaned on an out-of-band completion channel (plus a
`finish_url`
in the key response) to hand the flow back to the server.

The registration-delegation model removes that. II mints a **short-lived
registration chain `P_reg -> Y -> X`**: the canister signs `P_reg -> Y`
for an
**ephemeral browser-held key `Y`**, and the II frontend extends the
chain
locally with a browser-signed hop `Y -> X` to the server's per-connect
registration key `X` (from the link). The two-hop shape is load-bearing:
what
the canister signs transits the IC (the `get` query response passes the
answering replica and API boundary nodes) and must be inert on its own —
the
redeemable chain is assembled only in the consenting browser and reaches
the
server exclusively via a fragment navigation to a callback it
**declares** in
its `/.well-known/ii-auth-callbacks` allow-list (#4091). The server
redeems it
(`mcp_register_v2`) to bind its own long-lived session key `S`. Per
phase-2,
the canister records the **whole consent** (anchor, read-only choice,
grant
lifetime, trusted URL) on the registration entry and recovers it
server-side,
so the flow delivers **only the chain and the `state` echo** in the
fragment —
no anchor, no permissions, no ttl. The server passes only its session
key to
`mcp_register_v2`, so there is nothing for it to alter and it never
learns the
anchor.

> Now based on `main` (phase-2 #4092 has merged); this is the last PR in
the stack.

# Changes

**Frontend connect flow**
- `mcp/+page.ts`: the connect link carries a required `registration_key`
  (the server's public per-connect key `X`), validated with a single Zod
  schema (whole-fragment `safeParse`, per review).
- `mcp/utils.ts`: `mcpAuthorize` generates a non-extractable ECDSA `Y`,
  calls `prepare_mcp_registration_delegation` for `Y` (with the consent
  params, which `prepare` records on the entry) then
  `get_mcp_registration_delegation` handing back the returned `user_key`
(the link's `X` never reaches the canister; `get` recovers the seed from
  `user_key`), extends the chain browser-side via
`DelegationChain.create(..., { previous })`, and returns the **delivery
URL**: declared callback + `#delegation=…&state=…`. No consent value and
no
anchor is delivered (the canister recovers all of it). Canister errors
are
unwrapped via a `throwTextCanisterError` helper (the `mcp_*` family's
candid
  error is `text`, which `CanisterError`'s variant wrapper doesn't fit).
- `mcp/+page.svelte`: `handleAuthorize` exact-matches the link's
callback
against the server's declared allow-list (`matchDeclaredCallback`),
mints
  the chain, then hands the tab to the delivery URL.
- Removed the dead `finish_url` / completion-POST machinery.
- The close-view copy says the tab is being taken to the server to
finish
  connecting.

**Tests**
- `mcp/load.test.ts`, `mcp/utils.test.ts`: v2 params; the two-hop chain
shape
(hop 1 targets the browser key, hop 2 the link's `X`, hop-2 expiry
bounded
by hop 1); that the canister never sees `X`; fresh `Y` per attempt; that
`get` is called with the returned `user_key`; that the delivery fragment
carries **only** `delegation` + `state` for both access levels (no
anchor,
no permissions, no ttl); no network calls of II's own; error
propagation.
- `tests/e2e-playwright/fixtures/mcp.ts`: the MCP server stand-in
generates
`X` + `S`, declares its connect page in the allow-list, serves that page
(reads the delivered fragment — chain + state — clears it, POSTs it to a
  fixture endpoint), and — as the server backend holding `priv(X)` —
reconstructs the chain and redeems via `mcp_register_v2(session_key)`
(no
consent arguments), reading the granted level off the response, against
the
  local replica.
- `tests/e2e-playwright/routes/mcp.spec.ts`: all `/mcp` tests on the v2
flow;
  an undeclared callback path fails the connect without being contacted.

**Docs**
- `docs/mcp-server-guide.md`: rewritten for the declared-callbacks +
registration-chain contract (allow-list requirements, link format,
two-hop
chain format and why, the fragment carrying only the chain + state, and
redemption passing only the session key with the whole consent recovered
server-side — the 5-minute window and replace-not-add multi-use, a note
that
  the anchor is recovered server-side and never delivered, structural
  Consent-Bound Completion in the OAuth section, DCR `grant_types`
  clarification).

# Tests

- `tsc`, `svelte-check` (0 errors), ESLint (`--max-warnings 0`),
Prettier pass
  locally; `vitest` unit suites (authCallbacks + mcp) pass.
- The Playwright e2e suite requires a replica + browser and validates in
CI.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01VbjCCqTjsMn57fczTNGaKf

---------

Co-authored-by: Claude <[email protected]>
aterga added a commit that referenced this pull request Jul 13, 2026
…anchor (#4098)

# Motivation

A least-privilege hardening of the MCP registration-delegation flow
(shipped in #4091/#4092/#4093), surfaced by a post-merge holistic
review.

`get_mcp_registration_delegation` authenticated the caller for
`anchor_number` (via `check_authorization`) but did **not** verify that
the presented `user_key`'s stored registration entry actually *belongs*
to that anchor. Because the certified `P_reg -> Y` signature is looked
up purely from the recovered seed, an identity authorized for one anchor
could fetch a **different** anchor's certified hop by presenting that
anchor's `(user_key, Y, expiration)` — the same triple that anchor's own
frontend receives from `prepare`.

This is not an exploitable capability on its own: the canister-signed
hop is inert without the browser-held `priv(Y)`, and it transits the IC
in the clear (the `get` query response passes the answering replica and
API boundary nodes) regardless of who fetched it. So this is
defense-in-depth / least-privilege, not a plugged leak. But there is no
legitimate reason to ever serve one anchor another's registration
delegation.

# Changes

- **`src/internet_identity/src/mcp_registration.rs`** — `get()` now
computes `P_reg = self_authenticating(user_key)` and requires
`index[P_reg].anchor_number == anchor_number` before returning the
signature. A cross-anchor (or absent, or malformed-key) request returns
the same generic `"MCP registration failed: no such delegation."`, so
the method never reveals that a `P_reg` exists under a different anchor.
The repeated error string is factored into a `NO_SUCH_DELEGATION` const,
mirroring `register_v2`'s existing `NOT_AUTHORIZED` const.
- The legitimate flow is unaffected: `mcpAuthorize` calls `prepare` and
`get` with the same `identityNumber`, and `prepare` always writes the
entry, so the scoping check passes for the consenting user's own
connect.

# Tests

- New integration test
`mcp_get_registration_delegation_is_scoped_to_the_authenticating_anchor`
(`tests/integration/mcp.rs`): two anchors on separate device principals,
both trusting the MCP server. The anchor that minted a delegation
fetches its own successfully (positive control); a second,
separately-authenticated anchor presenting the first's `(user_key, Y,
expiration)` is rejected with "no such delegation".
- Full MCP integration suite green locally (33 tests); `cargo fmt` and
`cargo clippy` clean.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

https://claude.ai/code/session_01VbjCCqTjsMn57fczTNGaKf

---
_Generated by [Claude
Code](https://claude.ai/code/session_01VbjCCqTjsMn57fczTNGaKf)_

Co-authored-by: Claude <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants