Skip to content

Fix read-only sessions: decode II delegation permissions as opt text - #40

Merged
aterga merged 2 commits into
mainfrom
claude/readonly-delegation-fix
Jul 6, 2026
Merged

aterga merged 2 commits into
mainfrom
claude/readonly-delegation-fix

Conversation

@aterga

@aterga aterga commented Jul 6, 2026

Copy link
Copy Markdown
Collaborator

Symptom

Read-only (queries-scoped) sessions failed every per-app operation — balance reads, get_principal, any call_canister(domain=…) — with the replica error:

invalid delegation chain: sig not found in the signature tree

Full-access sessions worked, which is what made it look permission-specific.

Root cause

II's mcp_get_delegation returns the delegation's permissions field as opt text ("queries" / "all") — confirmed in II's live .did:

type Delegation = record { pubkey : PublicKey; expiration : Timestamp; targets : opt vec principal; permissions : opt text };

…but we decoded it as opt variant { queries; all }. Because the field is opt, Candid's opt-mismatch rule silently drops the type-mismatched text to None (no error). We then presented a sender_delegation without permissions, so the replica recomputed the no-permissions request id, and II's canister signature — which covers the permissions field — was not in the signature tree → rejected.

Full access was unaffected because II omits permissions when unrestricted, so there was nothing to lose (the no-permissions hash matched).

The symptom itself corroborates this: the error was the replica's sig not found (a downstream call), not our "could not decode get reply" — i.e. the decode succeeded with the permission quietly lost to None. That's the fingerprint of the opt-drop.

Fix

Decode permissions as Option<String> (matching II's opt text) and map "queries"/"all" into ic-agent's DelegationPermissions in into_agent — which re-serializes to the same text, so the reconstructed delegation hashes to exactly what II signed. Unknown/future values fall back to None.

Tests

The existing tests encoded the wrong wire shape (a variant) — which is precisely why the bug hid; a mocked variant reply round-tripped through a variant decode. They're corrected to opt text, and a new regression test proves both halves side by side:

  • decoding II's opt text as a variant drops it to None (the bug), and
  • the text decode preserves it end-to-end onto the ic-agent delegation (the fix).

54 tests green; no new clippy warnings.

Ops follow-up (not code)

Even with this fix, the delegation only verifies if the target subnet's replica understands the permissions field. A replica predating it would drop the field on its own decode and still yield sig not found. Confirm the subnet handling the signed call carries permissions in its Delegation type.

Separate from PR #39 (ICP funding), which is left untouched.

🤖 Generated with Claude Code

https://claude.ai/code/session_014T9N8USDfNK5yzznPGg7Ym


Generated by Claude Code

Read-only (queries-scoped) sessions failed every per-app call — balance
reads, get_principal, any call_canister(domain=…) — with the replica error
"invalid delegation chain: sig not found in the signature tree".

Root cause: II's mcp_get_delegation returns the delegation's `permissions`
field as `opt text` ("queries"/"all"), but we decoded it as `opt variant
{ queries; all }`. Because the field is `opt`, Candid's opt-mismatch rule
silently dropped the type-mismatched text to `None` — no error. We then
presented a sender_delegation WITHOUT permissions, so the replica recomputed
the no-permissions request id, and II's canister signature (which covers the
permissions field) was not in the signature tree → rejected. Full-access
sessions were unaffected because II omits permissions when unrestricted, so
there was nothing to lose.

Fix: decode `permissions` as `Option<String>` (matching II's `opt text`) and
map "queries"/"all" into ic-agent's `DelegationPermissions` in `into_agent`
(which re-serializes to the same text, so the reconstructed delegation hashes
to exactly what II signed). Unknown/future values fall back to None.

The existing tests encoded the wrong wire shape (a variant), which is why the
bug hid — they're corrected to `opt text`, and a regression test proves both
halves side by side: decoding II's opt-text as a variant drops it to None,
while the text decode preserves it through to the ic-agent delegation.

Note: even with this fix, the delegation only verifies if the target subnet's
replica understands the `permissions` field; a replica that predates it would
drop it on its own decode. Confirm the target replica carries it.

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

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Fixes Internet Identity (II) mcp_get_delegation permission handling so read-only (“queries”-scoped) sessions reconstruct delegations with a hash/signature that matches what II signed (avoiding replica “sig not found in the signature tree” failures).

Changes:

  • Decode Delegation.permissions as Option<String> to match II’s on-wire opt text representation.
  • Map "queries" / "all" into ic-agent’s DelegationPermissions during into_agent.
  • Update and extend tests to encode the correct wire shape and add a regression guard for the opt-mismatch silent-drop behavior.

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

Comment thread src/identities.rs Resolved
@aterga
aterga marked this pull request as ready for review July 6, 2026 20:37
Follow-up to the read-only fix (review): permissions_from_text mapped an
unknown permission string to None, and into_agent treated that like an absent
(unrestricted) permission. Since the canister signature covers the permissions
field, a future II permission value would then produce a delegation whose
signature can never verify — silently resurfacing the same "sig not found in
the signature tree" error this PR set out to end.

Return a clear error instead when `permissions` is present but unrecognized, so
the real cause surfaces and the behavior can't silently regress. Absent stays
None (unrestricted); "queries"/"all" map as before. Adds a test.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_014T9N8USDfNK5yzznPGg7Ym
@aterga
aterga merged commit 35d3031 into main Jul 6, 2026
1 check passed
aterga pushed a commit that referenced this pull request Jul 9, 2026
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
aterga added a commit 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 12, 2026
…llback page (#50)

* Reconcile registration-delegation with merged II contract; restyle callback page

Two related changes to the Phase-2 registration-delegation flow, both verified
against the beta II canister's live .did (fgte5-ciaaa-aaaad-aaatq-cai).

Merged mcp_register_v2 contract (correctness)
---------------------------------------------
II's merged frontend/canister no longer echo consent through the server:
mcp_register_v2 now takes a SINGLE argument, session_key. The user's chosen
permissions/max_ttl are captured earlier at prepare_mcp_registration_delegation
(stored server-side keyed by P_reg) and mcp_register_v2 recovers both them and
the anchor from caller() == P_reg. Our code was still on the older 3-arg echo;
it kept working only because Candid silently drops the two extra trailing args.

- Fragment/redeem: the pinned page forwards only {delegation, state}; RedeemBody
  drops permissions/ttl; parse_consent and the fragment reads are removed.
- Redemption: redeem_registration_delegation drops the consent argument and
  encodes Encode!(&session_der) (one arg). The reply (record { expiration;
  permissions }) is unchanged and still feeds the read-only guard.
- Removed RegistrationConsent and IiPermissions::from_text (now dead). The
  IiPermissions variant stays for decoding the reply; a test locks its on-wire
  queries/all labels (the #40 shape-drift lesson, moved to where it now lives).
- Docs (module headers, README Phase-2 section) rewritten for the merged shape.

Callback page rendering (UX)
----------------------------
The pinned callback page shipped a strict CSP (default-src 'none') with no
style-src, so the browser silently dropped the page's inline style attribute and
rendered "Finishing sign-in…" as unstyled top-left serif text. Fixed by moving
styling into a nonce'd <style> block and adding style-src 'nonce-…' to the CSP
(no 'unsafe-inline'). The shared stylesheet gives a centered card, system font,
a CSS-only spinner (disabled under prefers-reduced-motion), light/dark theming,
lang=en, and an accessible role=status/aria-live region; errors hide the spinner.
The sibling finishing_page and connect_error pages reuse the same look.

cargo test: 87 passing; no new build/clippy warnings.

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

* Style the connect pages to DFINITY brand guidelines

Restyle the OAuth connect interstitial/error pages (pinned callback, v1
finishing page, connect error) to the DFINITY brand system, and add the
official DFINITY logo.

- Palette: Parchment #faf9f5 / Ink #1a1a1a / Rust #a8482b, hairline surfaces,
  grid-paper texture; dark theme uses the brand's Bark #14110d / Bone #f0ebe0 /
  Ember #c25a37 via prefers-color-scheme with a data-theme override.
- Typography: editorial serif (Newsreader-style) for the status line, UI sans
  (Inter-style) for the eyebrow/hint, both from CSP-safe system-font stacks.
- Logo: the official gradient-infinity mark + DFINITY wordmark, taken from
  dfinity.org and inlined as SVG so it loads under the pinned page's strict
  default-src 'none' CSP (no external fetch). The wordmark uses currentColor so
  it follows the Ink/Bone text color across themes; the infinity keeps its
  brand gradients.
- Layout: centered card with hairline border and soft shadow, DFINITY logo, an
  "Internet Identity" eyebrow, the rust/ember spinner, and the status line.

Everything stays self-contained (no external fonts/images/stylesheets), so the
pinned callback page still renders under its strict CSP. cargo test: 87 passing.

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

* Address PR review: extract inlined assets to files; fix escaping and docs

Review feedback on PR #50:

- Move the inlined connect-page stylesheet and DFINITY logo out of auth.rs
  into real asset files (src/assets/connect.css, src/assets/dfinity-logo.svg)
  and embed them with include_str!. Content is still compiled into the binary
  (no runtime file I/O, still self-contained under the strict CSP); the served
  HTML is byte-identical. Authoring them as .css/.svg keeps auth.rs readable.
- connect_error: escape `&` first (then `<` and `>`) before interpolating the
  message into HTML, so a message containing `&` or entities can't be
  misread as markup.
- Docs: the README and auth.rs module doc described mcp_register_v2 as
  returning `record { expiration; permissions }`; it actually returns
  `variant { Ok : record { ... }; Err : text }` (a candid Result). Corrected
  both to the full variant shape (the Ok payload carries expiry + access level).

cargo test: 87 passing; no new build warnings.

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

* Address PR review round 2: narrow live region; fix remaining return-shape doc

- Accessibility (Copilot): move role=status / aria-live=polite off the whole
  <main> card and onto just the status <p> on both the pinned callback page and
  the v1 finishing page, so updating the message no longer risks re-announcing
  the logo's aria-label or the eyebrow.
- Docs (Copilot): the identities.rs redeem note still described the
  mcp_register_v2 reply as `record { expiration; permissions }`; correct it to
  the full `variant { Ok : record { ... }; Err : text }` (decoded as
  McpRegisterV2Reply; McpRegisterV2Ok is the Ok payload).

cargo test: 87 passing.

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

---------

Co-authored-by: Claude <[email protected]>
aterga pushed a commit that referenced this pull request Jul 24, 2026
…variant

Doc-only: the delegation record's permissions field is opt text, distinct from
the named Permissions variant (which is only the prepare_ argument / register
reply). Spell it out at the type so the distinction (the II #40 outage class)
isn't misread. No behavior change (Copilot review).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_017h4prMHkLo6UnwnuoPgmUj
aterga added a commit that referenced this pull request Jul 24, 2026
…nister (PocketIC) (#76)

* test: cover the MCP↔II connect handshake success path

The router tests exercised the handshake scaffolding (input validation,
endpoint wiring, the pinned callback page, the 401 challenge) but never the
success path: a redeemed grant becoming a working access token. Close that
gap with an end-to-end test of connect_redeem → token → session_for_token.

The one step that cannot run hermetically is the registration redemption:
DelegatedIdentity::new verifies the delivered chain against the IC mainnet
root key, and mcp_register_v2 is a live update call to Internet Identity. Add
a cfg(test)-only seam (Identities::with_register_override) that stands in for
exactly that step — so a fabricated-but-structurally-valid chain drives the
whole flow while everything around redemption (parse_registration_delegation,
the cookie/initiator and single-flight guards, PKCE-bound code minting, the
S256 token exchange, TTL-from-grant, token authentication, single-use codes)
runs unchanged. The seam adds nothing to non-test builds.

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

* Verify the registration chain against the injected agent's root key

registration_identity() built the redeeming DelegatedIdentity with
DelegatedIdentity::new, which hardcodes the IC mainnet BLS root key. Switch
to new_with_root_key(&self.agent.read_root_key()) so the delivered
P_reg -> Y -> X chain is verified against the SAME network the agent then
makes the mcp_register_v2 call to, instead of an independently pinned
mainnet key.

Behavior-preserving in production (the injected agent is mainnet and never
fetches another key, so read_root_key() == the mainnet key), and more
consistent: a host pointed at a non-mainnet IC — e.g. a local replica after
fetch_root_key — now verifies and signs against one trust anchor. This is
also what lets a real Internet Identity canister on PocketIC issue a chain
the server can verify, which the forthcoming end-to-end test relies on.

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

* Test the II<>MCP handshake against a live II canister in PocketIC

Replaces the cfg(test) registration seam and its mocked connect->token test
with a real end-to-end test: a genuine Internet Identity canister (release
wasm) runs in PocketIC and issues a real canister-signed registration
delegation, which the real server redeems through its own ic-agent. Nothing
about II is mocked.

The test (src/e2e_handshake.rs) plays only the browser/frontend role —
register an anchor, mcp_set_config to trust the server, then the
prepare_mcp_registration_delegation + get_mcp_registration_delegation
ceremony — and feeds the resulting real delegation to /oauth/connect/redeem.
The server verifies the canister signature against PocketIC's fetched root
key (via the new_with_root_key change) and signs mcp_register_v2 on the live
II, then /oauth/token issues a bearer token that authenticates. So the whole
redeem->code->token->auth path runs against a real II, not a stand-in.

Gating keeps the default build lean and offline:
- pocket-ic is an optional dependency behind a new `e2e` feature, so plain
  `cargo build`/`cargo test` neither compile nor download it.
- The test is in-crate under #[cfg(all(test, feature = "e2e"))] (an integration
  test in tests/ cannot use an optional dependency), and skips at runtime
  unless II_WASM and POCKET_IC_BIN are set:
    II_WASM=... POCKET_IC_BIN=... cargo test --features e2e

The II candid types are hand-rolled from internet_identity.did at tag
release-2026-07-17 so the crate takes no git dependency. Removing the seam
leaves redeem_registration_delegation with a single real path.

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

* Fix Cargo.toml comments to point at src/e2e_handshake.rs

The e2e test is an in-crate module (src/e2e_handshake.rs), not
tests/e2e_pocket_ic.rs — correct the two manifest references (Copilot review).

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

* e2e test: unique clients file + restore OAUTH_CLIENTS_FILE on drop

The PocketIC test set the process-global OAUTH_CLIENTS_FILE to a fixed temp
filename, which under parallel test threads could leak into other tests
calling SharedClients::load() and contend on the shared file. Use a
per-process/timestamped unique filename and a Drop guard that restores (or
clears) the env var even on panic-unwind, and removes the temp file (Copilot
review).

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

* Clarify that Delegation.permissions is opt text, not the Permissions variant

Doc-only: the delegation record's permissions field is opt text, distinct from
the named Permissions variant (which is only the prepare_ argument / register
reply). Spell it out at the type so the distinction (the II #40 outage class)
isn't misread. No behavior change (Copilot review).

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

---------

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.

3 participants