Skip to content

feat: allow CORS for configured origins - #195

Merged
uniqueg merged 5 commits into
devfrom
feat/187-cors
Nov 16, 2026
Merged

uniqueg merged 5 commits into
devfrom
feat/187-cors

Conversation

@uniqueg

@uniqueg uniqueg commented Nov 16, 2026 •

Copy link
Copy Markdown
Member

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 CorsConfigurationSource bean, so the security filter chains get no CORS filter and nothing changes. Answers carry no CORS headers, and with the auth profile 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 what HttpSecurityConfiguration looks for. Preflight requests of the allowed origins are then answered without a token, also with auth.

    • Allowed methods: GET, HEAD, POST.
    • Allowed request headers: Authorization, Content-Type.
    • Exposed header: WWW-Authenticate.
    • Max age: 30 minutes.
    • Credentials: not allowed.
    • Requests and preflights of other origins get 403.
  • Strict validation. Only exact http/https origins are accepted. These stop the app at startup with a message that names the setting:

    • wildcards (*, https://*.example.org) and null
    • paths, query, fragment and user info
    • non-canonical ports: empty, default, out of range, or with leading zeros
    • hosts that aren't ASCII host names (international ones must be given in punycode), and IPv4 addresses in other forms than four decimal numbers (e.g. 127.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 in api.md.

Closes #187

Verification

  • TDD. I wrote the integration tests first. They failed on dev's code (e.g. the CorsAuthIT preflight got 401 instead of 200, and CorsNoAuthIT answers had no Access-Control-Allow-Origin) and pass now.
  • Unit tests. CorsConfigTest covers:
    • the condition: off when unset, empty or blank
    • origin validation with 22 invalid forms, IP hosts, upper case, plus trimming and the trailing slash
    • the CORS settings
    • the context through ApplicationContextRunner: with origins, without, indexed, invalid
    • env var binding
  • Integration tests.
    • CorsAuthIT (auth with origins): a preflight succeeds without a token, and the user info endpoint (WireMocked with failOnUnmatchedRequests and no stubs) is never asked. Other origins, methods and headers get 403. A 401 carries the CORS headers, an authenticated cross-origin request gets 200 with them, and requests without Origin are unchanged.
    • CorsDisabledAuthIT (auth without origins): a preflight gets 401 and there are no CORS headers.
    • CorsNoAuthIT and CorsDisabledNoAuthIT cover the same for noauth.
  • Local checks.
    • ./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.
  • CI. On 32d6600 (the last commit) all checks pass and "CI passed" is green: Lint, Test, Docs, Smoke test, Scan image, CodeQL, and Codecov project and patch.
  • Sourcery. It raised 3 threads. Two are fixed in 32d6600 (non-canonical IPv4 hosts; the env var test now goes through 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:

  • Add tesk.cors.allowedOrigins: [] (a list, empty by default) to charts/tesk/values.yaml.
  • In templates/common/tesk-deployment.yaml, set TESK_API_CORS_ALLOWED_ORIGINS to the list joined with ,, only when the list isn't empty.
  • Document it like 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:

  • tests for authenticated requests and other methods
  • context-level tests
  • one shared binding
  • rejection and docs for default and non-canonical ports

I declined these:

  • No entry in the release notes or upgrade notes (quality, medium). feat: allow CORS for configured origins #187 has no milestone, and 2.0.0 isn't released yet. Which release notes this belongs in is a release-planning decision, so the entry follows when the milestone is set. The default is unchanged, so upgrades need no action.
  • Duplicated constants and setup across the four Cors*IT classes (quality, low). Each class needs its own Spring context. The classes already share the origin constants through CorsAuthIT, and the remaining duplication matches the repo's other ITs.
  • The trust note appears in both access-control.md and configuration.md (quality, low). The two pages have different readers (the security model versus the setting reference), and each states the note briefly.
  • Underscore and non-ASCII hosts are rejected (adversarial, low). This fails closed with a clear startup error, and browsers send punycode anyway. The docs now say so.

Open questions

None.

🤖 Generated with Claude Code

uniqueg and others added 4 commits November 16, 2026 06:28
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]>
@sourcery-ai

sourcery-ai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Implementation

Add the conditional CORS configuration, validate configured origins, and document how Spring Security applies the filter in both security profiles.

  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/CorsConfig.java L1-191
  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/NoAuthConfiguration.java L23-24
  • src/main/java/uk/ac/ebi/tsc/tesk/config/security/ResourceServerConfiguration.java L82-84

Configuration

Declare the empty-by-default CORS origins property so CORS remains disabled unless explicitly configured.

  • src/main/resources/application.properties L85-88

Documentation

Explain how to configure trusted CORS origins, the resulting browser behavior, and the security implications.

  • docs/access-control.md L21-23
  • docs/api.md L176-180
  • docs/configuration.md L40, L75-119

Tests

Test origin validation and binding, plus CORS behavior when enabled or disabled with and without authentication.

  • src/integration-test/java/uk/ac/ebi/tsc/tesk/CorsAuthIT.java L1-182
  • src/integration-test/java/uk/ac/ebi/tsc/tesk/CorsDisabledAuthIT.java L1-74
  • src/integration-test/java/uk/ac/ebi/tsc/tesk/CorsDisabledNoAuthIT.java L1-58
  • src/integration-test/java/uk/ac/ebi/tsc/tesk/CorsNoAuthIT.java L1-84
  • src/test/java/uk/ac/ebi/tsc/tesk/config/security/CorsConfigTest.java L1-243

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@codecov

codecov Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (bf9011c) to head (32d6600).

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@uniqueg
uniqueg marked this pull request as ready for review November 16, 2026 05:51
@sourcery-ai

sourcery-ai Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Linked issues

Checked at commit 32d6600

#187 feat: allow CORS for configured origins · 3 of 3 met

# Requirement Status Notes
1 An opt-in setting lists allowed origins, off by default and without a wildcard by default. ✅ Met The tesk.api.cors.allowed-origins setting defaults to empty; configured origins are validated as exact HTTP(S) origins.
2 Preflight requests work with the auth profile without a token. ✅ Met CorsAuthIT verifies an allowed-origin preflight succeeds without authentication.
3 Tests and configuration docs cover the setting. ✅ Met Unit and integration tests cover the setting; the configuration reference documents it.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

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]>
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.

feat: allow CORS for configured origins

1 participant