Skip to content

armgit / fider

Public Imported from GitHub
0

Open platform to collect and prioritize feedback

enhancement: add csp-report policy (#351)

Guilherme Oenning432abc5ab42c
diff --git a/app/handlers/common.go b/app/handlers/common.go
index 5e0c0e79e..627d92799 100644
--- a/app/handlers/common.go
+++ b/app/handlers/common.go
@@ -1,6 +1,7 @@
package handlers
import (
+ "io/ioutil"
"runtime"
"time"
@@ -37,6 +38,18 @@ func Page() web.HandlerFunc {
}
}
+//CSPReport logs every CSP policy issue reported by clients
+func CSPReport() web.HandlerFunc {
+ return func(c web.Context) error {
+ bytes, err := ioutil.ReadAll(c.Request.Body)
+ if err != nil {
+ return c.Failure(err)
+ }
+ c.Logger().Warnf("CSP Policy Failure: %s", string(bytes))
+ return c.Ok(web.Map{})
+ }
+}
+
func validateKey(kind models.EmailVerificationKind, c web.Context) (*models.EmailVerification, error) {
key := c.QueryParam("k")
diff --git a/app/handlers/common_test.go b/app/handlers/common_test.go
index 2c10bed99..37a267c45 100644
--- a/app/handlers/common_test.go
+++ b/app/handlers/common_test.go
@@ -1,6 +1,7 @@
package handlers_test
import (
+ "net/http"
"testing"
"github.com/getfider/fider/app/handlers"
@@ -20,5 +21,17 @@ func TestStatusHandler(t *testing.T) {
status, query := server.ExecuteAsJSON(handlers.Status(settings))
Expect(query.String("build")).To(Equal("today"))
- Expect(status).To(Equal(200))
+ Expect(status).To(Equal(http.StatusOK))
+}
+
+func TestCSPReportHandler(t *testing.T) {
+ RegisterTestingT(t)
+
+ server, _ := mock.NewServer()
+ status, _ := server.ExecutePost(
+ handlers.CSPReport(),
+ "This is the message body.",
+ )
+
+ Expect(status).To(Equal(http.StatusOK))
}
diff --git a/app/middlewares/security.go b/app/middlewares/security.go
index 71b83f416..3b1438de7 100644
--- a/app/middlewares/security.go
+++ b/app/middlewares/security.go
@@ -1,6 +1,8 @@
package middlewares
import (
+ "fmt"
+
"github.com/getfider/fider/app/pkg/web"
)
@@ -8,7 +10,9 @@ import (
func Secure() web.MiddlewareFunc {
return func(next web.HandlerFunc) web.HandlerFunc {
return func(c web.Context) error {
+ c.Response.Header().Add("Content-Security-Policy-Report-Only", fmt.Sprintf(web.CspPolicyTemplate, c.ContextID()))
c.Response.Header().Add("X-XSS-Protection", "1; mode=block")
+ c.Response.Header().Add("X-Frame-Options", "DENY")
c.Response.Header().Add("X-Content-Type-Options", "nosniff")
c.Response.Header().Add("Referrer-Policy", "no-referrer-when-downgrade")
return next(c)
diff --git a/app/middlewares/security_test.go b/app/middlewares/security_test.go
index 2ad64b805..005618560 100644
--- a/app/middlewares/security_test.go
+++ b/app/middlewares/security_test.go
@@ -1,6 +1,7 @@
package middlewares_test
import (
+ "fmt"
"net/http"
"testing"
@@ -15,12 +16,17 @@ func TestSecure(t *testing.T) {
server, _ := mock.NewServer()
server.Use(middlewares.Secure())
+
+ var id string
status, response := server.Execute(func(c web.Context) error {
+ id = c.ContextID()
return c.NoContent(http.StatusOK)
})
Expect(status).To(Equal(http.StatusOK))
+ Expect(response.Header().Get("Content-Security-Policy-Report-Only")).To(Equal(fmt.Sprintf(web.CspPolicyTemplate, id)))
Expect(response.Header().Get("X-XSS-Protection")).To(Equal("1; mode=block"))
+ Expect(response.Header().Get("X-Frame-Options")).To(Equal("DENY"))
Expect(response.Header().Get("X-Content-Type-Options")).To(Equal("nosniff"))
Expect(response.Header().Get("Referrer-Policy")).To(Equal("no-referrer-when-downgrade"))
}
diff --git a/app/pkg/web/context.go b/app/pkg/web/context.go
index 8b8557853..768075487 100644
--- a/app/pkg/web/context.go
+++ b/app/pkg/web/context.go
@@ -54,6 +54,7 @@ var (
//Context shared between http pipeline
type Context struct {
+ id string
Response http.ResponseWriter
Request *http.Request
engine *Engine
@@ -68,6 +69,11 @@ func (ctx *Context) Engine() *Engine {
return ctx.engine
}
+//ContextID returns the unique id for this context
+func (ctx *Context) ContextID() string {
+ return ctx.id
+}
+
//Commit everything that is pending on current context
func (ctx *Context) Commit() error {
if trx := ctx.ActiveTransaction(); trx != nil {
diff --git a/app/pkg/web/context_test.go b/app/pkg/web/context_test.go
index c1f6d9cc1..8747d8642 100644
--- a/app/pkg/web/context_test.go
+++ b/app/pkg/web/context_test.go
@@ -28,6 +28,15 @@ func newBodyContext(method string, params web.StringMap, body, contentType strin
return &ctx
}
+func TestContextID(t *testing.T) {
+ RegisterTestingT(t)
+
+ ctx := newGetContext(nil)
+
+ Expect(ctx.ContextID()).NotTo(BeEmpty())
+ Expect(ctx.ContextID()).To(HaveLen(32))
+}
+
func TestBaseURL(t *testing.T) {
RegisterTestingT(t)
diff --git a/app/pkg/web/engine.go b/app/pkg/web/engine.go
index c461e8b8a..0a9430587 100644
--- a/app/pkg/web/engine.go
+++ b/app/pkg/web/engine.go
@@ -8,16 +8,33 @@ import (
"os"
"runtime"
"strconv"
+ "strings"
"time"
"github.com/getfider/fider/app/models"
"github.com/getfider/fider/app/pkg/env"
"github.com/getfider/fider/app/pkg/errors"
"github.com/getfider/fider/app/pkg/log"
+ "github.com/getfider/fider/app/pkg/uuid"
"github.com/getfider/fider/app/pkg/worker"
"github.com/julienschmidt/httprouter"
)
+var (
+ cspBase = "base-uri 'self'"
+ cspDefault = "default-src 'self'"
+ cspStyle = "style-src 'self' https://fonts.googleapis.com"
+ cspScript = "script-src 'self' 'nonce-%s' https://cdn.polyfill.io https://www.google-analytics.com"
+ cspFont = "font-src 'self' https://fonts.gstatic.com data:"
+ cspImage = "img-src 'self' https: data:"
+ cspObject = "object-src 'none'"
+ cspMedia = "media-src 'none'"
+ cspReport = "report-uri /csp-report"
+
+ //CspPolicyTemplate is the template used to generate the policy
+ CspPolicyTemplate = fmt.Sprintf("%s; %s; %s; %s; %s; %s; %s; %s; %s", cspBase, cspDefault, cspStyle, cspScript, cspImage, cspFont, cspObject, cspMedia, cspReport)
+)
+
type notFoundHandler struct {
router *Engine
}
@@ -111,6 +128,7 @@ func (e *Engine) Start(address string) {
//NewContext creates and return a new context
func (e *Engine) NewContext(res http.ResponseWriter, req *http.Request, params StringMap) Context {
return Context{
+ id: strings.Replace(uuid.NewV4().String(), "-", "", 4),
Response: res,
Request: req,
engine: e,
diff --git a/app/pkg/web/renderer.go b/app/pkg/web/renderer.go
index d6d712fe1..924bd5f70 100644
--- a/app/pkg/web/renderer.go
+++ b/app/pkg/web/renderer.go
@@ -89,6 +89,7 @@ func (r *Renderer) Render(w io.Writer, name string, data interface{}, ctx *Conte
m["__StyleBundle"] = r.cssBundle
m["system"] = r.settings
+ m["contextID"] = ctx.ContextID()
m["baseURL"] = ctx.BaseURL()
m["tenant"] = ctx.Tenant()
m["auth"] = Map{
diff --git a/routes.go b/routes.go
index b4a3d9694..69f42020a 100644
--- a/routes.go
+++ b/routes.go
@@ -30,6 +30,8 @@ func GetMainEngine(settings *models.SystemSettings) *web.Engine {
noTenant := r.Group()
{
+ noTenant.Post("/csp-report", handlers.CSPReport())
+
noTenant.Post("/api/tenants", handlers.CreateTenant())
noTenant.Get("/api/tenants/:subdomain/availability", handlers.CheckAvailability())
noTenant.Get("/signup", handlers.SignUp())
diff --git a/views/base.html b/views/base.html
index 8a82897cd..810b46329 100644
--- a/views/base.html
+++ b/views/base.html
@@ -21,9 +21,9 @@
<p>Please enable JavaScript and then reload the page.</p>
</div>
</noscript>
-
+
{{ if ne .system.GoogleAnalytics "" }}
- <script>
+ <script type="text/javascript" nonce="{{ .contextID }}">
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
@@ -34,10 +34,12 @@
ga('send', 'pageview');
</script>
{{ end }}
+
{{template "content" .}}
+
<script src="https://cdn.polyfill.io/v2/polyfill.min.js?features=default,fetch"></script>
<script src="/assets/js/{{ .__JavaScriptBundle }}"></script>
- <script type="text/javascript">
+ <script type="text/javascript" nonce="{{ .contextID }}">
{{template "javascript" .}}
</script>
</body>