fleet/server/service/frontend.go
Roberto Dip 4042f8d826
add browser-related security headers to HTML responses (#8180)
related to #8031, this adds the following headers to HTML responses:

- Strict-Transport-Security: informs browsers that the site should only
  be accessed using HTTPS, and that any future attempts to access it
  using HTTP should automatically be converted to HTTPS.
- X-Frames-Options: disallows embedding the UI in other sites via
  <frame>, <iframe>, <embed> or <object>, which can prevent attacks like
  clickjacking.
- X-Content-Type-Options: prevents browsers from trying to guess the MIME
  type which can cause browsers to transform non-executable content into
  executable content.
- Referrer-Policy: prevents leaking the origin of the referrer in the
  Referer.

additionally, this ensures we set `X-Content-Type-Options` for CSV and
installer responses.
2022-10-12 10:19:21 -03:00

66 lines
1.5 KiB
Go

package service
import (
"html/template"
"io"
"net/http"
assetfs "github.com/elazarl/go-bindata-assetfs"
"github.com/fleetdm/fleet/v4/server/bindata"
"github.com/go-kit/kit/log"
)
func newBinaryFileSystem(root string) *assetfs.AssetFS {
return &assetfs.AssetFS{
Asset: bindata.Asset,
AssetDir: bindata.AssetDir,
AssetInfo: bindata.AssetInfo,
Prefix: root,
}
}
func ServeFrontend(urlPrefix string, sandbox bool, logger log.Logger) http.Handler {
herr := func(w http.ResponseWriter, err string) {
logger.Log("err", err)
http.Error(w, err, http.StatusInternalServerError)
}
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
writeBrowserSecurityHeaders(w)
fs := newBinaryFileSystem("/frontend")
file, err := fs.Open("templates/react.tmpl")
if err != nil {
herr(w, "load react template: "+err.Error())
return
}
data, err := io.ReadAll(file)
if err != nil {
herr(w, "read bindata file: "+err.Error())
return
}
t, err := template.New("react").Parse(string(data))
if err != nil {
herr(w, "create react template: "+err.Error())
return
}
serverType := "on-premise"
if sandbox {
serverType = "sandbox"
}
if err := t.Execute(w, struct {
URLPrefix string
ServerType string
}{
URLPrefix: urlPrefix,
ServerType: serverType,
}); err != nil {
herr(w, "execute react template: "+err.Error())
return
}
})
}
func ServeStaticAssets(path string) http.Handler {
return http.StripPrefix(path, http.FileServer(newBinaryFileSystem("/assets")))
}