Skip to content

Commit

Permalink
Prevent empty Access-Control-Expose-Headers header (#160)
Browse files Browse the repository at this point in the history
Fixes #159
  • Loading branch information
chrismeyers authored Sep 29, 2023
1 parent 20a76bd commit e19471c
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 1 deletion.
4 changes: 3 additions & 1 deletion cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,9 @@ func New(options Options) *Cors {
}

// Pre-compute exposed headers header value
c.exposedHeaders = []string{strings.Join(convert(options.ExposedHeaders, http.CanonicalHeaderKey), ", ")}
if len(options.ExposedHeaders) > 0 {
c.exposedHeaders = []string{strings.Join(convert(options.ExposedHeaders, http.CanonicalHeaderKey), ", ")}
}

// Pre-compute prefight Vary header to save allocations
if c.allowPrivateNetwork {
Expand Down
53 changes: 53 additions & 0 deletions cors_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -752,3 +752,56 @@ func TestCorsAreHeadersAllowed(t *testing.T) {
})
}
}

func TestAccessControlExposeHeadersPresence(t *testing.T) {
cases := []struct {
name string
options Options
want bool
}{
{
name: "omit",
options: Options{},
want: false,
},
{
name: "include",
options: Options{
ExposedHeaders: []string{"X-Something"},
},
want: true,
},
}

for _, tt := range cases {
t.Run(tt.name, func(t *testing.T) {
s := New(tt.options)

req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
req.Header.Add("Origin", "http://foobar.com")

assertExposeHeaders := func(t *testing.T, resHeaders http.Header) {
if _, have := resHeaders["Access-Control-Expose-Headers"]; have != tt.want {
t.Errorf("Access-Control-Expose-Headers have: %t want: %t", have, tt.want)
}
}

t.Run("Handler", func(t *testing.T) {
res := httptest.NewRecorder()
s.Handler(testHandler).ServeHTTP(res, req)
assertExposeHeaders(t, res.Header())
})
t.Run("HandlerFunc", func(t *testing.T) {
res := httptest.NewRecorder()
s.HandlerFunc(res, req)
assertExposeHeaders(t, res.Header())
})
t.Run("Negroni", func(t *testing.T) {
res := httptest.NewRecorder()
s.ServeHTTP(res, req, testHandler)
assertExposeHeaders(t, res.Header())
})
})
}

}

0 comments on commit e19471c

Please sign in to comment.