Skip to content

feat(cors): Global CORS Configuration for AMRIT API Services #48

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

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from

Conversation

kevalkanp1011
Copy link

@kevalkanp1011 kevalkanp1011 commented Apr 17, 2025

📋 Description

JIRA ID:

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

This PR introduces a global CORS configuration for the AMRIT platform API services, in alignment with requirements. The goal is to enhance cross-origin request handling by removing controller-level CORS annotations and setting up centralized, environment-based CORS policies.

✅ 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
    • Introduced configurable global CORS (Cross-Origin Resource Sharing) support, allowing administrators to specify permitted origins and enabling credentials for cross-origin requests.
  • Refactor
    • Updated controllers to remove individual CORS annotations, consolidating CORS management into a single global configuration.

Copy link

coderabbitai bot commented Apr 17, 2025

Warning

Rate limit exceeded

@kevalkanp1011 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 19 minutes and 53 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between bd71742 and 98fda42.

📒 Files selected for processing (5)
  • src/main/environment/common_dev.properties (1 hunks)
  • src/main/environment/common_example.properties (1 hunks)
  • src/main/environment/common_test.properties (1 hunks)
  • src/main/java/com/iemr/tm/config/CorsConfig.java (1 hunks)
  • src/main/java/com/iemr/tm/utils/DynamicCorsFilter.java (1 hunks)

Walkthrough

This change introduces a centralized, global CORS (Cross-Origin Resource Sharing) configuration for the application. A new CorsConfig class is added to configure allowed origins, methods, headers, and credentials at the application level by reading from properties. The @CrossOrigin annotations are removed from all relevant controller methods to eliminate per-endpoint CORS configuration. Corresponding configuration properties for allowed origins are added to both CI and example properties files, enabling environment-specific CORS control.

Changes

Files/Paths Change Summary
src/main/java/com/iemr/tm/config/CorsConfig.java Added new CorsConfig class implementing WebMvcConfigurer to set up global CORS configuration using application properties.
src/main/environment/common_ci.properties,
src/main/environment/common_example.properties
Added new property cors.allowed-origins for specifying allowed CORS origins in both CI and example property files.
src/main/java/com/iemr/tm/controller/schedule/SchedulingController.java,
src/main/java/com/iemr/tm/controller/specialist/SpecialistController.java,
src/main/java/com/iemr/tm/controller/van/VanController.java
Removed all @CrossOrigin annotations from controller methods, delegating CORS handling to the new global configuration.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant SpringApp
    participant CorsConfig
    participant Controller

    Client->>SpringApp: HTTP Request (with Origin header)
    SpringApp->>CorsConfig: Evaluate CORS policy (allowed origins, methods, headers)
    CorsConfig-->>SpringApp: CORS headers set (if allowed)
    SpringApp->>Controller: Route request
    Controller-->>SpringApp: Response
    SpringApp-->>Client: Response (with CORS headers if applicable)
Loading

Possibly related issues

✨ 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

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

♻️ Duplicate comments (8)
src/main/java/com/iemr/tm/controller/specialist/SpecialistController.java (2)

69-69: Duplicate: see comment at 53

Consistent removal of @CrossOrigin across methods aligns with the global configuration.


104-104: Duplicate: see comment at 53

Consistent removal of @CrossOrigin across methods aligns with the global configuration.

src/main/java/com/iemr/tm/controller/schedule/SchedulingController.java (6)

75-75: Duplicate: see comment at 55

Removal of @CrossOrigin is consistent with the centralized CORS configuration.


94-94: Duplicate: see comment at 55

Removal of @CrossOrigin is consistent with the centralized CORS configuration.


112-112: Duplicate: see comment at 55

Removal of @CrossOrigin is consistent with the centralized CORS configuration.


134-134: Duplicate: see comment at 55

Removal of @CrossOrigin is consistent with the centralized CORS configuration.


152-152: Duplicate: see comment at 55

Removal of @CrossOrigin is consistent with the centralized CORS configuration.


170-170: Duplicate: see comment at 55

Removal of @CrossOrigin is consistent with the centralized CORS configuration.

🧹 Nitpick comments (5)
src/main/environment/common_ci.properties (1)

27-27: Ensure environment variable injection for CORS allowed origins

The placeholder @CORS_ALLOWED_ORIGINS@ must be provided by your CI pipeline; if it’s unset or empty, CORS requests may be blocked. Consider adding a default fallback (e.g., using Spring’s ${…:default} syntax) or documenting this requirement in your deployment guide.

src/main/java/com/iemr/tm/config/CorsConfig.java (4)

11-12: Consider binding origins as a list for type safety.
Instead of injecting a raw comma-delimited string, you could use @ConfigurationProperties(prefix = "cors") to bind List<String> allowedOrigins, or inject directly:

@Value("${cors.allowed-origins}")
private List<String> allowedOrigins;

This removes manual splitting and improves readability.


16-17: Trim and validate origin patterns after splitting.
allowedOrigins.split(",") may yield entries with whitespace or empty strings. Use:

String[] origins = Arrays.stream(allowedOrigins.split(","))
    .map(String::trim)
    .filter(s -> !s.isEmpty())
    .toArray(String[]::new);
.allowedOriginPatterns(origins)

to avoid invalid patterns.


18-22: Externalize CORS parameters for flexibility.
Hardcoding HTTP methods, headers, exposed headers, credentials allowance, and maxAge limits flexibility. Consider moving these values to properties:

cors.allowed-methods=GET,POST,PUT,DELETE,OPTIONS
cors.allowed-headers=*
cors.exposed-headers=Authorization,Jwttoken
cors.allow-credentials=true
cors.max-age=3600

and bind via @ConfigurationProperties.


14-23: Add JavaDoc to document CORS policy behavior.
Including Javadoc on addCorsMappings explaining which origins, methods, and headers are configured aids maintainability for future readers.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between feb504f and bd71742.

📒 Files selected for processing (6)
  • src/main/environment/common_ci.properties (1 hunks)
  • src/main/environment/common_example.properties (1 hunks)
  • src/main/java/com/iemr/tm/config/CorsConfig.java (1 hunks)
  • src/main/java/com/iemr/tm/controller/schedule/SchedulingController.java (7 hunks)
  • src/main/java/com/iemr/tm/controller/specialist/SpecialistController.java (4 hunks)
  • src/main/java/com/iemr/tm/controller/van/VanController.java (1 hunks)
🔇 Additional comments (7)
src/main/environment/common_example.properties (1)

23-23: Validate wildcard support in global CORS configuration

You’re using wildcard patterns (http://localhost:*,http://127.0.0.1:*) in cors.allowed-origins. Verify that your CorsConfig calls allowedOriginPatterns(...) (introduced in Spring 5.3) rather than allowedOrigins(...), as only allowedOriginPatterns will correctly interpret these wildcards.

src/main/java/com/iemr/tm/controller/van/VanController.java (1)

49-49: Approve removal of method-level CORS annotation

Removing the @CrossOrigin from this endpoint is correct now that you have a centralized CORS policy. Don’t forget to clean up the leftover import org.springframework.web.bind.annotation.CrossOrigin since it’s no longer used.

src/main/java/com/iemr/tm/controller/specialist/SpecialistController.java (1)

53-53: Approve removal of CORS annotation

Centralizing CORS in CorsConfig is a good move—removing this per-method @CrossOrigin is appropriate. Please also remove the unused import org.springframework.web.bind.annotation.CrossOrigin;.

src/main/java/com/iemr/tm/controller/schedule/SchedulingController.java (1)

55-55: Approve removal of method-level CORS annotation

This endpoint no longer needs its own @CrossOrigin—the global CORS setup will apply. Clean up the now-unused import org.springframework.web.bind.annotation.CrossOrigin.

src/main/java/com/iemr/tm/config/CorsConfig.java (3)

3-6: Imports are appropriate. The necessary Spring MVC and configuration imports correctly set up the global CORS config.


8-9: Global CORS configuration is registered correctly. Using @Configuration with WebMvcConfigurer cleanly replaces per-controller @CrossOrigin annotations.


20-20: Verify the exposed header name for consistency.
The header "Jwttoken" may have inconsistent casing. Ensure this matches the actual header sent by clients, and consider defining these as constants to prevent typos.

Copy link

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.

1 participant