handler_test.go 2.38 KB
Newer Older
1 2 3 4 5 6 7
package http

import (
	"net/http"
	"net/http/httptest"
	"testing"

8 9
	cors "github.com/ipfs/go-ipfs/Godeps/_workspace/src/github.com/rs/cors"

10 11 12 13 14 15 16 17 18 19 20
	"github.com/ipfs/go-ipfs/commands"
)

func assertHeaders(t *testing.T, resHeaders http.Header, reqHeaders map[string]string) {
	for name, value := range reqHeaders {
		if resHeaders.Get(name) != value {
			t.Errorf("Invalid header `%s', wanted `%s', got `%s'", name, value, resHeaders.Get(name))
		}
	}
}

21 22 23 24 25 26 27 28
func originCfg(origin string) *ServerConfig {
	return &ServerConfig{
		CORSOpts: &cors.Options{
			AllowedOrigins: []string{origin},
		},
	}
}

29 30 31 32 33
func TestDisallowedOrigin(t *testing.T) {
	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
	req.Header.Add("Origin", "http://barbaz.com")

34
	handler := NewHandler(commands.Context{}, nil, originCfg(""))
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
	handler.ServeHTTP(res, req)

	assertHeaders(t, res.Header(), map[string]string{
		"Access-Control-Allow-Origin":      "",
		"Access-Control-Allow-Methods":     "",
		"Access-Control-Allow-Credentials": "",
		"Access-Control-Max-Age":           "",
		"Access-Control-Expose-Headers":    "",
	})
}

func TestWildcardOrigin(t *testing.T) {
	res := httptest.NewRecorder()
	req, _ := http.NewRequest("GET", "http://example.com/foo", nil)
	req.Header.Add("Origin", "http://foobar.com")

51
	handler := NewHandler(commands.Context{}, nil, originCfg("*"))
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
	handler.ServeHTTP(res, req)

	assertHeaders(t, res.Header(), map[string]string{
		"Access-Control-Allow-Origin":      "http://foobar.com",
		"Access-Control-Allow-Methods":     "",
		"Access-Control-Allow-Headers":     "",
		"Access-Control-Allow-Credentials": "",
		"Access-Control-Max-Age":           "",
		"Access-Control-Expose-Headers":    "",
	})
}

func TestAllowedMethod(t *testing.T) {
	res := httptest.NewRecorder()
	req, _ := http.NewRequest("OPTIONS", "http://example.com/foo", nil)
	req.Header.Add("Origin", "http://www.foobar.com")
	req.Header.Add("Access-Control-Request-Method", "PUT")

70
	handler := NewHandler(commands.Context{}, nil, originCfg("http://www.foobar.com"))
71 72 73 74 75 76 77 78 79 80 81
	handler.ServeHTTP(res, req)

	assertHeaders(t, res.Header(), map[string]string{
		"Access-Control-Allow-Origin":      "http://www.foobar.com",
		"Access-Control-Allow-Methods":     "PUT",
		"Access-Control-Allow-Headers":     "",
		"Access-Control-Allow-Credentials": "",
		"Access-Control-Max-Age":           "",
		"Access-Control-Expose-Headers":    "",
	})
}