Browse Source

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

custom-events
Jordan Wright 9 months ago
parent
commit
6df62e85fd
3 changed files with 28 additions and 1 deletions
  1. +1
    -1
      controllers/route.go
  2. +11
    -0
      middleware/middleware.go
  3. +16
    -0
      middleware/middleware_test.go

+ 1
- 1
controllers/route.go View File

@ -155,7 +155,7 @@ func (as *AdminServer) registerRoutes() {
csrf.FieldName("csrf_token"),
csrf.Secure(as.config.UseTLS))
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
gzipWrapper, _ := gziphandler.NewGzipLevelHandler(gzip.BestCompression)

+ 11
- 0
middleware/middleware.go 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
// status code and message
func JSONError(w http.ResponseWriter, c int, m string) {

+ 16
- 0
middleware/middleware_test.go View File

@ -181,3 +181,19 @@ func TestPasswordResetRequired(t *testing.T) {
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)
}
}
}

Loading…
Cancel
Save