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

Hotfix/token api break #2320

Open
wants to merge 4 commits into
base: develop
Choose a base branch
from
Open

Hotfix/token api break #2320

wants to merge 4 commits into from

Conversation

sunilsabatp
Copy link
Contributor

Fixed the invalid_grant (403 Forbidden) error by implementing a try-catch block in the useEffect for token retrieval.
If an error occurs while fetching the access token, the user is redirected to the login page to resolve the invalid or expired refresh token.

Copy link

vercel bot commented Dec 3, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
planet-webapp-multi-tenancy-setup 🛑 Canceled (Inspect) 💬 Add feedback Dec 3, 2024 10:13am
2 Skipped Deployments
Name Status Preview Comments Updated (UTC)
planet-webapp ⬜️ Ignored (Inspect) Dec 3, 2024 10:13am
planet-webapp-temp ⬜️ Ignored (Inspect) Dec 3, 2024 10:13am

Copy link
Contributor

coderabbitai bot commented Dec 3, 2024

Walkthrough

The changes introduce a new state variable redirectCount in the UserPropsProvider component of UserPropsContext.tsx to track redirect attempts during access token retrieval. The loadToken function is updated with error handling using a try-catch block, which logs errors in development mode and manages redirects based on the redirectCount. If the count reaches three, a message is logged indicating the limit has been reached. The dependencies of the loadToken effect are also updated to include redirectCount.

Changes

File Path Change Summary
src/features/common/Layout/UserPropsContext.tsx Added redirectCount state variable; updated loadToken with error handling and redirect logic.

Suggested labels

PR: reviewed-approved

Suggested reviewers

  • mohitb35

Poem

🐇 In the meadow where bunnies play,
A token was lost, but not for long, hooray!
With a catch and a try, it found its way,
Redirecting with joy, to a brighter day!
So hop along, friends, let’s dance and sing,
For error handling makes our hearts take wing! 🌼

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 eslint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

npm warn config production Use --omit=dev instead.
npm error code ERESOLVE
npm error ERESOLVE could not resolve
npm error
npm error While resolving: [email protected]
npm error Found: [email protected]
npm error node_modules/eslint
npm error dev eslint@"^8.26.0" from the root project
npm error peer eslint@"6 || 7 || 8" from @emotion/[email protected]
npm error node_modules/@emotion/eslint-plugin
npm error dev @emotion/eslint-plugin@"^11.12.0" from the root project
npm error 15 more (@eslint-community/eslint-utils, ...)
npm error
npm error Could not resolve dependency:
npm error peer eslint@"^5.16.0 || ^6.8.0 || ^7.2.0" from [email protected]
npm error node_modules/eslint-config-airbnb
npm error dev eslint-config-airbnb@"^18.2.0" from the root project
npm error
npm error Conflicting peer dependency: [email protected]
npm error node_modules/eslint
npm error peer eslint@"^5.16.0 || ^6.8.0 || ^7.2.0" from [email protected]
npm error node_modules/eslint-config-airbnb
npm error dev eslint-config-airbnb@"^18.2.0" from the root project
npm error
npm error Fix the upstream dependency conflict, or retry
npm error this command with --force or --legacy-peer-deps
npm error to accept an incorrect (and potentially broken) dependency resolution.
npm error
npm error
npm error For a full report see:
npm error /root/.npm/_logs/2024-12-03T09_56_34_505Z-eresolve-report.txt
npm error A complete log of this run can be found in: /root/.npm/_logs/2024-12-03T09_56_34_505Z-debug-0.log


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between bdd7259 and 78676a2.

📒 Files selected for processing (1)
  • src/features/common/Layout/UserPropsContext.tsx (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/features/common/Layout/UserPropsContext.tsx

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Outside diff range and nitpick comments (4)
src/features/common/Layout/UserPropsContext.tsx (4)

Line range hint 116-118: Enhance error handling for 403 status

The current implementation only removes impersonation data on 403 status without any user feedback or recovery action.

Consider this enhancement:

  } else if (res.status === 403) {
    localStorage.removeItem('impersonationData');
+   setIsImpersonationModeOn(false);
+   // Notify user about the permission issue
+   throw new Error('Permission denied. Impersonation session ended.');
  } else {

Line range hint 119-122: Implement proper error handling for the catch-all else case

The current implementation silently ignores other error cases.

Consider this enhancement:

  } else {
-   //any other error
+   // Handle unexpected errors
+   setUser(null);
+   setToken(null);
+   throw new Error(`Unexpected error occurred: ${res.status}`);
  }

Line range hint 66-122: Consider implementing a centralized error handling strategy

While the current changes address the immediate token API issues, consider implementing a more comprehensive error handling strategy:

  1. Create a centralized error handling utility for consistent error management
  2. Implement proper error tracking/monitoring
  3. Add user-friendly error messages and recovery flows
  4. Consider adding retry mechanisms for transient failures

Would you like assistance in designing a centralized error handling solution?


Error handling needed for impersonation API response

The getAccountInfo function in api.ts currently returns the raw response without proper error handling, while other authenticated requests in the same file properly handle various error scenarios. Specifically:

  • The function should handle API errors using the APIError class like other authenticated requests
  • Token validation and logout handling should be consistent with other authenticated endpoints
  • The impersonation-specific error cases should be properly propagated

Key locations that need attention:

  • src/utils/apiRequests/api.ts: Add error handling in getAccountInfo similar to getAuthenticatedRequest
  • src/features/user/Settings/ImpersonateUser/ImpersonateUserForm.tsx: Improve error handling in handleImpersonation to handle specific API error cases
🔗 Analysis chain

Line range hint 91-93: Address the TODO comment regarding error handling for impersonation

The comment indicates missing error handling for the impersonated email scenario in getAccountInfo.

Let's check the implementation of getAccountInfo:

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for getAccountInfo implementation to understand error handling needs
rg -A 10 "export const getAccountInfo"

Length of output: 40


Script:

#!/bin/bash
# Let's try different search patterns to locate getAccountInfo
rg -l "getAccountInfo"

# Also search for similar function names in case it was renamed
rg -l "AccountInfo"

# Search for API calls related to account information
ast-grep --pattern 'fetch($$$"/api/account"$$$)'

Length of output: 381


Script:

#!/bin/bash
# Let's examine the implementation of getAccountInfo in the API utils
cat src/utils/apiRequests/api.ts

# Also check how it's used in the impersonation form
cat src/features/user/Settings/ImpersonateUser/ImpersonateUserForm.tsx

Length of output: 14940

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 17a6715 and 840edf6.

📒 Files selected for processing (1)
  • src/features/common/Layout/UserPropsContext.tsx (1 hunks)

Comment on lines 66 to 75
try {
const accessToken = await getAccessTokenSilently();
setToken(accessToken);
} catch (error) {
console.error('Error fetching access token:', error);
loginWithRedirect({
redirectUri: `${window.location.origin}/login`,
ui_locales: localStorage.getItem('language') || 'en',
});
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Enhance error handling robustness and security

While the try-catch block addresses the immediate token retrieval issue, there are several improvements needed:

  1. Avoid logging sensitive information to console in production
  2. Different error types (like invalid_grant vs network errors) might need different handling
  3. Consider implementing a redirect counter to prevent infinite loops

Consider this enhanced implementation:

  try {
    const accessToken = await getAccessTokenSilently();
    setToken(accessToken);
  } catch (error) {
-   console.error('Error fetching access token:', error);
+   // Only log in development
+   if (process.env.NODE_ENV === 'development') {
+     console.error('Error fetching access token:', error);
+   }
+   // Check if we've already redirected to prevent loops
+   const redirectCount = parseInt(sessionStorage.getItem('auth_redirect_count') || '0');
+   if (redirectCount > 3) {
+     // Consider showing a user-friendly error message instead of redirecting
+     console.error('Multiple authentication failures');
+     return;
+   }
+   sessionStorage.setItem('auth_redirect_count', (redirectCount + 1).toString());
    loginWithRedirect({
      redirectUri: `${window.location.origin}/login`,
      ui_locales: localStorage.getItem('language') || 'en',
    });
  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
try {
const accessToken = await getAccessTokenSilently();
setToken(accessToken);
} catch (error) {
console.error('Error fetching access token:', error);
loginWithRedirect({
redirectUri: `${window.location.origin}/login`,
ui_locales: localStorage.getItem('language') || 'en',
});
}
try {
const accessToken = await getAccessTokenSilently();
setToken(accessToken);
} catch (error) {
// Only log in development
if (process.env.NODE_ENV === 'development') {
console.error('Error fetching access token:', error);
}
// Check if we've already redirected to prevent loops
const redirectCount = parseInt(sessionStorage.getItem('auth_redirect_count') || '0');
if (redirectCount > 3) {
// Consider showing a user-friendly error message instead of redirecting
console.error('Multiple authentication failures');
return;
}
sessionStorage.setItem('auth_redirect_count', (redirectCount + 1).toString());
loginWithRedirect({
redirectUri: `${window.location.origin}/login`,
ui_locales: localStorage.getItem('language') || 'en',
});
}

- log errors only in development to prevent exposing sensitive information in production.
- Implement redirect attempt counter to limit the number of redirects and prevent infinite loops.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant