Skip to content

Commit 3d539f9

Browse files
authored
fix: sort csp directives per w3 spec (#96)
1 parent 8b61a4e commit 3d539f9

File tree

3 files changed

+19
-2
lines changed

3 files changed

+19
-2
lines changed

.github/workflows/test.yaml

+1-1
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,4 @@ jobs:
2828
path: src/github.com/unrolled/secure
2929
- uses: golangci/golangci-lint-action@v4
3030
with:
31-
working-directory: src/github.com/7shifts/seven-deploy
31+
working-directory: src/github.com/unrolled/secure

cspbuilder/builder.go

+11-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package cspbuilder
22

33
import (
4+
"sort"
45
"strings"
56
)
67

@@ -62,7 +63,16 @@ func (builder *Builder) MustBuild() string {
6263
func (builder *Builder) Build() (string, error) {
6364
var sb strings.Builder
6465

65-
for directive := range builder.Directives {
66+
// Pull the directive keys out.
67+
directiveKeys := []string{}
68+
for key := range builder.Directives {
69+
directiveKeys = append(directiveKeys, key)
70+
}
71+
72+
// Sort the policies: https://www.w3.org/TR/CSP3/#framework-policy
73+
sort.Strings(directiveKeys)
74+
75+
for _, directive := range directiveKeys {
6676
if sb.Len() > 0 {
6777
sb.WriteString("; ")
6878
}

cspbuilder/builder_test.go

+7
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ func TestContentSecurityPolicyBuilder_Build_MultipleDirectives(t *testing.T) {
6363
directives map[string]([]string)
6464
builder Builder
6565
wantParts []string
66+
wantFull string
6667
wantErr bool
6768
}{
6869
{
@@ -86,6 +87,8 @@ func TestContentSecurityPolicyBuilder_Build_MultipleDirectives(t *testing.T) {
8687
"trusted-types policy-1 policy-#=_/@.% 'allow-duplicates'",
8788
"upgrade-insecure-requests",
8889
},
90+
91+
wantFull: "default-src 'self' example.com *.example.com; frame-ancestors 'self' http://*.example.com; report-to group1; require-trusted-types-for 'script'; sandbox allow-scripts; trusted-types policy-1 policy-#=_/@.% 'allow-duplicates'; upgrade-insecure-requests",
8992
},
9093
}
9194
for _, tt := range tests {
@@ -101,6 +104,10 @@ func TestContentSecurityPolicyBuilder_Build_MultipleDirectives(t *testing.T) {
101104
return
102105
}
103106

107+
if got != tt.wantFull {
108+
t.Errorf("ContentSecurityPolicyBuilder.Build() full = %v, but wanted %v", got, tt.wantFull)
109+
}
110+
104111
{
105112
startsWithDirective := false
106113

0 commit comments

Comments
 (0)