Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

return 4xx error instead of 5xx when failed to extract access token #397

Merged
merged 4 commits into from
Feb 9, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/polite-wolves-attack.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@gitbook/runtime': minor
---

return 4xx error instead of 5xx when failed to extract access token
28 changes: 24 additions & 4 deletions packages/runtime/src/oauth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,23 @@ export function createOAuthHandler(
const json = await response.json<OAuthResponse>();

// Store the credentials in the installation configuration
const credentials = await extractCredentials(json);
let credentials: RequestUpdateIntegrationInstallation;
try {
credentials = await extractCredentials(json);
} catch (error) {
logger.error(`extractCredentials error`, error.stack);
return new Response(
JSON.stringify({
error: `Failed to retrieve access_token from OAuth response. Please try again.`,
}),
{
status: 400,
headers: {
'Content-Type': 'application/json',
},
}
);
}

logger.debug(`exchange code for credentials`, credentials);

Expand Down Expand Up @@ -333,11 +349,15 @@ export async function getToken(
return creds.configuration.oauth_credentials.access_token;
}

/**
* Default implementation to extract the credentials from the OAuth response.
* throws an error if the `access_token` is not present in the response.
*/
function defaultExtractCredentials(response: OAuthResponse): RequestUpdateIntegrationInstallation {
if (!response.access_token) {
throw new Error(
`Could not extract access_token from response ${JSON.stringify(response, null, 4)}`
);
const message = `Failed to retrieve access_token from response`;
logger.error(`${message} ${JSON.stringify(response, null, 2)} `);
throw new Error(message);
}

return {
Expand Down
Loading