From a9df64c8da3d9273e912785fc00aebeab18bad8c Mon Sep 17 00:00:00 2001 From: Vishal Rana Date: Mon, 15 Sep 2025 20:54:12 -0700 Subject: [PATCH] Improve secure middleware readability and add deprecation notice MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Refactor HSTS header construction using slice and strings.Join for better readability instead of nested fmt.Sprintf - Add deprecation notice for X-XSS-Protection header with CSP recommendation - Remove unused fmt import Improves code maintainability and provides better user guidance. Fixes #2799 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude --- middleware/secure.go | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/middleware/secure.go b/middleware/secure.go index c904abf1a..e2cbc4c63 100644 --- a/middleware/secure.go +++ b/middleware/secure.go @@ -4,7 +4,8 @@ package middleware import ( - "fmt" + "strconv" + "strings" "github.com/labstack/echo/v4" ) @@ -16,6 +17,11 @@ type SecureConfig struct { // XSSProtection provides protection against cross-site scripting attack (XSS) // by setting the `X-XSS-Protection` header. + // + // NOTE: The X-XSS-Protection header is deprecated in modern browsers. + // Consider using Content-Security-Policy (CSP) header instead for better XSS protection. + // This setting is primarily for backward compatibility with older browsers. + // // Optional. Default value "1; mode=block". XSSProtection string `yaml:"xss_protection"` @@ -119,14 +125,14 @@ func SecureWithConfig(config SecureConfig) echo.MiddlewareFunc { res.Header().Set(echo.HeaderXFrameOptions, config.XFrameOptions) } if (c.IsTLS() || (req.Header.Get(echo.HeaderXForwardedProto) == "https")) && config.HSTSMaxAge != 0 { - subdomains := "" + directives := []string{"max-age=" + strconv.Itoa(config.HSTSMaxAge)} if !config.HSTSExcludeSubdomains { - subdomains = "; includeSubdomains" + directives = append(directives, "includeSubdomains") } if config.HSTSPreloadEnabled { - subdomains = fmt.Sprintf("%s; preload", subdomains) + directives = append(directives, "preload") } - res.Header().Set(echo.HeaderStrictTransportSecurity, fmt.Sprintf("max-age=%d%s", config.HSTSMaxAge, subdomains)) + res.Header().Set(echo.HeaderStrictTransportSecurity, strings.Join(directives, "; ")) } if config.ContentSecurityPolicy != "" { if config.CSPReportOnly {