Skip to content

Commit

Permalink
fix: sort csp directives per w3 spec (#96)
Browse files Browse the repository at this point in the history
  • Loading branch information
unrolled authored Jun 25, 2024
1 parent 8b61a4e commit 3d539f9
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,4 +28,4 @@ jobs:
path: src/github.com/unrolled/secure
- uses: golangci/golangci-lint-action@v4
with:
working-directory: src/github.com/7shifts/seven-deploy
working-directory: src/github.com/unrolled/secure
12 changes: 11 additions & 1 deletion cspbuilder/builder.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cspbuilder

import (
"sort"
"strings"
)

Expand Down Expand Up @@ -62,7 +63,16 @@ func (builder *Builder) MustBuild() string {
func (builder *Builder) Build() (string, error) {
var sb strings.Builder

for directive := range builder.Directives {
// Pull the directive keys out.
directiveKeys := []string{}
for key := range builder.Directives {
directiveKeys = append(directiveKeys, key)
}

// Sort the policies: https://www.w3.org/TR/CSP3/#framework-policy
sort.Strings(directiveKeys)

for _, directive := range directiveKeys {
if sb.Len() > 0 {
sb.WriteString("; ")
}
Expand Down
7 changes: 7 additions & 0 deletions cspbuilder/builder_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ func TestContentSecurityPolicyBuilder_Build_MultipleDirectives(t *testing.T) {
directives map[string]([]string)
builder Builder
wantParts []string
wantFull string
wantErr bool
}{
{
Expand All @@ -86,6 +87,8 @@ func TestContentSecurityPolicyBuilder_Build_MultipleDirectives(t *testing.T) {
"trusted-types policy-1 policy-#=_/@.% 'allow-duplicates'",
"upgrade-insecure-requests",
},

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",
},
}
for _, tt := range tests {
Expand All @@ -101,6 +104,10 @@ func TestContentSecurityPolicyBuilder_Build_MultipleDirectives(t *testing.T) {
return
}

if got != tt.wantFull {
t.Errorf("ContentSecurityPolicyBuilder.Build() full = %v, but wanted %v", got, tt.wantFull)
}

{
startsWithDirective := false

Expand Down

0 comments on commit 3d539f9

Please sign in to comment.