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

FIX: Missing HSTS-header #562

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions gddo-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -1016,8 +1016,9 @@ func main() {
}
}
}()
http.Handle("/", s)
log.Fatal(http.ListenAndServe(s.v.GetString(ConfigBindAddress), s))
ss := httputil.HSTS(s)
http.Handle("/", ss)
log.Fatal(http.ListenAndServe(s.v.GetString(ConfigBindAddress), ss))
}

// removeInternal removes the internal packages from the given package
Expand Down
14 changes: 14 additions & 0 deletions httputil/middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package httputil

import "net/http"

// HSTS will automatically inform the browser that the website can only be accessed through HTTPS.
func HSTS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// This enforces the use of HTTPS for 1 year, including present and future subdomains.
// Chrome and Mozilla Firefox maintain an HSTS preload list
// issue : golang.org/issue/26162
w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload")
next.ServeHTTP(w, r)
})
}
23 changes: 23 additions & 0 deletions httputil/middleware_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package httputil

import (
"io"
"net/http"
"net/http/httptest"
"testing"
)

func TestHSTS(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
respRecorder := httptest.NewRecorder()
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "")
})
handlerWithMiddlewareHSTS := HSTS(handler)
handlerWithMiddlewareHSTS.ServeHTTP(respRecorder, req)
want := "max-age=31536000; includeSubDomains; preload"
got := respRecorder.Header().Get("Strict-Transport-Security")
if got != want {
t.Error("middlewareHSTS do not add HSTS header")
}
}