Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prevent empty Access-Control-Expose-Headers header #160

Merged
merged 1 commit into from
Sep 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion cors.go
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
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())
})
})
}

}