Skip to content

Commit

Permalink
Fix * behavior to be standard compliant.
Browse files Browse the repository at this point in the history
When a user specifies *, then * should be returned by the server in
the access-control-allow-origin header, not the origin header.

All implementations of the CORS standard that reflect the origin header
when * is specified are incorrect, because an Access-Control-Allow-Origin
header of '*' has a different meaning than a reflected Origin header. Refer
to Section 6.1 https://www.w3.org/TR/cors/. When * is set, Credentials
are not allowed to be used in an authenticated request.

**What's the big deal?**
If you set Allow Credentials to True and Origins to * with this library
then you have turned off SAMEORIGIN policy for your website, which is
unexpected behavior and....really bad.
  • Loading branch information
ejcx committed Jul 25, 2018
1 parent dba6525 commit fccd395
Showing 1 changed file with 13 additions and 2 deletions.
15 changes: 13 additions & 2 deletions cors.go
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,7 @@ func (c *Cors) handlePreflight(w http.ResponseWriter, r *http.Request) {
c.logf("Preflight aborted: headers '%v' not allowed", reqHeaders)
return
}
headers.Set("Access-Control-Allow-Origin", origin)
headers.Set("Access-Control-Allow-Origin", c.FetchOrigin(origin))
// Spec says: Since the list of methods can be unbounded, simply returning the method indicated
// by Access-Control-Request-Method (if supported) can be enough
headers.Set("Access-Control-Allow-Methods", strings.ToUpper(reqMethod))
Expand Down Expand Up @@ -287,7 +287,7 @@ func (c *Cors) handleActualRequest(w http.ResponseWriter, r *http.Request) {

return
}
headers.Set("Access-Control-Allow-Origin", origin)
headers.Set("Access-Control-Allow-Origin", c.FetchOrigin(origin))
if len(c.exposedHeaders) > 0 {
headers.Set("Access-Control-Expose-Headers", strings.Join(c.exposedHeaders, ", "))
}
Expand All @@ -304,6 +304,13 @@ func (c *Cors) logf(format string, a ...interface{}) {
}
}

func (c *Cors) FetchOrigin(origin string) string {
if c.IsStar() {
return "*"
}
return origin
}

// isOriginAllowed checks if a given origin is allowed to perform cross-domain requests
// on the endpoint
func (c *Cors) isOriginAllowed(r *http.Request, origin string) bool {
Expand All @@ -327,6 +334,10 @@ func (c *Cors) isOriginAllowed(r *http.Request, origin string) bool {
return false
}

func (c *Cors) IsStar() bool {
return c.allowedOriginsAll
}

// isMethodAllowed checks if a given method can be used as part of a cross-domain request
// on the endpoing
func (c *Cors) isMethodAllowed(method string) bool {
Expand Down

0 comments on commit fccd395

Please sign in to comment.