Skip to content

authorizationHandler drops the OAuth state parameter on error redirects #2773

Open

Description

@Ssavan99

authorizationHandler omits state from the error redirect when authorization
parameter validation fails, so a client that validates state on the callback —
the standard CSRF check from RFC 6749 §4.1.2.1 — cannot accept or correlate the
error response. The client sees a state mismatch instead of the actual OAuth
error, and the real cause (invalid_request) never reaches the user.

RFC 6749 §4.1.2.1 requires state on the error response whenever the request
carried one:

state: REQUIRED if the "state" parameter was present in the client
authorization request. The exact value received from the client.

The success path echoes state correctly; only the error path drops it.

Reproduction

import express from 'express';
import { authorizationHandler } from '@modelcontextprotocol/sdk/server/auth/handlers/authorize.js';

const CLIENT = { client_id: 'test-client', redirect_uris: ['https://client.example.com/cb'] };
const provider = {
    clientsStore: { getClient: async id => (id === CLIENT.client_id ? CLIENT : undefined) },
    async authorize(client, params, res) {
        const u = new URL(params.redirectUri);
        u.searchParams.set('code', 'authcode');
        if (params.state) u.searchParams.set('state', params.state);
        res.redirect(302, u.href);
    }
};

const app = express();
app.use('/authorize', authorizationHandler({ provider, rateLimit: false }));
const server = app.listen(3000);

// state is echoed on success:
//   /authorize?client_id=test-client&redirect_uri=...&state=xyz789
//             &response_type=code&code_challenge=abc&code_challenge_method=S256
//   -> 302 https://client.example.com/cb?code=authcode&state=xyz789
//
// state is dropped as soon as any other parameter fails validation:
//   /authorize?client_id=test-client&redirect_uri=...&state=xyz789&response_type=code
//   -> 302 https://client.example.com/cb?error=invalid_request&error_description=...
//      (no state)

Any Phase-2 validation failure reproduces it: missing code_challenge,
code_challenge_method=plain, a non-URL resource.

Cause

In packages/server-legacy/src/auth/handlers/authorize.ts, state is read from
the parse result after the parse is checked:

let state;
try {
    const parseResult = RequestAuthorizationParamsSchema.safeParse(...);
    if (!parseResult.success) {
        throw new InvalidRequestError(parseResult.error.message);   // throws here
    }
    const { scope, code_challenge, resource } = parseResult.data;
    state = parseResult.data.state;                                 // never runs

The catch then calls createErrorRedirect(redirect_uri, error, state, issuer)
with state still undefined, and createErrorRedirect omits the parameter.

Expected

The error redirect carries state=xyz789, matching the success path and RFC 6749
§4.1.2.1.

Why this matters

I run an MCP server on this SDK in production — HTTP transport behind a public
URL, mcpAuthRouter with an OAuth read scope, remote clients — and found this
while reading through that auth path rather than from an incident. The impact is
still concrete: a client whose authorization request is malformed gets back a
callback it has to reject on CSRF grounds, so the operator sees a state-mismatch
error from the client and no trace of the real cause. It turns a one-line
parameter mistake into a blind debugging session, on the error path, which is
exactly where the diagnostic is supposed to work.

Environment

  • @modelcontextprotocol/sdk 1.29.0, and reproduced on main @ 5119ee7
  • Node 22.13.0, express 5.2.1

I have a fix with regression tests and can open a PR.

Disclosure: found and patched with AI assistance (Claude Code). I have reviewed
the diagnosis, the fix, and the tests, and can speak to any of it.

Activity

  1. Ben-Home commented on Sep 9, 2026

    @Ben-Home
  2. insuffer commented on Sep 22, 2026

    @insuffer

    Hi, I'd like to work on this. The state parameter is currently dropped from error redirects when RequestAuthorizationParamsSchema validation fails, which violates RFC 6749 §4.1.2.1 (error redirects MUST echo state for CSRF correlation).

    I have a minimal fix for the v1.x line (recover state from the raw request params before throwing on parse failure) with regression tests for both GET and POST — local tests are green (1649 passed, no regressions). Will send a PR shortly if this is still unclaimed.

  3. added
    v1
    v2
    on Sep 23, 2026
  4. anurag1504t commented on Nov 10, 2026

    @anurag1504t

    I tested both fixes. They work, and neither changes the paths that must stay the same.

    I mounted the real authorizationHandler in a small Express app with a stub provider that echoes
    state, and sent the same requests to the current v1.x tip (3b73021) with #2842 applied, the
    current main tip (1e608ca, packages/server-legacy) with #2774 applied, and each tip without a
    patch. Both patches apply cleanly.

    Request Before (both lines) After #2842 (v1.x) After #2774 (main)
    valid request (control) state echoed echoed echoed
    no code_challenge, GET state dropped echoed echoed
    no code_challenge, POST dropped echoed echoed
    code_challenge_method=plain dropped echoed echoed
    state = a b&c=d#e/ü, no challenge dropped echoed exactly echoed exactly
    state sent twice absent absent absent
    empty state= absent absent absent
    unregistered redirect_uri 400, no redirect same same
    unknown client_id 400, no redirect same same

    The last four rows are unchanged by either patch. A repeated state is not a string, so it is not
    echoed; an empty state= is left out because createErrorRedirect tests truthiness. Both are the
    same before and after. The authorize tests in both pull requests pass: 29 of 29 on v1.x, 35 of 35
    on main.

    I also hit the bug from the client side. A test client that matches redirects by state waited
    until its timeout on an error redirect from a server built on the 1.30.1 mcpAuthRouter, instead
    of reporting invalid_request.

    Both changes look correct to me.

    The probe I used (Node 20, run from a checkout, pass the built handler and a port)
    // Mounts the SDK's real authorizationHandler from a build, with a stub provider, and sends requests.
    import express from 'express';
    const [dist, port] = [process.argv[2], Number(process.argv[3] ?? 3101)];
    const mod = await import(dist.startsWith('/') ? dist : `./${dist}`);
    const authorizationHandler = mod.authorizationHandler;
    
    const CLIENT = { client_id: 'c1', redirect_uris: ['http://127.0.0.1:8765/callback'], scope: 'mcp' };
    const provider = {
      clientsStore: { getClient: async (id) => (id === 'c1' ? CLIENT : undefined) },
      async authorize(client, params, res) {
        const u = new URL(params.redirectUri);
        u.searchParams.set('code', 'code-1');
        if (params.state) u.searchParams.set('state', params.state);
        res.redirect(302, u.href);
      },
    };
    const app = express();
    app.use('/authorize', authorizationHandler({ provider, issuerUrl: new URL(`http://127.0.0.1:${port}`), rateLimit: false }));
    const server = app.listen(port, '127.0.0.1');
    const base = `http://127.0.0.1:${port}/authorize`;
    const CH = 'Gt9FmDu6VGwpNGe_IHn4aODoLCVoTdYvDoERwCANeEE';
    const ok = { response_type: 'code', client_id: 'c1', redirect_uri: 'http://127.0.0.1:8765/callback', code_challenge: CH, code_challenge_method: 'S256', scope: 'mcp' };
    const { code_challenge, code_challenge_method, ...noChallenge } = ok;
    
    const qs = (o) => Object.entries(o).flatMap(([k, v]) => (Array.isArray(v) ? v.map((x) => [k, x]) : [[k, v]])).map(([k, v]) => `${encodeURIComponent(k)}=${encodeURIComponent(v)}`).join('&');
    async function send(name, { method = 'GET', params, expectState }) {
      const url = method === 'GET' ? `${base}?${qs(params)}` : base;
      const res = await fetch(url, { method, redirect: 'manual', ...(method === 'POST' ? { headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: qs(params) } : {}) });
      const loc = res.headers.get('location');
      let where = '(no redirect)', state = '-', error = '-', iss = '-';
      if (loc) { const u = new URL(loc); where = `${u.origin}${u.pathname}`; state = u.searchParams.has('state') ? JSON.stringify(u.searchParams.get('state')) : 'ABSENT'; iss = u.searchParams.has('iss') ? 'iss' : 'no-iss'; error = u.searchParams.get('error') ?? (u.searchParams.has('code') ? '(code)' : '-'); }
      const verdict = expectState === undefined ? '' : (state === JSON.stringify(expectState) ? 'echoed' : state === 'ABSENT' ? 'DROPPED' : 'WRONG');
      console.log(`${name.padEnd(46)} ${String(res.status).padEnd(4)} ${error.padEnd(16)} state=${state.padEnd(22)} ${iss.padEnd(7)} ${verdict}`);
    }
    const weird = 'a b&c=d#e/ü';
    console.log(`# ${dist}`);
    await send('control: valid request', { params: { ...ok, state: 'abc' }, expectState: 'abc' });
    await send('BUG: no code_challenge, GET', { params: { ...noChallenge, state: 'abc' }, expectState: 'abc' });
    await send('BUG: no code_challenge, POST', { method: 'POST', params: { ...noChallenge, state: 'abc' }, expectState: 'abc' });
    await send('BUG: method plain, GET', { params: { ...ok, code_challenge_method: 'plain', state: 'abc' }, expectState: 'abc' });
    await send('special characters in state', { params: { ...noChallenge, state: weird }, expectState: weird });
    await send('state repeated (array), no challenge', { params: { ...noChallenge, state: ['a', 'b'] } });
    await send('empty state, no challenge', { params: { ...noChallenge, state: '' } });
    await send('no state at all, no challenge', { params: { ...noChallenge } });
    await send('SAFETY: unregistered redirect_uri', { params: { ...noChallenge, redirect_uri: 'https://evil.example/cb', state: 'abc' } });
    await send('SAFETY: unknown client_id', { params: { ...noChallenge, client_id: 'nope', state: 'abc' } });
    server.close();

    For v1.x: node probe.mjs dist/esm/server/auth/handlers/authorize.js 3101.
    For main: node probe.mjs <path to packages/server-legacy/dist/auth/index.mjs> 3101.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    v1v2

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions