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
491 }),491 }),
492 ),492 ),
493 );493 );
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 );
494});550});
495 551
496describe("refreshAccessToken", () => {552describe("refreshAccessToken", () => {
packages/core/sdk/src/oauth-helpers.ts+148−70
@@ -121,7 +121,60 @@ export const buildAuthorizationUrl = (input: BuildAuthorizationUrlInput): string · 120 unmodified lines
121// to reauth-required) across wrappers.121// to reauth-required) across wrappers.
122// ---------------------------------------------------------------------------122// ---------------------------------------------------------------------------
123 123
124const 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
130const 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
142const 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
153const 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
164const 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
124const toOAuth2Error = (cause: unknown): OAuth2Error => {176const toOAuth2Error = (cause: unknown): OAuth2Error => {
177 if (isOAuth2Error(cause)) return cause;
125 if (typeof cause === "object" && cause !== null) {178 if (typeof cause === "object" && cause !== null) {
126 const c = cause as {179 const c = cause as {
127 error?: unknown;180 error?: unknown;
@@ -147,6 +200,19 @@ const toOAuth2Error = (cause: unknown): OAuth2Error => { · 19 unmodified lines
147 });200 });
148};201};
149 202
203const 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
150// ---------------------------------------------------------------------------216// ---------------------------------------------------------------------------
151// oauth4webapi adapter helpers217// oauth4webapi adapter helpers
152// ---------------------------------------------------------------------------218// ---------------------------------------------------------------------------
@@ -282,33 +348,37 @@ export const exchangeAuthorizationCode = ( · 129 unmodified lines
282): Effect.Effect<OAuth2TokenResponse, OAuth2Error> =>348): Effect.Effect<OAuth2TokenResponse, OAuth2Error> =>
283 Effect.tryPromise({349 Effect.tryPromise({
284 try: async () => {350 try: async () => {
285 const as = asFromTokenUrlAndIssuer(input.tokenUrl, input.issuerUrl, {351 try {
286 idTokenSigningAlgValuesSupported: input.idTokenSigningAlgValuesSupported,352 const as = asFromTokenUrlAndIssuer(input.tokenUrl, input.issuerUrl, {
287 });353 idTokenSigningAlgValuesSupported: input.idTokenSigningAlgValuesSupported,
288 const client: oauth.Client = { client_id: input.clientId };354 });
289 const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body");355 const client: oauth.Client = { client_id: input.clientId };
290 // `authorizationCodeGrantRequest` requires its `callbackParameters`356 const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body");
291 // to have been returned from `validateAuthResponse`. Our public API357 // `authorizationCodeGrantRequest` requires its `callbackParameters`
292 // takes the `code` directly (the UI already validated `state` by358 // to have been returned from `validateAuthResponse`. Our public API
293 // looking up the session), so skip the library's state-validation359 // takes the `code` directly (the UI already validated `state` by
294 // rail and go through the generic grant request instead.360 // looking up the session), so skip the library's state-validation
295 const params = new URLSearchParams({361 // rail and go through the generic grant request instead.
296 code: input.code,362 const params = new URLSearchParams({
297 redirect_uri: input.redirectUrl,363 code: input.code,
298 code_verifier: input.codeVerifier,364 redirect_uri: input.redirectUrl,
299 });365 code_verifier: input.codeVerifier,
300 if (input.resource) {366 });
301 params.set("resource", input.resource);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);
302 }381 }
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);
312 },382 },
313 catch: toOAuth2Error,383 catch: toOAuth2Error,
314 });384 });
@@ -332,22 +402,26 @@ export const exchangeClientCredentials = ( · 17 unmodified lines
332): Effect.Effect<OAuth2TokenResponse, OAuth2Error> =>402): Effect.Effect<OAuth2TokenResponse, OAuth2Error> =>
333 Effect.tryPromise({403 Effect.tryPromise({
334 try: async () => {404 try: async () => {
335 const as = asFromTokenUrl(input.tokenUrl);405 try {
336 const client: oauth.Client = { client_id: input.clientId };406 const as = asFromTokenUrl(input.tokenUrl);
337 const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body");407 const client: oauth.Client = { client_id: input.clientId };
338 const params = new URLSearchParams();408 const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body");
339 if (input.scopes && input.scopes.length > 0) {409 const params = new URLSearchParams();
340 params.set("scope", input.scopes.join(input.scopeSeparator ?? " "));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);
341 }424 }
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);
351 },425 },
352 catch: toOAuth2Error,426 catch: toOAuth2Error,
353 });427 });
@@ -378,36 +452,40 @@ export const refreshAccessToken = ( · 24 unmodified lines
378): Effect.Effect<OAuth2TokenResponse, OAuth2Error> =>452): Effect.Effect<OAuth2TokenResponse, OAuth2Error> =>
379 Effect.tryPromise({453 Effect.tryPromise({
380 try: async () => {454 try: async () => {
381 const as = asFromTokenUrlAndIssuer(input.tokenUrl, input.issuerUrl, {455 try {
382 idTokenSigningAlgValuesSupported: input.idTokenSigningAlgValuesSupported,456 const as = asFromTokenUrlAndIssuer(input.tokenUrl, input.issuerUrl, {
383 });457 idTokenSigningAlgValuesSupported: input.idTokenSigningAlgValuesSupported,
384 const client: oauth.Client = { client_id: input.clientId };458 });
385 const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body");459 const client: oauth.Client = { client_id: input.clientId };
386 const extraParams = new URLSearchParams();460 const clientAuth = pickClientAuth(input.clientSecret, input.clientAuth ?? "body");
387 if (input.scopes && input.scopes.length > 0) {461 const extraParams = new URLSearchParams();
388 extraParams.set("scope", input.scopes.join(input.scopeSeparator ?? " "));462 if (input.scopes && input.scopes.length > 0) {
389 }463 extraParams.set("scope", input.scopes.join(input.scopeSeparator ?? " "));
390 if (input.resource) {464 }
391 extraParams.set("resource", input.resource);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);
392 }488 }
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);
411 },489 },
412 catch: toOAuth2Error,490 catch: toOAuth2Error,
413 });491 });

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