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

added 2 checks for the function. 1. exp check for iaAuthenticatedFact… #224

Conversation

mohitsinhchavda
Copy link

@mohitsinhchavda mohitsinhchavda commented Oct 18, 2024

…ory function 2. issuer check, both are to determine the token is expired or not

Bug/Issue

If the tokens just exists in the cookies storage, the isAuthenticatedFactory() function returns true, without checking expiration of issuer of the token, which is causing the issue.

Changes

Added few checks for isAuthenticatedFactory function.

  1. It checks the token is expired or not with the help of field exp
  2. it checks the token has the right issuer or not.

Checklist

🛟 If you need help, consider asking for advice over in the Kinde community.

…ory function 2. issuer check, both are to determine the token is expired or not
Copy link
Contributor

coderabbitai bot commented Oct 18, 2024

Walkthrough

The changes in this pull request significantly update the isAuthenticatedFactory function in src/session/isAuthenticated.js. The function now implements a comprehensive user authentication validation process using JSON Web Tokens (JWT). It checks for the existence of a user, retrieves and validates the JWT from the request header, and verifies the token's expiration and issuer. These enhancements ensure a more robust authentication mechanism.

Changes

File Path Change Summary
src/session/isAuthenticated.js Modified isAuthenticatedFactory to include JWT validation logic, checking user existence, token presence, decoding, expiration, and issuer verification.

Possibly related PRs

Suggested reviewers

  • coel
  • evgenyk
  • peterphanouvong
  • DaveOrDead
  • alex72508

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: 4

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 0f43965 and d874b45.

📒 Files selected for processing (1)
  • src/session/isAuthenticated.js (2 hunks)
🧰 Additional context used
🔇 Additional comments (1)
src/session/isAuthenticated.js (1)

18-21: Ensure Authorization Header Format

The extraction of the token assumes the Authorization header follows the format Bearer <token>. If the format varies, the token extraction might fail.

Please verify that all clients send the Authorization header in the expected format. Run the following script to check for any inconsistencies in the codebase:

✅ Verification successful

Authorization Header Format is consistent across the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the format of the Authorization header usage in the codebase.

# Search for usage of 'Authorization' header.
rg --type javascript "Authorization"

# Check if there are any variations in how the token is extracted.
rg --type javascript "req.headers.authorization"

Length of output: 155


Script:

#!/bin/bash
# Description: Verify the format of the Authorization header usage in the codebase.

# Search for usage of 'Authorization' header.
rg --type js "Authorization"

# Check if there are any variations in how the token is extracted.
rg --type js "req.headers.authorization"

Length of output: 158


Script:

#!/bin/bash
# Description: Verify the format of the Authorization header usage in the codebase.

# Search for usage of 'Authorization' header.
rg --type js "Authorization"

# Check if there are any variations in how the token is extracted.
rg --type js "req.headers.authorization"

Length of output: 158


return true;
} catch (error) {
console.error('Token decoding failed:', error);
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid Logging Sensitive Error Information

Logging the entire error object with console.error('Token decoding failed:', error); may expose sensitive information in your logs. This could include stack traces or token contents, which could be a security concern. Consider logging only a generic error message.

Apply this diff to fix the issue:

-    console.error('Token decoding failed:', error);
+    console.error('Token verification failed');
📝 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
console.error('Token decoding failed:', error);
console.error('Token verification failed');

Comment on lines +29 to +31
const { exp, iss } = decoded;
const currentTime = Math.floor(Date.now() / 1000);

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

Potential Redundancy in Expiration Check

After using jwt.verify, the token's expiration is already validated. The jwt.verify function will throw an error if the token is expired. Therefore, the manual expiration check may be unnecessary.

You can simplify the code by removing the manual expiration check:

     const { exp, iss } = decoded;
     const currentTime = Math.floor(Date.now() / 1000);

-    // Check expiration
-    if (exp < currentTime) {
-      return false;
-    }

Committable suggestion was skipped due to low confidence.

Comment on lines +38 to +40
if (iss !== removeTrailingSlash(process.env.KINDE_ISSUER_URL)) {
return false;
}
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

Issuer Validation Already Handled

The issuer validation is specified in the jwt.verify options. The manual issuer check might be redundant if you've included the issuer option in jwt.verify.

You can remove the manual issuer check:

     // Verify issuer
-    if (iss !== removeTrailingSlash(process.env.KINDE_ISSUER_URL)) {
-      return false;
-    }

Ensure that the issuer is correctly specified in the jwt.verify options to handle this validation.

📝 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
if (iss !== removeTrailingSlash(process.env.KINDE_ISSUER_URL)) {
return false;
}
// Verify issuer

Comment on lines +24 to +42
const decoded = jwtDecode(token);
if (!decoded) {
return false;
}

const { exp, iss } = decoded;
const currentTime = Math.floor(Date.now() / 1000);

// Check expiration
if (exp < currentTime) {
return false;
}

// Verify issuer
if (iss !== removeTrailingSlash(process.env.KINDE_ISSUER_URL)) {
return false;
}

return true;
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Security Issue: JWT Signature Not Verified

Currently, the JWT is decoded using jwtDecode without verifying its signature, which poses a significant security risk. An attacker could provide a forged token that passes decoding, expiration, and issuer checks. It is crucial to verify the token's signature to ensure the token is authentic and has not been tampered with.

Apply this diff to fix the issue:

-import jwtDecode from 'jwt-decode';
+import jwt from 'jsonwebtoken';

 export const isAuthenticatedFactory = (req, res) => async () => {
   const user = await getUserFactory(req, res)();
   
   if (!user) {
     return false;
   }

   const token = req.headers.authorization?.split(' ')[1];
   if (!token) {
     return false;
   }

   try {
-    const decoded = jwtDecode(token);
+    const decoded = jwt.verify(token, publicKey, {
+      issuer: removeTrailingSlash(process.env.KINDE_ISSUER_URL),
+      algorithms: ['RS256'], // Use the appropriate algorithm
+    });

     const { exp, iss } = decoded;
     const currentTime = Math.floor(Date.now() / 1000);

     // Check expiration
     if (exp < currentTime) {
       return false;
     }

     // Verify issuer (already handled in jwt.verify options)

     return true;
   } catch (error) {
-    console.error('Token decoding failed:', error);
+    console.error('Token verification failed');
     return false;
   }
 };

Note: You'll need to:

  • Import the public key used to sign the JWTs, which can often be obtained from your authentication provider's discovery document or metadata endpoint.
  • Replace publicKey in the code with the actual key or a reference to where you've stored it.
  • Specify the correct algorithm used to sign your JWTs in the algorithms array.

Committable suggestion was skipped due to low confidence.

@DanielRivers
Copy link
Contributor

Thanks for creating this PR, this was fixed in created PR which handled it more inline with the rest of the SDK. We really appreciate you taking the time to contribute and welcome future contributions. 🙏

@mohitsinhchavda mohitsinhchavda deleted the bugfix/add-exp-check-to-isAuthenticatedFactory-function branch October 21, 2024 05:43
@mohitsinhchavda
Copy link
Author

Thanks for informing @DanielRivers .
It would be great if you could tell me about, when are you folks planning to release it in the next version, as it is important for my team to get this issue fixed.

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.

2 participants