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

fix: interceptor fixes to make new call if access_token is not present and not throw access_token errors to sentry #3263

Merged
merged 3 commits into from
Nov 18, 2024

Conversation

Aniruddha-Shriwant
Copy link
Contributor

@Aniruddha-Shriwant Aniruddha-Shriwant commented Nov 18, 2024

Clickup

https://app.clickup.com/t/86cwqkdza

Code Coverage

Please add code coverage here

UI Preview

Please add screenshots for UI changes

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for token refresh processes, improving the stability of user sessions.
    • Streamlined logic for accessing tokens, ensuring a valid token is requested when necessary.
  • Bug Fixes

    • Resolved issues with error propagation during token refresh, leading to more reliable logout and cache clearing operations.
  • Tests

    • Updated test cases to verify the correct execution of services during error scenarios without relying on error objects.

…t and not throw access_token errors to sentry
Copy link

coderabbitai bot commented Nov 18, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The changes in this pull request focus on enhancing the error handling logic within the HttpConfigInterceptor class. Modifications include updates to the refreshAccessToken method to use EMPTY for error handling, and adjustments in the intercept method to prevent certain errors from propagating. The test cases have also been revised to reflect these changes, ensuring that the logout and cache clearing operations are executed correctly when token refresh failures occur.

Changes

File Path Change Summary
src/app/core/interceptors/httpInterceptor.spec.ts Updated error handling in refreshAccessToken and modified test cases to ensure correct service calls.
src/app/core/interceptors/httpInterceptor.ts Altered error handling to return EMPTY, modified access token checks, and adjusted error handling in intercept.

Suggested labels

size/S

Suggested reviewers

  • Chethan-Fyle
  • arjunaj5

In the land of code where logic flows,
Errors once tangled, now gracefully go.
With EMPTY in hand, we clear the way,
For tokens to shine, come what may!
Interceptors dance, in error's embrace,
A smoother path, we now can trace! 🌟

Warning

Rate limit exceeded

@Aniruddha-Shriwant has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 15 minutes and 50 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 9b4cdce and f1a1f39.


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.

@github-actions github-actions bot added the size/XS Extra Small PR label Nov 18, 2024
@@ -14,7 +14,7 @@ import { BehaviorSubject, of, throwError } from 'rxjs';
import { extendedDeviceInfoMockData, extendedDeviceInfoMockDataWoApp } from '../mock-data/extended-device-info.data';
import { HttpErrorResponse, HttpHeaders, HttpRequest } from '@angular/common/http';

describe('HttpConfigInterceptor', () => {
fdescribe('HttpConfigInterceptor', () => {
Copy link
Contributor

Choose a reason for hiding this comment

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

Is fdescribe() intentional?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

hey yes, I was about to fix this 🤣
Your speed ⚡

Copy link
Contributor Author

Choose a reason for hiding this comment

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

this is fixed

Copy link

@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: 2

🧹 Outside diff range comments (1)
src/app/core/interceptors/httpInterceptor.ts (1)

Line range hint 70-171: Listen up! Here's some architectural wisdom, thalaiva style!

While silently handling token errors is good for user experience, we need a strategy to monitor these silent failures. Consider:

  1. Adding a dedicated error tracking service for authentication failures
  2. Implementing retry mechanisms with backoff for transient failures
  3. Adding metrics to track the frequency of token refreshes and failures

This way, we maintain the style of silent handling while keeping an eye on system health!

📜 Review details

Configuration used: CodeRabbit UI
Review profile: ASSERTIVE

📥 Commits

Reviewing files that changed from the base of the PR and between 57df4fb and 9b4cdce.

📒 Files selected for processing (2)
  • src/app/core/interceptors/httpInterceptor.spec.ts (1 hunks)
  • src/app/core/interceptors/httpInterceptor.ts (4 hunks)
🔇 Additional comments (3)
src/app/core/interceptors/httpInterceptor.ts (2)

12-12: Mind it! The import changes are perfect, just like my style!

Adding EMPTY from rxjs is the right move to handle errors silently, exactly what we need for our token handling makeover.


91-91: Mind it! Let's verify our token validation logic!

The condition !accessToken || this.expiringSoon(accessToken) looks good, but we need to ensure we're handling all token scenarios correctly.

✅ Verification successful

Let me get more information about the token validation implementation to ensure we're handling all cases properly.


Let me try one more command to get the complete picture, mind it!


Mind it! The token validation logic is perfectly safe and sound!

Listen here, I've analyzed the token validation style like a true superstar, and here's what I found:

  1. The expiringSoon method is doing its job with style:

    • Checks token expiration with precision (2 minutes threshold)
    • Has proper error handling that defaults to true (safer side)
    • Uses JWT helper service for proper token validation
  2. The token refresh mechanism is robust:

    • Handles null/undefined tokens gracefully
    • Prevents token refresh race conditions
    • Automatically refreshes when token is expiring soon

The condition !accessToken || this.expiringSoon(accessToken) is not just good, it's PERFECT! Like how I handle my stunts - with complete safety and precision!

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for all token validation patterns in the codebase
echo "Checking token validation patterns..."
rg "getAccessToken|expiringSoon|refreshAccessToken" --type ts

# Look for potential token checks we might have missed
echo "Checking for other token-related patterns..."
ast-grep --pattern 'if ($_ !== null && $_ !== undefined)' --lang ts

Length of output: 9473


Script:

#!/bin/bash
# Check the implementation of expiringSoon method
echo "Checking expiringSoon implementation..."
rg "expiringSoon.*{" -A 10 --type ts

# Check token service implementation
echo "Checking TokenService implementation..."
rg "class TokenService" -A 30 --type ts

# Look for JWT token decoding patterns
echo "Checking JWT token handling..."
rg "decodeToken|parseToken|jwtHelper" --type ts

Length of output: 6468


Script:

#!/bin/bash
# Let's check the expiringSoon method with a better pattern
echo "Checking expiringSoon implementation..."
rg "expiringSoon.*\(" -B 1 -A 8 --type ts

# Check for token expiry related code
echo "Checking token expiry handling..."
rg "getExpirationDate|expiryDate|tokenExpiry" -A 3 --type ts

Length of output: 17808

src/app/core/interceptors/httpInterceptor.spec.ts (1)

Line range hint 171-177: Mind it! The error handling looks solid, macha! 🕶️

The test case now properly verifies that when access token refresh fails, the system performs a clean logout by checking:

  • userEventService.logout is called
  • secureStorageService.clearAll is called
  • storageService.clearAll is called

This aligns perfectly with our mission to handle access token errors gracefully. Like I always say in my movies: "When system fails, clean up with style!"

@@ -168,7 +168,7 @@ export class HttpConfigInterceptor implements HttpInterceptor {
this.secureStorageService.clearAll();
this.storageService.clearAll();
globalCacheBusterNotifier.next();
return throwError(error);
return EMPTY;
Copy link

@coderabbitai coderabbitai bot Nov 18, 2024

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Kabali style suggestion: Add telemetry before going silent!

While returning EMPTY for 401s is stylish, we should track these occurrences for monitoring purposes.

Here's how to do it with panache:

+              // Track authentication failures for monitoring
+              const errorContext = {
+                status: error.status,
+                blocked: error.headers.get('X-Mobile-App-Blocked'),
+                url: request.url
+              };
+              console.warn('Authentication failed - handling silently', errorContext);
               return EMPTY;
📝 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
return EMPTY;
// Track authentication failures for monitoring
const errorContext = {
status: error.status,
blocked: error.headers.get('X-Mobile-App-Blocked'),
url: request.url
};
console.warn('Authentication failed - handling silently', errorContext);
return EMPTY;

Copy link
Contributor Author

Choose a reason for hiding this comment

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

nopes, access_token 401 is not something we should track

Copy link

Choose a reason for hiding this comment

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

@Aniruddha-Shriwant, got it, boss! We'll skip tracking access_token 401 errors. Moving ahead!


✏️ Learnings added
Learnt from: Aniruddha-Shriwant
PR: fylein/fyle-mobile-app#3263
File: src/app/core/interceptors/httpInterceptor.ts:171-171
Timestamp: 2024-11-18T04:24:04.253Z
Learning: In the `HttpConfigInterceptor` class in `src/app/core/interceptors/httpInterceptor.ts`, do not track access_token 401 errors.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

Comment on lines +70 to 76
catchError(() => {
this.userEventService.logout();
this.secureStorageService.clearAll();
this.storageService.clearAll();
globalCacheBusterNotifier.next();
return throwError(error);
return EMPTY;
}),
Copy link

@coderabbitai coderabbitai bot Nov 18, 2024

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Listen up! Let's add some style to our error handling, machan!

The silent error handling with EMPTY is cool, but we might miss important token refresh failures. Let's add some logging before we go silent.

Here's how to do it with style:

 catchError(() => {
+  console.warn('Token refresh failed - cleaning up and logging out silently');
   this.userEventService.logout();
   this.secureStorageService.clearAll();
   this.storageService.clearAll();
   globalCacheBusterNotifier.next();
   return EMPTY;
 }),
📝 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
catchError(() => {
this.userEventService.logout();
this.secureStorageService.clearAll();
this.storageService.clearAll();
globalCacheBusterNotifier.next();
return throwError(error);
return EMPTY;
}),
catchError(() => {
console.warn('Token refresh failed - cleaning up and logging out silently');
this.userEventService.logout();
this.secureStorageService.clearAll();
this.storageService.clearAll();
globalCacheBusterNotifier.next();
return EMPTY;
}),

Copy link
Contributor Author

Choose a reason for hiding this comment

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

not needed

Copy link

Choose a reason for hiding this comment

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

@Aniruddha-Shriwant, no worries, boss! We'll leave it as it is.

Copy link

Unit Test Coverage % values
Statements 95.95% ( 19189 / 19997 )
Branches 91.11% ( 10566 / 11596 )
Functions 94.36% ( 5731 / 6073 )
Lines 95.99% ( 18318 / 19083 )

@Aniruddha-Shriwant Aniruddha-Shriwant merged commit fbf0c91 into master Nov 18, 2024
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
size/XS Extra Small PR
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants