Added a simple Content-Security-Policy to mitigate clickjacking attempts.

custom-events
Jordan Wright 2020-08-20 10:39:23 -05:00
parent e3352f481e
commit 6df62e85fd
3 changed files with 28 additions and 1 deletions

View File

@ -155,7 +155,7 @@ func (as *AdminServer) registerRoutes() {
csrf.FieldName("csrf_token"), csrf.FieldName("csrf_token"),
csrf.Secure(as.config.UseTLS)) csrf.Secure(as.config.UseTLS))
adminHandler := csrfHandler(router) adminHandler := csrfHandler(router)
adminHandler = mid.Use(adminHandler.ServeHTTP, mid.CSRFExceptions, mid.GetContext) adminHandler = mid.Use(adminHandler.ServeHTTP, mid.CSRFExceptions, mid.GetContext, mid.ApplySecurityHeaders)
// Setup GZIP compression // Setup GZIP compression
gzipWrapper, _ := gziphandler.NewGzipLevelHandler(gzip.BestCompression) gzipWrapper, _ := gziphandler.NewGzipLevelHandler(gzip.BestCompression)

View File

@ -176,6 +176,17 @@ func RequirePermission(perm string) func(http.Handler) http.HandlerFunc {
} }
} }
// ApplySecurityHeaders applies various security headers according to best-
// practices.
func ApplySecurityHeaders(next http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
csp := "frame-ancestors 'none';"
w.Header().Set("Content-Security-Policy", csp)
w.Header().Set("X-Frame-Options", "DENY")
next.ServeHTTP(w, r)
}
}
// JSONError returns an error in JSON format with the given // JSONError returns an error in JSON format with the given
// status code and message // status code and message
func JSONError(w http.ResponseWriter, c int, m string) { func JSONError(w http.ResponseWriter, c int, m string) {

View File

@ -181,3 +181,19 @@ func TestPasswordResetRequired(t *testing.T) {
t.Fatalf("incorrect location header received. expected %s got %s", expectedLocation, gotLocation) t.Fatalf("incorrect location header received. expected %s got %s", expectedLocation, gotLocation)
} }
} }
func TestApplySecurityHeaders(t *testing.T) {
expected := map[string]string{
"Content-Security-Policy": "frame-ancestors 'none';",
"X-Frame-Options": "DENY",
}
req := httptest.NewRequest(http.MethodGet, "/", nil)
response := httptest.NewRecorder()
ApplySecurityHeaders(successHandler).ServeHTTP(response, req)
for header, value := range expected {
got := response.Header().Get(header)
if got != value {
t.Fatalf("incorrect security header received for %s: expected %s got %s", header, value, got)
}
}
}