cors.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352
  1. package handlers
  2. import (
  3. "net/http"
  4. "strconv"
  5. "strings"
  6. )
  7. // CORSOption represents a functional option for configuring the CORS middleware.
  8. type CORSOption func(*cors) error
  9. type cors struct {
  10. h http.Handler
  11. allowedHeaders []string
  12. allowedMethods []string
  13. allowedOrigins []string
  14. allowedOriginValidator OriginValidator
  15. exposedHeaders []string
  16. maxAge int
  17. ignoreOptions bool
  18. allowCredentials bool
  19. optionStatusCode int
  20. }
  21. // OriginValidator takes an origin string and returns whether or not that origin is allowed.
  22. type OriginValidator func(string) bool
  23. var (
  24. defaultCorsOptionStatusCode = http.StatusOK
  25. defaultCorsMethods = []string{http.MethodGet, http.MethodHead, http.MethodPost}
  26. defaultCorsHeaders = []string{"Accept", "Accept-Language", "Content-Language", "Origin"}
  27. // (WebKit/Safari v9 sends the Origin header by default in AJAX requests).
  28. )
  29. const (
  30. corsOptionMethod string = http.MethodOptions
  31. corsAllowOriginHeader string = "Access-Control-Allow-Origin"
  32. corsExposeHeadersHeader string = "Access-Control-Expose-Headers"
  33. corsMaxAgeHeader string = "Access-Control-Max-Age"
  34. corsAllowMethodsHeader string = "Access-Control-Allow-Methods"
  35. corsAllowHeadersHeader string = "Access-Control-Allow-Headers"
  36. corsAllowCredentialsHeader string = "Access-Control-Allow-Credentials"
  37. corsRequestMethodHeader string = "Access-Control-Request-Method"
  38. corsRequestHeadersHeader string = "Access-Control-Request-Headers"
  39. corsOriginHeader string = "Origin"
  40. corsVaryHeader string = "Vary"
  41. corsOriginMatchAll string = "*"
  42. )
  43. func (ch *cors) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  44. origin := r.Header.Get(corsOriginHeader)
  45. if !ch.isOriginAllowed(origin) {
  46. if r.Method != corsOptionMethod || ch.ignoreOptions {
  47. ch.h.ServeHTTP(w, r)
  48. }
  49. return
  50. }
  51. if r.Method == corsOptionMethod {
  52. if ch.ignoreOptions {
  53. ch.h.ServeHTTP(w, r)
  54. return
  55. }
  56. if _, ok := r.Header[corsRequestMethodHeader]; !ok {
  57. w.WriteHeader(http.StatusBadRequest)
  58. return
  59. }
  60. method := r.Header.Get(corsRequestMethodHeader)
  61. if !ch.isMatch(method, ch.allowedMethods) {
  62. w.WriteHeader(http.StatusMethodNotAllowed)
  63. return
  64. }
  65. requestHeaders := strings.Split(r.Header.Get(corsRequestHeadersHeader), ",")
  66. allowedHeaders := []string{}
  67. for _, v := range requestHeaders {
  68. canonicalHeader := http.CanonicalHeaderKey(strings.TrimSpace(v))
  69. if canonicalHeader == "" || ch.isMatch(canonicalHeader, defaultCorsHeaders) {
  70. continue
  71. }
  72. if !ch.isMatch(canonicalHeader, ch.allowedHeaders) {
  73. w.WriteHeader(http.StatusForbidden)
  74. return
  75. }
  76. allowedHeaders = append(allowedHeaders, canonicalHeader)
  77. }
  78. if len(allowedHeaders) > 0 {
  79. w.Header().Set(corsAllowHeadersHeader, strings.Join(allowedHeaders, ","))
  80. }
  81. if ch.maxAge > 0 {
  82. w.Header().Set(corsMaxAgeHeader, strconv.Itoa(ch.maxAge))
  83. }
  84. if !ch.isMatch(method, defaultCorsMethods) {
  85. w.Header().Set(corsAllowMethodsHeader, method)
  86. }
  87. } else if len(ch.exposedHeaders) > 0 {
  88. w.Header().Set(corsExposeHeadersHeader, strings.Join(ch.exposedHeaders, ","))
  89. }
  90. if ch.allowCredentials {
  91. w.Header().Set(corsAllowCredentialsHeader, "true")
  92. }
  93. if len(ch.allowedOrigins) > 1 {
  94. w.Header().Set(corsVaryHeader, corsOriginHeader)
  95. }
  96. returnOrigin := origin
  97. if ch.allowedOriginValidator == nil && len(ch.allowedOrigins) == 0 {
  98. returnOrigin = "*"
  99. } else {
  100. for _, o := range ch.allowedOrigins {
  101. // A configuration of * is different than explicitly setting an allowed
  102. // origin. Returning arbitrary origin headers in an access control allow
  103. // origin header is unsafe and is not required by any use case.
  104. if o == corsOriginMatchAll {
  105. returnOrigin = "*"
  106. break
  107. }
  108. }
  109. }
  110. w.Header().Set(corsAllowOriginHeader, returnOrigin)
  111. if r.Method == corsOptionMethod {
  112. w.WriteHeader(ch.optionStatusCode)
  113. return
  114. }
  115. ch.h.ServeHTTP(w, r)
  116. }
  117. // CORS provides Cross-Origin Resource Sharing middleware.
  118. // Example:
  119. //
  120. // import (
  121. // "net/http"
  122. //
  123. // "github.com/gorilla/handlers"
  124. // "github.com/gorilla/mux"
  125. // )
  126. //
  127. // func main() {
  128. // r := mux.NewRouter()
  129. // r.HandleFunc("/users", UserEndpoint)
  130. // r.HandleFunc("/projects", ProjectEndpoint)
  131. //
  132. // // Apply the CORS middleware to our top-level router, with the defaults.
  133. // http.ListenAndServe(":8000", handlers.CORS()(r))
  134. // }
  135. func CORS(opts ...CORSOption) func(http.Handler) http.Handler {
  136. return func(h http.Handler) http.Handler {
  137. ch := parseCORSOptions(opts...)
  138. ch.h = h
  139. return ch
  140. }
  141. }
  142. func parseCORSOptions(opts ...CORSOption) *cors {
  143. ch := &cors{
  144. allowedMethods: defaultCorsMethods,
  145. allowedHeaders: defaultCorsHeaders,
  146. allowedOrigins: []string{},
  147. optionStatusCode: defaultCorsOptionStatusCode,
  148. }
  149. for _, option := range opts {
  150. _ = option(ch) //TODO: @bharat-rajani, return error to caller if not nil?
  151. }
  152. return ch
  153. }
  154. //
  155. // Functional options for configuring CORS.
  156. //
  157. // AllowedHeaders adds the provided headers to the list of allowed headers in a
  158. // CORS request.
  159. // This is an append operation so the headers Accept, Accept-Language,
  160. // and Content-Language are always allowed.
  161. // Content-Type must be explicitly declared if accepting Content-Types other than
  162. // application/x-www-form-urlencoded, multipart/form-data, or text/plain.
  163. func AllowedHeaders(headers []string) CORSOption {
  164. return func(ch *cors) error {
  165. for _, v := range headers {
  166. normalizedHeader := http.CanonicalHeaderKey(strings.TrimSpace(v))
  167. if normalizedHeader == "" {
  168. continue
  169. }
  170. if !ch.isMatch(normalizedHeader, ch.allowedHeaders) {
  171. ch.allowedHeaders = append(ch.allowedHeaders, normalizedHeader)
  172. }
  173. }
  174. return nil
  175. }
  176. }
  177. // AllowedMethods can be used to explicitly allow methods in the
  178. // Access-Control-Allow-Methods header.
  179. // This is a replacement operation so you must also
  180. // pass GET, HEAD, and POST if you wish to support those methods.
  181. func AllowedMethods(methods []string) CORSOption {
  182. return func(ch *cors) error {
  183. ch.allowedMethods = []string{}
  184. for _, v := range methods {
  185. normalizedMethod := strings.ToUpper(strings.TrimSpace(v))
  186. if normalizedMethod == "" {
  187. continue
  188. }
  189. if !ch.isMatch(normalizedMethod, ch.allowedMethods) {
  190. ch.allowedMethods = append(ch.allowedMethods, normalizedMethod)
  191. }
  192. }
  193. return nil
  194. }
  195. }
  196. // AllowedOrigins sets the allowed origins for CORS requests, as used in the
  197. // 'Allow-Access-Control-Origin' HTTP header.
  198. // Note: Passing in a []string{"*"} will allow any domain.
  199. func AllowedOrigins(origins []string) CORSOption {
  200. return func(ch *cors) error {
  201. for _, v := range origins {
  202. if v == corsOriginMatchAll {
  203. ch.allowedOrigins = []string{corsOriginMatchAll}
  204. return nil
  205. }
  206. }
  207. ch.allowedOrigins = origins
  208. return nil
  209. }
  210. }
  211. // AllowedOriginValidator sets a function for evaluating allowed origins in CORS requests, represented by the
  212. // 'Allow-Access-Control-Origin' HTTP header.
  213. func AllowedOriginValidator(fn OriginValidator) CORSOption {
  214. return func(ch *cors) error {
  215. ch.allowedOriginValidator = fn
  216. return nil
  217. }
  218. }
  219. // OptionStatusCode sets a custom status code on the OPTIONS requests.
  220. // Default behaviour sets it to 200 to reflect best practices. This is option is not mandatory
  221. // and can be used if you need a custom status code (i.e 204).
  222. //
  223. // More informations on the spec:
  224. // https://fetch.spec.whatwg.org/#cors-preflight-fetch
  225. func OptionStatusCode(code int) CORSOption {
  226. return func(ch *cors) error {
  227. ch.optionStatusCode = code
  228. return nil
  229. }
  230. }
  231. // ExposedHeaders can be used to specify headers that are available
  232. // and will not be stripped out by the user-agent.
  233. func ExposedHeaders(headers []string) CORSOption {
  234. return func(ch *cors) error {
  235. ch.exposedHeaders = []string{}
  236. for _, v := range headers {
  237. normalizedHeader := http.CanonicalHeaderKey(strings.TrimSpace(v))
  238. if normalizedHeader == "" {
  239. continue
  240. }
  241. if !ch.isMatch(normalizedHeader, ch.exposedHeaders) {
  242. ch.exposedHeaders = append(ch.exposedHeaders, normalizedHeader)
  243. }
  244. }
  245. return nil
  246. }
  247. }
  248. // MaxAge determines the maximum age (in seconds) between preflight requests. A
  249. // maximum of 10 minutes is allowed. An age above this value will default to 10
  250. // minutes.
  251. func MaxAge(age int) CORSOption {
  252. return func(ch *cors) error {
  253. // Maximum of 10 minutes.
  254. if age > 600 {
  255. age = 600
  256. }
  257. ch.maxAge = age
  258. return nil
  259. }
  260. }
  261. // IgnoreOptions causes the CORS middleware to ignore OPTIONS requests, instead
  262. // passing them through to the next handler. This is useful when your application
  263. // or framework has a pre-existing mechanism for responding to OPTIONS requests.
  264. func IgnoreOptions() CORSOption {
  265. return func(ch *cors) error {
  266. ch.ignoreOptions = true
  267. return nil
  268. }
  269. }
  270. // AllowCredentials can be used to specify that the user agent may pass
  271. // authentication details along with the request.
  272. func AllowCredentials() CORSOption {
  273. return func(ch *cors) error {
  274. ch.allowCredentials = true
  275. return nil
  276. }
  277. }
  278. func (ch *cors) isOriginAllowed(origin string) bool {
  279. if origin == "" {
  280. return false
  281. }
  282. if ch.allowedOriginValidator != nil {
  283. return ch.allowedOriginValidator(origin)
  284. }
  285. if len(ch.allowedOrigins) == 0 {
  286. return true
  287. }
  288. for _, allowedOrigin := range ch.allowedOrigins {
  289. if allowedOrigin == origin || allowedOrigin == corsOriginMatchAll {
  290. return true
  291. }
  292. }
  293. return false
  294. }
  295. func (ch *cors) isMatch(needle string, haystack []string) bool {
  296. for _, v := range haystack {
  297. if v == needle {
  298. return true
  299. }
  300. }
  301. return false
  302. }