Repository navigation
Conversation
…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)
WalkthroughThe HTTP server now configures trusted proxies, applies security response headers, and replaces permissive CORS behavior with validated environment-based origin allowlists and fallback configuration. ChangesHTTP security controls
Estimated code review effort: 3 (Moderate) | ~20 minutes Suggested reviewers: Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (8)
.env.examplemain.gomiddleware/cors.gomiddleware/cors_test.gomiddleware/security_headers.gomiddleware/security_headers_test.gotrusted_proxy.gotrusted_proxy_test.go
| require.Empty(t, recorder.Header().Get("Access-Control-Allow-Origin")) | ||
| require.NotEqual(t, http.StatusNoContent, recorder.Code) | ||
| } |
There was a problem hiding this comment.
📐 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: Replacerequire.Empty,require.Equal, andrequire.NotEqualwith theirassertequivalents 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: Replacerequire.Equalwithassert.Equalfor theclientIPvalue check here and on line 25, and add the correspondingassertimport. (Therequire.NoErroron lines 15, 23, andrequire.Erroron 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
| 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")) | ||
| }) | ||
| } |
There was a problem hiding this comment.
📐 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.
| 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
|
No blocking functional findings from CodeRabbit (test-style nits only). Leaving as OPEN for maintainer review; happy to table-drive assert style if requested. |
移植自上游 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]>
|
Withdrawing this contribution. No further action needed from maintainers. Closing and deleting the head branch. |
Summary
Small, independently reviewable security middleware PR (extracted from the withdrawn large hardening effort).
TRUSTED_PROXY_CIDRSconfigures GinSetTrustedProxies(default empty = do not trustX-Forwarded-For/X-Real-IP).AllowAllOriginswith explicitCORS_ALLOWED_ORIGINSallowlist (comma-separated origins; no wildcards). Same-origin deployments need no config.X-Content-Type-Options,Referrer-Policy,X-Frame-Options;Strict-Transport-Securityonly when the request is HTTPS (includingX-Forwarded-Protofrom a reverse proxy).Default behavior stays safe for single-host / same-origin deploys. Operators behind Cloudflare/Tunnel should set
TRUSTED_PROXY_CIDRSappropriately (e.g.127.0.0.1/32when only local reverse proxy terminates TLS).Test plan
go test ./middleware ./Access-Control-Allow-Origin: *CORS_ALLOWED_ORIGINS=https://example.comonly allows that originX-Forwarded-Proto: https) sets HSTS; plain HTTP does notNotes
Summary by CodeRabbit
New Features
Bug Fixes