Skip to content

Support constrained subdomain wildcards in CORS origins - #2847

Open
stevehu wants to merge 4 commits into
masterfrom
feat/cors-scoped-wildcards-2841
Open

stevehu wants to merge 4 commits into
masterfrom
feat/cors-scoped-wildcards-2841

Conversation

@stevehu

@stevehu stevehu commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Support scoped CORS origins such as https://*.example.com through the compiled cors-config policy and Undertow handler. Patterns match complete subdomain labels at every depth, exclude the apex, and match scheme and normalized port. Reject unrestricted/partial wildcards, public/private PSL suffixes, unknown suffixes, and malformed origins.

  • Compile all enabled global/per-path policies before activation using the bundled PSL. Invalid refreshes retain the whole previous policy. Missing named configuration or an absent enabled key remains disabled; the packaged YAML explicitly enables CORS.
  • Require one validated request Origin, echo exactly that value on the configured-handler path, and preserve credential support. Merge Origin into Vary at response commit so backend cache keys survive NetworkNT proxy header copying.
  • Keep request decisions local, reject invalid/untrusted origins with audit and 403, and terminate rejected preflights without a subsequent 200. Requests without Origin continue downstream, even with Access-Control-Request-* headers.
  • Keep the public collection-based matchOrigin helper stateless and exact-only, with its original configured-string/server-origin return contract. Raw wildcard entries do not opt callers into wider trust; this helper does no compilation or PSL lookup. Its handler argument remains for compatibility and is ignored.
  • Update schema/YAML descriptions and cors/README.md with policy semantics, runtime consumer requirements, trust boundaries, and verification steps.

Consumer coordination

Lambda companion: networknt/light-lambda-native#196 (draft). It migrates request/preflight matching to CorsConfig.policyForPath(path).origins().matches(origin) and carries the validated origin/method snapshot into response handling, preserving backend Vary values.

Consumers that still compare getAllowedOrigins()/getPathPrefixAllowed() strings do not implement wildcard matching. Lambda must upgrade both middleware and the framework artifact. The companion was qualified locally against core commit 2209f4b, but remains draft until this API is available in the framework artifact. No artifacts were published and no CI source pins/workflows were changed.

Compatibility decisions

  • Preserve Undertow's server-origin fallback after allowlist misses, including missing/empty lists. Lambda retains its existing explicit-allowlist behavior without that implicit fallback.
  • Preserve first raw-prefix match in map order, per-path replacement of origins/methods, and global fallback for unmatched paths. Prefixes remain non-segment-aware; Host/proxy trust implications are documented.
  • Exact configured origins retain custom schemes, underscore/trailing-dot hosts, IP literals, ASCII/Punycode hostnames, default-port normalization, and explicit null opt-in. Wildcards remain HTTP/HTTPS-only and strict DNS patterns; underscores, trailing dots, custom schemes, and opaque null cannot match them.
  • Disabled CORS may retain unused invalid entries; enabling first validates the complete policy. Named diagnostics identify the config, exact path key, property, and index. CSV gaps remain harmless; malformed typed list entries raise actionable ConfigException errors.
  • Guava 33.8.0-jre is managed in parent dependency management. Its runtime transitive dependency is documented; PSL data updates remain a framework maintenance responsibility. PSL validation does not establish organizational trust.

Re-review findings

Finding Resolution / evidence
Lambda still used literal origin strings Companion #196 uses the shared compiled policy for actual/preflight requests. Reproduced matching wildcard -> 403 before migration and verified success afterward. Includes per-path, custom-scheme, normalized-port, multi-value-header and refresh coverage.
Missing enabled changed to true Restored default false. Tests cover missing named files and a map with no enabled key; enabled test fixtures now opt in explicitly.
Named config missing from startup diagnostics Retain the config name and construct complete global/per-path diagnostic locations.
replace() corrupted path keys / method location Build origins/methods locations from an explicit base plus property constants. Regression includes a path key containing allowedOrigins.
Public helper widened trust through raw wildcards Removed the legacy compiler/cache path; collections are literal-only and cannot grant wildcard access. The configured handler uses its prevalidated policy separately.
Public helper returned raw request instead of config entry Restored the configured-string return value, request-side default-port comparison, and derived server-origin fallback. Mixed-case/default-port regression tests cover the distinction.
Misleading handler-parameter Javadoc Documents ignored compatibility parameter and identical stateless behavior for null/non-null handlers.
Null/alternating lists recompiled / dropped entries No compatibility-path compilation, cache, or PSL work remains. Tests alternate collections with a null handler and assert no PSL interactions. Malformed entries are literal non-matches; rejection retains debug/audit/403 behavior.
Handwritten authority/port parser Delegate splitting, bracket enforcement and port-range checks to Guava HostAndPort. Keep explicit guards for empty ports, negative zero and scoped IPv6, which Guava can otherwise accept.

The earlier proxy-cache, concurrency, per-path isolation, disabled-startup, validation-type, dependency-management, and public port-utility findings remain covered. sanitizeDefaultPort stays as a deprecated adapter to the shared parser rather than removing a public API.

Validation

  • JDK 25, offline Maven: 93 core/proxy tests passed, no failures/errors/skips, including Chromium, real ProxyHandler Vary integration, deterministic/concurrent request isolation, and four existing proxy streaming tests:
    mvn -o -pl cors-config,cors -am test -Dtest='Cors*Test,ProxyHandlerSseTest' -Dsurefire.failIfNoSpecifiedTests=false -Dcors.browserSmoke=true
  • Full Lambda JVM suite against the locally installed matching framework source: 115 tests, 111 passed, 4 skipped, no failures/errors (mvn -o test). No AWS deployment/invocation or GraalVM native-image qualification was performed.
  • Observed the new default/diagnostic/public-helper/Lambda regressions failing before their fixes. Existing and new CORS tests pass afterward.
  • The previous remote failure accepted http://[fe80::1%eth0] on CI but rejected it locally; zone identifiers are now rejected explicitly before literal parsing. Also synchronized isEnabled with its setter to address the remaining earlier-head Sonar reliability finding.
  • Regenerated CORS schema/YAML; git diff --check passed. GitNexus pre-edit impact, staged diff and comparison with master completed. Core diff risk was LOW; Lambda companion diff was HIGH across request/preflight/response flows, reviewed against the refreshed graph and full JVM suite.
  • Core Sonar and pre-commit checks passed for this head; remote Maven CI is still running. Lambda remote CI confirmed its artifact blocker: the currently resolved snapshot lacks CorsConfig.Policy and policyForPath. Local coordinated-source success does not establish published/native/deployed qualification.

Closes #2841.

Sonar cleanup qualification

Commit da162fd addresses the 22 remaining Sonar findings. Fresh Sonar analysis fef9fa0b-46dc-4f3e-80f2-e85de2e3bca2 reports 0 unresolved issues and Quality Gate OK; both GitHub Sonar checks and pre-commit passed for this head. Maven CI is still running.

The cleanup uses unnamed catch variables, single-operation exception-test lambdas, an equivalent description text block, and switch-based list parsing. Absent-field legacy null getters are preserved and explicitly covered; schema/YAML regeneration produced no diff. Focused tests and the opt-in Chromium smoke passed.

Four narrowly scoped exemptions preserve intentional compatibility/conventions: three S1133 reminders on retained deprecated public APIs, and S1845 on the established enabled/ENABLED backing-field/key convention. Deprecation replacements, since/forRemoval metadata, and reasons are documented in source. No global rule exclusions or public API removals were introduced.

@stevehu

stevehu commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Code review summary (xhigh, two rounds + fix check)

Round 1 (9891b46): 13 findings, all fixed in a6353c4

  • Pre-set Vary: Origin caused ProxyHandler.copyHeaders to drop the backend's Vary on all proxied responses. It's now merged with a response-commit listener (CorsProxyVaryTest).
  • Requests that carried Access-Control-Request-* without an Origin got 403. isCorsRequest now requires Origin.
  • Strict java.net.URI parsing broke exact and fallback matching for underscore hosts, trailing dots, and custom schemes (capacitor://, chrome-extension://, …). Exact entries now keep these, and wildcards stay strict HTTP/HTTPS DNS.
  • Invalid origins aborted startup even with CORS disabled; empty comma items and null/non-string elements produced bad diagnostics.
  • The public matchOrigin threw or recompiled on every call. Also: the hot path recompiled regexes, the Guava version was pinned in the module pom, and there were redundant checks, a predicate with side effects, and a dead sanitizeDefaultPort.

Round 2 (a6353c4): 9 findings, all fixed in 2209f4b

  • The enabled default had flipped to true; it's back to false, and the docs now say a missing config stays disabled.
  • The legacy matchOrigin honored wildcards and returned the request origin. It's now exact-only and returns the matching configured entry.
  • Startup errors now include the config name. Authority parsing uses Guava HostAndPort, the String.replace used to build the methods location is gone, and the Javadoc is corrected.
  • light-lambda-native's RequestCorsMiddleware matched origins literally and ignored the new wildcards. That's addressed in draft PR Use shared compiled CORS policies in Lambda middleware light-lambda-native#196, whose CI is blocked until a framework snapshot with the new API is published.

Not yet done: a full bug review of 2209f4b itself beyond confirming these fixes. Remote Maven CI is still pending.

@sonarqubecloud

Copy link
Copy Markdown

@stevehu

stevehu commented Nov 10, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up check of da162fd (Sonar cleanup)

I didn't find any new issues; the changes look behavior-preserving:

  • readList now uses a pattern switch, with text input split out into readTextList. Getters still return null for absent allowedOrigins/allowedMethods, because readList is only called when the field is present.
  • The pathPrefixAllowed description is now a text block. I compared it with cors-schema.json: the text is identical, including the leading space before /api and the blank lines.
  • Pattern switch and unnamed _ catch variables compile because java.version is 25.
  • The @Deprecated(since = "3.0.0", forRemoval = false) on CorsUtil.sanitizeDefaultPort matches the project version 3.0.0-SNAPSHOT. Each @SuppressWarnings exemption has a comment explaining why it's there.

Scope: I read the main-source diff only and didn't rerun tests locally. Maven CI is still pending. networknt/light-lambda-native#196 still needs this PR merged and a framework snapshot published before its CI can pass.

This branch has not been deployed

No deployments
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.

Support constrained subdomain wildcards in CORS allowedOrigins

1 participant