From 37241fd6c06de9547bad783e43810d81989a0c26 Mon Sep 17 00:00:00 2001 From: barco Date: Wed, 2 Oct 2024 15:47:32 +0200 Subject: [PATCH] feat: add security headers --- pkg/ui/handlers.go | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/pkg/ui/handlers.go b/pkg/ui/handlers.go index 37e3f6cfb..0cbdadbdb 100644 --- a/pkg/ui/handlers.go +++ b/pkg/ui/handlers.go @@ -7,8 +7,9 @@ import ( "path" "strings" - "github.com/canonical/identity-platform-login-ui/internal/logging" "github.com/go-chi/chi/v5" + + "github.com/canonical/identity-platform-login-ui/internal/logging" ) const UI = "/ui" @@ -19,8 +20,34 @@ type API struct { } func (a *API) RegisterEndpoints(mux *chi.Mux) { + + uiHandlerWithHeaders := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // Set the UI headers + // Disables the FLoC (Federated Learning of Cohorts) feature on the browser, + // preventing the current page from being included in the user's FLoC calculation. + // FLoC is a proposed replacement for third-party cookies to enable interest-based advertising. + w.Header().Set("Permissions-Policy", "interest-cohort=()") + // Prevents the browser from trying to guess the MIME type, which can have security implications. + // This tells the browser to strictly follow the MIME type provided in the Content-Type header. + w.Header().Set("X-Content-Type-Options", "nosniff") + // Restricts the page from being displayed in a frame, iframe, or object to avoid click jacking attacks, + // but allows it if the site is navigating to the same origin. + w.Header().Set("X-Frame-Options", "SAMEORIGIN") + // Sets the Content Security Policy (CSP) for the page, which helps mitigate XSS attacks and data injection attacks. + // The policy allows loading resources (scripts, styles, images, etc.) only from the same origin ('self'), data URLs, and all subdomains of ubuntu.com. + w.Header().Set("Content-Security-Policy", "default-src 'self' data: https://*.ubuntu.com; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'") + + // `no-store`: This will tell any cache system not to cache the index.html file + // `no-cache`: This will tell any cache system to check if there is a newer version in the server + // `must-revalidate`: This will tell any cache system to check for newer version of the file + // this is considered best practice with SPAs + w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") + + a.uiFiles(w, r) + }) + // TODO @shipperizer unsure if we deal with any POST/PUT/PATCH via js - mux.HandleFunc(fmt.Sprintf("%s/*", UI), a.uiFiles) + mux.HandleFunc(fmt.Sprintf("%s/*", UI), uiHandlerWithHeaders) }