Skip to content

Conversation

@ravishanigarapu
Copy link
Contributor

@ravishanigarapu ravishanigarapu commented May 19, 2025

πŸ“‹ Description

JIRA ID: AMM-1456

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 configuration options to enable or disable API documentation and Swagger UI based on environment settings.
  • Bug Fixes

    • Improved request handling by allowing mobile clients to bypass JWT validation, ensuring smoother access for mobile users.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 19, 2025

"""

Walkthrough

Two new configuration properties for enabling or disabling Springdoc OpenAPI and Swagger UI are introduced in the CI properties file, both controlled by an environment variable. In the JWT user ID validation filter, requests from mobile clients are now detected via the User-Agent header and bypass JWT validation, and requests without JWT tokens are allowed to proceed only if from recognized mobile clients with authorization headers; otherwise, unauthorized requests receive a 401 response.

Changes

File(s) Change Summary
src/main/environment/common_ci.properties Added springdoc.api-docs.enabled and springdoc.swagger-ui.enabled, both set to @env.SWAGGER_DOC_ENABLED@.
src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java Refactored path skipping logic; added mobile client detection via User-Agent; separated JWT token validation from cookies and headers; unauthorized requests now return 401 unless from mobile clients with authorization headers.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant JwtUserIdValidationFilter
    participant Application

    Client->>JwtUserIdValidationFilter: Sends HTTP request
    JwtUserIdValidationFilter->>JwtUserIdValidationFilter: Check if path should be skipped
    alt Path skipped
        JwtUserIdValidationFilter->>Application: Pass request
    else
        JwtUserIdValidationFilter->>JwtUserIdValidationFilter: Retrieve JWT from cookie
        JwtUserIdValidationFilter->>JwtUserIdValidationFilter: Validate JWT from cookie
        alt Valid cookie JWT
            JwtUserIdValidationFilter->>Application: Pass request
        else
            JwtUserIdValidationFilter->>JwtUserIdValidationFilter: Retrieve JWT from header
            JwtUserIdValidationFilter->>JwtUserIdValidationFilter: Validate JWT from header
            alt Valid header JWT
                JwtUserIdValidationFilter->>Application: Pass request
            else
                JwtUserIdValidationFilter->>JwtUserIdValidationFilter: Check User-Agent for mobile client and Authorization header
                alt Mobile client with Authorization header
                    JwtUserIdValidationFilter->>Application: Pass request
                else
                    JwtUserIdValidationFilter->>Client: Respond 401 Unauthorized
                end
            end
        end
    end
Loading

Poem

In the warren of code, new configs appear,
Swagger and docs now toggled with cheer.
Mobile clients hop past JWT with ease,
While others face 401's breeze.
πŸ‡ The burrow is safer, the flow is more brightβ€”
CodeRabbit approves, all through the night!
✨ Hop on, dear devs, the future is light!
"""

Note

⚑️ AI Code Reviews for VS Code, Cursor, Windsurf

CodeRabbit now has a plugin for VS Code, Cursor and Windsurf. This brings AI code reviews directly in the code editor. Each commit is reviewed immediately, finding bugs before the PR is raised. Seamless context handoff to your AI code agent ensures that you can easily incorporate review feedback.
Learn more here.


Note

⚑️ Faster reviews with caching

CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.
Enjoy the performance boostβ€”your workflow just got faster.


πŸ“œ Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 48ed61d and 8b203a4.

πŸ“’ Files selected for processing (1)
  • src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (java)
✨ 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.

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

🧹 Nitpick comments (1)
src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java (1)

37-96: Architectural concern: Authentication bypass impacts overall security model

The changes to bypass authentication for mobile clients and allow requests without JWT tokens fundamentally weaken the security architecture. The combination of these two changes means that any client can:

  1. Spoof a mobile User-Agent to bypass JWT validation
  2. Even without spoofing, proceed through the filter chain without a valid token

These changes should be thoroughly reviewed with your security team before implementation.

Consider the following alternatives:

  1. Implement a dedicated authentication filter for mobile clients that uses appropriate security measures
  2. Use a different authentication scheme for mobile (e.g., OAuth2 with refresh tokens)
  3. If JWT is problematic for mobile, address the specific issues rather than bypassing authentication entirely
πŸ“œ Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
Cache: Disabled due to data retention organization setting
Knowledge Base: Disabled due to data retention organization setting

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 5314e79 and d926226.

πŸ“’ Files selected for processing (2)
  • src/main/environment/common_ci.properties (1 hunks)
  • src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java (3 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (java)
πŸ”‡ Additional comments (1)
src/main/environment/common_ci.properties (1)

117-118: Added Springdoc configuration for API documentation

These new properties control the visibility of OpenAPI documentation and Swagger UI, both tied to the same environment variable SWAGGER_DOC_ENABLED. This is a good practice for toggling documentation visibility in different environments.

Comment on lines 118 to 127
private boolean isMobileClient(String userAgent) {
if (userAgent == null) return false;
userAgent = userAgent.toLowerCase();
// Common indicators for mobile apps
return userAgent.contains("okhttp") || // Android OkHttp client
userAgent.contains("android") || // Generic Android apps
userAgent.contains("dalvik") || // Android runtime
userAgent.contains("iphone") || // iOS device
userAgent.contains("ios"); // Custom iOS client
}
Copy link
Contributor

Choose a reason for hiding this comment

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

πŸ’‘ Verification agent

❓ Verification inconclusive

Security concern: Mobile client detection may be insufficient

The isMobileClient implementation relies on common user agent string patterns which can be easily spoofed. This approach doesn't provide strong guarantees about the client's authenticity.

If bypassing JWT validation for mobile clients is a requirement, consider implementing a more robust authentication mechanism specific to mobile clients, such as:

  1. API keys with additional verification
  2. Client certificates
  3. Mobile-specific tokens with proper validation

🏁 Script executed:

#!/bin/bash
# Check if there are any existing security measures for mobile clients
grep -r "mobile.*auth" --include="*.java" .

Length of output: 45


Strengthen mobile client authentication

Relying solely on user-agent strings in isMobileClient (e.g. checking for β€œokhttp”, β€œandroid”, β€œiphone”) is easily spoofed and effectively allows any client that sets those headers to bypass JWT validation. To prevent unauthorized access:

β€’ File: src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java (lines 118–127)
– The UA‐based check should not trigger a bypass of your primary authentication.
β€’ Replace or complement it with a stronger mechanism, for example:

  1. Issue and validate mobile‐specific API keys or tokens with HMAC signing
  2. Enforce client certificates (mTLS) for trusted mobile apps
  3. Use a mobile SDK to securely store and rotate credentials (e.g., OAuth2 with PKCE)
πŸ€– Prompt for AI Agents
In src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java around
lines 118 to 127, the current isMobileClient method relies solely on user-agent
string checks, which are easily spoofed and insecure for bypassing JWT
validation. To fix this, remove or disable the user-agent based bypass and
implement a stronger authentication mechanism for mobile clients, such as
validating mobile-specific API keys or tokens with HMAC, enforcing client
certificates (mTLS), or integrating OAuth2 with PKCE via a mobile SDK to
securely manage credentials and ensure proper authentication.

Comment on lines 37 to 42
String userAgent = request.getHeader("User-Agent");
if (isMobileClient(userAgent)) {
logger.info("Skipping JWT validation for X-Request-Source : "+userAgent);
filterChain.doFilter(servletRequest, servletResponse);
return;
}
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 concern: Bypassing JWT validation for mobile clients

The code now bypasses JWT authentication entirely for mobile clients by checking the User-Agent header, which can be easily spoofed. This creates a significant security vulnerability as any request can claim to be from a mobile client.

Consider implementing a more secure authentication mechanism for mobile clients, such as:

  1. Using a different authentication token specifically for mobile clients
  2. Implementing app-specific signatures that can't be easily spoofed
  3. Adding additional validation steps for mobile clients
-    if (isMobileClient(userAgent)) {
-        logger.info("Skipping JWT validation for X-Request-Source : "+userAgent);
-        filterChain.doFilter(servletRequest, servletResponse);
-        return;
-    }
+    // If mobile client, use alternative authentication
+    if (isMobileClient(userAgent)) {
+        logger.info("Mobile client detected, applying mobile authentication: "+userAgent);
+        // Validate mobile-specific authentication mechanism
+        if (!validateMobileAuthentication(request)) {
+            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid mobile authentication");
+            return;
+        }
+        filterChain.doFilter(servletRequest, servletResponse);
+        return;
+    }

Committable suggestion skipped: line range outside the PR's diff.

πŸ€– Prompt for AI Agents
In src/main/java/com/wipro/fhir/utils/JwtUserIdValidationFilter.java around
lines 37 to 42, the current code bypasses JWT validation based on the User-Agent
header, which is insecure due to easy spoofing. Remove the bypass logic that
skips JWT validation for mobile clients. Instead, implement a secure
authentication mechanism for mobile clients, such as requiring a separate
authentication token, verifying app-specific signatures, or adding additional
validation steps before allowing the request to proceed.

@drtechie
Copy link
Member

  1. Let's check only for okhttp user agent
  2. Ensure all public routes like forgotpassword are skipped
  3. Indent the files properly

@sonarqubecloud
Copy link

@ravishanigarapu ravishanigarapu merged commit 4da0340 into PSMRI:develop May 20, 2025
7 of 8 checks passed
@coderabbitai coderabbitai bot mentioned this pull request May 22, 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.

2 participants