Skip to content

Conversation

@drtechie
Copy link
Member

@drtechie drtechie commented May 30, 2025

πŸ“‹ Description

JIRA ID: AMM-1507

Check if jti is present in deny list before authenticating.

βœ… 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)

Summary by CodeRabbit

  • New Features
    • Introduced a denylist mechanism for tokens, enhancing security by allowing tokens to be invalidated and checked against a denylist.
  • Improvements
    • Enhanced token validation logic to check if a token has been denylisted.
    • Improved error handling for token claim extraction and validation.
  • Removals
    • Removed the ability to generate new tokens from the application.

@coderabbitai
Copy link

coderabbitai bot commented May 30, 2025

Walkthrough

A new TokenDenylist component was introduced to manage JWT token invalidation using Redis. The JwtUtil class was refactored to remove token generation, update parsing and validation to modern APIs, and integrate denylist checks by verifying the token's jti against the denylist. Several method signatures and implementations were updated accordingly.

Changes

File(s) Change Summary
src/main/java/com/iemr/hwc/utils/JwtUtil.java Removed token generation; updated parsing and validation to use new APIs; added denylist check via TokenDenylist; refactored methods and key type.
src/main/java/com/iemr/hwc/utils/TokenDenylist.java Introduced new Spring component for JWT denylist management using Redis, with methods to add and check denied jti.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant JwtUtil
    participant TokenDenylist
    participant Redis

    Client->>JwtUtil: validateToken(token)
    JwtUtil->>JwtUtil: Parse token, extract claims
    JwtUtil->>TokenDenylist: isTokenDenylisted(jti)
    TokenDenylist->>Redis: Check "denied_{jti}" key
    Redis-->>TokenDenylist: Key presence/absence
    TokenDenylist-->>JwtUtil: true/false
    alt jti is denylisted
        JwtUtil-->>Client: Return null (token invalid)
    else jti not denylisted
        JwtUtil-->>Client: Return claims (token valid)
    end
Loading

Poem

In the warren of code, a new rule unfurled,
Denylist in Redis, JWTs in the world.
No more tokens made, but now we can seeβ€”
If a jti’s banned, it’s as gone as can be!
With hops and with hashes, security grows,
As the rabbit in code, down safe tunnels goes. πŸ‡

✨ Finishing Touches
  • πŸ“ Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❀️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

@sonarqubecloud
Copy link

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

πŸ”­ Outside diff range comments (1)
src/main/java/com/iemr/hwc/utils/JwtUtil.java (1)

15-67: πŸ’‘ Verification agent

🧩 Analysis chain

Verify token generation is handled elsewhere after removal.

The AI summary indicates that the token generation method was removed from this class. Please ensure that JWT token generation is properly handled elsewhere in the system.


🏁 Script executed:

#!/bin/bash
# Description: Search for JWT token generation in the codebase to ensure it's handled after removal from JwtUtil

# Search for JWT token generation patterns
echo "=== Searching for JWT token generation ==="
rg -A 5 "Jwts\.builder\(\)" --type java

# Search for token signing patterns
echo -e "\n=== Searching for JWT signing patterns ==="
rg -A 5 "signWith|compact\(\)" --type java

# Search for any remaining token generation methods
echo -e "\n=== Searching for generateToken methods ==="
ast-grep --pattern 'generateToken($_) { $$$ }'

Length of output: 434


Token generation logic is missing in the codebase

Our automated search found no evidence of JWT issuance anywhere:

  • No Jwts.builder() usages
  • No signWith(...) or compact() calls
  • No generateToken(...) methods

Please ensure that JWT token creation is implemented in another module or restore the token‐generation functionality so clients can obtain valid tokens.

🧹 Nitpick comments (4)
src/main/java/com/iemr/hwc/utils/TokenDenylist.java (3)

24-39: Consider consistent error handling and clarify time unit in documentation.

The method has good input validation, but there are a few suggestions:

  1. The error handling is inconsistent - null jti returns silently while invalid expirationTime throws an exception
  2. The comment should specify that expirationTime is in milliseconds
  3. Consider whether throwing RuntimeException is appropriate, as it might cause transaction rollbacks

Consider this improved implementation:

-    // Add a token's jti to the denylist with expiration time
-    public void addTokenToDenylist(String jti, Long expirationTime) {
+    // Add a token's jti to the denylist with expiration time in milliseconds
+    public void addTokenToDenylist(String jti, Long expirationTime) {
         if (jti == null || jti.trim().isEmpty()) {
+            logger.warn("Attempted to denylist token with null or empty jti");
             return;
         }
         if (expirationTime == null || expirationTime <= 0) {
             throw new IllegalArgumentException("Expiration time must be positive");
         }

         try {
             String key = getKey(jti);  // Use helper method to get the key
             redisTemplate.opsForValue().set(key, " ", expirationTime, TimeUnit.MILLISECONDS);
+            logger.debug("Successfully denylisted token with jti: {}", jti);
         } catch (Exception e) {
-            throw new RuntimeException("Failed to denylist token", e);
+            logger.error("Failed to denylist token with jti: {}", jti, e);
+            throw new RuntimeException("Failed to denylist token", e);
         }
     }

50-50: Use parameterized logging instead of string concatenation.

String concatenation in logging statements should be avoided for performance reasons.

-            logger.error("Failed to check denylist status for jti: " + jti, e);
+            logger.error("Failed to check denylist status for jti: {}", jti, e);

41-54: Excellent resilience pattern for high availability.

The fail-open approach in isTokenDenylisted (returning false on Redis failures) is a great architectural decision that prevents Redis outages from blocking authentication. This ensures system availability while logging the issues for monitoring.

src/main/java/com/iemr/hwc/utils/JwtUtil.java (1)

33-52: Well-implemented denylist integration with proper null handling.

The integration with TokenDenylist is clean and the null check on jti prevents issues with tokens that don't have an ID. The migration to the new JWT parser API is also correct.

Consider adding debug logging to help with troubleshooting:

         } catch (Exception e) {
+            logger.debug("Token validation failed", e);
             return null; // Handle token parsing/validation errors
         }
πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between e749b0b and 25e9642.

πŸ“’ Files selected for processing (2)
  • src/main/java/com/iemr/hwc/utils/JwtUtil.java (3 hunks)
  • src/main/java/com/iemr/hwc/utils/TokenDenylist.java (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/main/java/com/iemr/hwc/utils/TokenDenylist.java (1)
src/main/java/com/iemr/hwc/utils/JwtUtil.java (1)
  • Component (15-67)
src/main/java/com/iemr/hwc/utils/JwtUtil.java (3)
src/main/java/com/iemr/hwc/utils/TokenDenylist.java (1)
  • Component (11-55)
src/main/java/com/iemr/hwc/utils/JwtUserIdValidationFilter.java (1)
  • Component (18-129)
src/main/java/com/iemr/hwc/utils/JwtAuthenticationUtil.java (1)
  • Component (21-126)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (java)
πŸ”‡ Additional comments (3)
src/main/java/com/iemr/hwc/utils/TokenDenylist.java (1)

11-22: Good design with proper Redis key namespacing.

The component structure follows Spring best practices, and using a prefix for Redis keys helps prevent collisions with other data in Redis.

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

4-4: Good type safety improvement.

Using SecretKey instead of the generic Key interface provides better type safety and aligns with the JWT library's recommendations.

Also applies to: 25-25


58-61: Good defensive programming with null check.

Adding the null check prevents potential NullPointerException when token parsing fails.

Comment on lines 63 to 66
private Claims extractAllClaims(String token) {
return Jwts.parser().setSigningKey(getSigningKey()).build().parseClaimsJws(token).getBody();
JwtParser parser = Jwts.parser().verifyWith(getSigningKey()).build();
return parser.parseSignedClaims(token).getPayload();
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add exception handling to prevent unhandled exceptions.

The extractAllClaims method can throw JWT parsing exceptions that aren't handled, which could propagate to calling methods.

     private Claims extractAllClaims(String token) {
-        JwtParser parser = Jwts.parser().verifyWith(getSigningKey()).build();
-        return parser.parseSignedClaims(token).getPayload();
+        try {
+            JwtParser parser = Jwts.parser().verifyWith(getSigningKey()).build();
+            return parser.parseSignedClaims(token).getPayload();
+        } catch (Exception e) {
+            return null;
+        }
     }
πŸ“ 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
private Claims extractAllClaims(String token) {
return Jwts.parser().setSigningKey(getSigningKey()).build().parseClaimsJws(token).getBody();
JwtParser parser = Jwts.parser().verifyWith(getSigningKey()).build();
return parser.parseSignedClaims(token).getPayload();
}
private Claims extractAllClaims(String token) {
+ try {
+ JwtParser parser = Jwts.parser().verifyWith(getSigningKey()).build();
+ return parser.parseSignedClaims(token).getPayload();
+ } catch (Exception e) {
+ return null;
+ }
}
πŸ€– Prompt for AI Agents
In src/main/java/com/iemr/hwc/utils/JwtUtil.java around lines 63 to 66, the
extractAllClaims method currently does not handle exceptions that may occur
during JWT parsing. To fix this, wrap the parsing logic in a try-catch block to
catch relevant JWT exceptions, such as JwtException or its subclasses, and
handle them appropriately, for example by logging the error and returning null
or throwing a custom exception. This will prevent unhandled exceptions from
propagating to calling methods.

Copy link
Contributor

@srishtigrp78 srishtigrp78 left a comment

Choose a reason for hiding this comment

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

approved.

@srishtigrp78 srishtigrp78 merged commit e443152 into develop Jun 2, 2025
7 checks passed
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.

3 participants