History

Strip id_token from OAuth token responses before validation (#527)

Some providers (PostHog, etc.) emit id_tokens on plain OAuth 2.0 token responses even when the client never requested `openid`. oauth4webapi then strict-validates the id_token against AS metadata, rejecting tokens whose access_token portion is valid. We never consume the id_token, so strip it before delegation. Removes the alg-mismatch tolerance which is now subsumed.

Rhys Sullivan committed 6 months ago

Commit a7f2c661 parent a8b3aec2 files · +104 −106Browse files

Unified · Split

2 files
  1. packages/core/sdk/src/oauth-helpers.test.ts +68 −48
  2. packages/core/sdk/src/oauth-helpers.ts +36 −58
packages/core/sdk/src/oauth-helpers.test.ts+68−48
@@ -201,12 +201,13 @@ describe("exchangeAuthorizationCode", () => { · 200 unmodified lines
201201 expect(body.has("client_secret")).toBe(false);
202202 });
203203
204− it("validates ID tokens against an explicit issuer when token host differs", async () => {
204+ it("strips id_tokens whose iss does not match AS metadata (PostHog-style OIDC backend behind plain OAuth 2.0 metadata)", async () => {
205205 captureFetch(
206206 jsonResponse(200, {
207207 ...validBody,
208208 id_token: unsignedJwt({
209− iss: "https://accounts.google.com",
209+ // Upstream OP issuer — does NOT match issuerUrl below
210+ iss: "https://us.posthog.com",
210211 aud: "cid",
211212 sub: "user-1",
212213 exp: Math.floor(Date.now() / 1000) + 3600,
@@ -216,8 +217,8 @@ describe("exchangeAuthorizationCode", () => { · 3 unmodified lines
216217 );
217218 const result = await Effect.runPromise(
218219 exchangeAuthorizationCode({
219− tokenUrl: "https://oauth2.googleapis.com/token",
220− issuerUrl: "https://accounts.google.com",
220+ tokenUrl: "https://oauth.posthog.com/oauth/token",
221+ issuerUrl: "https://oauth.posthog.com",
221222 clientId: "cid",
222223 redirectUrl: "https://app.example.com/cb",
223224 codeVerifier: "verifier",
@@ -225,41 +226,77 @@ describe("exchangeAuthorizationCode", () => { · 1 unmodified line
225226 }),
226227 );
227228 expect(result.access_token).toBe("tok");
229+ expect(result.refresh_token).toBe("rtok");
228230 });
229231
230− it("accepts ID token signing algorithms advertised by authorization server metadata", async () => {
232+ it("strips id_tokens whose aud does not match the client_id", async () => {
231233 captureFetch(
232234 jsonResponse(200, {
233235 ...validBody,
234− id_token: unsignedJwt(
235− {
236− iss: "https://railway.com",
237− aud: "cid",
238− sub: "user-1",
239− exp: Math.floor(Date.now() / 1000) + 3600,
240− iat: Math.floor(Date.now() / 1000),
241− },
242− "ES256",
243− ),
236+ id_token: unsignedJwt({
237+ iss: "https://example.com",
238+ // aud belongs to some other client
239+ aud: "another-client",
240+ sub: "user-1",
241+ exp: Math.floor(Date.now() / 1000) + 3600,
242+ iat: Math.floor(Date.now() / 1000),
243+ }),
244244 }),
245245 );
246−
247246 const result = await Effect.runPromise(
248247 exchangeAuthorizationCode({
249− tokenUrl: "https://backboard.railway.com/oauth/token",
250− issuerUrl: "https://railway.com",
248+ tokenUrl: "https://example.com/token",
249+ issuerUrl: "https://example.com",
251250 clientId: "cid",
252251 redirectUrl: "https://app.example.com/cb",
253252 codeVerifier: "verifier",
254253 code: "abc",
255− idTokenSigningAlgValuesSupported: ["ES256"],
256254 }),
257255 );
256+ expect(result.access_token).toBe("tok");
257+ });
258258
259+ it("happy path: token endpoint with no id_token still parses normally", async () => {
260+ captureFetch(jsonResponse(200, validBody));
261+ const result = await Effect.runPromise(
262+ exchangeAuthorizationCode({
263+ tokenUrl: "https://example.com/token",
264+ clientId: "cid",
265+ redirectUrl: "https://app.example.com/cb",
266+ codeVerifier: "verifier",
267+ code: "abc",
268+ }),
269+ );
259270 expect(result.access_token).toBe("tok");
271+ expect(result.refresh_token).toBe("rtok");
272+ expect(result.expires_in).toBe(3600);
260273 });
261274
262− it("ignores unusable ID tokens when the access-token response is otherwise valid", async () => {
275+ it("still surfaces RFC 6749 §5.2 error envelopes after the id_token strip", async () => {
276+ captureFetch(
277+ jsonResponse(400, {
278+ error: "invalid_grant",
279+ error_description: "authorization code expired",
280+ }),
281+ );
282+ const exit = await Effect.runPromiseExit(
283+ exchangeAuthorizationCode({
284+ tokenUrl: "https://example.com/token",
285+ clientId: "cid",
286+ redirectUrl: "https://app.example.com/cb",
287+ codeVerifier: "verifier",
288+ code: "abc",
289+ }),
290+ );
291+ expect(Exit.isFailure(exit)).toBe(true);
292+ if (!Exit.isFailure(exit)) return;
293+ const failure = JSON.stringify(exit.cause);
294+ expect(failure).toContain("OAuth2Error");
295+ expect(failure).toContain("invalid_grant");
296+ expect(failure).toContain("authorization code expired");
297+ });
298+
299+ it("strips id_tokens with algorithms not advertised in AS metadata (e.g. ES256 without supported list)", async () => {
263300 captureFetch(
264301 jsonResponse(200, {
265302 ...validBody,
@@ -420,12 +457,12 @@ describe("refreshAccessToken", () => { · 154 unmodified lines
420457 expect(body.has("scope")).toBe(false);
421458 });
422459
423− it("validates refreshed ID tokens against an explicit issuer", async () => {
460+ it("strips refreshed id_tokens whose iss does not match AS metadata", async () => {
424461 captureFetch(
425462 jsonResponse(200, {
426463 ...validBody,
427464 id_token: unsignedJwt({
428− iss: "https://accounts.google.com",
465+ iss: "https://us.posthog.com",
429466 aud: "cid",
430467 sub: "user-1",
431468 exp: Math.floor(Date.now() / 1000) + 3600,
@@ -435,8 +472,8 @@ describe("refreshAccessToken", () => { · 3 unmodified lines
435472 );
436473 const result = await Effect.runPromise(
437474 refreshAccessToken({
438− tokenUrl: "https://oauth2.googleapis.com/token",
439− issuerUrl: "https://accounts.google.com",
475+ tokenUrl: "https://oauth.posthog.com/oauth/token",
476+ issuerUrl: "https://oauth.posthog.com",
440477 clientId: "cid",
441478 refreshToken: "old",
442479 }),
@@ -444,13 +481,13 @@ describe("refreshAccessToken", () => { · 1 unmodified line
444481 expect(result.access_token).toBe("tok2");
445482 });
446483
447− it("accepts refreshed ID token signing algorithms advertised by authorization server metadata", async () => {
484+ it("strips refreshed id_tokens with algorithms not advertised in AS metadata", async () => {
448485 captureFetch(
449486 jsonResponse(200, {
450487 ...validBody,
451488 id_token: unsignedJwt(
452489 {
453− iss: "https://railway.com",
490+ iss: "https://backboard.railway.com",
454491 aud: "cid",
455492 sub: "user-1",
456493 exp: Math.floor(Date.now() / 1000) + 3600,
@@ -464,43 +501,26 @@ describe("refreshAccessToken", () => { · 7 unmodified lines
464501 const result = await Effect.runPromise(
465502 refreshAccessToken({
466503 tokenUrl: "https://backboard.railway.com/oauth/token",
467− issuerUrl: "https://railway.com",
504+ issuerUrl: "https://backboard.railway.com",
468505 clientId: "cid",
469506 refreshToken: "old",
470− idTokenSigningAlgValuesSupported: ["ES256"],
471507 }),
472508 );
473509
474510 expect(result.access_token).toBe("tok2");
475511 });
476512
477− it("ignores unusable refreshed ID tokens when the access-token response is otherwise valid", async () => {
478− captureFetch(
479− jsonResponse(200, {
480− ...validBody,
481− id_token: unsignedJwt(
482− {
483− iss: "https://backboard.railway.com",
484− aud: "cid",
485− sub: "user-1",
486− exp: Math.floor(Date.now() / 1000) + 3600,
487− iat: Math.floor(Date.now() / 1000),
488− },
489− "ES256",
490− ),
491− }),
492− );
493−
513+ it("happy path: refresh response with no id_token parses normally", async () => {
514+ captureFetch(jsonResponse(200, validBody));
494515 const result = await Effect.runPromise(
495516 refreshAccessToken({
496− tokenUrl: "https://backboard.railway.com/oauth/token",
497− issuerUrl: "https://backboard.railway.com",
517+ tokenUrl: "https://example.com/token",
498518 clientId: "cid",
499519 refreshToken: "old",
500520 }),
501521 );
502−
503522 expect(result.access_token).toBe("tok2");
523+ expect(result.expires_in).toBe(3600);
504524 });
505525 });
506526
packages/core/sdk/src/oauth-helpers.ts+36−58
@@ -224,59 +224,43 @@ const tokenResponseFrom = ( · 223 unmodified lines
224224 scope: r.scope,
225225 });
226226
227−const isUnexpectedIdTokenAlg = (cause: unknown): boolean =>
228− cause instanceof Error &&
229− cause.message.includes('unexpected JWT "alg" header parameter');
230−
231−const looseTokenResponseFrom = (body: unknown): OAuth2TokenResponse => {
232− if (typeof body !== "object" || body === null) {
233− throw new Error("token endpoint response body is not an object");
234− }
235− const record = body as Record<string, unknown>;
236− if (typeof record.access_token !== "string" || !record.access_token) {
237− throw new Error('token endpoint response is missing "access_token"');
227+// MCP source connections are pure OAuth 2.0 — we never request `openid` and
228+// never consume `id_token`. Some providers (PostHog, etc.) front an OIDC
229+// backend and emit an `id_token` anyway; oauth4webapi then strict-validates
230+// its claims against the AS metadata and rejects mismatches we don't care
231+// about. Strip the field before delegation.
232+const stripIdToken = async (response: Response): Promise<Response> => {
233+ const body = await response
234+ .clone()
235+ .json()
236+ .catch(() => null);
237+ if (
238+ !body ||
239+ typeof body !== "object" ||
240+ !("id_token" in (body as Record<string, unknown>))
241+ ) {
242+ return response;
238243 }
239− const expiresIn =
240− typeof record.expires_in === "number"
241− ? record.expires_in
242− : typeof record.expires_in === "string"
243− ? Number.parseFloat(record.expires_in)
244− : undefined;
245− if (expiresIn !== undefined && !Number.isFinite(expiresIn)) {
246− throw new Error('token endpoint response has invalid "expires_in"');
247− }
248− return {
249− access_token: record.access_token,
250− token_type:
251− typeof record.token_type === "string" ? record.token_type : undefined,
252− refresh_token:
253− typeof record.refresh_token === "string"
254− ? record.refresh_token
255− : undefined,
256− expires_in: expiresIn,
257− scope: typeof record.scope === "string" ? record.scope : undefined,
258− };
244+ const { id_token: _ignored, ...rest } = body as Record<string, unknown>;
245+ return new Response(JSON.stringify(rest), {
246+ status: response.status,
247+ statusText: response.statusText,
248+ headers: response.headers,
249+ });
259250 };
260251
261252 const processTokenEndpointResponse = async (
262253 as: oauth.AuthorizationServer,
263254 client: oauth.Client,
264255 response: Response,
265−): Promise<OAuth2TokenResponse> => {
266− const fallback = response.clone();
267− try {
268− return tokenResponseFrom(
269− await oauth.processGenericTokenEndpointResponse(as, client, response),
270− );
271− } catch (cause) {
272− if (!isUnexpectedIdTokenAlg(cause)) throw cause;
273− // Some OAuth-only providers include an ID token even when their metadata
274− // does not advertise enough OIDC signing metadata for strict validation.
275− // Executor stores only access/refresh tokens for source auth, so tolerate
276− // an unusable ID token after the access token response itself is valid.
277− return looseTokenResponseFrom(await fallback.json());
278− }
279−};
256+): Promise<OAuth2TokenResponse> =>
257+ tokenResponseFrom(
258+ await oauth.processGenericTokenEndpointResponse(
259+ as,
260+ client,
261+ await stripIdToken(response),
262+ ),
263+ );
280264
281265 // ---------------------------------------------------------------------------
282266 // Exchange authorization code → tokens
@@ -425,18 +409,12 @@ export const refreshAccessToken = ( · 142 unmodified lines
425409 additionalParameters,
426410 },
427411 );
428− const fallback = response.clone();
429− try {
430− const result = await oauth.processRefreshTokenResponse(
431− as,
432− client,
433− response,
434− );
435− return tokenResponseFrom(result);
436− } catch (cause) {
437− if (!isUnexpectedIdTokenAlg(cause)) throw cause;
438− return looseTokenResponseFrom(await fallback.json());
439− }
412+ const result = await oauth.processRefreshTokenResponse(
413+ as,
414+ client,
415+ await stripIdToken(response),
416+ );
417+ return tokenResponseFrom(result);
440418 },
441419 catch: toOAuth2Error,
442420 });

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t