Skip to content

⚡ perf: Optimize CORS exact-origin lookup to O(1)#4368

Merged
ReneWerner87 merged 2 commits into
mainfrom
copilot/optimize-cors-origin-lookup
May 28, 2026
Merged

⚡ perf: Optimize CORS exact-origin lookup to O(1)#4368
ReneWerner87 merged 2 commits into
mainfrom
copilot/optimize-cors-origin-lookup

Conversation

Copy link
Copy Markdown
Contributor

Copilot AI commented May 28, 2026

Description

The CORS middleware performed a linear scan over configured exact origins on every request with an Origin header. This change precomputes a normalized exact-origin set at middleware construction time, reducing per-request exact-match lookup from O(n) to O(1) without changing matching semantics.

  • Exact-origin lookup

    • Replace the normalized AllowOrigins slice used for exact matches with a map[string]struct{} built once during middleware initialization.
    • Keep wildcard/subdomain matching on the existing path; only exact-origin membership checks change.
  • Behavior preservation

    • Preserve existing normalization rules for configured origins and existing response behavior, including reflecting the raw request origin value when a normalized match succeeds.
  • Regression coverage

    • Add coverage for normalized exact-origin matching to ensure whitespace, trailing slash, and case normalization still resolve to the expected request origin.
allowOrigins := make(map[string]struct{}, len(cfg.AllowOrigins))
for _, origin := range cfg.AllowOrigins {
    // normalize origin once during setup
    allowOrigins[normalizedOrigin] = struct{}{}
}

if _, ok := allowOrigins[originHeader]; ok {
    allowOrigin = originHeaderRaw
}

Changes introduced

  • Benchmarks: Not included in this PR; the change removes repeated exact-origin linear scans from the hot path.
  • Documentation Update: No documentation changes.
  • Changelog/What's New: CORS exact-origin matching now uses precomputed set membership for lower per-request overhead with large origin lists.
  • Migration Guide: Not needed; no API or configuration changes.
  • API Alignment with Express: Not applicable; internal middleware optimization only.
  • API Longevity: No public API changes; existing configuration and matching behavior remain intact.
  • Examples: See the exact-origin set lookup snippet above.

Type of change

Please delete options that are not relevant.

  • New feature (non-breaking change which adds functionality)
  • Enhancement (improvement to existing features and functionality)
  • Documentation update (changes to documentation)
  • Performance improvement (non-breaking change which improves efficiency)
  • Code consistency (non-breaking change which improves code reliability and robustness)

Checklist

Before you submit your pull request, please make sure you meet these requirements:

  • Followed the inspiration of the Express.js framework for new functionalities, making them similar in usage.
  • Conducted a self-review of the code and provided comments for complex or critical parts.
  • Updated the documentation in the /docs/ directory for Fiber's documentation.
  • Added or updated unit tests to validate the effectiveness of the changes or new features.
  • Ensured that new and existing unit tests pass locally with the changes.
  • Verified that any new dependencies are essential and have been agreed upon by the maintainers/community.
  • Aimed for optimal performance with minimal allocations in the new code.
  • Provided benchmarks for the new code to analyze and improve upon.

Commit formatting

Please use emojis in commit messages for an easy way to identify the purpose or intention of a commit. Check out the emoji cheatsheet here: CONTRIBUTING.md

Copilot AI changed the title [WIP] Optimize CORS origin lookup from O(n) to O(1) using map Optimize CORS exact-origin lookup to O(1) May 28, 2026
Copilot finished work on behalf of gaby May 28, 2026 04:23
Copilot AI requested a review from gaby May 28, 2026 04:23
@ReneWerner87 ReneWerner87 added this to v3 May 28, 2026
@ReneWerner87 ReneWerner87 added this to the v3 milestone May 28, 2026
@gaby gaby changed the title Optimize CORS exact-origin lookup to O(1) ⚡ perf: Optimize CORS exact-origin lookup to O(1) May 28, 2026
@codecov
Copy link
Copy Markdown

codecov Bot commented May 28, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 91.34%. Comparing base (e5e93e6) to head (928e35d).
⚠️ Report is 6 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main    #4368      +/-   ##
==========================================
- Coverage   91.39%   91.34%   -0.05%     
==========================================
  Files         132      132              
  Lines       13098    13098              
==========================================
- Hits        11971    11965       -6     
- Misses        710      715       +5     
- Partials      417      418       +1     
Flag Coverage Δ
unittests 91.34% <100.00%> (-0.05%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 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.

@gaby gaby marked this pull request as ready for review May 28, 2026 04:33
@gaby gaby requested a review from a team as a code owner May 28, 2026 04:33
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Optimizes the CORS middleware’s exact-origin matching by replacing per-request linear scans over normalized allowed origins with a precomputed set, reducing exact-match lookup from O(n) to O(1) while preserving existing normalization and response behavior.

Changes:

  • Precompute normalized exact origins into a map[string]struct{} during middleware initialization for constant-time exact-origin checks.
  • Keep existing wildcard/subdomain matching logic unchanged.
  • Add a regression test ensuring normalized configured origins (whitespace/trailing slash/case) still match the request origin as expected.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated no comments.

File Description
middleware/cors/cors.go Builds a normalized exact-origin set once and switches exact-match checks to map membership.
middleware/cors/cors_test.go Adds a test covering normalized configured origin lookup behavior for exact matches.

@ReneWerner87 ReneWerner87 merged commit 0ca4249 into main May 28, 2026
30 checks passed
@ReneWerner87 ReneWerner87 deleted the copilot/optimize-cors-origin-lookup branch May 28, 2026 05:29
@github-project-automation github-project-automation Bot moved this to Done in v3 May 28, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

Status: Done

Development

Successfully merging this pull request may close these issues.

🔥 feat: optimize CORS origin lookup from O(n) to O(1) using map

4 participants