inspector/core/auth/node/runner-interactive-oauth.ts
cliffhall f4fb4b50c9 Forward RFC 9207 iss to the v2 SDK (fixes OAuth + EMA leg 1)
SDK v2 added RFC 9207 §2.4 authorization-response issuer validation
(`validateAuthorizationResponseIssuer` / `IssuerMismatchError`) as a mix-up
attack defense. It is strict: when AS metadata advertises
`authorization_response_iss_parameter_supported: true` and no `iss` reaches
`exchangeAuthorization`/`auth()`, the exchange throws.

v1.29.0 had no `iss` parameter and no RFC 9207 validation at all, so dropping
the callback `iss` was harmless. The migration swapped in the stricter SDK
without feeding it the new input, breaking the authorization-code exchange
against any RFC 9207 authorization server (Okta/xaa.dev advertise it):

    Issuer mismatch in authorization response (RFC 9207):
    expected "https://idp.xaa.dev", received undefined

Found by smoke-testing EMA against live xaa.dev staging; not caught by CI
because the mock IdP never advertised the parameter, so the SDK took its
lenient path (a missing `iss` is only fatal when advertised).

`iss` was dropped in three places, with the plumbing half-built —
`oauthManager`/`inspectorClient` already accepted `iss`, but nothing supplied
or forwarded it:

- `parseOAuthCallbackParams` never extracted `iss` from the callback query
- `mcpAuth` never forwarded `options.iss` to SDK `auth()` — its own comment
  ("forwarded on v2 upgrade; ignored by v1 SDK auth()") predicted this exact
  gap, so standard OAuth was broken identically, not just EMA
- EMA leg 1 (`completeIdpOidcAuthorization`) never passed `iss` to
  `exchangeAuthorization`

Thread `iss` end to end: callback query -> CallbackParams -> resumeAfterOAuth
-> completeOAuthFlow -> {mcpAuth | EMA leg 1} -> SDK. The Node callback server
and runner carry it for CLI/TUI.

Tests: `ema-mock-servers.ts` now advertises
`authorization_response_iss_parameter_supported: true` so the mock is at least
as strict as real IdPs — with it absent the SDK silently takes the lenient path
and a dropped `iss` goes unnoticed. Flipping it made three existing tests
reproduce the failure. Adds regression coverage for forwarding and for
rejecting a mismatched `iss` before any network call.

Verified end to end against live xaa.dev staging: EMA legs 1-3 (IdP SSO ->
ID-JAG mint -> resource token) now complete and the MCP session initializes.

web 3099, cli 212, tui 274 green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VjMemXZohSR2EndBQYif2b
2026-07-15 20:16:43 -04:00

142 lines
4.8 KiB
TypeScript

import type { AuthChallenge } from "../challenge.js";
import {
createOAuthCallbackServer,
type OAuthCallbackServer,
} from "./oauth-callback-server.js";
import type { RunnerOAuthCallbackConfig } from "./runner-oauth-callback.js";
/** Minimal InspectorClient surface for runner interactive OAuth. */
export interface RunnerInteractiveOAuthClient {
authenticate(): Promise<URL | undefined>;
beginInteractiveAuthorization(authorizationUrl: URL): Promise<void>;
completeOAuthFlow(authorizationCode: string, iss?: string): Promise<void>;
checkAuthChallengeSatisfied(challenge: AuthChallenge): Promise<boolean>;
}
export interface RunnerInteractiveOAuthRedirectProvider {
redirectUrl: string;
}
export type RunnerInteractiveOAuthResult =
| { kind: "success" }
| { kind: "already_authorized" }
| { kind: "insufficient_scope"; challenge: AuthChallenge };
/** Default wait for loopback OAuth callback (15 minutes). */
export const DEFAULT_RUNNER_INTERACTIVE_OAUTH_TIMEOUT_MS = 15 * 60 * 1000;
export interface RunRunnerInteractiveOAuthOptions {
client: RunnerInteractiveOAuthClient;
redirectUrlProvider: RunnerInteractiveOAuthRedirectProvider;
callbackListen: RunnerOAuthCallbackConfig;
/** When set, use deferred interactive authorization (mid-session step-up / re-login). */
authorizationUrl?: URL;
/** When set, verify scopes after a successful token exchange (SEP-2350 step-up). */
authChallenge?: AuthChallenge;
createCallbackServer?: () => OAuthCallbackServer;
/** Invoked after the listener binds; hosts may keep a ref for unmount cleanup. */
onCallbackServer?: (server: OAuthCallbackServer) => void;
/** Max wait for browser callback; defaults to {@link DEFAULT_RUNNER_INTERACTIVE_OAUTH_TIMEOUT_MS}. */
callbackTimeoutMs?: number;
}
/**
* Run interactive OAuth for Node runners (TUI / CLI): loopback callback server,
* browser redirect, authorization-code exchange via {@link completeOAuthFlow}.
*/
export async function runRunnerInteractiveOAuth(
options: RunRunnerInteractiveOAuthOptions,
): Promise<RunnerInteractiveOAuthResult> {
const createServer =
options.createCallbackServer ?? createOAuthCallbackServer;
const server = createServer();
let flowResolve!: () => void;
let flowReject!: (err: Error) => void;
const flowDone = new Promise<void>((resolve, reject) => {
flowResolve = resolve;
flowReject = reject;
});
let timeoutId: ReturnType<typeof setTimeout> | undefined;
try {
const { redirectUrl } = await server.start({
hostname: options.callbackListen.hostname,
port: options.callbackListen.port,
path: options.callbackListen.pathname,
onCallback: async (params) => {
try {
await options.client.completeOAuthFlow(params.code, params.iss);
flowResolve();
} catch (err) {
flowReject(err instanceof Error ? err : new Error(String(err)));
}
},
onError: (params) => {
flowReject(
new Error(
/* v8 ignore next -- params.error is a required non-null string, so the "OAuth error" fallback is unreachable */
params.error_description ?? params.error ?? "OAuth error",
),
);
},
});
options.onCallbackServer?.(server);
options.redirectUrlProvider.redirectUrl = redirectUrl;
const timeoutMs =
options.callbackTimeoutMs ?? DEFAULT_RUNNER_INTERACTIVE_OAUTH_TIMEOUT_MS;
const waitForCallback = Promise.race([
flowDone.finally(() => {
/* v8 ignore next 3 -- timeoutId is assigned synchronously while the race is constructed, before flowDone can settle, so the undefined arm is unreachable */
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
}),
new Promise<void>((_, reject) => {
timeoutId = setTimeout(() => {
reject(
new Error(
`OAuth callback timed out after ${Math.round(timeoutMs / 1000)}s`,
),
);
}, timeoutMs);
}),
]);
if (options.authorizationUrl) {
await options.client.beginInteractiveAuthorization(
options.authorizationUrl,
);
await waitForCallback;
} else {
const authUrl = await options.client.authenticate();
if (authUrl !== undefined) {
await waitForCallback;
} else {
return { kind: "already_authorized" };
}
}
if (options.authChallenge) {
const satisfied = await options.client.checkAuthChallengeSatisfied(
options.authChallenge,
);
if (!satisfied) {
return {
kind: "insufficient_scope",
challenge: options.authChallenge,
};
}
}
return { kind: "success" };
} finally {
if (timeoutId !== undefined) {
clearTimeout(timeoutId);
}
await server.stop().catch(() => {});
}
}