Skip to content

Cors-config refactor#143

Merged
Tyreviel merged 5 commits intomainfrom
refactor/cors-config
Mar 2, 2026
Merged

Cors-config refactor#143
Tyreviel merged 5 commits intomainfrom
refactor/cors-config

Conversation

@SandraNelj
Copy link

@SandraNelj SandraNelj commented Feb 26, 2026

This PR updates the CORS filter so that allowed origins and HTTP methods are now loaded from the application configuration file instead of being hardcoded.

No more hardcoded CORS rules in code.

Makes it easier to add or change allowed origins/methods without changing code.

Improves flexibility and maintainability for future CORS changes.

Summary by CodeRabbit

  • Improvements
    • CORS is now driven by application configuration instead of hardcoded values, allowing runtime customization of allowed origins and HTTP methods.
    • Runtime origin validation and preflight handling now use configurable lists, with sensible defaults to ensure common cross-origin requests work out of the box and reduce deployment friction.
  • New Features
    • Added configuration-backed access to CORS settings and a new config section to define allowed origins and methods.

…ods are now loaded from the application configuration file instead of being hardcoded.

No more hardcoded CORS rules in code.

Makes it easier to add or change allowed origins/methods without changing code.

Improves flexibility and maintainability for future CORS changes.
@coderabbitai
Copy link

coderabbitai bot commented Feb 26, 2026

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1eb3723 and 7ebdfc7.

📒 Files selected for processing (2)
  • src/main/java/org/juv25d/util/ConfigLoader.java
  • src/main/resources/application-properties.yml
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/java/org/juv25d/util/ConfigLoader.java
  • src/main/resources/application-properties.yml

📝 Walkthrough

Walkthrough

Replaces hardcoded CORS values with runtime-configured values: CorsFilter now reads allowed origins and methods from ConfigLoader, which parses a new cors section in application-properties.yml.

Changes

Cohort / File(s) Summary
CORS Filter
src/main/java/org/juv25d/filter/CorsFilter.java
Replaces static ALLOWED_* constants with private allowedOrigins and allowedMethods populated from ConfigLoader; adds public CorsFilter() constructor; origin checks and OPTIONS preflight use dynamic config.
Config Loader
src/main/java/org/juv25d/util/ConfigLoader.java
Adds allowedOrigins and allowedMethods fields; parses cors.allowed-origins and cors.allowed-methods (with defaults) during load; exposes getAllowedOrigins() and getAllowedMethods().
Application Properties
src/main/resources/application-properties.yml
Adds cors section containing allowed-origins (e.g., http://localhost:3000) and allowed-methods (GET, POST, PUT, PATCH, DELETE, OPTIONS).

Sequence Diagram(s)

sequenceDiagram
  participant App as AppStart
  participant Config as ConfigLoader
  participant Filter as CorsFilter
  participant Server as Server
  participant Client as Client

  App->>Config: load application-properties.yml (cors.allowed-origins, cors.allowed-methods)
  Config-->>App: return allowedOrigins, allowedMethods
  App->>Filter: new CorsFilter() (reads from ConfigLoader singleton)
  Filter-->>App: initialized with dynamic CORS values

  Client->>Server: HTTP request (with Origin header)
  Server->>Filter: evaluate origin & method
  Filter->>Server: set CORS response headers (Access-Control-Allow-Origin/Methods based on config)
  Server-->>Client: response (with CORS headers)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • Tyreviel
  • fmazmz

Poem

🐇 I sniffed the config, found the gates ajar,
Constants hopped out — I followed the star,
Origins and methods now dance from a file,
I nibble the bugs and then sit for a while,
Hooray—CORS hops free, across near and far. 🎉

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'Cors-config refactor' accurately and concisely summarizes the main change: refactoring CORS configuration from hardcoded values to configuration-driven values.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch refactor/cors-config

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

Comment @coderabbitai help to get the list of available commands and usage tips.

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

🧹 Nitpick comments (1)
src/main/resources/application-properties.yml (1)

19-28: CORS configuration looks good for development; consider adding common options for completeness.

The refactor to externalize CORS settings is a solid improvement. A few suggestions:

  1. Missing common CORS options: Consider adding allowed-headers (e.g., Content-Type, Authorization), max-age for preflight caching, and allow-credentials if cookie-based auth is needed.

  2. Production readiness: The http://localhost:3000 origin is fine for local development. Ensure there's a strategy for production (e.g., separate profile or environment variable override).

💡 Example with additional options
 cors:
   allowed-origins:
     - http://localhost:3000
   allowed-methods:
     - GET
     - POST
     - PUT
     - PATCH
     - DELETE
     - OPTIONS
+  allowed-headers:
+    - Content-Type
+    - Authorization
+  max-age: 3600
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/resources/application-properties.yml` around lines 19 - 28, Add
missing common CORS options to the YAML by extending the cors block: add
cors.allowed-headers (e.g., Content-Type, Authorization), cors.allow-credentials
(true/false) and cors.max-age (seconds) so preflight caching, credential
handling and allowed headers are explicit, and update configuration loading so
cors.allowed-origins can be overridden per environment (use a profile or
environment-variable-based override) to replace the hardcoded
http://localhost:3000 for production; update any code that reads cors.* keys to
use these new properties.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/main/java/org/juv25d/util/ConfigLoader.java`:
- Line 9: Remove the unused import by deleting the line importing
java.util.stream.Collectors from the ConfigLoader class; locate the import
statement at the top of ConfigLoader.java (the import of Collectors) and remove
it so Spotless/CI no longer flags the unused import and the build can proceed.
- Around line 127-141: The CORS parsing in ConfigLoader reads corsConfig entries
into allowedOrigins and allowedMethods but doesn't normalize or filter them,
which lets blank strings and mixed-case methods slip through; update the parsing
for the "allowed-origins" and "allowed-methods" keys (in class ConfigLoader,
methods/fields allowedOrigins and allowedMethods, and variable corsConfig) to:
trim each entry and filter out empty/blank values for origins, and for methods
trim, filter blanks and normalize to uppercase (e.g., map(String::trim) ->
filter(not blank) -> map(s -> s.toUpperCase())); also ensure that if the value
is not a List<?> you fall back to safe defaults (empty list for origins and the
current default methods list for methods).

---

Nitpick comments:
In `@src/main/resources/application-properties.yml`:
- Around line 19-28: Add missing common CORS options to the YAML by extending
the cors block: add cors.allowed-headers (e.g., Content-Type, Authorization),
cors.allow-credentials (true/false) and cors.max-age (seconds) so preflight
caching, credential handling and allowed headers are explicit, and update
configuration loading so cors.allowed-origins can be overridden per environment
(use a profile or environment-variable-based override) to replace the hardcoded
http://localhost:3000 for production; update any code that reads cors.* keys to
use these new properties.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e46bb6b and adb841e.

📒 Files selected for processing (3)
  • src/main/java/org/juv25d/filter/CorsFilter.java
  • src/main/java/org/juv25d/util/ConfigLoader.java
  • src/main/resources/application-properties.yml

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

♻️ Duplicate comments (1)
src/main/java/org/juv25d/util/ConfigLoader.java (1)

126-137: ⚠️ Potential issue | 🟡 Minor

CORS entries still need normalization/filtering before use.

This remains vulnerable to whitespace/null/casing mismatches and can fail runtime CORS matching.

Proposed fix
                 Object origins = corsConfig.get("allowed-origins");
                 if (origins instanceof List<?> list) {
                     this.allowedOrigins = list.stream()
+                        .filter(Objects::nonNull)
                         .map(String::valueOf)
+                        .map(String::trim)
+                        .filter(s -> !s.isEmpty())
                         .toList();
                 }

                 Object methods = corsConfig.get("allowed-methods");
                 if (methods instanceof List<?> methodList) {
-                    this.allowedMethods = methodList.stream()
+                    List<String> parsedMethods = methodList.stream()
+                        .filter(Objects::nonNull)
                         .map(String::valueOf)
+                        .map(String::trim)
+                        .filter(s -> !s.isEmpty())
+                        .map(s -> s.toUpperCase(Locale.ROOT))
                         .toList();
+                    this.allowedMethods = parsedMethods.isEmpty()
+                        ? List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
+                        : parsedMethods;
                 } else {
                     this.allowedMethods = List.of("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS");
                 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/main/java/org/juv25d/util/ConfigLoader.java` around lines 126 - 137, In
ConfigLoader, normalize and filter CORS lists produced from
corsConfig.get("allowed-origins") and corsConfig.get("allowed-methods") before
assigning to allowedOrigins and allowedMethods: when converting the List<?> (the
variables named origins/list and methods/methodList) map each entry to a String,
trim whitespace, filter out null or empty strings, convert to a consistent case
(e.g., toLowerCase for origins and methods or as appropriate for your matching
logic), and remove duplicates before collecting to the final list; ensure this
normalization happens inside the same conditional blocks that check instanceof
List<?> to avoid runtime mismatches.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@src/main/java/org/juv25d/util/ConfigLoader.java`:
- Around line 57-58: ConfigLoader currently sets allowedMethods to an empty list
when the CORS section is missing, breaking preflight; update the default
initialization in the ConfigLoader constructor (replace this.allowedMethods =
List.of()) to a safe allow-list (e.g., include
"GET","POST","PUT","DELETE","OPTIONS","HEAD") so preflight works when cors is
absent, and make the same change for the other default assignment block
referenced around lines 121-141 so both initialization sites use the safe
default while preserving existing parsing logic that overrides these values when
cors is present.

---

Duplicate comments:
In `@src/main/java/org/juv25d/util/ConfigLoader.java`:
- Around line 126-137: In ConfigLoader, normalize and filter CORS lists produced
from corsConfig.get("allowed-origins") and corsConfig.get("allowed-methods")
before assigning to allowedOrigins and allowedMethods: when converting the
List<?> (the variables named origins/list and methods/methodList) map each entry
to a String, trim whitespace, filter out null or empty strings, convert to a
consistent case (e.g., toLowerCase for origins and methods or as appropriate for
your matching logic), and remove duplicates before collecting to the final list;
ensure this normalization happens inside the same conditional blocks that check
instanceof List<?> to avoid runtime mismatches.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between adb841e and 2b13950.

📒 Files selected for processing (1)
  • src/main/java/org/juv25d/util/ConfigLoader.java

…back from CodeRabbit.

Ensures safe default HTTP methods are always set, even if cors is missing in YAML.

Hardens parsing of allowed-origins and allowed-methods:
Filters out null and blank values
Trims whitespace
Normalizes HTTP methods to uppercase
Johan-jans
Johan-jans previously approved these changes Feb 27, 2026
Copy link

@Johan-jans Johan-jans left a comment

Choose a reason for hiding this comment

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

Nice improvement making CORS fully config-driven and more flexible

Copy link

@FionaSprinkles FionaSprinkles left a comment

Choose a reason for hiding this comment

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

Great refactor for the maintainabillity of this project :)

Copy link

@Tyreviel Tyreviel left a comment

Choose a reason for hiding this comment

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

Nice fix, approved!

@Tyreviel Tyreviel merged commit f61f94e into main Mar 2, 2026
2 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.

4 participants