History

Include HTTP summary on OAuth2 token endpoint failures

Rhys Sullivan committed 6 months ago

Commit cbe85fe1 parent 70725e62 files · +204 −70Browse files

Unified · Split

2 files
  1. packages/core/sdk/src/oauth-helpers.test.ts +56 −0
  2. packages/core/sdk/src/oauth-helpers.ts +148 −70
packages/core/sdk/src/oauth-helpers.test.ts+56−0
@@ -491,6 +491,62 @@ describe("exchangeAuthorizationCode", () => { · 490 unmodified lines
491491 }),
492492 ),
493493 );
494+
495+ it.effect("includes HTTP status and body preview for non-OAuth token endpoint errors", () =>
496+ withTokenEndpoint(
497+ () => HttpServerResponse.text("route not found", { status: 404 }),
498+ ({ tokenUrl }) =>
499+ Effect.gen(function* () {
500+ const exit = yield* Effect.exit(
501+ exchangeAuthorizationCode({
502+ tokenUrl,
503+ clientId: "cid",
504+ redirectUrl: "https://cb",
505+ codeVerifier: "v",
506+ code: "c",
507+ }),
508+ );
509+ expect(Exit.isFailure(exit)).toBe(true);
510+ if (!Exit.isFailure(exit)) return;
511+ const failure = JSON.stringify(exit.cause);
512+ expect(failure).toContain("HTTP 404");
513+ expect(failure).toContain("route not found");
514+ }),
515+ ),
516+ );
517+
518+ it.effect("preserves provider error codes while redacting token endpoint secrets", () =>
519+ withTokenEndpoint(
520+ () =>
521+ json(400, {
522+ error: {
523+ code: "invalid_client_id",
524+ message: "Invalid client_id",
525+ },
526+ client_secret: "do-not-log",
527+ }),
528+ ({ tokenUrl }) =>
529+ Effect.gen(function* () {
530+ const exit = yield* Effect.exit(
531+ exchangeAuthorizationCode({
532+ tokenUrl,
533+ clientId: "cid",
534+ redirectUrl: "https://cb",
535+ codeVerifier: "v",
536+ code: "c",
537+ }),
538+ );
539+ expect(Exit.isFailure(exit)).toBe(true);
540+ if (!Exit.isFailure(exit)) return;
541+ const failure = JSON.stringify(exit.cause);
542+ expect(failure).toContain("invalid_client_id");
543+ expect(failure).toContain("Invalid client_id");
544+ expect(failure).toContain("client_secret");
545+ expect(failure).toContain("[redacted]");
546+ expect(failure).not.toContain("do-not-log");
547+ }),
548+ ),
549+ );
494550 });
495551
496552 describe("refreshAccessToken", () => {
packages/core/sdk/src/oauth-helpers.ts+148−70
@@ -121,7 +121,60 @@ export const buildAuthorizationUrl = (input: BuildAuthorizationUrlInput): string · 120 unmodified lines
121121 // to reauth-required) across wrappers.
122122 // ---------------------------------------------------------------------------
123123
124+const isOAuth2Error = (cause: unknown): cause is OAuth2Error =>
125+ typeof cause === "object" &&
126+ cause !== null &&
127+ "_tag" in cause &&
128+ (cause as { readonly _tag?: unknown })._tag === "OAuth2Error";
129+
130+const responseFromOAuthErrorCause = (cause: unknown): Response | undefined => {
131+ if (cause instanceof Response) return cause;
132+ if (typeof cause !== "object" || cause === null) return undefined;
133+ const envelope = cause as {
134+ readonly cause?: unknown;
135+ readonly response?: unknown;
136+ };
137+ if (envelope.response instanceof Response) return envelope.response;
138+ if (envelope.cause instanceof Response) return envelope.cause;
139+ return undefined;
140+};
141+
142+const redactTokenEndpointBody = (body: string): string =>
143+ body
144+ .replaceAll(
145+ /("(?:access_token|refresh_token|id_token|client_secret)"\s*:\s*")[^"]*(")/gi,
146+ "$1[redacted]$2",
147+ )
148+ .replaceAll(
149+ /((?:access_token|refresh_token|id_token|client_secret|code)=)[^&\s]*/gi,
150+ "$1[redacted]",
151+ );
152+
153+const tokenEndpointHttpSummary = async (response: Response): Promise<string> => {
154+ const status = `HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ""}`;
155+ const contentType = response.headers.get("content-type");
156+ const url = response.url ? ` from ${response.url}` : "";
157+ const parts = [`${status}${url}`];
158+ if (contentType) parts.push(`content-type ${contentType}`);
159+ const preview = await bodyPreviewFromResponse(response);
160+ if (preview) parts.push(`body: ${preview}`);
161+ return parts.join("; ");
162+};
163+
164+const bodyPreviewFromResponse = async (response: Response): Promise<string | undefined> => {
165+ const text = await Promise.resolve()
166+ .then(() => response.clone().text())
167+ .then(
168+ (value) => value.trim(),
169+ () => "",
170+ );
171+ if (!text) return undefined;
172+ const redacted = redactTokenEndpointBody(text.replaceAll(/\s+/g, " "));
173+ return redacted.length > 500 ? `${redacted.slice(0, 500)}...` : redacted;
174+};
175+
124176 const toOAuth2Error = (cause: unknown): OAuth2Error => {
177+ if (isOAuth2Error(cause)) return cause;
125178 if (typeof cause === "object" && cause !== null) {
126179 const c = cause as {
127180 error?: unknown;
@@ -147,6 +200,19 @@ const toOAuth2Error = (cause: unknown): OAuth2Error => { · 19 unmodified lines
147200 });
148201 };
149202
203+const toOAuth2ErrorWithHttpSummary = async (cause: unknown): Promise<OAuth2Error> => {
204+ if (isOAuth2Error(cause)) return cause;
205+ const base = toOAuth2Error(cause);
206+ const response = responseFromOAuthErrorCause(cause);
207+ if (!response) return base;
208+ const summary = await tokenEndpointHttpSummary(response);
209+ return new OAuth2Error({
210+ message: `${base.message} (${summary})`,
211+ error: base.error,
212+ cause,
213+ });
214+};
215+
150216 // ---------------------------------------------------------------------------
151217 // oauth4webapi adapter helpers
152218 // ---------------------------------------------------------------------------
@@ -282,33 +348,37 @@ export const exchangeAuthorizationCode = ( · 129 unmodified lines
282348 ): Effect.Effect<OAuth2TokenResponse, OAuth2Error> =>
283349 Effect.tryPromise({
284350 try: async () => {
285− const as = asFromTokenUrlAndIssuer(input.tokenUrl, input.issuerUrl, {
286− idTokenSigningAlgValuesSupported: input.idTokenSigningAlgValuesSupported,
287− });
288− const client: oauth.Client = { client_id: input.clientId };
289− const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body");
290− // `authorizationCodeGrantRequest` requires its `callbackParameters`
291− // to have been returned from `validateAuthResponse`. Our public API
292− // takes the `code` directly (the UI already validated `state` by
293− // looking up the session), so skip the library's state-validation
294− // rail and go through the generic grant request instead.
295− const params = new URLSearchParams({
296− code: input.code,
297− redirect_uri: input.redirectUrl,
298− code_verifier: input.codeVerifier,
299− });
300− if (input.resource) {
301− params.set("resource", input.resource);
351+ try {
352+ const as = asFromTokenUrlAndIssuer(input.tokenUrl, input.issuerUrl, {
353+ idTokenSigningAlgValuesSupported: input.idTokenSigningAlgValuesSupported,
354+ });
355+ const client: oauth.Client = { client_id: input.clientId };
356+ const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body");
357+ // `authorizationCodeGrantRequest` requires its `callbackParameters`
358+ // to have been returned from `validateAuthResponse`. Our public API
359+ // takes the `code` directly (the UI already validated `state` by
360+ // looking up the session), so skip the library's state-validation
361+ // rail and go through the generic grant request instead.
362+ const params = new URLSearchParams({
363+ code: input.code,
364+ redirect_uri: input.redirectUrl,
365+ code_verifier: input.codeVerifier,
366+ });
367+ if (input.resource) {
368+ params.set("resource", input.resource);
369+ }
370+ const response = await oauth.genericTokenEndpointRequest(
371+ as,
372+ client,
373+ clientAuth,
374+ "authorization_code",
375+ params,
376+ oauth4webapiRequestOptions(input.tokenUrl, input.timeoutMs),
377+ );
378+ return await processTokenEndpointResponse(as, client, response);
379+ } catch (cause) {
380+ throw await toOAuth2ErrorWithHttpSummary(cause);
302381 }
303− const response = await oauth.genericTokenEndpointRequest(
304− as,
305− client,
306− clientAuth,
307− "authorization_code",
308− params,
309− oauth4webapiRequestOptions(input.tokenUrl, input.timeoutMs),
310− );
311− return processTokenEndpointResponse(as, client, response);
312382 },
313383 catch: toOAuth2Error,
314384 });
@@ -332,22 +402,26 @@ export const exchangeClientCredentials = ( · 17 unmodified lines
332402 ): Effect.Effect<OAuth2TokenResponse, OAuth2Error> =>
333403 Effect.tryPromise({
334404 try: async () => {
335− const as = asFromTokenUrl(input.tokenUrl);
336− const client: oauth.Client = { client_id: input.clientId };
337− const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body");
338− const params = new URLSearchParams();
339− if (input.scopes && input.scopes.length > 0) {
340− params.set("scope", input.scopes.join(input.scopeSeparator ?? " "));
405+ try {
406+ const as = asFromTokenUrl(input.tokenUrl);
407+ const client: oauth.Client = { client_id: input.clientId };
408+ const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body");
409+ const params = new URLSearchParams();
410+ if (input.scopes && input.scopes.length > 0) {
411+ params.set("scope", input.scopes.join(input.scopeSeparator ?? " "));
412+ }
413+ const response = await oauth.clientCredentialsGrantRequest(
414+ as,
415+ client,
416+ clientAuth,
417+ params,
418+ oauth4webapiRequestOptions(input.tokenUrl, input.timeoutMs),
419+ );
420+ const result = await oauth.processClientCredentialsResponse(as, client, response);
421+ return tokenResponseFrom(result);
422+ } catch (cause) {
423+ throw await toOAuth2ErrorWithHttpSummary(cause);
341424 }
342− const response = await oauth.clientCredentialsGrantRequest(
343− as,
344− client,
345− clientAuth,
346− params,
347− oauth4webapiRequestOptions(input.tokenUrl, input.timeoutMs),
348− );
349− const result = await oauth.processClientCredentialsResponse(as, client, response);
350− return tokenResponseFrom(result);
351425 },
352426 catch: toOAuth2Error,
353427 });
@@ -378,36 +452,40 @@ export const refreshAccessToken = ( · 24 unmodified lines
378452 ): Effect.Effect<OAuth2TokenResponse, OAuth2Error> =>
379453 Effect.tryPromise({
380454 try: async () => {
381− const as = asFromTokenUrlAndIssuer(input.tokenUrl, input.issuerUrl, {
382− idTokenSigningAlgValuesSupported: input.idTokenSigningAlgValuesSupported,
383− });
384− const client: oauth.Client = { client_id: input.clientId };
385− const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body");
386− const extraParams = new URLSearchParams();
387− if (input.scopes && input.scopes.length > 0) {
388− extraParams.set("scope", input.scopes.join(input.scopeSeparator ?? " "));
389− }
390− if (input.resource) {
391− extraParams.set("resource", input.resource);
455+ try {
456+ const as = asFromTokenUrlAndIssuer(input.tokenUrl, input.issuerUrl, {
457+ idTokenSigningAlgValuesSupported: input.idTokenSigningAlgValuesSupported,
458+ });
459+ const client: oauth.Client = { client_id: input.clientId };
460+ const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body");
461+ const extraParams = new URLSearchParams();
462+ if (input.scopes && input.scopes.length > 0) {
463+ extraParams.set("scope", input.scopes.join(input.scopeSeparator ?? " "));
464+ }
465+ if (input.resource) {
466+ extraParams.set("resource", input.resource);
467+ }
468+ const additionalParameters =
469+ Array.from(extraParams.keys()).length > 0 ? extraParams : undefined;
470+ const response = await oauth.refreshTokenGrantRequest(
471+ as,
472+ client,
473+ clientAuth,
474+ input.refreshToken,
475+ {
476+ ...oauth4webapiRequestOptions(input.tokenUrl, input.timeoutMs),
477+ additionalParameters,
478+ },
479+ );
480+ const result = await oauth.processRefreshTokenResponse(
481+ as,
482+ client,
483+ await stripIdToken(response),
484+ );
485+ return tokenResponseFrom(result);
486+ } catch (cause) {
487+ throw await toOAuth2ErrorWithHttpSummary(cause);
392488 }
393− const additionalParameters =
394− Array.from(extraParams.keys()).length > 0 ? extraParams : undefined;
395− const response = await oauth.refreshTokenGrantRequest(
396− as,
397− client,
398− clientAuth,
399− input.refreshToken,
400− {
401− ...oauth4webapiRequestOptions(input.tokenUrl, input.timeoutMs),
402− additionalParameters,
403− },
404− );
405− const result = await oauth.processRefreshTokenResponse(
406− as,
407− client,
408− await stripIdToken(response),
409− );
410− return tokenResponseFrom(result);
411489 },
412490 catch: toOAuth2Error,
413491 });

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