security (improvement): add secure headers and disable asset indexing

This commit is contained in:
Mickael KERJEAN 2018-09-22 15:09:10 +10:00
parent 5b6af8934a
commit 6eca5d0840
2 changed files with 21 additions and 7 deletions

View file

@ -12,6 +12,7 @@ import (
func Init(a *App) *http.Server {
r := mux.NewRouter()
// API
session := r.PathPrefix("/api/session").Subrouter()
session.HandleFunc("", APIHandler(SessionIsValid, *a)).Methods("GET")
session.HandleFunc("", APIHandler(SessionAuthenticate, *a)).Methods("POST")
@ -33,8 +34,8 @@ func Init(a *App) *http.Server {
share.HandleFunc("/{id}", APIHandler(ShareUpsert, *a)).Methods("POST")
share.HandleFunc("/{id}", APIHandler(ShareDelete, *a)).Methods("DELETE")
// APP
r.HandleFunc("/api/config", CtxInjector(ConfigHandler, *a))
r.PathPrefix("/assets").Handler(StaticHandler("./data/public/", *a))
r.NotFoundHandler = IndexHandler("./data/public/index.html", *a)

View file

@ -12,25 +12,32 @@ import (
func StaticHandler(_path string, ctx App) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
header := res.Header()
header.Set("Content-Type", mime.TypeByExtension(filepath.Ext(req.URL.Path)))
header.Set("Cache-Control", "max-age=2592000")
SecureHeader(&header)
if strings.HasSuffix(req.URL.Path, "/") {
http.NotFound(res, req)
return
}
absPath := ctx.Helpers.AbsolutePath(_path)
fsrv := http.FileServer(http.Dir(absPath))
_, err := os.Open(path.Join(absPath, req.URL.Path+".gz"))
mType := mime.TypeByExtension(filepath.Ext(req.URL.Path))
res.Header().Set("Content-Type", mType)
if err == nil && strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") {
res.Header().Set("Content-Encoding", "gzip")
req.URL.Path += ".gz"
}
res.Header().Set("Cache-Control", "max-age=2592000")
fsrv.ServeHTTP(res, req)
})
}
func IndexHandler(_path string, ctx App) http.Handler {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
res.Header().Set("Content-Type", "text/html")
header := res.Header()
header.Set("Content-Type", "text/html")
SecureHeader(&header)
p := _path
if _, err := os.Open(path.Join(ctx.Config.Runtime.Dirname, p+".gz")); err == nil && strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") {
@ -40,3 +47,9 @@ func IndexHandler(_path string, ctx App) http.Handler {
http.ServeFile(res, req, ctx.Helpers.AbsolutePath(p))
})
}
func SecureHeader(header *http.Header) {
header.Set("X-XSS-Protection", "1; mode=block")
header.Set("X-Content-Type-Options", "nosniff")
header.Set("X-Frame-Options", "DENY")
}