From 9b4dde7430105471edd7dc16e6d6b5b82563f077 Mon Sep 17 00:00:00 2001 From: Kristian Bremberg <114284895+KristianGrafana@users.noreply.github.com> Date: Tue, 1 Aug 2023 10:27:44 +0200 Subject: [PATCH] Modify Content-Security-Policy for Swagger UI (#63568) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Modify Content-Security-Policy for Swagger UI * check if CSP is empty Co-authored-by: João Calisto * check if CSP is empty in swagger.go --------- Co-authored-by: João Calisto Co-authored-by: Sofia Papagiannaki <1632407+papagian@users.noreply.github.com> --- pkg/api/openapi3.go | 13 ++++++++++++- pkg/api/swagger.go | 13 ++++++++++++- public/views/openapi3.html | 6 +++--- public/views/swagger.html | 6 +++--- 4 files changed, 30 insertions(+), 8 deletions(-) diff --git a/pkg/api/openapi3.go b/pkg/api/openapi3.go index a5f3eb483a4..4c0abf44de7 100644 --- a/pkg/api/openapi3.go +++ b/pkg/api/openapi3.go @@ -2,10 +2,21 @@ package api import ( "net/http" + "strings" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" ) func openapi3(c *contextmodel.ReqContext) { - c.HTML(http.StatusOK, "openapi3", nil) + data := map[string]interface{}{ + "Nonce": c.RequestNonce, + } + + // Add CSP for unpkg.com to allow loading of Swagger UI assets + if existingCSP := c.Resp.Header().Get("Content-Security-Policy"); existingCSP != "" { + newCSP := strings.Replace(existingCSP, "style-src", "style-src https://unpkg.com/", 1) + c.Resp.Header().Set("Content-Security-Policy", newCSP) + } + + c.HTML(http.StatusOK, "openapi3", data) } diff --git a/pkg/api/swagger.go b/pkg/api/swagger.go index 667871fbe1b..9bc46c9fec5 100644 --- a/pkg/api/swagger.go +++ b/pkg/api/swagger.go @@ -2,10 +2,21 @@ package api import ( "net/http" + "strings" contextmodel "github.com/grafana/grafana/pkg/services/contexthandler/model" ) func swaggerUI(c *contextmodel.ReqContext) { - c.HTML(http.StatusOK, "swagger", nil) + data := map[string]interface{}{ + "Nonce": c.RequestNonce, + } + + // Add CSP for unpkg.com to allow loading of Swagger UI assets + if existingCSP := c.Resp.Header().Get("Content-Security-Policy"); existingCSP != "" { + newCSP := strings.Replace(existingCSP, "style-src", "style-src https://unpkg.com/", 1) + c.Resp.Header().Set("Content-Security-Policy", newCSP) + } + + c.HTML(http.StatusOK, "swagger", data) } diff --git a/public/views/openapi3.html b/public/views/openapi3.html index 3825608b378..87c1fae1a19 100644 --- a/public/views/openapi3.html +++ b/public/views/openapi3.html @@ -33,9 +33,9 @@
- - - + + - - + +