Skip to content

feat(security): trusted proxies, CORS allowlist, HTTPS security headers - #6297

Closed
xvyimu wants to merge 1 commit into
QuantumNous:mainfrom
xvyimu:pr/b1-security-headers-cors-proxy
Closed

xvyimu wants to merge 1 commit into
QuantumNous:mainfrom
xvyimu:pr/b1-security-headers-cors-proxy

Conversation

@xvyimu

@xvyimu xvyimu commented Jul 18, 2026 •

Copy link
Copy Markdown

Summary

Small, independently reviewable security middleware PR (extracted from the withdrawn large hardening effort).

  • Trusted proxies: TRUSTED_PROXY_CIDRS configures Gin SetTrustedProxies (default empty = do not trust X-Forwarded-For / X-Real-IP).
  • CORS: replace AllowAllOrigins with explicit CORS_ALLOWED_ORIGINS allowlist (comma-separated origins; no wildcards). Same-origin deployments need no config.
  • Security headers: X-Content-Type-Options, Referrer-Policy, X-Frame-Options; Strict-Transport-Security only when the request is HTTPS (including X-Forwarded-Proto from a reverse proxy).

Default behavior stays safe for single-host / same-origin deploys. Operators behind Cloudflare/Tunnel should set TRUSTED_PROXY_CIDRS appropriately (e.g. 127.0.0.1/32 when only local reverse proxy terminates TLS).

Test plan

  • go test ./middleware ./
  • Manual: with empty env, no Access-Control-Allow-Origin: *
  • Manual: CORS_ALLOWED_ORIGINS=https://example.com only allows that origin
  • Manual: HTTPS (or X-Forwarded-Proto: https) sets HSTS; plain HTTP does not

Notes

  • No UI / channel / billing changes.
  • Does not include session-refresh, SPA routing, adaptive balance, or delivery-seam work (those will be separate PRs).

Summary by CodeRabbit

  • New Features

    • Added configurable CORS origin allowlists with credential support and stricter validation.
    • Added standard security response headers, including HTTPS-only HSTS protection.
    • Added trusted reverse-proxy configuration for safer client IP handling.
    • Documented the new security-related environment settings and their defaults.
  • Bug Fixes

    • Prevented unrestricted cross-origin access when no trusted origins are configured.
    • Rejected invalid or wildcard origin and proxy configurations.

…eaders

- Honor TRUSTED_PROXY_CIDRS for Gin client IP / X-Forwarded-* (default: trust none)
- Replace AllowAllOrigins CORS with explicit CORS_ALLOWED_ORIGINS allowlist
- Add SecurityHeaders (nosniff, Referrer-Policy, X-Frame-Options, conditional HSTS)
@coderabbitai

coderabbitai Bot commented Jul 18, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

The HTTP server now configures trusted proxies, applies security response headers, and replaces permissive CORS behavior with validated environment-based origin allowlists and fallback configuration.

Changes

HTTP security controls

Layer / File(s) Summary
CORS origin allowlist
.env.example, middleware/cors.go, middleware/cors_test.go
CORS origins are validated, normalized, deduplicated, and sourced from CORS_ALLOWED_ORIGINS or SESSION_COOKIE_TRUSTED_URL; tests cover rejection, credentials, fallback, invalid values, and trailing slashes.
Trusted proxy startup configuration
trusted_proxy.go, trusted_proxy_test.go, main.go
Gin trusted proxies are configured from TRUSTED_PROXY_CIDRS, invalid entries abort startup, and tests verify forwarded client IP behavior.
Security response headers
middleware/security_headers.go, middleware/security_headers_test.go, main.go
The middleware sets common security headers and adds HSTS for direct TLS or HTTPS forwarded-protocol requests.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Suggested reviewers: calcium-ion

Poem

I’m a rabbit with headers, alert in the night,
Guarding each origin, keeping paths right.
Trusted hops now whisper, “Forwarded is true,”
While HSTS blooms when HTTPS comes through.
CORS gates swing softly, secure and bright—
Hop-hop hooray for a safer flight!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.52% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately captures the main security-focused changes: trusted proxy config, CORS allowlisting, and HTTPS security headers.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@middleware/cors_test.go`:
- Around line 36-38: Replace non-fatal response checks throughout
middleware/cors_test.go, including require.Empty, require.Equal, and
require.NotEqual, with assert equivalents and add the assert import; retain
require only for setup/fatal checks. In trusted_proxy_test.go, replace the
clientIP require.Equal checks at lines 17-18 and 25 with assert.Equal and add
the corresponding import, while leaving require.NoError and require.Error
unchanged.

In `@middleware/security_headers_test.go`:
- Around line 3-48: Refactor TestSecurityHeadersSetsHSTSOnlyForHTTPS into a
table-driven test that centralizes the repeated Gin engine and request setup
while varying HTTP, forwarded HTTPS, and direct TLS cases. Replace non-fatal
header and status comparisons with testify/assert, retaining require only for
setup failures, and add assertions covering Referrer-Policy and X-Frame-Options
in every case.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7910eab3-0226-43b2-ae0d-5417ff4e04dc

📥 Commits

Reviewing files that changed from the base of the PR and between 5a6c53d and 935068b.

📒 Files selected for processing (8)
  • .env.example
  • main.go
  • middleware/cors.go
  • middleware/cors_test.go
  • middleware/security_headers.go
  • middleware/security_headers_test.go
  • trusted_proxy.go
  • trusted_proxy_test.go

Comment thread middleware/cors_test.go
Comment on lines +36 to +38
require.Empty(t, recorder.Header().Get("Access-Control-Allow-Origin"))
require.NotEqual(t, http.StatusNoContent, recorder.Code)
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use assert for non-fatal value checks instead of require.

Both test files violate the coding guideline for assertions: "New or substantially rewritten Go backend tests must use testify/require for setup and fatal assertions and testify/assert for non-fatal value checks." Using assert ensures that if multiple value checks fail in a single test, all failures are reported rather than halting on the first one.

  • middleware/cors_test.go#L36-L38: Replace require.Empty, require.Equal, and require.NotEqual with their assert equivalents for verifying the response here and throughout the file. Remember to add "github.com/stretchr/testify/assert" to the imports block.
  • trusted_proxy_test.go#L17-L18: Replace require.Equal with assert.Equal for the clientIP value check here and on line 25, and add the corresponding assert import. (The require.NoError on lines 15, 23, and require.Error on line 30 are correct, as they validate test setup).
📍 Affects 2 files
  • middleware/cors_test.go#L36-L38 (this comment)
  • trusted_proxy_test.go#L17-L18
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@middleware/cors_test.go` around lines 36 - 38, Replace non-fatal response
checks throughout middleware/cors_test.go, including require.Empty,
require.Equal, and require.NotEqual, with assert equivalents and add the assert
import; retain require only for setup/fatal checks. In trusted_proxy_test.go,
replace the clientIP require.Equal checks at lines 17-18 and 25 with
assert.Equal and add the corresponding import, while leaving require.NoError and
require.Error unchanged.

Source: Coding guidelines

Comment on lines +3 to +48
import (
"crypto/tls"
"net/http"
"net/http/httptest"
"testing"

"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)

func TestSecurityHeadersSetsHSTSOnlyForHTTPS(t *testing.T) {
gin.SetMode(gin.TestMode)

t.Run("plain http no hsts", func(t *testing.T) {
engine := gin.New()
engine.Use(SecurityHeaders())
engine.GET("/x", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
rec := httptest.NewRecorder()
engine.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/x", nil))
require.Equal(t, http.StatusOK, rec.Code)
require.Empty(t, rec.Header().Get("Strict-Transport-Security"))
require.Equal(t, "nosniff", rec.Header().Get("X-Content-Type-Options"))
})

t.Run("x-forwarded-proto https sets hsts", func(t *testing.T) {
engine := gin.New()
engine.Use(SecurityHeaders())
engine.GET("/x", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/x", nil)
req.Header.Set("X-Forwarded-Proto", "https")
engine.ServeHTTP(rec, req)
require.Equal(t, "max-age=15768000", rec.Header().Get("Strict-Transport-Security"))
})

t.Run("direct tls sets hsts", func(t *testing.T) {
engine := gin.New()
engine.Use(SecurityHeaders())
engine.GET("/x", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/x", nil)
req.TLS = &tls.ConnectionState{}
engine.ServeHTTP(rec, req)
require.Equal(t, "max-age=15768000", rec.Header().Get("Strict-Transport-Security"))
})
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use assert for value checks and prefer table-driven tests.

As per coding guidelines, backend tests should prefer deterministic table tests and must use testify/assert for non-fatal value checks (like header comparisons), reserving testify/require for setup and fatal assertions.

Refactoring to a table test eliminates the repetitive Gin engine setup across subtests and allows you to easily assert the presence of the other security headers (Referrer-Policy and X-Frame-Options) that are currently missing from the coverage.

♻️ Proposed refactor
 import (
 	"crypto/tls"
 	"net/http"
 	"net/http/httptest"
 	"testing"
 
 	"github.com/gin-gonic/gin"
+	"github.com/stretchr/testify/assert"
 	"github.com/stretchr/testify/require"
 )
 
 func TestSecurityHeadersSetsHSTSOnlyForHTTPS(t *testing.T) {
 	gin.SetMode(gin.TestMode)
 
-	t.Run("plain http no hsts", func(t *testing.T) {
-		engine := gin.New()
-		engine.Use(SecurityHeaders())
-		engine.GET("/x", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
-		rec := httptest.NewRecorder()
-		engine.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/x", nil))
-		require.Equal(t, http.StatusOK, rec.Code)
-		require.Empty(t, rec.Header().Get("Strict-Transport-Security"))
-		require.Equal(t, "nosniff", rec.Header().Get("X-Content-Type-Options"))
-	})
-
-	t.Run("x-forwarded-proto https sets hsts", func(t *testing.T) {
-		engine := gin.New()
-		engine.Use(SecurityHeaders())
-		engine.GET("/x", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
-		rec := httptest.NewRecorder()
-		req := httptest.NewRequest(http.MethodGet, "/x", nil)
-		req.Header.Set("X-Forwarded-Proto", "https")
-		engine.ServeHTTP(rec, req)
-		require.Equal(t, "max-age=15768000", rec.Header().Get("Strict-Transport-Security"))
-	})
-
-	t.Run("direct tls sets hsts", func(t *testing.T) {
-		engine := gin.New()
-		engine.Use(SecurityHeaders())
-		engine.GET("/x", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
-		rec := httptest.NewRecorder()
-		req := httptest.NewRequest(http.MethodGet, "/x", nil)
-		req.TLS = &tls.ConnectionState{}
-		engine.ServeHTTP(rec, req)
-		require.Equal(t, "max-age=15768000", rec.Header().Get("Strict-Transport-Security"))
-	})
+	tests := []struct {
+		name         string
+		setupReq     func() *http.Request
+		expectedHSTS string
+	}{
+		{
+			name: "plain http no hsts",
+			setupReq: func() *http.Request {
+				return httptest.NewRequest(http.MethodGet, "/x", nil)
+			},
+			expectedHSTS: "",
+		},
+		{
+			name: "x-forwarded-proto https sets hsts",
+			setupReq: func() *http.Request {
+				req := httptest.NewRequest(http.MethodGet, "/x", nil)
+				req.Header.Set("X-Forwarded-Proto", "https")
+				return req
+			},
+			expectedHSTS: "max-age=15768000",
+		},
+		{
+			name: "direct tls sets hsts",
+			setupReq: func() *http.Request {
+				req := httptest.NewRequest(http.MethodGet, "/x", nil)
+				req.TLS = &tls.ConnectionState{}
+				return req
+			},
+			expectedHSTS: "max-age=15768000",
+		},
+	}
+
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			engine := gin.New()
+			engine.Use(SecurityHeaders())
+			engine.GET("/x", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
+			
+			rec := httptest.NewRecorder()
+			engine.ServeHTTP(rec, tt.setupReq())
+			
+			require.Equal(t, http.StatusOK, rec.Code) // fatal assertion for setup
+			if tt.expectedHSTS == "" {
+				assert.Empty(t, rec.Header().Get("Strict-Transport-Security"))
+			} else {
+				assert.Equal(t, tt.expectedHSTS, rec.Header().Get("Strict-Transport-Security"))
+			}
+			assert.Equal(t, "nosniff", rec.Header().Get("X-Content-Type-Options"))
+			assert.Equal(t, "strict-origin-when-cross-origin", rec.Header().Get("Referrer-Policy"))
+			assert.Equal(t, "SAMEORIGIN", rec.Header().Get("X-Frame-Options"))
+		})
+	}
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
import (
"crypto/tls"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
)
func TestSecurityHeadersSetsHSTSOnlyForHTTPS(t *testing.T) {
gin.SetMode(gin.TestMode)
t.Run("plain http no hsts", func(t *testing.T) {
engine := gin.New()
engine.Use(SecurityHeaders())
engine.GET("/x", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
rec := httptest.NewRecorder()
engine.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/x", nil))
require.Equal(t, http.StatusOK, rec.Code)
require.Empty(t, rec.Header().Get("Strict-Transport-Security"))
require.Equal(t, "nosniff", rec.Header().Get("X-Content-Type-Options"))
})
t.Run("x-forwarded-proto https sets hsts", func(t *testing.T) {
engine := gin.New()
engine.Use(SecurityHeaders())
engine.GET("/x", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/x", nil)
req.Header.Set("X-Forwarded-Proto", "https")
engine.ServeHTTP(rec, req)
require.Equal(t, "max-age=15768000", rec.Header().Get("Strict-Transport-Security"))
})
t.Run("direct tls sets hsts", func(t *testing.T) {
engine := gin.New()
engine.Use(SecurityHeaders())
engine.GET("/x", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
rec := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/x", nil)
req.TLS = &tls.ConnectionState{}
engine.ServeHTTP(rec, req)
require.Equal(t, "max-age=15768000", rec.Header().Get("Strict-Transport-Security"))
})
}
import (
"crypto/tls"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestSecurityHeadersSetsHSTSOnlyForHTTPS(t *testing.T) {
gin.SetMode(gin.TestMode)
tests := []struct {
name string
setupReq func() *http.Request
expectedHSTS string
}{
{
name: "plain http no hsts",
setupReq: func() *http.Request {
return httptest.NewRequest(http.MethodGet, "/x", nil)
},
expectedHSTS: "",
},
{
name: "x-forwarded-proto https sets hsts",
setupReq: func() *http.Request {
req := httptest.NewRequest(http.MethodGet, "/x", nil)
req.Header.Set("X-Forwarded-Proto", "https")
return req
},
expectedHSTS: "max-age=15768000",
},
{
name: "direct tls sets hsts",
setupReq: func() *http.Request {
req := httptest.NewRequest(http.MethodGet, "/x", nil)
req.TLS = &tls.ConnectionState{}
return req
},
expectedHSTS: "max-age=15768000",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
engine := gin.New()
engine.Use(SecurityHeaders())
engine.GET("/x", func(c *gin.Context) { c.String(http.StatusOK, "ok") })
rec := httptest.NewRecorder()
engine.ServeHTTP(rec, tt.setupReq())
require.Equal(t, http.StatusOK, rec.Code)
if tt.expectedHSTS == "" {
assert.Empty(t, rec.Header().Get("Strict-Transport-Security"))
} else {
assert.Equal(t, tt.expectedHSTS, rec.Header().Get("Strict-Transport-Security"))
}
assert.Equal(t, "nosniff", rec.Header().Get("X-Content-Type-Options"))
assert.Equal(t, "strict-origin-when-cross-origin", rec.Header().Get("Referrer-Policy"))
assert.Equal(t, "SAMEORIGIN", rec.Header().Get("X-Frame-Options"))
})
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@middleware/security_headers_test.go` around lines 3 - 48, Refactor
TestSecurityHeadersSetsHSTSOnlyForHTTPS into a table-driven test that
centralizes the repeated Gin engine and request setup while varying HTTP,
forwarded HTTPS, and direct TLS cases. Replace non-fatal header and status
comparisons with testify/assert, retaining require only for setup failures, and
add assertions covering Referrer-Policy and X-Frame-Options in every case.

Source: Coding guidelines

@xvyimu

xvyimu commented Jul 19, 2026

Copy link
Copy Markdown
Author

No blocking functional findings from CodeRabbit (test-style nits only). Leaving as OPEN for maintainer review; happy to table-drive assert style if requested.

JacksonsY added a commit to JacksonsY/new-api that referenced this pull request Jul 19, 2026
移植自上游 PR QuantumNous#6297 的安全头部分(trusted proxies 已在 5906f85
移植;CORS 部分与本 fork 自有方案冲突,不取)。新增 SecurityHeaders
中间件:X-Content-Type-Options=nosniff、Referrer-Policy、
X-Frame-Options=SAMEORIGIN;HSTS 仅在判定 HTTPS(r.TLS 或最左
X-Forwarded-Proto=https)时发送,避免本机 http 被浏览器错误 HSTS。
挂在中间件链靠前位置。补 HTTP/XFP/TLS 三态测试。

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@xvyimu

xvyimu commented Jul 23, 2026

Copy link
Copy Markdown
Author

Withdrawing this contribution. No further action needed from maintainers. Closing and deleting the head branch.

@xvyimu xvyimu closed this Jul 23, 2026
@xvyimu
xvyimu deleted the pr/b1-security-headers-cors-proxy branch July 23, 2026 05:44
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.

2 participants