Skip to content

Commit 22a9859

Browse files
committed
Enable adding preload tag to HSTS header
1 parent 3f8b45c commit 22a9859

File tree

2 files changed

+31
-0
lines changed

2 files changed

+31
-0
lines changed

middleware/secure.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,12 @@ type (
5353
// trusted web page context.
5454
// Optional. Default value "".
5555
ContentSecurityPolicy string `yaml:"content_security_policy"`
56+
57+
// HSTSPreloadEnabled will add the preload tag in the `Strict Transport Security`
58+
// header, which enables the domain to be included in the HSTS preload list
59+
// maintained by Chrome (and used by Firefox and Safari): https://hstspreload.org/
60+
// Optional. Default value false.
61+
HSTSPreloadEnabled bool `yaml:"hsts_preload_enabled"`
5662
}
5763
)
5864

@@ -63,6 +69,7 @@ var (
6369
XSSProtection: "1; mode=block",
6470
ContentTypeNosniff: "nosniff",
6571
XFrameOptions: "SAMEORIGIN",
72+
HSTSPreloadEnabled: false,
6673
}
6774
)
6875

@@ -105,6 +112,9 @@ func SecureWithConfig(config SecureConfig) echo.MiddlewareFunc {
105112
if !config.HSTSExcludeSubdomains {
106113
subdomains = "; includeSubdomains"
107114
}
115+
if config.HSTSPreloadEnabled {
116+
subdomains = fmt.Sprintf("%s; preload", subdomains)
117+
}
108118
res.Header().Set(echo.HeaderStrictTransportSecurity, fmt.Sprintf("max-age=%d%s", config.HSTSMaxAge, subdomains))
109119
}
110120
if config.ContentSecurityPolicy != "" {

middleware/secure_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,4 +42,25 @@ func TestSecure(t *testing.T) {
4242
assert.Equal(t, "", rec.Header().Get(echo.HeaderXFrameOptions))
4343
assert.Equal(t, "max-age=3600; includeSubdomains", rec.Header().Get(echo.HeaderStrictTransportSecurity))
4444
assert.Equal(t, "default-src 'self'", rec.Header().Get(echo.HeaderContentSecurityPolicy))
45+
46+
// Custom, with preload option enabled
47+
req.Header.Set(echo.HeaderXForwardedProto, "https")
48+
rec = httptest.NewRecorder()
49+
c = e.NewContext(req, rec)
50+
SecureWithConfig(SecureConfig{
51+
HSTSMaxAge: 3600,
52+
HSTSPreloadEnabled: true,
53+
})(h)(c)
54+
assert.Equal(t, "max-age=3600; includeSubdomains; preload", rec.Header().Get(echo.HeaderStrictTransportSecurity))
55+
56+
// Custom, with preload option enabled and subdomains excluded
57+
req.Header.Set(echo.HeaderXForwardedProto, "https")
58+
rec = httptest.NewRecorder()
59+
c = e.NewContext(req, rec)
60+
SecureWithConfig(SecureConfig{
61+
HSTSMaxAge: 3600,
62+
HSTSPreloadEnabled: true,
63+
HSTSExcludeSubdomains: true,
64+
})(h)(c)
65+
assert.Equal(t, "max-age=3600; preload", rec.Header().Get(echo.HeaderStrictTransportSecurity))
4566
}

0 commit comments

Comments
 (0)