Skip to content

Commit a9df64c

Browse files
vishrclaude
andcommitted
Improve secure middleware readability and add deprecation notice
- 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 <[email protected]>
1 parent f1ebc67 commit a9df64c

File tree

1 file changed

+11
-5
lines changed

1 file changed

+11
-5
lines changed

middleware/secure.go

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44
package middleware
55

66
import (
7-
"fmt"
7+
"strconv"
8+
"strings"
89

910
"github.com/labstack/echo/v4"
1011
)
@@ -16,6 +17,11 @@ type SecureConfig struct {
1617

1718
// XSSProtection provides protection against cross-site scripting attack (XSS)
1819
// by setting the `X-XSS-Protection` header.
20+
//
21+
// NOTE: The X-XSS-Protection header is deprecated in modern browsers.
22+
// Consider using Content-Security-Policy (CSP) header instead for better XSS protection.
23+
// This setting is primarily for backward compatibility with older browsers.
24+
//
1925
// Optional. Default value "1; mode=block".
2026
XSSProtection string `yaml:"xss_protection"`
2127

@@ -119,14 +125,14 @@ func SecureWithConfig(config SecureConfig) echo.MiddlewareFunc {
119125
res.Header().Set(echo.HeaderXFrameOptions, config.XFrameOptions)
120126
}
121127
if (c.IsTLS() || (req.Header.Get(echo.HeaderXForwardedProto) == "https")) && config.HSTSMaxAge != 0 {
122-
subdomains := ""
128+
directives := []string{"max-age=" + strconv.Itoa(config.HSTSMaxAge)}
123129
if !config.HSTSExcludeSubdomains {
124-
subdomains = "; includeSubdomains"
130+
directives = append(directives, "includeSubdomains")
125131
}
126132
if config.HSTSPreloadEnabled {
127-
subdomains = fmt.Sprintf("%s; preload", subdomains)
133+
directives = append(directives, "preload")
128134
}
129-
res.Header().Set(echo.HeaderStrictTransportSecurity, fmt.Sprintf("max-age=%d%s", config.HSTSMaxAge, subdomains))
135+
res.Header().Set(echo.HeaderStrictTransportSecurity, strings.Join(directives, "; "))
130136
}
131137
if config.ContentSecurityPolicy != "" {
132138
if config.CSPReportOnly {

0 commit comments

Comments
 (0)