Skip to content

Conversation

@vishwab1
Copy link
Member

@vishwab1 vishwab1 commented Jun 17, 2025

πŸ“‹ Description

JIRA ID: AMM-1246

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

    • Centralized CORS (Cross-Origin Resource Sharing) configuration has been introduced, allowing flexible management of permitted origins for API requests.
    • CORS settings can now be controlled via configuration properties, supporting wildcard patterns and dynamic environment values.
  • Refactor

    • CORS handling has been removed from individual API endpoints and is now managed globally.
    • Minor formatting improvements and annotation clean-up across several controllers.
  • Bug Fixes

    • Improved handling of CORS preflight (OPTIONS) requests and response headers for cross-origin requests.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 17, 2025

Walkthrough

This change centralizes and enhances Cross-Origin Resource Sharing (CORS) configuration for the application. It removes all @CrossOrigin annotations from controller classes and methods, introduces a global CORS configuration class, and updates the JWT validation filter to handle CORS headers based on configurable allowed origins.

Changes

File(s) Change Summary
src/main/environment/104_ci.properties, src/main/environment/104_example.properties Added cors.allowed-origins property to configuration files.
src/main/java/com/iemr/helpline104/config/CorsConfig.java Introduced new global CORS configuration class using WebMvcConfigurer.
src/main/java/com/iemr/helpline104/utils/FilterConfig.java Injected cors.allowed-origins property and passed it to the JWT filter; set filter precedence.
src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java Enhanced filter to handle CORS headers and preflight requests based on allowed origins; added origin-matching logic and updated constructor.
All files under src/main/java/com/iemr/helpline104/controller/... Removed all @CrossOrigin annotations from controllers and their methods. Minor formatting and import cleanup in some controllers.
src/main/java/com/iemr/helpline104/service/CTI/CTIService.java, src/main/java/com/iemr/helpline104/controller/version/VersionController.java, src/main/java/com/iemr/helpline104/controller/healthCareWorkerType/HealthCareWorkerTypeController.java Removed unused CrossOrigin imports.
src/main/java/com/iemr/helpline104/controller/drugGroup/DrugGroupController.java, src/main/java/com/iemr/helpline104/controller/secondaryCrmReports/SecondaryCRMReports.java, src/main/java/com/iemr/helpline104/controller/bloodComponent/BloodComponentController.java Minor formatting adjustments to annotations and method signatures.

Sequence Diagram(s)

sequenceDiagram
    participant Browser
    participant Filter as JwtUserIdValidationFilter
    participant Spring as Spring Dispatcher
    participant Controller

    Browser->>Filter: HTTP Request (with Origin header)
    alt OPTIONS (Preflight)
        Filter->>Browser: Set CORS headers, 200 OK, skip JWT validation
    else Non-OPTIONS
        Filter->>Filter: Check Origin against allowed origins
        alt Origin allowed
            Filter->>Browser: Set CORS headers
            Filter->>Filter: Validate JWT (skip for certain paths/clients)
            alt JWT valid or bypassed
                Filter->>Spring: Forward request
                Spring->>Controller: Route to endpoint
                Controller-->>Spring: Response
                Spring-->>Filter: Response
                Filter-->>Browser: Response with CORS headers
            else JWT invalid
                Filter-->>Browser: 401 Unauthorized
            end
        else Origin not allowed
            Filter-->>Browser: 403 Forbidden (no CORS headers)
        end
    end
Loading

Possibly related PRs

Suggested reviewers

  • ravishanigarapu

Poem

πŸ‡
A hop and a skip, CORS rules in a line,
No more annotations, the config is fine!
Filters now check where requests come from,
Only allowed originsβ€”others are glum.
With headers in place, the code’s looking neat,
This bunny approvesβ€”now cross-origin’s sweet!
πŸ₯•

✨ 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

@vishwab1 vishwab1 changed the title CORS Configuration for FHIR API Services CORS Configuration for HELP104 API Services Jun 17, 2025
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: 5

πŸ”­ Outside diff range comments (3)
src/main/java/com/iemr/helpline104/controller/covidMaster/CovidMasterController.java (1)

26-26: Avoid mixing JAX-RS and Spring MediaType imports
You're importing jakarta.ws.rs.core.MediaType but using it in Spring MVC annotations. Prefer org.springframework.http.MediaType for consistency and clarity.

src/main/java/com/iemr/helpline104/controller/directory/DirectoryServicesController.java (1)

53-55: Inconsistent endpoint naming
The mapping "/getdirectorySearchHistory" is missing a slash after get. It should be "/get/directorySearchHistory" to align with the naming conventions used elsewhere.

src/main/java/com/iemr/helpline104/controller/epidemicOutbreak/EpidemicOutbreakController.java (1)

108-112: Compile-time failure – wrong variable used in updateEpidemicOutbreakComplaint

InputMapper.gson() is referenced statically, but InputMapper exposes gson() as an instance method (as used elsewhere in the same class). This line will not compile unless a matching static method exists.

-            T_EpidemicOutbreak t_epidemicOutbreak = InputMapper.gson().fromJson(request, T_EpidemicOutbreak.class);
+            T_EpidemicOutbreak t_epidemicOutbreak = inputMapper.gson().fromJson(request, T_EpidemicOutbreak.class);

Please fix to restore build.

🧹 Nitpick comments (8)
src/main/java/com/iemr/helpline104/service/CTI/CTIService.java (1)

29-29: Remove unused import
The RequestMapping import isn’t used in this @Service class. Cleaning up unused imports improves code maintainability.

src/main/java/com/iemr/helpline104/controller/foodSafetyComplaint/FoodSafetyComplaintController.java (1)

67-68: Remove commented-out logging
The two commented logger.info lines are inactive and can be removed to clean up the code.

src/main/java/com/iemr/helpline104/controller/beneficiarycall/BeneficiaryCallController.java (1)

90-100: Improve parameter naming and validation
Rename the method parameter String beneficiaryCall to requestBody or similar to avoid confusion with the BeneficiaryCall entity. Also consider validating the JSON payload before mapping to guard against malformed input.

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

12-26: Duplicate origin parsing logic – consider single source of truth

Both CorsConfig and JwtUserIdValidationFilter parse the same cors.allowed-origins string. Divergence over time is very easy (e.g., someone changes the parsing in one place only). Extract a small CorsProperties @ConfigurationProperties bean and inject it here and into CorsConfig & the filter.
This keeps behaviour consistent and avoids β€œworks in dev, breaks in prod” surprises.

src/main/java/com/iemr/helpline104/controller/drugGroup/DrugGroupController.java (1)

56-60: Consider returning strong types instead of raw String

The controller converts the POJO list to toString() and returns it as the body. This produces a non-JSON response and loses type information. Expose the list directly (Spring will serialise to JSON) or wrap it in an OutputResponse DTO and return a ResponseEntity.

Not blocking the CORS refactor, but improving this now avoids downstream parsing hacks.

src/main/java/com/iemr/helpline104/controller/secondaryCrmReports/SecondaryCRMReports.java (1)

31-35: Unused imports can be removed

After dropping @CrossOrigin, the org.springframework.http.MediaType import at line 30 is never referenced in this file. Trimming it keeps the file tidy and avoids IDE warnings.

src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java (2)

6-9: Remove leftover @Component import

org.springframework.stereotype.Component is no longer used now that the annotation was dropped. Keeping it will trigger an β€œunused import” compilation warning.

-import org.springframework.stereotype.Component;

143-151: isOriginAllowed wildcard conversion is fragile

Chaining String.replace() mangles the pattern before the special β€œlocalhost with any port” replacement executes, so
http://localhost:* becomes http://localhost\:* and the final replace never matches. Consider pre-compiling a Pattern or at least changing the order:

-        return Arrays.stream(allowedOrigins.split(","))
-                .map(String::trim)
-                .anyMatch(pattern -> {
-                    String regex = pattern
-                            .replace(".", "\\.")
-                            .replace("*", ".*")
-                            .replace("http://localhost:.*", "http://localhost:\\d+");
-                    return origin.matches(regex);
-                });
+        return Arrays.stream(allowedOrigins.split(","))
+                .map(String::trim)
+                .map(this::convertToRegex)
+                .anyMatch(origin::matches);
...
+    private String convertToRegex(String pattern) {
+        if ("*".equals(pattern)) {
+            return ".*";
+        }
+
+        if (pattern.startsWith("http://localhost:") && pattern.endsWith("*")) {
+            // wildcard port
+            return pattern.replace("*", "\\\\d+");
+        }
+        return pattern.replace(".", "\\\\.").replace("*", ".*");
+    }
πŸ“œ Review details

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

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 8d55ee7 and d395640.

πŸ“’ Files selected for processing (35)
  • src/main/environment/104_ci.properties (1 hunks)
  • src/main/environment/104_example.properties (1 hunks)
  • src/main/java/com/iemr/helpline104/config/CorsConfig.java (1 hunks)
  • src/main/java/com/iemr/helpline104/controller/IMRMMR/IMRMMRController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/balVivha/BalVivahController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/beneficiarycall/BeneficiaryCallController.java (1 hunks)
  • src/main/java/com/iemr/helpline104/controller/bloodComponent/BloodComponentController.java (2 hunks)
  • src/main/java/com/iemr/helpline104/controller/bloodRequest/BloodRequestController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/callqamapping/CallQAMappingController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/casesheet/Helpline104BeneficiaryHistoryController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/cdss/ClinicalDecisionSupportController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/covidMaster/CovidMasterController.java (2 hunks)
  • src/main/java/com/iemr/helpline104/controller/directory/DirectoryServicesController.java (1 hunks)
  • src/main/java/com/iemr/helpline104/controller/disease/DiseaseController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/diseaseScreening/DiseaseScreeningController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/drugGroup/DrugGroupController.java (6 hunks)
  • src/main/java/com/iemr/helpline104/controller/epidemicOutbreak/EpidemicOutbreakController.java (1 hunks)
  • src/main/java/com/iemr/helpline104/controller/feedback/FeedbackController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/feedbackType/FeedbackTypeController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/foodSafetyComplaint/FoodSafetyComplaintController.java (1 hunks)
  • src/main/java/com/iemr/helpline104/controller/healthCareWorkerType/HealthCareWorkerTypeController.java (1 hunks)
  • src/main/java/com/iemr/helpline104/controller/hihl/HIHLController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/location/CountryCityController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/location/LocationController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/organDonation/OrganDonationController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/prescription/PrescriptionController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/scheme/SchemeController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/secondaryCrmReports/SecondaryCRMReports.java (16 hunks)
  • src/main/java/com/iemr/helpline104/controller/sioHistory/ServiceImprovementOfficerController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/snomedct/SnomedController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/users/IEMRAdminController.java (0 hunks)
  • src/main/java/com/iemr/helpline104/controller/version/VersionController.java (1 hunks)
  • src/main/java/com/iemr/helpline104/service/CTI/CTIService.java (1 hunks)
  • src/main/java/com/iemr/helpline104/utils/FilterConfig.java (1 hunks)
  • src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java (5 hunks)
πŸ’€ Files with no reviewable changes (19)
  • src/main/java/com/iemr/helpline104/controller/hihl/HIHLController.java
  • src/main/java/com/iemr/helpline104/controller/location/CountryCityController.java
  • src/main/java/com/iemr/helpline104/controller/disease/DiseaseController.java
  • src/main/java/com/iemr/helpline104/controller/feedback/FeedbackController.java
  • src/main/java/com/iemr/helpline104/controller/cdss/ClinicalDecisionSupportController.java
  • src/main/java/com/iemr/helpline104/controller/diseaseScreening/DiseaseScreeningController.java
  • src/main/java/com/iemr/helpline104/controller/balVivha/BalVivahController.java
  • src/main/java/com/iemr/helpline104/controller/callqamapping/CallQAMappingController.java
  • src/main/java/com/iemr/helpline104/controller/casesheet/Helpline104BeneficiaryHistoryController.java
  • src/main/java/com/iemr/helpline104/controller/feedbackType/FeedbackTypeController.java
  • src/main/java/com/iemr/helpline104/controller/organDonation/OrganDonationController.java
  • src/main/java/com/iemr/helpline104/controller/scheme/SchemeController.java
  • src/main/java/com/iemr/helpline104/controller/IMRMMR/IMRMMRController.java
  • src/main/java/com/iemr/helpline104/controller/snomedct/SnomedController.java
  • src/main/java/com/iemr/helpline104/controller/location/LocationController.java
  • src/main/java/com/iemr/helpline104/controller/sioHistory/ServiceImprovementOfficerController.java
  • src/main/java/com/iemr/helpline104/controller/bloodRequest/BloodRequestController.java
  • src/main/java/com/iemr/helpline104/controller/users/IEMRAdminController.java
  • src/main/java/com/iemr/helpline104/controller/prescription/PrescriptionController.java
🧰 Additional context used
🧬 Code Graph Analysis (2)
src/main/java/com/iemr/helpline104/config/CorsConfig.java (1)
src/main/java/com/iemr/helpline104/utils/FilterConfig.java (1)
  • Configuration (9-28)
src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java (1)
src/main/java/com/iemr/helpline104/utils/UserAgentContext.java (1)
  • UserAgentContext (3-18)
πŸͺ› ast-grep (0.38.1)
src/main/java/com/iemr/helpline104/utils/JwtUserIdValidationFilter.java

[warning] 180-180: The application does not appear to verify inbound requests which can lead to a Cross-site request forgery (CSRF) vulnerability. If the application uses cookie-based authentication, an attacker can trick users into sending authenticated HTTP requests without their knowledge from any arbitrary domain they visit. To prevent this vulnerability start by identifying if the framework or library leveraged has built-in features or offers plugins for CSRF protection. CSRF tokens should be unique and securely random. The Synchronizer Token or Double Submit Cookie patterns with defense-in-depth mechanisms such as the sameSite cookie flag can help prevent CSRF. For more information, see: [Cross-site request forgery prevention](https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Req\ uest_Forgery_Prevention_Cheat_Sheet.html).
Context: response.addCookie(cookie);
Note: [CWE-352] Cross-Site Request Forgery (CSRF). [REFERENCES]
- https://stackoverflow.com/questions/42717210/samesite-cookie-in-java-application

(cookie-missing-samesite-java)

⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Analyze (java)
πŸ”‡ Additional comments (10)
src/main/java/com/iemr/helpline104/controller/version/VersionController.java (1)

31-31: Approve removal of @CrossOrigin import
Centralizing CORS via CorsConfig replaces per-controller annotations; removing the unused CrossOrigin import aligns this controller with the new global policy.

src/main/environment/104_ci.properties (1)

30-30: Approve addition of cors.allowed-origins
This new property feeds into CorsConfig for global CORS management. Ensure the CI environment variable CORS_ALLOWED_ORIGINS is defined in your deployment pipeline.

src/main/environment/104_example.properties (2)

25-25: Unrelated change detected
The update to logging.file.name isn’t mentioned in the PR summary. Please confirm whether this change should be scoped into this CORS-focused pull request.

Likely an incorrect or invalid review comment.


27-27: Approve addition of cors.allowed-origins
Setting cors.allowed-origins=http://localhost:* in the example properties aligns with the centralized CORS configuration approach.

src/main/java/com/iemr/helpline104/controller/bloodComponent/BloodComponentController.java (2)

53-53: Approve formatting refinement
Removed extra spaces in the @Parameter annotation description for saveBloodComponentDetails, improving consistency with JSON schema representations.


72-72: Approve formatting refinement
Cleaned up spacing in the @Parameter annotation for getBloodComponentDetails, aligning with code style standards.

src/main/java/com/iemr/helpline104/controller/healthCareWorkerType/HealthCareWorkerTypeController.java (2)

30-30: Remove redundant CrossOrigin import
The @CrossOrigin import was removed to delegate CORS handling to the global configuration. Ensure your CorsConfig covers this controller's /beneficiary path.


52-53: Removed method-level CORS annotation
The @CrossOrigin annotation was deleted here; confirm that your centralized CORS settings allow requests to /beneficiary/get/healthCareWorkerTypes. Consider adding an integration test to verify CORS preflight on this endpoint.

src/main/java/com/iemr/helpline104/controller/directory/DirectoryServicesController.java (1)

30-30: Removed CrossOrigin import
The standalone @CrossOrigin import was removed; ensure your global CorsConfig covers all /beneficiary endpoints.

src/main/java/com/iemr/helpline104/controller/beneficiarycall/BeneficiaryCallController.java (1)

92-99: Null-check logic is sound
Good addition of the null guard for beneficiaryRegID. It prevents NPEs and ensures updates are only attempted when an ID is provided.

@vishwab1 vishwab1 requested review from drtechie and vanitha1822 June 17, 2025 16:14
@vishwab1 vishwab1 merged commit 7f1bfa6 into develop Jun 18, 2025
8 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