Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
91 changes: 91 additions & 0 deletions http/cors.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
package http

import (
"time"

"github.com/rs/cors"
"github.com/rs/zerolog"
)

// DefaultCORSMaxAge is how long browsers may cache a preflight response when
// CORSConfig does not say.
const DefaultCORSMaxAge = 24 * time.Hour

// CORSConfig is the cross-origin policy of an API, in the form services take
// it in their configuration. Options turns it into rs/cors options and
// Middleware into a middleware.
//
// Nothing is allowed unless an origin is listed or AllowLocalhost is set; an
// empty config is closed, unlike rs/cors, which allows every origin when it is
// given none.
type CORSConfig struct {
// AllowedOrigins are the origins that may call the API. "*" allows every
// origin.
AllowedOrigins []string `desc:"origins that may call the API" mapstructure:"allowed-origins"`

// AllowLocalhost also allows localhost origins. It is for a local UI that
// calls the API and for development. With AllowCredentials it lets any page
// on the user's machine make credentialed requests, so enable it only
// where that is meant.
AllowLocalhost bool `desc:"also allow localhost origins" mapstructure:"allow-localhost"`

// AllowedMethods defaults to the methods rs/cors allows, GET, POST and HEAD.
AllowedMethods []string `desc:"methods allowed on cross-origin requests" mapstructure:"allowed-methods"`

// AllowedHeaders defaults to Content-Type and Authorization.
AllowedHeaders []string `desc:"request headers allowed on cross-origin requests" mapstructure:"allowed-headers"`

// ExposedHeaders are the response headers a browser may read.
ExposedHeaders []string `desc:"response headers exposed to browsers" mapstructure:"exposed-headers"`

// AllowCredentials lets browsers send cookies and authorisation headers.
AllowCredentials bool `desc:"allow credentialed cross-origin requests" mapstructure:"allow-credentials"`

// AllowPrivateNetwork answers Private Network Access preflights, for a
// public page calling an API on a private network.
AllowPrivateNetwork bool `desc:"allow private network access preflights" mapstructure:"allow-private-network"`

// MaxAgeSeconds is how long browsers may cache a preflight response. It
// defaults to DefaultCORSMaxAge.
MaxAgeSeconds int `desc:"seconds a preflight response may be cached" mapstructure:"max-age-seconds"`
}

// Options returns the rs/cors options for c, logging through logger and, with
// debug, logging every decision.
func (c CORSConfig) Options(logger zerolog.Logger, debug bool) cors.Options {
headers := c.AllowedHeaders
if len(headers) == 0 {
headers = []string{"Content-Type", "Authorization"}
}
maxAge := c.MaxAgeSeconds
if maxAge <= 0 {
maxAge = int(DefaultCORSMaxAge / time.Second)
}

return cors.Options{
AllowOriginFunc: c.allowOrigin,
AllowedMethods: c.AllowedMethods,
AllowedHeaders: headers,
ExposedHeaders: c.ExposedHeaders,
AllowCredentials: c.AllowCredentials,
AllowPrivateNetwork: c.AllowPrivateNetwork,
MaxAge: maxAge,
Debug: debug,
Logger: &logger,
}
}

// Middleware returns the CORS middleware for c. See Options.
func (c CORSConfig) Middleware(logger zerolog.Logger, debug bool) Middleware {
return CORSHandler(c.Options(logger, debug))
}

func (c CORSConfig) allowOrigin(origin string) bool {
for _, allowed := range c.AllowedOrigins {
if allowed == "*" || allowed == origin {
return true
}
}

return c.AllowLocalhost && CORSAllowLocalhostOrigin(origin)
}
73 changes: 73 additions & 0 deletions http/cors_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
package http

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

"github.com/rs/zerolog"
"github.com/stretchr/testify/assert"
)

func TestCORSConfig_AllowsOnlyWhatItLists(t *testing.T) {
t.Parallel()

tests := []struct {
name string
cfg CORSConfig
origin string
want bool
}{
{"empty config is closed", CORSConfig{}, "https://app.example.com", false},
{"listed origin", CORSConfig{AllowedOrigins: []string{"https://app.example.com"}}, "https://app.example.com", true},
{"unlisted origin", CORSConfig{AllowedOrigins: []string{"https://app.example.com"}}, "https://evil.example.com", false},
{"wildcard", CORSConfig{AllowedOrigins: []string{"*"}}, "https://anything.example.com", true},
{"localhost not allowed by default", CORSConfig{}, "http://localhost:3000", false},
{"localhost when allowed", CORSConfig{AllowLocalhost: true}, "http://localhost:3000", true},
{"allowing localhost keeps other origins out", CORSConfig{AllowLocalhost: true}, "https://evil.example.com", false},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()

rec := httptest.NewRecorder()
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil)
req.Header.Set("Origin", tc.origin)
tc.cfg.Middleware(zerolog.Nop(), false)(http.HandlerFunc(func(http.ResponseWriter, *http.Request) {})).ServeHTTP(rec, req)

got := rec.Header().Get("Access-Control-Allow-Origin") == tc.origin
assert.Equal(t, tc.want, got)
})
}
}

func TestCORSConfig_OptionsApplyDefaults(t *testing.T) {
t.Parallel()

got := CORSConfig{}.Options(zerolog.Nop(), false)

assert.Equal(t, []string{"Content-Type", "Authorization"}, got.AllowedHeaders)
assert.Equal(t, 24*60*60, got.MaxAge)
assert.False(t, got.AllowCredentials, "credentials are opt-in")
}

func TestCORSConfig_OptionsKeepWhatIsSet(t *testing.T) {
t.Parallel()

got := CORSConfig{
AllowedHeaders: []string{"X-Custom"},
AllowedMethods: []string{"GET", "DELETE"},
ExposedHeaders: []string{"X-Request-Id"},
AllowCredentials: true,
AllowPrivateNetwork: true,
MaxAgeSeconds: 60,
}.Options(zerolog.Nop(), true)

assert.Equal(t, []string{"X-Custom"}, got.AllowedHeaders)
assert.Equal(t, []string{"GET", "DELETE"}, got.AllowedMethods)
assert.Equal(t, []string{"X-Request-Id"}, got.ExposedHeaders)
assert.True(t, got.AllowCredentials)
assert.True(t, got.AllowPrivateNetwork)
assert.Equal(t, 60, got.MaxAge)
assert.True(t, got.Debug)
}
Loading