Skip to content

Conversation

@indraniBan
Copy link
Contributor

@indraniBan indraniBan commented Dec 2, 2024

πŸ“‹ Description

JIRA ID:

Please provide a summary of the change and the motivation behind it. Include relevant context and details.


βœ… Type of Change

  • 🐞 Bug fix (non-breaking change which resolves an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • πŸ”₯ Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • πŸ›  Refactor (change that is neither a fix nor a new feature)
  • βš™οΈ Config change (configuration file or build script updates)
  • πŸ“š Documentation (updates to docs or readme)
  • πŸ§ͺ Tests (adding new or updating existing tests)
  • 🎨 UI/UX (changes that affect the user interface)
  • πŸš€ Performance (improves performance)
  • 🧹 Chore (miscellaneous changes that don't modify src or test files)

ℹ️ Additional Information

Please describe how the changes were tested, and include any relevant screenshots, logs, or other information that provides additional context.

Summary by CodeRabbit

  • New Features

    • Added multiple configuration properties for JWT secret management across various environment files.
    • Introduced a utility class for managing cookies and handling JWT tokens.
    • Implemented a filter for validating JWT tokens and user IDs in HTTP requests.
    • Added a configuration class for Redis caching with a dedicated Redis template for user objects.
    • Introduced a new interface for user login repository with a custom query method.
  • Bug Fixes

    • Updated application properties to reflect new external service connection settings.
  • Chores

    • Created a new .gitignore file to manage ignored files and directories.
    • Updated GitHub Actions workflow for packaging to use a newer version of the upload artifact action.

@coderabbitai
Copy link

coderabbitai bot commented Dec 2, 2024

Walkthrough

The pull request introduces a comprehensive JWT (JSON Web Token) authentication mechanism for the Admin-API project. The changes include adding JWT dependencies, configuring JWT-related properties across different environments, and implementing utility classes for JWT token generation, validation, and management. The implementation involves creating several new utility classes like JwtUtil, JwtAuthenticationUtil, and JwtUserIdValidationFilter to handle token-based authentication, along with supporting configurations for Redis caching and cookie management.

Changes

File Change Summary
pom.xml Added JWT dependencies: jjwt-api, jjwt-impl, jjwt-jackson
src/main/environment/*.properties Added jwt.secret configuration across CI, DEV, UAT, TEST, and EXAMPLE environments
src/main/java/com/iemr/admin/utils/CookieUtil.java New utility class for managing cookie-related operations
src/main/java/com/iemr/admin/utils/FilterConfig.java Added filter configuration for JWT user ID validation
src/main/java/com/iemr/admin/utils/JwtAuthenticationUtil.java New utility for JWT token validation and user authentication
src/main/java/com/iemr/admin/utils/JwtUserIdValidationFilter.java Servlet filter for JWT token and user ID validation
src/main/java/com/iemr/admin/utils/JwtUtil.java Utility class for JWT token generation and management
src/main/resources/application.properties Minor updates to configuration settings
src/main/java/com/iemr/admin/config/RedisConfig.java New Redis configuration class
src/main/java/com/iemr/admin/RoleMasterApplication.java Added Redis template configuration method
bin/.gitignore New .gitignore file for build artifacts and IDE configurations
src/main/java/com/iemr/admin/data/user/M_User.java Updated class to implement Serializable and added JSON ignore properties
src/main/java/com/iemr/admin/repository/user/UserLoginRepo.java New interface for user login repository with custom query method
.github/workflows/package.yml Updated action version for artifact uploading in GitHub Actions

Suggested reviewers

  • drtechie

Poem

🐰 JWT Rabbit's Ballad πŸ”

In cookies and tokens, a security dance,
Validation filters give authentication a chance.
Redis caches secrets, tokens take flight,
Securing our system with algorithmic might!

  • Hoppy the Security Bunny πŸ•΅οΈβ€β™€οΈ

Tip

🌐 Web search-backed reviews and chat
  • We have enabled web search-based reviews and chat for all users. This feature allows CodeRabbit to access the latest documentation and information on the web.
  • You can disable this feature by setting web_search: false in the knowledge_base settings.
  • Please share any feedback in the Discord discussion.

πŸ“œ Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between f1a62ce and fc1f083.

πŸ“’ Files selected for processing (1)
  • .github/workflows/package.yml (1 hunks)
βœ… Files skipped from review due to trivial changes (1)
  • .github/workflows/package.yml
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (java)

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 generate docstrings to generate docstrings for this PR. (Beta)
  • @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

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

🧹 Outside diff range and nitpick comments (7)
src/main/java/com/iemr/admin/utils/JwtUserIdValidationFilter.java (1)

87-87: Enhancement: Catch Specific Exceptions Instead of General Exception

Catching the general Exception class can obscure the root cause of errors and make debugging more difficult. It's better to catch specific exceptions that you expect might occur.

Consider modifying the catch block to handle specific exceptions, such as IOException, ServletException, or any custom exceptions thrown by validateUserIdAndJwtToken method.

src/main/java/com/iemr/admin/utils/JwtUtil.java (2)

29-29: Specify character encoding when converting SECRET_KEY to bytes

When converting SECRET_KEY to bytes, it's advisable to specify the character encoding to ensure consistent behavior across different platforms. For example:

- return Keys.hmacShaKeyFor(SECRET_KEY.getBytes());
+ return Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8));

71-76: Handle exceptions consistently in extractAllClaims method

The extractAllClaims method does not handle exceptions that may occur during token parsing. Consider adding exception handling similar to the validateToken method to ensure consistent error handling throughout the class.

Suggested change:

 private Claims extractAllClaims(String token) {
     try {
         return Jwts.parserBuilder()
                    .setSigningKey(getSigningKey())
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
     } catch (Exception e) {
+        throw new JwtValidationException("Invalid JWT token", e);
     }
 }
src/main/java/com/iemr/admin/utils/CookieUtil.java (2)

15-25: Add logging for security events

Consider adding debug logging for cookie operations to aid in troubleshooting and security monitoring.

+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
 @Service
 public class CookieUtil {
+    private static final Logger logger = LoggerFactory.getLogger(CookieUtil.class);
+
     public Optional<String> getCookieValue(HttpServletRequest request, String cookieName) {
+        logger.debug("Attempting to retrieve cookie: {}", cookieName);
         Cookie[] cookies = request.getCookies();
         if (cookies != null) {
             for (Cookie cookie : cookies) {
                 if (cookieName.equals(cookie.getName())) {
+                    logger.debug("Found cookie: {}", cookieName);
                     return Optional.of(cookie.getValue());
                 }
             }
         }
+        logger.debug("Cookie not found: {}", cookieName);
         return Optional.empty();
     }

1-44: Consider adding unit tests

The cookie utility class handles security-sensitive operations and should be thoroughly tested.

Would you like me to help generate comprehensive unit tests for this class? The tests should cover:

  • Cookie retrieval with null/empty cookies
  • Cookie security attributes
  • Token management scenarios
pom.xml (2)

67-70: Consider updating logback-ecs-encoder version

The current version (1.3.2) is stable but outdated. Consider upgrading to version 1.5.0 for the latest features and security fixes.

 <dependency>
   <groupId>co.elastic.logging</groupId>
   <artifactId>logback-ecs-encoder</artifactId>
-  <version>1.3.2</version>
+  <version>1.5.0</version>
 </dependency>

Line range hint 242-253: Critical: Avoid using release candidate versions in production

Using Jackson RC versions (2.17.0-rc1) in production is risky as they may contain unstable features. Since you're using Spring Boot 3.2.2 as parent, it's recommended to:

  1. Remove explicit Jackson dependencies and use the versions managed by Spring Boot
  2. If specific version is needed, use the latest stable version (2.16.1)
-<dependency>
-    <groupId>com.fasterxml.jackson.core</groupId>
-    <artifactId>jackson-databind</artifactId>
-    <version>2.17.0-rc1</version>
-</dependency>
-
-<dependency>
-    <groupId>com.fasterxml.jackson.core</groupId>
-    <artifactId>jackson-core</artifactId>
-    <version>2.17.0-rc1</version>
-</dependency>
πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between fc08c9e and 4456916.

πŸ“’ Files selected for processing (13)
  • pom.xml (7 hunks)
  • src/main/environment/admin_ci.properties (1 hunks)
  • src/main/environment/admin_dev.properties (1 hunks)
  • src/main/environment/admin_example.properties (1 hunks)
  • src/main/environment/admin_test.properties (1 hunks)
  • src/main/environment/admin_uat.properties (1 hunks)
  • src/main/java/com/iemr/admin/repository/user/UserLoginRepo.java (1 hunks)
  • src/main/java/com/iemr/admin/utils/CookieUtil.java (1 hunks)
  • src/main/java/com/iemr/admin/utils/FilterConfig.java (1 hunks)
  • src/main/java/com/iemr/admin/utils/JwtAuthenticationUtil.java (1 hunks)
  • src/main/java/com/iemr/admin/utils/JwtUserIdValidationFilter.java (1 hunks)
  • src/main/java/com/iemr/admin/utils/JwtUtil.java (1 hunks)
  • src/main/resources/application.properties (0 hunks)
πŸ’€ Files with no reviewable changes (1)
  • src/main/resources/application.properties
πŸ”‡ Additional comments (6)
src/main/java/com/iemr/admin/repository/user/UserLoginRepo.java (2)

1-9: LGTM!

Package structure and imports are clean and appropriate.


14-15: πŸ› οΈ Refactor suggestion

Consider adding index hint and Optional return type

The query implementation could be improved for better security and maintainability:

  1. Consider returning Optional<M_User> to handle the case when user is not found:
-public M_User getUserByUserID(@Param("userID") Long userID);
+public Optional<M_User> getUserByUserID(@Param("userID") Long userID);
  1. Ensure the userID column is properly indexed for query performance.

  2. Consider adding method-level security using @PreAuthorize to prevent unauthorized access.

Let's verify the database schema and security configuration:

src/main/java/com/iemr/admin/utils/JwtUserIdValidationFilter.java (1)

58-60: Verify the Use of equalsIgnoreCase for Path Comparison

Using equalsIgnoreCase for URL path comparison may lead to unintended bypasses of security checks, as URL paths are case-sensitive. This can introduce security risks if not handled properly.

Please confirm whether case-insensitive comparison is intentional and appropriate for the endpoint /user/logOutUserFromConcurrentSession. If case sensitivity is required, consider using equals instead.

src/main/java/com/iemr/admin/utils/FilterConfig.java (1)

12-17: LGTM: Filter Registration Implemented Correctly

The filter registration for JwtUserIdValidationFilter is correctly implemented, and the filter will apply to all API endpoints as intended.

pom.xml (2)

254-273: LGTM: JWT dependencies are properly configured

The JWT implementation uses appropriate dependencies with correct runtime scopes for implementation modules.


Line range hint 385-389: LGTM: Build configuration changes are appropriate

The maven-antrun-plugin configuration for property file concatenation is correctly implemented.

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

πŸ”­ Outside diff range comments (1)
pom.xml (1)

Line range hint 242-253: Avoid using Release Candidate versions in production

The Jackson dependencies are using version 2.17.0-rc1 which is a Release Candidate. This could introduce instability in production.

Consider using the latest stable version:

-<version>2.17.0-rc1</version>
+<version>2.16.1</version>
♻️ Duplicate comments (3)
src/main/java/com/iemr/admin/utils/CookieUtil.java (1)

26-29: ⚠️ Potential issue

Fix potential NullPointerException in getJwtTokenFromCookie

The method assumes cookies array is non-null, which could lead to NPE.

Apply this fix:

 public String getJwtTokenFromCookie(HttpServletRequest request) {
+    Cookie[] cookies = request.getCookies();
+    if (cookies == null) {
+        return null;
+    }
-    return Arrays.stream(request.getCookies())
+    return Arrays.stream(cookies)
         .filter(cookie -> "Jwttoken".equals(cookie.getName()))
         .map(Cookie::getValue)
         .findFirst()
         .orElse(null);
 }
pom.xml (1)

254-273: ⚠️ Potential issue

Add Spring Security dependency for JWT implementation

For a robust JWT implementation, it's recommended to add Spring Security.

src/main/java/com/iemr/admin/utils/JwtAuthenticationUtil.java (1)

22-33: πŸ› οΈ Refactor suggestion

Choose a consistent dependency injection approach

The class mixes field injection with constructor injection, and the RedisTemplate is not included in the constructor.

🧹 Nitpick comments (4)
src/main/java/com/iemr/admin/utils/CookieUtil.java (1)

14-24: Consider using Optional.ofNullable for null safety

The null check can be simplified using Optional.ofNullable for better readability and null safety.

 public Optional<String> getCookieValue(HttpServletRequest request, String cookieName) {
-    Cookie[] cookies = request.getCookies();
-    if (cookies != null) {
-        for (Cookie cookie : cookies) {
-            if (cookieName.equals(cookie.getName())) {
-                return Optional.of(cookie.getValue());
-            }
-        }
-    }
-    return Optional.empty();
+    return Optional.ofNullable(request.getCookies())
+        .flatMap(cookies -> Arrays.stream(cookies)
+            .filter(cookie -> cookieName.equals(cookie.getName()))
+            .findFirst()
+            .map(Cookie::getValue));
 }
src/main/java/com/iemr/admin/utils/JwtUtil.java (1)

31-40: Consider configurable token expiration time

The token expiration time is hardcoded to 1 day. Consider making it configurable through properties.

 @Component
 public class JwtUtil {
+    @Value("${jwt.token.expiration:86400000}")
+    private long tokenExpiration;
-    private static final long EXPIRATION_TIME = 24L * 60 * 60 * 1000; // 1 day in milliseconds

     public String generateToken(String username, String userId) {
         Date now = new Date();
-        Date expiryDate = new Date(now.getTime() + EXPIRATION_TIME);
+        Date expiryDate = new Date(now.getTime() + tokenExpiration);
src/main/java/com/iemr/admin/utils/JwtAuthenticationUtil.java (2)

86-97: Enhance cache retrieval error handling

The method logs warnings but doesn't provide detailed error information for debugging.

Consider enhancing the error handling:

 private M_User getUserFromCache(String userId) {
     String redisKey = "user_" + userId;
     try {
         M_User user = (M_User) redisTemplate.opsForValue().get(redisKey);
         if (user == null) {
-            logger.warn("User not found in Redis.");
+            logger.warn("User not found in Redis for userId: {}", userId);
         } else {
-            logger.info("User fetched successfully from Redis.");
+            logger.debug("User fetched successfully from Redis for userId: {}", userId);
         }
         return user;
+    } catch (Exception e) {
+        logger.error("Error fetching user from Redis for userId: {}", userId, e);
+        return null;
     }
 }

62-84: Add rate limiting for token validation

The token validation endpoint could be susceptible to brute force attacks.

Consider implementing rate limiting using Redis:

  1. Track validation attempts per IP/user
  2. Implement exponential backoff for failed attempts
  3. Add appropriate headers (X-RateLimit-*) in responses

Would you like me to provide a detailed implementation for rate limiting?

πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 4456916 and 700b0b7.

πŸ“’ Files selected for processing (14)
  • bin/.gitignore (1 hunks)
  • pom.xml (7 hunks)
  • src/main/environment/admin_ci.properties (1 hunks)
  • src/main/environment/admin_dev.properties (1 hunks)
  • src/main/environment/admin_example.properties (1 hunks)
  • src/main/environment/admin_test.properties (1 hunks)
  • src/main/environment/admin_uat.properties (1 hunks)
  • src/main/java/com/iemr/admin/RoleMasterApplication.java (2 hunks)
  • src/main/java/com/iemr/admin/config/RedisConfig.java (1 hunks)
  • src/main/java/com/iemr/admin/utils/CookieUtil.java (1 hunks)
  • src/main/java/com/iemr/admin/utils/FilterConfig.java (1 hunks)
  • src/main/java/com/iemr/admin/utils/JwtAuthenticationUtil.java (1 hunks)
  • src/main/java/com/iemr/admin/utils/JwtUserIdValidationFilter.java (1 hunks)
  • src/main/java/com/iemr/admin/utils/JwtUtil.java (1 hunks)
βœ… Files skipped from review due to trivial changes (1)
  • bin/.gitignore
🚧 Files skipped from review as they are similar to previous changes (7)
  • src/main/environment/admin_uat.properties
  • src/main/environment/admin_test.properties
  • src/main/environment/admin_dev.properties
  • src/main/environment/admin_example.properties
  • src/main/environment/admin_ci.properties
  • src/main/java/com/iemr/admin/utils/FilterConfig.java
  • src/main/java/com/iemr/admin/utils/JwtUserIdValidationFilter.java
πŸ”‡ Additional comments (2)
src/main/java/com/iemr/admin/utils/JwtUtil.java (2)

43-49: ⚠️ Potential issue

Improve error handling in validateToken

Returning null on validation failure can lead to NPEs. Consider throwing a custom exception.

+public class JwtValidationException extends RuntimeException {
+    public JwtValidationException(String message, Throwable cause) {
+        super(message, cause);
+    }
+}

 public Claims validateToken(String token) {
     try {
         return Jwts.parser()
             .setSigningKey(getSigningKey())
             .build()
             .parseClaimsJws(token)
             .getBody();
     } catch (Exception e) {
-        return null; // Handle token parsing/validation errors
+        throw new JwtValidationException("Invalid JWT token", e);
     }
 }

Likely invalid or redundant comment.


24-29: ⚠️ Potential issue

Strengthen SECRET_KEY validation and cache signing key

Current implementation has two issues:

  1. The SECRET_KEY validation should check for minimum length and complexity
  2. The signing key is regenerated for each request
 @Component
 public class JwtUtil {
+    private Key signingKey;
+
+    @PostConstruct
+    public void init() {
+        if (SECRET_KEY == null || SECRET_KEY.length() < 32) {
+            throw new IllegalStateException("JWT secret key must be at least 32 characters long");
+        }
+        this.signingKey = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());
+    }
+
     private Key getSigningKey() {
-        if (SECRET_KEY == null || SECRET_KEY.isEmpty()) {
-            throw new IllegalStateException("JWT secret key is not set in application.properties");
-        }
-        return Keys.hmacShaKeyFor(SECRET_KEY.getBytes());
+        return signingKey;
     }

Likely invalid or redundant comment.

@sonarqubecloud
Copy link

@sonarqubecloud
Copy link

sonarqubecloud bot commented Feb 6, 2025

Copy link
Contributor

@ravishanigarapu ravishanigarapu left a comment

Choose a reason for hiding this comment

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

looks ok

@ravishanigarapu ravishanigarapu merged commit 482481d into develop Feb 10, 2025
7 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Nov 10, 2025
10 tasks
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.

4 participants