← Back to Pull requests

api: support regex CORS origins in SecurityPolicy #9966

Merged
kahirokunn merged 21 files (963 lines) on Oct 01, 2026 23:50 UTC
View on GitHub
kahirokunn kahirokunn commented on Sep 07, 2026 12:55 UTC
Author

Fixes #9965

What this PR does / why we need it:

Add cors.allowOriginRegexes to SecurityPolicy for origins such as https://preview-123.example.com, where allowing every subdomain with a wildcard is too broad.

The new field is a list of CORSOriginRegex strings. Use allowOrigins for exact origins, hostname wildcards, and allow-all. An origin is allowed if it matches either list.

spec:
  cors:
    allowOrigins:
      - https://app.example.com
    allowOriginRegexes:
      - "https://preview-[0-9]+\\.example\\.com"

Regexes use RE2 syntax, the same contract as the other regular expression fields in the API, and are validated with the existing regex.Validate helper. They match the full Origin header, including the scheme and port when present. Invalid patterns follow the existing SecurityPolicy error handling: Accepted=False and a 500 response on affected routes. Regular expressions that match the literal string "" are rejected because Envoy's CORS filter treats any matcher that matches "" as allow-all; use allowOrigins: ["*"] to allow any origin explicitly.

Which issue(s) this PR fixes:

Fixes #9965

---

PR Checklist

  • Authorship & ownership: I have reviewed every change, understand how and why it works, can explain and maintain it, and take full responsibility for this PR.

  • DCO: All commits are signed off.

  • API agreed first: Proposed in #9965. The field name allowOriginRegexes and the CORSOriginRegex type follow @zhaohuabing's suggestion in this PR; awaiting maintainer sign-off.

  • Required checks pass: GitHub Actions is awaiting maintainer approval.

  • Tests added/updated: Translator, admission, status, and E2E coverage added.

  • Docs: CORS task and API reference updated.

  • Release notes: Added 9965-cors-origin-regexes.md.

  • Generated files committed: make gen-check passes with a clean working tree.

  • Scope & compatibility: Existing allowOrigins behavior is preserved.

  • Codex review

  • Copilot review
  • Diff: 963 lines (+957 / -6) across 21 files Reviewer: zhaohuabing Review duration: 35214m
    All Vouch review confidence checks passed
    Residual risk 0.13 = Change Risk (0.95) × (1 − Review Confidence (0.87)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.95 · 963 lines diff across 21 files
    0.95
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.90 · 5 substantive comment(s)
    0.90
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    86%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Sensitive Paths sensitive_paths
    0.095
    Mass File Touch mass_file_touch
    0.080
    Real PR Conversation Timeline
    24 items
    netlify[bot] netlify[bot] commented on Sep 07, 2026 12:55 UTC
    Bot

    <span aria-hidden="true">✅</span> Deploy Preview for cerulean-figolla-1f9435 ready!

    | Name | Link |
    |:-:|------------------------|
    |<span aria-hidden="true">🔨</span> Latest commit | ed68383ca6d6d8b44e5d5a1b4714fdde26ff6847 |
    |<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/cerulean-figolla-1f9435/deploys/6aa8a2f505244500084143e2 |
    |<span aria-hidden="true">😎</span> Deploy Preview | https://deploy-preview-9966--cerulean-figolla-1f9435.netlify.app |
    |<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />!QR Code<br /><br />_Use your smartphone camera to open QR code link._</details> |
    ---
    <!-- cerulean-figolla-1f9435 Preview -->
    _To edit notification comments on pull requests, go to your Netlify project configuration._

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Sep 07, 2026 12:55 UTC
    Bot

    <!-- codex-pull-request-review-summary -->

    Codex Review Summary

    This comment shows the latest Codex review activity on this pull request.

    | Review | Status | Commit | Review trigger |
    | --- | --- | --- | --- |
    | 📝 Code Review | ✅ Completed <relative-time datetime="2026-09-09T14:17:32.033338Z">2026-09-09T14:17:32.033338Z</relative-time> | 55319c4 | Draft marked ready |

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review" or "@codex security review".
  • Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

    </details>

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Sep 07, 2026 15:16 UTC
    Reviewer

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: cf13812269

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

    </details>

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Sep 07, 2026 15:16 UTC
    Code Review
    internal/gatewayapi/securitypolicy.go:1
    @@ -1748,6 +1752,21 @@ func (t *Translator) buildCORS(cors *egv1a1.CORS) *ir.CORS {
     		}
     	}
     
    +	for i, match := range cors.AllowOriginMatches {
    +		value := match.Value
    +		switch ptr.Deref(match.Type, egv1a1.CORSOriginMatchExact) {
    +		case egv1a1.CORSOriginMatchExact:
    +			allowOrigins = append(allowOrigins, &ir.StringMatch{Exact: &value})

    *<sub><sub>!P2 Badge</sub></sub> Preserve wildcard semantics for exact origins*

    When allowOriginMatches contains an Exact entry with value "", this branch emits an Envoy exact string matcher, which only matches a literal Origin: rather than allowing every origin. This contradicts the new API and task documentation, which explicitly promise that "" allows any origin; translate this special value to the same wildcard matcher used by allowOrigins.

    Useful? React with 👍 / 👎.

    kahirokunn kahirokunn commented on code on Sep 07, 2026 15:46 UTC
    Code Review
    internal/gatewayapi/securitypolicy.go:1
    @@ -1748,6 +1752,21 @@ func (t *Translator) buildCORS(cors *egv1a1.CORS) *ir.CORS {
     		}
     	}
     
    +	for i, match := range cors.AllowOriginMatches {
    +		value := match.Value
    +		switch ptr.Deref(match.Type, egv1a1.CORSOriginMatchExact) {
    +		case egv1a1.CORSOriginMatchExact:
    +			allowOrigins = append(allowOrigins, &ir.StringMatch{Exact: &value})

    Not the case. Envoy's CORS filter tries match("") on every matcher first (https://github.com/envoyproxy/envoy/blob/3afc515c9e0319d33304cddde7f95f50c3e4d83d/source/extensions/filters/http/cors/cors_filter.cc#L210), so an exact already allows any origin.

    hsubramanianaks hsubramanianaks commented on code on Sep 07, 2026 22:42 UTC
    Code Review
    internal/gatewayapi/securitypolicy_test.go:1
    @@ -27,6 +27,83 @@ import (
     	"github.com/envoyproxy/gateway/internal/ir"
     )
     
    +func TestBuildCORSOriginMatches(t *testing.T) {
    +	const pattern = `https://preview-[0-9]+\.example\.com(:8443)?`
    +	tests := []struct {
    +		name      string
    +		matchType *egv1a1.CORSOriginMatchType
    +		value     string
    +		want      *ir.StringMatch
    +		wantError string
    +	}{
    +		{
    +			name:  "default exact",
    +			value: "https://app.example.com",
    +			want:  &ir.StringMatch{Exact: new("https://app.example.com")},
    +		},
    +		{
    +			name:      "explicit exact with port",
    +			matchType: new(egv1a1.CORSOriginMatchExact),
    +			value:     "https://app.example.com:8443",
    +			want:      &ir.StringMatch{Exact: new("https://app.example.com:8443")},
    +		},
    +		{
    +			name:  "exact treats wildcard literally",
    +			value: "https://*.example.com",
    +			want:  &ir.StringMatch{Exact: new("https://*.example.com")},
    +		},
    +		{
    +			name:      "regular expression is preserved",
    +			matchType: new(egv1a1.CORSOriginMatchRegularExpression),
    +			value:     pattern,
    +			want:      &ir.StringMatch{SafeRegex: new(pattern)},
    +		},
    +		{
    +			name:      "invalid regular expression",
    +			matchType: new(egv1a1.CORSOriginMatchRegularExpression),
    +			value:     "[",
    +			wantError: `regex "[" is invalid`,
    +		},
    +		{
    +			name:      "unsupported prefix",
    +			matchType: new(egv1a1.CORSOriginMatchType("Prefix")),
    +			value:     "https://app.example.com",
    +			wantError: `unsupported origin match type "Prefix"`,
    +		},
    +		{
    +			name:      "unknown match type",

    how is the valid RE2 regular expression works in this case? I think this might cause issue to allow-all origin matcher (interpreted by Envoy CORS filter to match *) , May be add explicit e2e tests for this ? and also how can users avoid this ?
    https://github.com/envoyproxy/envoy/blob/v1.39.1/source/extensions/filters/http/cors/cors_filter.cc#L207-L215

    allowOriginMatches:
    - type: RegularExpression
      value: '[^/]+'
    

    hsubramanianaks hsubramanianaks commented on Sep 07, 2026 23:00 UTC
    Contributor

    I would recommend adding following (suggestions though, but highly recommend getting some maintainers opinions on this) @envoyproxy/gateway-maintainers thoughts on this please ?

    Allow-all should be expressed explicitly using Exact match:

    allowOriginMatches:
    - type: Exact
      value: "*"
    
    

    Regex based match should reject if evaluates to allow-all and only be used for constraint based dynamic origins.

    for example:

    if err := regex.Validate(match.Value); err != nil {
        return nil, err
    }
    
    if fullMatch(match.Value, "*") {
        return nil, fmt.Errorf(
            "CORS origin regular expression must not match %q; use an Exact matcher with value %q to allow all origins",
            "*", "*",
        )
    }
    

    kahirokunn kahirokunn commented on code on Sep 08, 2026 01:04 UTC
    Code Review
    internal/gatewayapi/securitypolicy_test.go:1
    @@ -27,6 +27,83 @@ import (
     	"github.com/envoyproxy/gateway/internal/ir"
     )
     
    +func TestBuildCORSOriginMatches(t *testing.T) {
    +	const pattern = `https://preview-[0-9]+\.example\.com(:8443)?`
    +	tests := []struct {
    +		name      string
    +		matchType *egv1a1.CORSOriginMatchType
    +		value     string
    +		want      *ir.StringMatch
    +		wantError string
    +	}{
    +		{
    +			name:  "default exact",
    +			value: "https://app.example.com",
    +			want:  &ir.StringMatch{Exact: new("https://app.example.com")},
    +		},
    +		{
    +			name:      "explicit exact with port",
    +			matchType: new(egv1a1.CORSOriginMatchExact),
    +			value:     "https://app.example.com:8443",
    +			want:      &ir.StringMatch{Exact: new("https://app.example.com:8443")},
    +		},
    +		{
    +			name:  "exact treats wildcard literally",
    +			value: "https://*.example.com",
    +			want:  &ir.StringMatch{Exact: new("https://*.example.com")},
    +		},
    +		{
    +			name:      "regular expression is preserved",
    +			matchType: new(egv1a1.CORSOriginMatchRegularExpression),
    +			value:     pattern,
    +			want:      &ir.StringMatch{SafeRegex: new(pattern)},
    +		},
    +		{
    +			name:      "invalid regular expression",
    +			matchType: new(egv1a1.CORSOriginMatchRegularExpression),
    +			value:     "[",
    +			wantError: `regex "[" is invalid`,
    +		},
    +		{
    +			name:      "unsupported prefix",
    +			matchType: new(egv1a1.CORSOriginMatchType("Prefix")),
    +			value:     "https://app.example.com",
    +			wantError: `unsupported origin match type "Prefix"`,
    +		},
    +		{
    +			name:      "unknown match type",

    Thanks for catching this. I've added the check 🙏

    zhaohuabing zhaohuabing commented on Sep 09, 2026 02:10 UTC
    Contributor

    Since allowOrigins already covers exact origins and , the Exact type in allowOriginMatches seems to add a second spelling for the same thing. is not an exact match, so labelling it Exact may be confusing.

    Thinking out loud here, but one option would be to drop Exact and make the new field regex-only, e.g. allowOriginRegexes with a CORSOriginRegex type, and keep allow-all in allowOrigins. The *-rejection check would still apply.

    zhaohuabing zhaohuabing commented on Sep 09, 2026 07:09 UTC
    Contributor

    @codex review

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on code on Sep 09, 2026 07:14 UTC
    Code Review
    internal/gatewayapi/securitypolicy.go:1
    @@ -1748,6 +1754,21 @@ func (t *Translator) buildCORS(cors *egv1a1.CORS) *ir.CORS {
     		}
     	}
     
    +	for _, originRegex := range cors.AllowOriginRegexes {
    +		regexStr := string(originRegex)
    +		re, err := regexp.Compile(regexStr)

    <sub><sub>!P2 Badge</sub></sub> Accept the complete documented RE2 syntax

    When an origin pattern uses RE2's supported \C byte escape (for example, https://\C+\.example\.com), regexp.Compile rejects it because Go documents its dialect as RE2 syntax except for \C. The API explicitly promises RE2 syntax and Envoy's matcher uses RE2, so this causes a valid documented pattern to mark the SecurityPolicy invalid and replace affected routes with 500 responses; either validate with an Envoy-compatible RE2 parser or explicitly narrow the API contract.

    Useful? React with 👍 / 👎.

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Sep 09, 2026 07:14 UTC
    Reviewer

    💡 Codex Review

    Here are some automated review suggestions for this pull request.

    Reviewed commit: 1dbfdc0685

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

    </details>

    codecov[bot] codecov[bot] commented on Sep 09, 2026 07:20 UTC
    Bot

    Codecov Report


    :x: Patch coverage is 94.11765% with 1 line in your changes missing coverage. Please review.
    :white_check_mark: Project coverage is 81.32%. Comparing base (27abd5a) to head (ed68383).
    :warning: Report is 2 commits behind head on main.

    | Files with missing lines | Patch % | Lines |
    |---|---|---|
    | internal/gatewayapi/securitypolicy.go | 94.11% | 1 Missing :warning: |

    <details><summary>Additional details and impacted files</summary>

    @@            Coverage Diff             @@
    ##             main    #9966      +/-   ##
    ==========================================
    - Coverage   81.34%   81.32%   -0.02%     
    ==========================================
      Files         264      264              
      Lines       40973    40987      +14     
    ==========================================
    + Hits        33328    33333       +5     
    - Misses       7644     7653       +9     
      Partials        1        1              
    

    </details>

    :umbrella: View full report in Codecov by Harness.
    :loudspeaker: Have feedback on the report? Share it here.
    <details><summary> :rocket: New features to boost your workflow: </summary>

  • :snowflake: Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

  • :package: JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

  • </details>

    kahirokunn kahirokunn commented on code on Sep 09, 2026 07:29 UTC
    Code Review
    internal/gatewayapi/securitypolicy.go:1
    @@ -1748,6 +1754,21 @@ func (t *Translator) buildCORS(cors *egv1a1.CORS) *ir.CORS {
     		}
     	}
     
    +	for _, originRegex := range cors.AllowOriginRegexes {
    +		regexStr := string(originRegex)
    +		re, err := regexp.Compile(regexStr)

    Updated the API docs to specify Go's regexp syntax, without \C.

    kahirokunn kahirokunn commented on Sep 09, 2026 14:23 UTC
    Author

    @zhaohuabing Makes sense, done. Dropped Exact, renamed the field to allowOriginRegexes (type CORSOriginRegex), and left allow-all to allowOrigins. The * rejection check is still there.

    FWIW I had allowOriginRegexes in mind at first too, but went with the type: Exact | RegularExpression shape since that's what StringMatch fields like removeOnMatch use, and wasn't sure which way to go. Glad to have a call on it.

    PTAL when you get a chance.

    zhaohuabing zhaohuabing commented on Sep 14, 2026 07:02 UTC
    Contributor

    @codex review

    chatgpt-codex-connector[bot] chatgpt-codex-connector[bot] commented on Sep 14, 2026 07:06 UTC
    Bot

    Codex Review: Didn't find any major issues. :tada:

    Reviewed commit: 55319c4ba7

    <details> <summary>ℹ️ About Codex in GitHub</summary>
    <br/>

    Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review

  • Mark a draft as ready

  • Comment "@codex review".
  • If Codex has suggestions, it will comment; otherwise it will react with 👍.

    Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

    </details>

    zhaohuabing zhaohuabing approved these changes on Sep 14, 2026 07:19 UTC
    Approved Reviewer

    LGTM. Thanks!

    kahirokunn kahirokunn commented on Sep 14, 2026 07:33 UTC
    Author

    Thanks for your review 🙏

    kkk777-7 kkk777-7 approved these changes on Oct 01, 2026 14:25 UTC
    Approved Reviewer

    Approved these changes.

    kkk777-7 kkk777-7 commented on Oct 01, 2026 14:25 UTC
    Contributor

    LGTM, thanks!

    kkk777-7 kkk777-7 commented on Oct 01, 2026 14:25 UTC
    Contributor

    /retest

    kahirokunn kahirokunn commented on Oct 01, 2026 14:41 UTC
    Author

    Thanks for your review 😆

    Reviewers
    Assignees
    kahirokunn kahirokunn
    Labels
    risk: low confidence: 86.6% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 94.7% (HIGH) · Higher = larger blast radius
    94.7%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 86.6% · Lower = rushed or shallow review
    86.6%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 12.7% · Safe to merge
    12.7%