From 119dbaef97f2dde97d1329b87cb3724fd88786f9 Mon Sep 17 00:00:00 2001 From: Daniel Date: Mon, 1 Aug 2022 11:03:37 +0200 Subject: [PATCH] Move security headers to the start of the router --- api/router.go | 36 ++++++++++++++++++------------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/api/router.go b/api/router.go index 953768d..7f9ae3d 100644 --- a/api/router.go +++ b/api/router.go @@ -105,6 +105,24 @@ func (mh *mainHandler) handle(w http.ResponseWriter, r *http.Request) error { tracer.Submit() }() + // Add security headers. + w.Header().Set("Referrer-Policy", "no-referrer") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("X-Frame-Options", "deny") + w.Header().Set("X-XSS-Protection", "1; mode=block") + w.Header().Set("X-DNS-Prefetch-Control", "off") + + // Add CSP Header in production mode. + if !devMode() { + w.Header().Set( + "Content-Security-Policy", + "default-src 'self'; "+ + "connect-src https://*.safing.io 'self'; "+ + "style-src 'self' 'unsafe-inline'; "+ + "img-src 'self' data:", + ) + } + // Check Cross-Origin Requests. origin := r.Header.Get("Origin") isPreflighCheck := false @@ -202,24 +220,6 @@ func (mh *mainHandler) handle(w http.ResponseWriter, r *http.Request) error { return nil } - // Add security headers. - w.Header().Set("Referrer-Policy", "no-referrer") - w.Header().Set("X-Content-Type-Options", "nosniff") - w.Header().Set("X-Frame-Options", "deny") - w.Header().Set("X-XSS-Protection", "1; mode=block") - w.Header().Set("X-DNS-Prefetch-Control", "off") - - // Add CSP Header in production mode. - if !devMode() { - w.Header().Set( - "Content-Security-Policy", - "default-src 'self'; "+ - "connect-src https://*.safing.io 'self'; "+ - "style-src 'self' 'unsafe-inline'; "+ - "img-src 'self' data:", - ) - } - // At this point we know the method is allowed and there's a handler for the request. // If this is just a CORS-Preflight, we'll accept the request with StatusOK now. // There's no point in trying to authenticate the request because the Browser will