Skip to content

Commit 5434a53

Browse files
hchoodvishr
authored andcommitted
Enable adding preload tag to HSTS header (#1247)
1 parent 08db4bd commit 5434a53

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
@@ -60,6 +60,12 @@ type (
6060
// have occurred instead of blocking the resource.
6161
// Optional. Default value false.
6262
CSPReportOnly bool `yaml:"csp_report_only"`
63+
64+
// HSTSPreloadEnabled will add the preload tag in the `Strict Transport Security`
65+
// header, which enables the domain to be included in the HSTS preload list
66+
// maintained by Chrome (and used by Firefox and Safari): https://hstspreload.org/
67+
// Optional. Default value false.
68+
HSTSPreloadEnabled bool `yaml:"hsts_preload_enabled"`
6369
}
6470
)
6571

@@ -70,6 +76,7 @@ var (
7076
XSSProtection: "1; mode=block",
7177
ContentTypeNosniff: "nosniff",
7278
XFrameOptions: "SAMEORIGIN",
79+
HSTSPreloadEnabled: false,
7380
}
7481
)
7582

@@ -112,6 +119,9 @@ func SecureWithConfig(config SecureConfig) echo.MiddlewareFunc {
112119
if !config.HSTSExcludeSubdomains {
113120
subdomains = "; includeSubdomains"
114121
}
122+
if config.HSTSPreloadEnabled {
123+
subdomains = fmt.Sprintf("%s; preload", subdomains)
124+
}
115125
res.Header().Set(echo.HeaderStrictTransportSecurity, fmt.Sprintf("max-age=%d%s", config.HSTSMaxAge, subdomains))
116126
}
117127
if config.ContentSecurityPolicy != "" {

middleware/secure_test.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,4 +62,25 @@ func TestSecure(t *testing.T) {
6262
assert.Equal(t, "max-age=3600; includeSubdomains", rec.Header().Get(echo.HeaderStrictTransportSecurity))
6363
assert.Equal(t, "default-src 'self'", rec.Header().Get(echo.HeaderContentSecurityPolicyReportOnly))
6464
assert.Equal(t, "", rec.Header().Get(echo.HeaderContentSecurityPolicy))
65+
66+
// Custom, with preload option enabled
67+
req.Header.Set(echo.HeaderXForwardedProto, "https")
68+
rec = httptest.NewRecorder()
69+
c = e.NewContext(req, rec)
70+
SecureWithConfig(SecureConfig{
71+
HSTSMaxAge: 3600,
72+
HSTSPreloadEnabled: true,
73+
})(h)(c)
74+
assert.Equal(t, "max-age=3600; includeSubdomains; preload", rec.Header().Get(echo.HeaderStrictTransportSecurity))
75+
76+
// Custom, with preload option enabled and subdomains excluded
77+
req.Header.Set(echo.HeaderXForwardedProto, "https")
78+
rec = httptest.NewRecorder()
79+
c = e.NewContext(req, rec)
80+
SecureWithConfig(SecureConfig{
81+
HSTSMaxAge: 3600,
82+
HSTSPreloadEnabled: true,
83+
HSTSExcludeSubdomains: true,
84+
})(h)(c)
85+
assert.Equal(t, "max-age=3600; preload", rec.Header().Get(echo.HeaderStrictTransportSecurity))
6586
}

0 commit comments

Comments
 (0)