Browse Source

Add "Vary: Origin" to prevent caching CORS origin header

Daniel Friedman 6 years ago
parent
commit
3557fc074e
2 changed files with 38 additions and 0 deletions
  1. 37 0
      cors_test.go
  2. 1 0
      server.go

+ 37 - 0
cors_test.go

@@ -0,0 +1,37 @@
+package gold
+
+import (
+	"net/http"
+	"testing"
+
+	"github.com/stretchr/testify/assert"
+)
+
+func TestCORSRequestHasOrigin(t *testing.T) {
+	requestOrigin := "https://example.com"
+	url := testServer.URL + "/_test/user1"
+	req, err := http.NewRequest("GET", url, nil)
+	assert.NoError(t, err)
+	req.Header.Set("Origin", requestOrigin)
+	resp, err := httpClient.Do(req)
+	assert.NoError(t, err)
+	assert.Equal(t, requestOrigin, resp.Header.Get("Access-Control-Allow-Origin"))
+}
+
+func TestCORSRequestHasNoOrigin(t *testing.T) {
+	url := testServer.URL + "/_test/user1"
+	req, err := http.NewRequest("GET", url, nil)
+	assert.NoError(t, err)
+	resp, err := httpClient.Do(req)
+	assert.NoError(t, err)
+	assert.Equal(t, "*", resp.Header.Get("Access-Control-Allow-Origin"))
+}
+
+func TestVaryHeader(t *testing.T) {
+	url := testServer.URL + "/_test/user1"
+	req, err := http.NewRequest("GET", url, nil)
+	assert.NoError(t, err)
+	resp, err := httpClient.Do(req)
+	assert.NoError(t, err)
+	assert.Equal(t, "Origin", resp.Header.Get("Vary"))
+}

+ 1 - 0
server.go

@@ -309,6 +309,7 @@ func (s *Server) handle(w http.ResponseWriter, req *httpRequest) (r *response) {
 	w.Header().Set("Accept-Patch", "application/json, application/sparql-update")
 	w.Header().Set("Accept-Post", "text/turtle, application/json")
 	w.Header().Set("Allow", strings.Join(methodsAll, ", "))
+	w.Header().Set("Vary", "Origin")
 
 	switch req.Method {
 	case "OPTIONS":