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

Commit

Permalink
FIX: Missing HSTS-header
Browse files Browse the repository at this point in the history
  • Loading branch information
AlphaWong committed Jul 4, 2018
1 parent daffe1f commit 4104bd1
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 2 deletions.
Binary file added gddo-server/debug.test
Binary file not shown.
17 changes: 15 additions & 2 deletions gddo-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -989,6 +989,18 @@ func (s *server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
s.root.ServeHTTP(w, r)
}

const HSTSHeaderKey = "Strict-Transport-Security"

func middlewareHSTS(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
// that automatically informs the browser that the website can only be accessed through HTTPS.
w.Header().Set(HSTSHeaderKey, "max-age=31536000; includeSubDomains; preload")
next.ServeHTTP(w, r)
})
}

func main() {
ctx := context.Background()
v, err := loadConfig(ctx, os.Args)
Expand Down Expand Up @@ -1016,8 +1028,9 @@ func main() {
}
}
}()
http.Handle("/", s)
log.Fatal(http.ListenAndServe(s.v.GetString(ConfigBindAddress), s))
ss := middlewareHSTS(s)
http.Handle("/", ss)
log.Fatal(http.ListenAndServe(s.v.GetString(ConfigBindAddress), ss))
}

// removeInternal removes the internal packages from the given package
Expand Down
19 changes: 19 additions & 0 deletions gddo-server/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@
package main

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

Expand Down Expand Up @@ -111,3 +114,19 @@ func TestRemoveInternalPkgs(t *testing.T) {
})
}
}

func TestMiddlewareHSTS(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 := middlewareHSTS(handler)
handlerWithMiddlewareHSTS.ServeHTTP(respRecorder, req)
want := "max-age=31536000; includeSubDomains; preload"
got := respRecorder.Header().Get(HSTSHeaderKey)
if got != want {
t.Error("middlewareHSTS do not add HSTS header")
}
}
1 change: 1 addition & 0 deletions vendor/github.com/stretchr/testify
Submodule testify added at f35b8a

0 comments on commit 4104bd1

Please sign in to comment.