Repository navigation
feat: allow CORS for configured origins - #195
Conversation
Add TESK_API_CORS_ALLOWED_ORIGINS (tesk.api.cors.allowed-origins), an opt-in list of exact origins. Without it, nothing changes: there is no CorsConfigurationSource bean, so the security filter chains get no CORS filter. With it, Spring Security adds the CORS filter to the chains of both profiles before authentication, so preflight requests need no token with the auth profile. Wildcards, paths, user info and other schemes than http and https stop the app at startup; credentials are not allowed. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Configuration reference and section, a note on browser clients in Access control, and the CORS item of the API differences. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Read the origins with the Binder in the constructor too, as the condition does, so that list forms (e.g. indexed) configure the same origins in both. Reject origins with a default or empty port, which browsers never send. Add tests of the context, of an authenticated cross-origin request and of other methods, and document default ports and same-origin requests behind proxies. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reject ports with leading zeros, out of range or 0, which browsers never send, so such origins can't fail silently with 403. Document that hosts must be ASCII (punycode) without underscores. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviewer's GuideImplementationAdd the conditional CORS configuration, validate configured origins, and document how Spring Security applies the filter in both security profiles.
ConfigurationDeclare the empty-by-default CORS origins property so CORS remains disabled unless explicitly configured.
DocumentationExplain how to configure trusted CORS origins, the resulting browser behavior, and the security implications.
TestsTest origin validation and binding, plus CORS behavior when enabled or disabled with and without authentication.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## dev #195 +/- ##
=========================================
Coverage 100.00% 100.00%
=========================================
Files 53 54 +1
Lines 2257 2314 +57
Branches 254 272 +18
=========================================
+ Hits 2257 2314 +57 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
Linked issuesChecked at commit 32d6600 #187 feat: allow CORS for configured origins · 3 of 3 met
|
There was a problem hiding this comment.
Hey - I've found 3 issues
Prompt for AI Agents
Please address the comments from this code review:
## Individual Comments
### Comment 1
<location path="src/main/java/uk/ac/ebi/tsc/tesk/config/security/CorsConfig.java" line_range="99" />
<code_context>
+ ("http".equalsIgnoreCase(uri.getScheme())
+ || "https".equalsIgnoreCase(uri.getScheme()))
+ // null also for hosts that aren't valid host names, e.g. with wildcards
+ && uri.getHost() != null
+ && uri.getRawUserInfo() == null
+ && (path.isEmpty() || "/".equals(path))
</code_context>
<issue_to_address>
**Configured browser origin is refused**
When an allowed origin is configured with a non-canonical numeric IPv4 host such as `http://127.1`, `validated` accepts the short numeric host and `setAllowedOrigins` stores it verbatim, but browsers serialize it as its canonical IPv4 address. The CORS filter then rejects the browser’s actual `Origin`, so configured browser clients get 403 responses.
Reject numeric IPv4 host forms that browsers canonicalize, or canonicalize the configured host before storing it.
</issue_to_address>
### Comment 2
<location path="src/main/java/uk/ac/ebi/tsc/tesk/config/security/CorsConfig.java" line_range="108" />
<code_context>
+ if (!valid) {
+ throw invalid(origin);
+ }
+ return origin;
+ }
+
</code_context>
<issue_to_address>
**Capitalized origins are silently rejected**
When a configured origin uses uppercase letters in its scheme or host, when a configured origin uses uppercase scheme or host letters, `validated` returns it unchanged, while browsers serialize the `Origin` header in lowercase and Spring matches allowed origins exactly. The CORS filter therefore rejects the browser request, despite the documentation saying case is ignored.
Normalize the scheme and host to lowercase before storing allowed origins, or reject non-lowercase values and document that requirement.
Also at `docs/configuration.md:110`.
</issue_to_address>
### Comment 3
<location path="src/test/java/uk/ac/ebi/tsc/tesk/config/security/CorsConfigTest.java" line_range="150-154" />
<code_context>
+ "https://a.example.org,https://b.example.org")));
+ ConfigurationPropertySources.attach(environment);
+
+ assertEquals(
+ List.of("https://a.example.org", "https://b.example.org"),
+ Binder.get(environment)
+ .bind(CorsConfig.PROPERTY, Bindable.listOf(String.class))
+ .get());
+ }
+
</code_context>
<issue_to_address>
**Environment test bypasses configuration**
When `CorsConfig.configured` stops binding the environment-backed property, `environmentVariable_bindsCommaSeparatedList` calls Spring's `Binder` directly at lines 150–154 instead of `CorsConfig.configured`; the test still passes if the application's environment-variable binding breaks, so deployments can silently ignore the setting.
Exercise `CorsConfig.configured` or load the configuration with the environment variable and assert the resulting CORS origins.
</issue_to_address>Sourcery assessment
Needs a human reviewer. 3 findings to address first, and a listed origin can read API responses in a browser when its page holds a valid token; if an untrusted origin is listed, data may be exposed. Removing it stops future browser access, but cannot retract responses already read.
Blocking findings: src/main/java/uk/ac/ebi/tsc/tesk/config/security/CorsConfig.java:99, src/main/java/uk/ac/ebi/tsc/tesk/config/security/CorsConfig.java:108, src/test/java/uk/ac/ebi/tsc/tesk/config/security/CorsConfigTest.java:154
Browsers send IPv4 hosts as four decimal numbers (e.g. 127.1 as 127.0.0.1), so other numeric forms would never match. Test that upper-case origins match browser origins, and test the environment variable through CorsConfig.configured (Sourcery review). Co-Authored-By: Claude Opus 5.5 <[email protected]>
Summary
Opt-in CORS for configured origins:
TESK_API_CORS_ALLOWED_ORIGINS(tesk.api.cors.allowed-origins), a comma-separated list of exact origins.Off by default. Without origins there is no
CorsConfigurationSourcebean, so the security filter chains get no CORS filter and nothing changes. Answers carry no CORS headers, and with theauthprofile preflight requests still need a token.With origins, Spring Security 7 adds its CORS filter to the chains of both profiles, before authentication. It finds the bean (
CorsConfig) by its type,UrlBasedCorsConfigurationSource, which is whatHttpSecurityConfigurationlooks for. Preflight requests of the allowed origins are then answered without a token, also withauth.GET,HEAD,POST.Authorization,Content-Type.WWW-Authenticate.403.Strict validation. Only exact
http/httpsorigins are accepted. These stop the app at startup with a message that names the setting:*,https://*.example.org) andnull127.1)The bean and its condition read the setting the same way, through
Binder, so the comma-separated and indexed forms both work.Docs:
configuration.md(settings table and a new "Cross-origin requests (CORS)" section),access-control.md(browser clients, and what CORS does and doesn't protect), and the CORS item inapi.md.Closes #187
Verification
CorsAuthITpreflight got401instead of200, andCorsNoAuthITanswers had noAccess-Control-Allow-Origin) and pass now.CorsConfigTestcovers:ApplicationContextRunner: with origins, without, indexed, invalidCorsAuthIT(authwith origins): a preflight succeeds without a token, and the user info endpoint (WireMocked withfailOnUnmatchedRequestsand no stubs) is never asked. Other origins, methods and headers get403. A401carries the CORS headers, an authenticated cross-origin request gets200with them, and requests withoutOriginare unchanged.CorsDisabledAuthIT(authwithout origins): a preflight gets401and there are no CORS headers.CorsNoAuthITandCorsDisabledNoAuthITcover the same fornoauth../mvnw clean verify(Java 21): 18598 unit tests and 140 integration tests pass, and Maven reports "All coverage checks have been met" (100% JaCoCo)../mvnw spotless:check checkstyle:check(Java 8, as in CI): pass.mkdocs build --strict: pass.CorsConfig.configured). The third, upper-case origins, is already handled by Spring, which compares origins ignoring case; I answered it and added a test. All three threads are resolved.Helm chart (TESK), not changed here
The TESK chart has no CORS value yet. A follow-up in elixir-cloud-aai/TESK could do this:
tesk.cors.allowedOrigins: [](a list, empty by default) tocharts/tesk/values.yaml.templates/common/tesk-deployment.yaml, setTESK_API_CORS_ALLOWED_ORIGINSto the list joined with,, only when the list isn't empty.auth.serviceInfoPublic, including which tesk-api version it needs.Declined review findings
Two review rounds (adversarial and quality). I fixed all medium findings and most low ones:
I declined these:
Cors*ITclasses (quality, low). Each class needs its own Spring context. The classes already share the origin constants throughCorsAuthIT, and the remaining duplication matches the repo's other ITs.access-control.mdandconfiguration.md(quality, low). The two pages have different readers (the security model versus the setting reference), and each states the note briefly.Open questions
None.
🤖 Generated with Claude Code