cors.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. package cors
  2. import (
  3. "fmt"
  4. "net/http"
  5. "strconv"
  6. "strings"
  7. )
  8. // CORSRule represents a single CORS rule
  9. type CORSRule struct {
  10. AllowedHeaders []string `xml:"AllowedHeader,omitempty" json:"AllowedHeaders,omitempty"`
  11. AllowedMethods []string `xml:"AllowedMethod" json:"AllowedMethods"`
  12. AllowedOrigins []string `xml:"AllowedOrigin" json:"AllowedOrigins"`
  13. ExposeHeaders []string `xml:"ExposeHeader,omitempty" json:"ExposeHeaders,omitempty"`
  14. MaxAgeSeconds *int `xml:"MaxAgeSeconds,omitempty" json:"MaxAgeSeconds,omitempty"`
  15. ID string `xml:"ID,omitempty" json:"ID,omitempty"`
  16. }
  17. // CORSConfiguration represents the CORS configuration for a bucket
  18. type CORSConfiguration struct {
  19. CORSRules []CORSRule `xml:"CORSRule" json:"CORSRules"`
  20. }
  21. // CORSRequest represents a CORS request
  22. type CORSRequest struct {
  23. Origin string
  24. Method string
  25. RequestHeaders []string
  26. IsPreflightRequest bool
  27. AccessControlRequestMethod string
  28. AccessControlRequestHeaders []string
  29. }
  30. // CORSResponse represents the response for a CORS request
  31. type CORSResponse struct {
  32. AllowOrigin string
  33. AllowMethods string
  34. AllowHeaders string
  35. ExposeHeaders string
  36. MaxAge string
  37. AllowCredentials bool
  38. }
  39. // ValidateConfiguration validates a CORS configuration
  40. func ValidateConfiguration(config *CORSConfiguration) error {
  41. if config == nil {
  42. return fmt.Errorf("CORS configuration cannot be nil")
  43. }
  44. if len(config.CORSRules) == 0 {
  45. return fmt.Errorf("CORS configuration must have at least one rule")
  46. }
  47. if len(config.CORSRules) > 100 {
  48. return fmt.Errorf("CORS configuration cannot have more than 100 rules")
  49. }
  50. for i, rule := range config.CORSRules {
  51. if err := validateRule(&rule); err != nil {
  52. return fmt.Errorf("invalid CORS rule at index %d: %v", i, err)
  53. }
  54. }
  55. return nil
  56. }
  57. // ParseRequest parses an HTTP request to extract CORS information
  58. func ParseRequest(r *http.Request) *CORSRequest {
  59. corsReq := &CORSRequest{
  60. Origin: r.Header.Get("Origin"),
  61. Method: r.Method,
  62. }
  63. // Check if this is a preflight request
  64. if r.Method == "OPTIONS" {
  65. corsReq.IsPreflightRequest = true
  66. corsReq.AccessControlRequestMethod = r.Header.Get("Access-Control-Request-Method")
  67. if headers := r.Header.Get("Access-Control-Request-Headers"); headers != "" {
  68. corsReq.AccessControlRequestHeaders = strings.Split(headers, ",")
  69. for i := range corsReq.AccessControlRequestHeaders {
  70. corsReq.AccessControlRequestHeaders[i] = strings.TrimSpace(corsReq.AccessControlRequestHeaders[i])
  71. }
  72. }
  73. }
  74. return corsReq
  75. }
  76. // validateRule validates a single CORS rule
  77. func validateRule(rule *CORSRule) error {
  78. if len(rule.AllowedMethods) == 0 {
  79. return fmt.Errorf("AllowedMethods cannot be empty")
  80. }
  81. if len(rule.AllowedOrigins) == 0 {
  82. return fmt.Errorf("AllowedOrigins cannot be empty")
  83. }
  84. // Validate allowed methods
  85. validMethods := map[string]bool{
  86. "GET": true,
  87. "PUT": true,
  88. "POST": true,
  89. "DELETE": true,
  90. "HEAD": true,
  91. }
  92. for _, method := range rule.AllowedMethods {
  93. if !validMethods[method] {
  94. return fmt.Errorf("invalid HTTP method: %s", method)
  95. }
  96. }
  97. // Validate origins
  98. for _, origin := range rule.AllowedOrigins {
  99. if origin == "*" {
  100. continue
  101. }
  102. if err := validateOrigin(origin); err != nil {
  103. return fmt.Errorf("invalid origin %s: %v", origin, err)
  104. }
  105. }
  106. // Validate MaxAgeSeconds
  107. if rule.MaxAgeSeconds != nil && *rule.MaxAgeSeconds < 0 {
  108. return fmt.Errorf("MaxAgeSeconds cannot be negative")
  109. }
  110. return nil
  111. }
  112. // validateOrigin validates an origin string
  113. func validateOrigin(origin string) error {
  114. if origin == "" {
  115. return fmt.Errorf("origin cannot be empty")
  116. }
  117. // Special case: "*" is always valid
  118. if origin == "*" {
  119. return nil
  120. }
  121. // Count wildcards
  122. wildcardCount := strings.Count(origin, "*")
  123. if wildcardCount > 1 {
  124. return fmt.Errorf("origin can contain at most one wildcard")
  125. }
  126. // If there's a wildcard, it should be in a valid position
  127. if wildcardCount == 1 {
  128. // Must be in the format: http://*.example.com or https://*.example.com
  129. if !strings.HasPrefix(origin, "http://") && !strings.HasPrefix(origin, "https://") {
  130. return fmt.Errorf("origin with wildcard must start with http:// or https://")
  131. }
  132. }
  133. return nil
  134. }
  135. // EvaluateRequest evaluates a CORS request against a CORS configuration
  136. func EvaluateRequest(config *CORSConfiguration, corsReq *CORSRequest) (*CORSResponse, error) {
  137. if config == nil || corsReq == nil {
  138. return nil, fmt.Errorf("config and corsReq cannot be nil")
  139. }
  140. if corsReq.Origin == "" {
  141. return nil, fmt.Errorf("origin header is required for CORS requests")
  142. }
  143. // Find the first rule that matches the origin
  144. for _, rule := range config.CORSRules {
  145. if matchesOrigin(rule.AllowedOrigins, corsReq.Origin) {
  146. // For preflight requests, we need more detailed validation
  147. if corsReq.IsPreflightRequest {
  148. return buildPreflightResponse(&rule, corsReq), nil
  149. } else {
  150. // For actual requests, check method
  151. if containsString(rule.AllowedMethods, corsReq.Method) {
  152. return buildResponse(&rule, corsReq), nil
  153. }
  154. }
  155. }
  156. }
  157. return nil, fmt.Errorf("no matching CORS rule found")
  158. }
  159. // buildPreflightResponse builds a CORS response for preflight requests
  160. func buildPreflightResponse(rule *CORSRule, corsReq *CORSRequest) *CORSResponse {
  161. response := &CORSResponse{
  162. AllowOrigin: corsReq.Origin,
  163. }
  164. // Check if the requested method is allowed
  165. methodAllowed := corsReq.AccessControlRequestMethod == "" || containsString(rule.AllowedMethods, corsReq.AccessControlRequestMethod)
  166. // Check requested headers
  167. var allowedRequestHeaders []string
  168. allHeadersAllowed := true
  169. if len(corsReq.AccessControlRequestHeaders) > 0 {
  170. // Check if wildcard is allowed
  171. hasWildcard := false
  172. for _, header := range rule.AllowedHeaders {
  173. if header == "*" {
  174. hasWildcard = true
  175. break
  176. }
  177. }
  178. if hasWildcard {
  179. // All requested headers are allowed with wildcard
  180. allowedRequestHeaders = corsReq.AccessControlRequestHeaders
  181. } else {
  182. // Check each requested header individually
  183. for _, requestedHeader := range corsReq.AccessControlRequestHeaders {
  184. if matchesHeader(rule.AllowedHeaders, requestedHeader) {
  185. allowedRequestHeaders = append(allowedRequestHeaders, requestedHeader)
  186. } else {
  187. allHeadersAllowed = false
  188. }
  189. }
  190. }
  191. }
  192. // Only set method and header info if both method and ALL headers are allowed
  193. if methodAllowed && allHeadersAllowed {
  194. response.AllowMethods = strings.Join(rule.AllowedMethods, ", ")
  195. if len(allowedRequestHeaders) > 0 {
  196. response.AllowHeaders = strings.Join(allowedRequestHeaders, ", ")
  197. }
  198. // Set exposed headers
  199. if len(rule.ExposeHeaders) > 0 {
  200. response.ExposeHeaders = strings.Join(rule.ExposeHeaders, ", ")
  201. }
  202. // Set max age
  203. if rule.MaxAgeSeconds != nil {
  204. response.MaxAge = strconv.Itoa(*rule.MaxAgeSeconds)
  205. }
  206. }
  207. return response
  208. }
  209. // buildResponse builds a CORS response from a matching rule
  210. func buildResponse(rule *CORSRule, corsReq *CORSRequest) *CORSResponse {
  211. response := &CORSResponse{
  212. AllowOrigin: corsReq.Origin,
  213. }
  214. // Set allowed methods
  215. response.AllowMethods = strings.Join(rule.AllowedMethods, ", ")
  216. // Set allowed headers
  217. if len(rule.AllowedHeaders) > 0 {
  218. response.AllowHeaders = strings.Join(rule.AllowedHeaders, ", ")
  219. }
  220. // Set expose headers
  221. if len(rule.ExposeHeaders) > 0 {
  222. response.ExposeHeaders = strings.Join(rule.ExposeHeaders, ", ")
  223. }
  224. // Set max age
  225. if rule.MaxAgeSeconds != nil {
  226. response.MaxAge = strconv.Itoa(*rule.MaxAgeSeconds)
  227. }
  228. return response
  229. }
  230. // Helper functions
  231. // matchesOrigin checks if the request origin matches any allowed origin
  232. func matchesOrigin(allowedOrigins []string, origin string) bool {
  233. for _, allowedOrigin := range allowedOrigins {
  234. if allowedOrigin == "*" {
  235. return true
  236. }
  237. if allowedOrigin == origin {
  238. return true
  239. }
  240. // Handle wildcard patterns like https://*.example.com
  241. if strings.Contains(allowedOrigin, "*") {
  242. if matchWildcard(allowedOrigin, origin) {
  243. return true
  244. }
  245. }
  246. }
  247. return false
  248. }
  249. // matchWildcard performs wildcard matching for origins
  250. func matchWildcard(pattern, text string) bool {
  251. // Simple wildcard matching - only supports single * at the beginning
  252. if strings.HasPrefix(pattern, "http://*") {
  253. suffix := pattern[8:] // Remove "http://*"
  254. return strings.HasPrefix(text, "http://") && strings.HasSuffix(text, suffix)
  255. }
  256. if strings.HasPrefix(pattern, "https://*") {
  257. suffix := pattern[9:] // Remove "https://*"
  258. return strings.HasPrefix(text, "https://") && strings.HasSuffix(text, suffix)
  259. }
  260. return false
  261. }
  262. // matchesHeader checks if a header is allowed
  263. func matchesHeader(allowedHeaders []string, header string) bool {
  264. // If no headers are specified, all headers are allowed
  265. if len(allowedHeaders) == 0 {
  266. return true
  267. }
  268. // Header matching is case-insensitive
  269. header = strings.ToLower(header)
  270. for _, allowedHeader := range allowedHeaders {
  271. allowedHeaderLower := strings.ToLower(allowedHeader)
  272. // Wildcard match
  273. if allowedHeaderLower == "*" {
  274. return true
  275. }
  276. // Exact match
  277. if allowedHeaderLower == header {
  278. return true
  279. }
  280. // Prefix wildcard match (e.g., "x-amz-*" matches "x-amz-date")
  281. if strings.HasSuffix(allowedHeaderLower, "*") {
  282. prefix := strings.TrimSuffix(allowedHeaderLower, "*")
  283. if strings.HasPrefix(header, prefix) {
  284. return true
  285. }
  286. }
  287. }
  288. return false
  289. }
  290. // containsString checks if a slice contains a specific string
  291. func containsString(slice []string, item string) bool {
  292. for _, s := range slice {
  293. if s == item {
  294. return true
  295. }
  296. }
  297. return false
  298. }
  299. // ApplyHeaders applies CORS headers to an HTTP response
  300. func ApplyHeaders(w http.ResponseWriter, corsResp *CORSResponse) {
  301. if corsResp == nil {
  302. return
  303. }
  304. if corsResp.AllowOrigin != "" {
  305. w.Header().Set("Access-Control-Allow-Origin", corsResp.AllowOrigin)
  306. }
  307. if corsResp.AllowMethods != "" {
  308. w.Header().Set("Access-Control-Allow-Methods", corsResp.AllowMethods)
  309. }
  310. if corsResp.AllowHeaders != "" {
  311. w.Header().Set("Access-Control-Allow-Headers", corsResp.AllowHeaders)
  312. }
  313. if corsResp.ExposeHeaders != "" {
  314. w.Header().Set("Access-Control-Expose-Headers", corsResp.ExposeHeaders)
  315. }
  316. if corsResp.MaxAge != "" {
  317. w.Header().Set("Access-Control-Max-Age", corsResp.MaxAge)
  318. }
  319. if corsResp.AllowCredentials {
  320. w.Header().Set("Access-Control-Allow-Credentials", "true")
  321. }
  322. }