1
0
mirror of https://github.com/labstack/echo.git synced 2025-11-27 22:38:25 +02:00

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 <noreply@anthropic.com>
This commit is contained in:
Vishal Rana
2025-09-15 20:54:12 -07:00
parent f1ebc67c56
commit a9df64c8da

View File

@@ -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 {