aboutsummaryrefslogtreecommitdiff
path: root/echo/middleware/csp_test.go
blob: 71c3f57807fc240f84e630772e5d06f24d5fb011 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package middleware

import (
	"encoding/json"
	"net/url"
	"testing"
	"time"

	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/suite"
)

func UrlMustParse(s string) *url.URL {
	u, err := url.Parse(s)
	if err != nil {
		panic(err)
	}
	return u
}

type ContentSecurityPolicyConfigSuite struct {
	suite.Suite
}

func TestContentSecurityPolicyConfigSuite(t *testing.T) {
	suite.Run(t, &ContentSecurityPolicyConfigSuite{})
}

func (s *ContentSecurityPolicyConfigSuite) TestBoolField() {
	c := &ContentSecurityPolicyConfig{
		DefaultSrc: []CSPDirective{
			CSPSelf,
			CSPHost("https://example.com"),
		},
		UpgradeInsecureRequests: true,
	}

	assert.Equal(
		s.T(),
		"default-src 'self' https://example.com; upgrade-insecure-requests;",
		c.String(),
	)
}

func (s *ContentSecurityPolicyConfigSuite) TestListOfStrings() {
	c := &ContentSecurityPolicyConfig{
		DefaultSrc: []CSPDirective{
			CSPSelf,
			CSPHost("https://example.com"),
		},
		ConnectSrc: []CSPDirective{
			CSPData,
			CSPHost("https://*.example.com"),
		},
	}

	assert.Equal(
		s.T(),
		"default-src 'self' https://example.com; connect-src data: https://*.example.com;",
		c.String(),
	)
}

func (s *ContentSecurityPolicyConfigSuite) TestListOfUrls() {
	c := &ContentSecurityPolicyConfig{
		ReportUri: []*url.URL{
			UrlMustParse("https://example.com/report"),
			UrlMustParse("https://example.com/report2"),
		},
	}

	assert.Equal(
		s.T(),
		"report-uri https://example.com/report https://example.com/report2;",
		c.String(),
	)
}

func TestReportToMarshalJSON(t *testing.T) {
	c := &CSPReportTo{
		GroupName: "group",
		MaxAge:    24 * time.Hour,
		Endpoints: []*url.URL{
			UrlMustParse("https://example.com/report"),
			UrlMustParse("https://example.com/report2"),
		},
	}

	b, err := json.Marshal(c)
	if err != nil {
		t.Fail()
	}

	assert.Equal(
		t,
		`{"endpoints":[{"url":"https://example.com/report"},{"url":"https://example.com/report2"}],"group":"group","max_age":86400}`,
		string(b),
	)
}