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
201 expect(body.has("client_secret")).toBe(false);201 expect(body.has("client_secret")).toBe(false);
202 });202 });
203 203
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 () => {
205 captureFetch(205 captureFetch(
206 jsonResponse(200, {206 jsonResponse(200, {
207 ...validBody,207 ...validBody,
208 id_token: unsignedJwt({208 id_token: unsignedJwt({
209 iss: "https://accounts.google.com",209 // Upstream OP issuer — does NOT match issuerUrl below
210 iss: "https://us.posthog.com",
210 aud: "cid",211 aud: "cid",
211 sub: "user-1",212 sub: "user-1",
212 exp: Math.floor(Date.now() / 1000) + 3600,213 exp: Math.floor(Date.now() / 1000) + 3600,
@@ -216,8 +217,8 @@ describe("exchangeAuthorizationCode", () => { · 3 unmodified lines
216 );217 );
217 const result = await Effect.runPromise(218 const result = await Effect.runPromise(
218 exchangeAuthorizationCode({219 exchangeAuthorizationCode({
219 tokenUrl: "https://oauth2.googleapis.com/token",220 tokenUrl: "https://oauth.posthog.com/oauth/token",
220 issuerUrl: "https://accounts.google.com",221 issuerUrl: "https://oauth.posthog.com",
221 clientId: "cid",222 clientId: "cid",
222 redirectUrl: "https://app.example.com/cb",223 redirectUrl: "https://app.example.com/cb",
223 codeVerifier: "verifier",224 codeVerifier: "verifier",
@@ -225,41 +226,77 @@ describe("exchangeAuthorizationCode", () => { · 1 unmodified line
225 }),226 }),
226 );227 );
227 expect(result.access_token).toBe("tok");228 expect(result.access_token).toBe("tok");
229 expect(result.refresh_token).toBe("rtok");
228 });230 });
229 231
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 () => {
231 captureFetch(233 captureFetch(
232 jsonResponse(200, {234 jsonResponse(200, {
233 ...validBody,235 ...validBody,
234 id_token: unsignedJwt(236 id_token: unsignedJwt({
235 {237 iss: "https://example.com",
236 iss: "https://railway.com",238 // aud belongs to some other client
237 aud: "cid",239 aud: "another-client",
238 sub: "user-1",240 sub: "user-1",
239 exp: Math.floor(Date.now() / 1000) + 3600,241 exp: Math.floor(Date.now() / 1000) + 3600,
240 iat: Math.floor(Date.now() / 1000),242 iat: Math.floor(Date.now() / 1000),
241 },243 }),
242 "ES256",
243 ),
244 }),244 }),
245 );245 );
246
247 const result = await Effect.runPromise(246 const result = await Effect.runPromise(
248 exchangeAuthorizationCode({247 exchangeAuthorizationCode({
249 tokenUrl: "https://backboard.railway.com/oauth/token",248 tokenUrl: "https://example.com/token",
250 issuerUrl: "https://railway.com",249 issuerUrl: "https://example.com",
251 clientId: "cid",250 clientId: "cid",
252 redirectUrl: "https://app.example.com/cb",251 redirectUrl: "https://app.example.com/cb",
253 codeVerifier: "verifier",252 codeVerifier: "verifier",
254 code: "abc",253 code: "abc",
255 idTokenSigningAlgValuesSupported: ["ES256"],
256 }),254 }),
257 );255 );
256 expect(result.access_token).toBe("tok");
257 });
258 258
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 );
259 expect(result.access_token).toBe("tok");270 expect(result.access_token).toBe("tok");
271 expect(result.refresh_token).toBe("rtok");
272 expect(result.expires_in).toBe(3600);
260 });273 });
261 274
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 () => {
263 captureFetch(300 captureFetch(
264 jsonResponse(200, {301 jsonResponse(200, {
265 ...validBody,302 ...validBody,
@@ -420,12 +457,12 @@ describe("refreshAccessToken", () => { · 154 unmodified lines
420 expect(body.has("scope")).toBe(false);457 expect(body.has("scope")).toBe(false);
421 });458 });
422 459
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 () => {
424 captureFetch(461 captureFetch(
425 jsonResponse(200, {462 jsonResponse(200, {
426 ...validBody,463 ...validBody,
427 id_token: unsignedJwt({464 id_token: unsignedJwt({
428 iss: "https://accounts.google.com",465 iss: "https://us.posthog.com",
429 aud: "cid",466 aud: "cid",
430 sub: "user-1",467 sub: "user-1",
431 exp: Math.floor(Date.now() / 1000) + 3600,468 exp: Math.floor(Date.now() / 1000) + 3600,
@@ -435,8 +472,8 @@ describe("refreshAccessToken", () => { · 3 unmodified lines
435 );472 );
436 const result = await Effect.runPromise(473 const result = await Effect.runPromise(
437 refreshAccessToken({474 refreshAccessToken({
438 tokenUrl: "https://oauth2.googleapis.com/token",475 tokenUrl: "https://oauth.posthog.com/oauth/token",
439 issuerUrl: "https://accounts.google.com",476 issuerUrl: "https://oauth.posthog.com",
440 clientId: "cid",477 clientId: "cid",
441 refreshToken: "old",478 refreshToken: "old",
442 }),479 }),
@@ -444,13 +481,13 @@ describe("refreshAccessToken", () => { · 1 unmodified line
444 expect(result.access_token).toBe("tok2");481 expect(result.access_token).toBe("tok2");
445 });482 });
446 483
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 () => {
448 captureFetch(485 captureFetch(
449 jsonResponse(200, {486 jsonResponse(200, {
450 ...validBody,487 ...validBody,
451 id_token: unsignedJwt(488 id_token: unsignedJwt(
452 {489 {
453 iss: "https://railway.com",490 iss: "https://backboard.railway.com",
454 aud: "cid",491 aud: "cid",
455 sub: "user-1",492 sub: "user-1",
456 exp: Math.floor(Date.now() / 1000) + 3600,493 exp: Math.floor(Date.now() / 1000) + 3600,
@@ -464,43 +501,26 @@ describe("refreshAccessToken", () => { · 7 unmodified lines
464 const result = await Effect.runPromise(501 const result = await Effect.runPromise(
465 refreshAccessToken({502 refreshAccessToken({
466 tokenUrl: "https://backboard.railway.com/oauth/token",503 tokenUrl: "https://backboard.railway.com/oauth/token",
467 issuerUrl: "https://railway.com",504 issuerUrl: "https://backboard.railway.com",
468 clientId: "cid",505 clientId: "cid",
469 refreshToken: "old",506 refreshToken: "old",
470 idTokenSigningAlgValuesSupported: ["ES256"],
471 }),507 }),
472 );508 );
473 509
474 expect(result.access_token).toBe("tok2");510 expect(result.access_token).toBe("tok2");
475 });511 });
476 512
477 it("ignores unusable refreshed ID tokens when the access-token response is otherwise valid", async () => {513 it("happy path: refresh response with no id_token parses normally", async () => {
478 captureFetch(514 captureFetch(jsonResponse(200, validBody));
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
494 const result = await Effect.runPromise(515 const result = await Effect.runPromise(
495 refreshAccessToken({516 refreshAccessToken({
496 tokenUrl: "https://backboard.railway.com/oauth/token",517 tokenUrl: "https://example.com/token",
497 issuerUrl: "https://backboard.railway.com",
498 clientId: "cid",518 clientId: "cid",
499 refreshToken: "old",519 refreshToken: "old",
500 }),520 }),
501 );521 );
502
503 expect(result.access_token).toBe("tok2");522 expect(result.access_token).toBe("tok2");
523 expect(result.expires_in).toBe(3600);
504 });524 });
505});525});
506 526
packages/core/sdk/src/oauth-helpers.ts+36−58
@@ -224,59 +224,43 @@ const tokenResponseFrom = ( · 223 unmodified lines
224 scope: r.scope,224 scope: r.scope,
225});225});
226 226
227const isUnexpectedIdTokenAlg = (cause: unknown): boolean =>227// MCP source connections are pure OAuth 2.0 — we never request `openid` and
228 cause instanceof Error &&228// never consume `id_token`. Some providers (PostHog, etc.) front an OIDC
229 cause.message.includes('unexpected JWT "alg" header parameter');229// backend and emit an `id_token` anyway; oauth4webapi then strict-validates
230 230// its claims against the AS metadata and rejects mismatches we don't care
231const looseTokenResponseFrom = (body: unknown): OAuth2TokenResponse => {231// about. Strip the field before delegation.
232 if (typeof body !== "object" || body === null) {232const stripIdToken = async (response: Response): Promise<Response> => {
233 throw new Error("token endpoint response body is not an object");233 const body = await response
234 }234 .clone()
235 const record = body as Record<string, unknown>;235 .json()
236 if (typeof record.access_token !== "string" || !record.access_token) {236 .catch(() => null);
237 throw new Error('token endpoint response is missing "access_token"');237 if (
238 !body ||
239 typeof body !== "object" ||
240 !("id_token" in (body as Record<string, unknown>))
241 ) {
242 return response;
238 }243 }
239 const expiresIn =244 const { id_token: _ignored, ...rest } = body as Record<string, unknown>;
240 typeof record.expires_in === "number"245 return new Response(JSON.stringify(rest), {
241 ? record.expires_in246 status: response.status,
242 : typeof record.expires_in === "string"247 statusText: response.statusText,
243 ? Number.parseFloat(record.expires_in)248 headers: response.headers,
244 : undefined;249 });
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 };
259};250};
260 251
261const processTokenEndpointResponse = async (252const processTokenEndpointResponse = async (
262 as: oauth.AuthorizationServer,253 as: oauth.AuthorizationServer,
263 client: oauth.Client,254 client: oauth.Client,
264 response: Response,255 response: Response,
265): Promise<OAuth2TokenResponse> => {256): Promise<OAuth2TokenResponse> =>
266 const fallback = response.clone();257 tokenResponseFrom(
267 try {258 await oauth.processGenericTokenEndpointResponse(
268 return tokenResponseFrom(259 as,
269 await oauth.processGenericTokenEndpointResponse(as, client, response),260 client,
270 );261 await stripIdToken(response),
271 } catch (cause) {262 ),
272 if (!isUnexpectedIdTokenAlg(cause)) throw cause;263 );
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};
280 264
281// ---------------------------------------------------------------------------265// ---------------------------------------------------------------------------
282// Exchange authorization code → tokens266// Exchange authorization code → tokens
@@ -425,18 +409,12 @@ export const refreshAccessToken = ( · 142 unmodified lines
425 additionalParameters,409 additionalParameters,
426 },410 },
427 );411 );
428 const fallback = response.clone();412 const result = await oauth.processRefreshTokenResponse(
429 try {413 as,
430 const result = await oauth.processRefreshTokenResponse(414 client,
431 as,415 await stripIdToken(response),
432 client,416 );
433 response,417 return tokenResponseFrom(result);
434 );
435 return tokenResponseFrom(result);
436 } catch (cause) {
437 if (!isUnexpectedIdTokenAlg(cause)) throw cause;
438 return looseTokenResponseFrom(await fallback.json());
439 }
440 },418 },
441 catch: toOAuth2Error,419 catch: toOAuth2Error,
442 });420 });

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