Explorar el Código

refactor(ui): build the CSP header with directives in a fixed order

The policy was built from a map, so the order of its directives changed
on every request and the tests could only look for substrings of it.
Frédéric Guillot hace 3 horas
padre
commit
e54fe2abb0
Se han modificado 3 ficheros con 65 adiciones y 153 borrados
  1. 33 98
      internal/ui/view/csp_test.go
  2. 28 41
      internal/ui/view/view.go
  3. 4 14
      internal/ui/view/view_test.go

+ 33 - 98
internal/ui/view/csp_test.go

@@ -4,108 +4,43 @@
 package view
 
 import (
-	"strings"
 	"testing"
 
 	"miniflux.app/v2/internal/model"
 )
 
-func TestCSPExternalFont(t *testing.T) {
-	want := []string{
-		`default-src 'none';`,
-		`img-src * data:;`,
-		`media-src *;`,
-		`frame-src *;`,
-		`style-src 'nonce-1234';`,
-		`script-src 'nonce-1234'`,
-		`'strict-dynamic';`,
-		`font-src test.com;`,
-		`require-trusted-types-for 'script';`,
-		`trusted-types html url;`,
-		`manifest-src 'self';`,
-	}
-	got := csp(&model.User{ExternalFontHosts: "test.com"}, "1234")
-
-	for _, value := range want {
-		if !strings.Contains(got, value) {
-			t.Errorf(`Unexpected result, didn't find %q in %q`, value, got)
-		}
-	}
-}
-
-func TestCSPNoUser(t *testing.T) {
-	want := []string{
-		`default-src 'none';`,
-		`img-src * data:;`,
-		`media-src *;`,
-		`frame-src *;`,
-		`style-src 'nonce-1234';`,
-		`script-src 'nonce-1234'`,
-		`'strict-dynamic';`,
-		`require-trusted-types-for 'script';`,
-		`trusted-types html url;`,
-		`manifest-src 'self';`,
-	}
-	got := csp(nil, "1234")
-
-	for _, value := range want {
-		if !strings.Contains(got, value) {
-			t.Errorf(`Unexpected result, didn't find %q in %q`, value, got)
-		}
-	}
-}
-
-func TestCSPCustomJSExternalFont(t *testing.T) {
-	want := []string{
-		`default-src 'none';`,
-		`img-src * data:;`,
-		`media-src *;`,
-		`frame-src *;`,
-		`style-src 'nonce-1234';`,
-		`script-src 'nonce-1234'`,
-		`'strict-dynamic';`,
-		`require-trusted-types-for 'script';`,
-		`trusted-types html url;`,
-		`manifest-src 'self';`,
-	}
-	got := csp(&model.User{ExternalFontHosts: "test.com", CustomJS: "alert(1)"}, "1234")
-
-	for _, value := range want {
-		if !strings.Contains(got, value) {
-			t.Errorf(`Unexpected result, didn't find %q in %q`, value, got)
-		}
-	}
-}
-
-func TestCSPExternalFontStylesheet(t *testing.T) {
-	want := []string{
-		`default-src 'none';`,
-		`img-src * data:;`,
-		`media-src *;`,
-		`frame-src *;`,
-		`style-src 'nonce-1234' test.com;`,
-		`script-src 'nonce-1234'`,
-		`'strict-dynamic';`,
-		`require-trusted-types-for 'script';`,
-		`trusted-types html url;`,
-		`manifest-src 'self';`,
-	}
-	got := csp(&model.User{ExternalFontHosts: "test.com", Stylesheet: "a {color: red;}"}, "1234")
-
-	for _, value := range want {
-		if !strings.Contains(got, value) {
-			t.Errorf(`Unexpected result, didn't find %q in %q`, value, got)
-		}
-	}
-}
-
-// CSP must not come back as a meta tag: it ships as a response header.
-// See deadhead rule meta/http-equiv-content-security-policy (harmful).
-func TestCSPDoesNotReturnMetaTag(t *testing.T) {
-	got := csp(nil, "1234")
-
-	lower := strings.ToLower(got)
-	if strings.Contains(lower, "<meta") || strings.Contains(lower, "http-equiv") {
-		t.Fatalf("csp() must return a header value, not a meta tag, got %q", got)
+func TestCSP(t *testing.T) {
+	const (
+		defaultPolicy = `default-src 'none'; connect-src 'self'; frame-src *; img-src * data:; manifest-src 'self'; media-src *; ` +
+			`require-trusted-types-for 'script'; script-src 'nonce-1234' 'strict-dynamic'; style-src 'nonce-1234'; trusted-types html url`
+
+		externalFontPolicy = `default-src 'none'; connect-src 'self'; font-src test.com; frame-src *; img-src * data:; manifest-src 'self'; media-src *; ` +
+			`require-trusted-types-for 'script'; script-src 'nonce-1234' 'strict-dynamic'; style-src 'nonce-1234'; trusted-types html url`
+	)
+
+	scenarios := []struct {
+		name string
+		user *model.User
+		want string
+	}{
+		{"no user", nil, defaultPolicy},
+		{"no external font hosts", &model.User{}, defaultPolicy},
+		{"stylesheet without external font hosts", &model.User{Stylesheet: "a {color: red;}"}, defaultPolicy},
+		{"external font hosts", &model.User{ExternalFontHosts: "test.com"}, externalFontPolicy},
+		{"custom JavaScript keeps the policy", &model.User{ExternalFontHosts: "test.com", CustomJS: "alert(1)"}, externalFontPolicy},
+		{
+			"external font hosts with a stylesheet",
+			&model.User{ExternalFontHosts: "test.com", Stylesheet: "a {color: red;}"},
+			`default-src 'none'; connect-src 'self'; font-src test.com; frame-src *; img-src * data:; manifest-src 'self'; media-src *; ` +
+				`require-trusted-types-for 'script'; script-src 'nonce-1234' 'strict-dynamic'; style-src 'nonce-1234' test.com; trusted-types html url`,
+		},
+	}
+
+	for _, scenario := range scenarios {
+		t.Run(scenario.name, func(t *testing.T) {
+			if got := csp(scenario.user, "1234"); got != scenario.want {
+				t.Errorf("Unexpected policy:\ngot  %q\nwant %q", got, scenario.want)
+			}
+		})
 	}
 }

+ 28 - 41
internal/ui/view/view.go

@@ -35,58 +35,45 @@ func (v *view) Render(template string) []byte {
 }
 
 // CSP returns the Content-Security-Policy header value for this view.
-// The policy is delivered as an HTTP header (never as a meta tag, see
-// deadhead rule meta/http-equiv-content-security-policy): meta policies
-// drop frame-ancestors/report-uri/sandbox, stop the preload scanner, and
-// apply late.
 func (v *view) CSP() string {
-	var user *model.User
-	if u, ok := v.params["user"].(*model.User); ok {
-		user = u
-	}
+	user, _ := v.params["user"].(*model.User)
 	nonce, _ := v.params["cspNonce"].(string)
 	return csp(user, nonce)
 }
 
-// csp builds the Content-Security-Policy header value for templated pages.
-// It lives in the view layer because every templated page ships the policy
-// as a response header (never as a meta tag, see deadhead rule
-// meta/http-equiv-content-security-policy): meta policies drop
-// frame-ancestors/report-uri/sandbox, stop the preload scanner, and apply
-// late.
+// csp returns the Content-Security-Policy of templated pages, with the directives in a fixed order.
 func csp(user *model.User, nonce string) string {
-	policies := map[string]string{
-		"default-src":               "'none'",
-		"frame-src":                 "*",
-		"img-src":                   "* data:",
-		"manifest-src":              "'self'",
-		"media-src":                 "*",
-		"require-trusted-types-for": "'script'",
-		"script-src":                "'nonce-" + nonce + "' 'strict-dynamic'",
-		"style-src":                 "'nonce-" + nonce + "'",
-		"trusted-types":             "html url",
-		"connect-src":               "'self'",
-	}
-
-	if user != nil {
-		if user.ExternalFontHosts != "" {
-			policies["font-src"] = user.ExternalFontHosts
-			if user.Stylesheet != "" {
-				policies["style-src"] += " " + user.ExternalFontHosts
-			}
+	var fontSrc string
+	styleSrc := "'nonce-" + nonce + "'"
+	if user != nil && user.ExternalFontHosts != "" {
+		fontSrc = user.ExternalFontHosts
+		if user.Stylesheet != "" {
+			styleSrc += " " + user.ExternalFontHosts
 		}
 	}
 
-	var policy strings.Builder
-	policy.Grow(350)
-	for key, value := range policies {
-		policy.WriteString(key)
-		policy.WriteString(" ")
-		policy.WriteString(value)
-		policy.WriteString("; ")
+	directives := []struct{ name, value string }{
+		{"default-src", "'none'"},
+		{"connect-src", "'self'"},
+		{"font-src", fontSrc},
+		{"frame-src", "*"},
+		{"img-src", "* data:"},
+		{"manifest-src", "'self'"},
+		{"media-src", "*"},
+		{"require-trusted-types-for", "'script'"},
+		{"script-src", "'nonce-" + nonce + "' 'strict-dynamic'"},
+		{"style-src", styleSrc},
+		{"trusted-types", "html url"},
 	}
 
-	return policy.String()
+	policy := make([]string, 0, len(directives))
+	for _, directive := range directives {
+		// font-src is only set when the user has external font hosts.
+		if directive.value != "" {
+			policy = append(policy, directive.name+" "+directive.value)
+		}
+	}
+	return strings.Join(policy, "; ")
 }
 
 // HTML renders the given template and writes it as an HTML response with

+ 4 - 14
internal/ui/view/view_test.go

@@ -70,8 +70,7 @@ func TestNewIncludesCSRFToken(t *testing.T) {
 	}
 }
 
-// Every HTML view must carry a per-request CSP nonce and be able to
-// render its Content-Security-Policy header value (no meta tag).
+// Every HTML view must carry a per-request CSP nonce and use it in its Content-Security-Policy.
 func TestViewSetsCSPNonceAndPolicy(t *testing.T) {
 	configureTestOptions(t)
 
@@ -85,11 +84,7 @@ func TestViewSetsCSPNonceAndPolicy(t *testing.T) {
 		t.Fatalf("view params must contain a non-empty cspNonce, got %v", v.params["cspNonce"])
 	}
 
-	policy := v.CSP()
-	if strings.Contains(strings.ToLower(policy), "<meta") {
-		t.Fatalf("view CSP() must not return a <meta> tag, got %q", policy)
-	}
-	if !strings.Contains(policy, "'nonce-"+nonce+"'") {
+	if policy := v.CSP(); !strings.Contains(policy, "'nonce-"+nonce+"'") {
 		t.Fatalf("view CSP() must contain the request nonce, nonce=%q policy=%q", nonce, policy)
 	}
 }
@@ -106,13 +101,8 @@ func TestViewHTMLSetsCSPHeaderWithMatchingNonce(t *testing.T) {
 	v := New(engine, r)
 	v.HTML(w, r, "offline")
 
-	resp := w.Result()
-	policy := resp.Header.Get("Content-Security-Policy")
-	if policy == "" {
-		t.Fatal("view HTML() must set a Content-Security-Policy header")
-	}
-	if strings.Contains(strings.ToLower(policy), "<meta") {
-		t.Fatalf("CSP header must be a header value, not a meta tag, got %q", policy)
+	if policy := w.Result().Header.Get("Content-Security-Policy"); policy != v.CSP() {
+		t.Fatalf("view HTML() must send the policy of the view, got %q, want %q", policy, v.CSP())
 	}
 
 	body := w.Body.String()