2017-06-17 04:04:55 +00:00
|
|
|
package http
|
|
|
|
|
|
|
|
import (
|
2017-06-19 22:20:44 +00:00
|
|
|
"fmt"
|
2017-06-17 04:04:55 +00:00
|
|
|
"net/http"
|
|
|
|
"strings"
|
|
|
|
|
|
|
|
"github.com/hashicorp/vault/helper/strutil"
|
|
|
|
"github.com/hashicorp/vault/vault"
|
|
|
|
)
|
|
|
|
|
|
|
|
var allowedMethods = []string{
|
|
|
|
http.MethodDelete,
|
|
|
|
http.MethodGet,
|
|
|
|
http.MethodOptions,
|
|
|
|
http.MethodPost,
|
|
|
|
http.MethodPut,
|
|
|
|
"LIST", // LIST is not an official HTTP method, but Vault supports it.
|
|
|
|
}
|
|
|
|
|
|
|
|
func wrapCORSHandler(h http.Handler, core *vault.Core) http.Handler {
|
|
|
|
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
|
|
|
corsConf := core.CORSConfig()
|
|
|
|
|
|
|
|
// If CORS is not enabled or if no Origin header is present (i.e. the request
|
|
|
|
// is from the Vault CLI. A browser will always send an Origin header), then
|
|
|
|
// just return a 204.
|
2018-06-09 20:57:57 +00:00
|
|
|
if !corsConf.IsEnabled() {
|
|
|
|
h.ServeHTTP(w, req)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
origin := req.Header.Get("Origin")
|
|
|
|
requestMethod := req.Header.Get("Access-Control-Request-Method")
|
|
|
|
|
|
|
|
if origin == "" {
|
2017-06-17 04:04:55 +00:00
|
|
|
h.ServeHTTP(w, req)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2017-08-07 14:03:30 +00:00
|
|
|
// Return a 403 if the origin is not allowed to make cross-origin requests.
|
2017-06-17 04:04:55 +00:00
|
|
|
if !corsConf.IsValidOrigin(origin) {
|
2017-06-19 22:20:44 +00:00
|
|
|
respondError(w, http.StatusForbidden, fmt.Errorf("origin not allowed"))
|
2017-06-17 04:04:55 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if req.Method == http.MethodOptions && !strutil.StrListContains(allowedMethods, requestMethod) {
|
|
|
|
w.WriteHeader(http.StatusMethodNotAllowed)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
w.Header().Set("Access-Control-Allow-Origin", origin)
|
|
|
|
w.Header().Set("Vary", "Origin")
|
|
|
|
|
|
|
|
// apply headers for preflight requests
|
|
|
|
if req.Method == http.MethodOptions {
|
|
|
|
w.Header().Set("Access-Control-Allow-Methods", strings.Join(allowedMethods, ","))
|
2017-08-07 14:03:30 +00:00
|
|
|
w.Header().Set("Access-Control-Allow-Headers", strings.Join(corsConf.AllowedHeaders, ","))
|
|
|
|
w.Header().Set("Access-Control-Max-Age", "300")
|
2017-06-17 04:04:55 +00:00
|
|
|
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
h.ServeHTTP(w, req)
|
|
|
|
return
|
|
|
|
})
|
|
|
|
}
|