Skip to content
This repository was archived by the owner on Jan 16, 2021. It is now read-only.

Commit 4104bd1

Browse files
committed
FIX: Missing HSTS-header
1 parent daffe1f commit 4104bd1

File tree

4 files changed

+35
-2
lines changed

4 files changed

+35
-2
lines changed

gddo-server/debug.test

20 MB
Binary file not shown.

gddo-server/main.go

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -989,6 +989,18 @@ func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
989989
s.root.ServeHTTP(w, r)
990990
}
991991

992+
const HSTSHeaderKey = "Strict-Transport-Security"
993+
994+
func middlewareHSTS(next http.Handler) http.Handler {
995+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
996+
// This enforces the use of HTTPS for 1 year, including present and future subdomains.
997+
// Chrome and Mozilla Firefox maintain an HSTS preload list
998+
// that automatically informs the browser that the website can only be accessed through HTTPS.
999+
w.Header().Set(HSTSHeaderKey, "max-age=31536000; includeSubDomains; preload")
1000+
next.ServeHTTP(w, r)
1001+
})
1002+
}
1003+
9921004
func main() {
9931005
ctx := context.Background()
9941006
v, err := loadConfig(ctx, os.Args)
@@ -1016,8 +1028,9 @@ func main() {
10161028
}
10171029
}
10181030
}()
1019-
http.Handle("/", s)
1020-
log.Fatal(http.ListenAndServe(s.v.GetString(ConfigBindAddress), s))
1031+
ss := middlewareHSTS(s)
1032+
http.Handle("/", ss)
1033+
log.Fatal(http.ListenAndServe(s.v.GetString(ConfigBindAddress), ss))
10211034
}
10221035

10231036
// removeInternal removes the internal packages from the given package

gddo-server/main_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,9 @@
77
package main
88

99
import (
10+
"io"
11+
"net/http"
12+
"net/http/httptest"
1013
"reflect"
1114
"testing"
1215

@@ -111,3 +114,19 @@ func TestRemoveInternalPkgs(t *testing.T) {
111114
})
112115
}
113116
}
117+
118+
func TestMiddlewareHSTS(t *testing.T) {
119+
120+
req := httptest.NewRequest(http.MethodGet, "/", nil)
121+
respRecorder := httptest.NewRecorder()
122+
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
123+
io.WriteString(w, "")
124+
})
125+
handlerWithMiddlewareHSTS := middlewareHSTS(handler)
126+
handlerWithMiddlewareHSTS.ServeHTTP(respRecorder, req)
127+
want := "max-age=31536000; includeSubDomains; preload"
128+
got := respRecorder.Header().Get(HSTSHeaderKey)
129+
if got != want {
130+
t.Error("middlewareHSTS do not add HSTS header")
131+
}
132+
}

vendor/github.com/stretchr/testify

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)