ingress-nginx-helm/internal/ingress/annotations/cors/main.go
Christopher Larivière 65b8eeddec
Support cors-allow-origin with multiple origins (#7614)
* Add Initial support for multiple cors origins in nginx

- bump cluster version for `make dev-env`
- add buildOriginRegex function in nginx.tmpl
- add e2e 4 e2e tests for cors.go
- refers to feature request #5496

* add tests + use search to identify '*' origin

* add tests + use search to identify '*' origin

Signed-off-by: Christopher Larivière <lariviere.c@gmail.com>

* fix "should enable cors test" looking at improper values

* Modify tests and add some logic for origin validation

- add origin validation in cors ingress annotations
- add extra tests to validate regex
- properly escape regex using "QuoteMeta"
- fix some copy/paste errors

* add TrimSpace and length validation before adding a new origin

* modify documentation for cors and remove dangling comment

* add support for optional port mapping on origin

* support single-level wildcard subdomains + tests

* Remove automatic `*` fonctionality from incorrect origins

- use []string instead of basic string to avoid reparsing in template.go
- fix typo in docs
- modify template to properly enable only if the whole block is enabled
- modify cors parsing
- test properly by validating that the value returned is the proper
  origin
- update unit tests and annotation tests

* Re-add `*` when no cors origins are supplied + fix tests

- fix e2e tests to allow for `*`
- re-add `*` to cors parsing if trimmed cors-allow-origin is empty
(supplied but empty) and if it wasn't supplied at all.

* remove unecessary logic for building cors origin + remove comments

- add some edge cases in e2e tests
- rework logic for building cors origin

there was no need for logic in template.go for buildCorsOriginRegex
if there is a `*` it ill be short-circuited by first if.

if it's a wildcard domain or any domain (without a wildcard), it MUST
match the main/cors.go regex format.

if there's a star in a wildcard domain, it must be replaced with
`[A-Za-z0-9]+`

* add missing check in e2e tests
2021-11-02 12:31:42 -07:00

169 lines
5.3 KiB
Go

/*
Copyright 2016 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package cors
import (
"regexp"
"strings"
networking "k8s.io/api/networking/v1"
"k8s.io/klog/v2"
"k8s.io/ingress-nginx/internal/ingress/annotations/parser"
"k8s.io/ingress-nginx/internal/ingress/resolver"
)
const (
// Default values
defaultCorsMethods = "GET, PUT, POST, DELETE, PATCH, OPTIONS"
defaultCorsHeaders = "DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization"
defaultCorsMaxAge = 1728000
)
var (
// Regex are defined here to prevent information leak, if user tries to set anything not valid
// that could cause the Response to contain some internal value/variable (like returning $pid, $upstream_addr, etc)
// Origin must contain a http/s Origin (including or not the port) or the value '*'
corsOriginRegex = regexp.MustCompile(`^(https?://(\*\.)?[A-Za-z0-9\-\.]*(:[0-9]+)?|\*)?$`)
// Method must contain valid methods list (PUT, GET, POST, BLA)
// May contain or not spaces between each verb
corsMethodsRegex = regexp.MustCompile(`^([A-Za-z]+,?\s?)+$`)
// Headers must contain valid values only (X-HEADER12, X-ABC)
// May contain or not spaces between each Header
corsHeadersRegex = regexp.MustCompile(`^([A-Za-z0-9\-\_]+,?\s?)+$`)
// Expose Headers must contain valid values only (*, X-HEADER12, X-ABC)
// May contain or not spaces between each Header
corsExposeHeadersRegex = regexp.MustCompile(`^(([A-Za-z0-9\-\_]+|\*),?\s?)+$`)
)
type cors struct {
r resolver.Resolver
}
// Config contains the Cors configuration to be used in the Ingress
type Config struct {
CorsEnabled bool `json:"corsEnabled"`
CorsAllowOrigin []string `json:"corsAllowOrigin"`
CorsAllowMethods string `json:"corsAllowMethods"`
CorsAllowHeaders string `json:"corsAllowHeaders"`
CorsAllowCredentials bool `json:"corsAllowCredentials"`
CorsExposeHeaders string `json:"corsExposeHeaders"`
CorsMaxAge int `json:"corsMaxAge"`
}
// NewParser creates a new CORS annotation parser
func NewParser(r resolver.Resolver) parser.IngressAnnotation {
return cors{r}
}
// Equal tests for equality between two External types
func (c1 *Config) Equal(c2 *Config) bool {
if c1 == c2 {
return true
}
if c1 == nil || c2 == nil {
return false
}
if c1.CorsMaxAge != c2.CorsMaxAge {
return false
}
if c1.CorsExposeHeaders != c2.CorsExposeHeaders {
return false
}
if c1.CorsAllowCredentials != c2.CorsAllowCredentials {
return false
}
if c1.CorsAllowHeaders != c2.CorsAllowHeaders {
return false
}
if c1.CorsAllowMethods != c2.CorsAllowMethods {
return false
}
if c1.CorsEnabled != c2.CorsEnabled {
return false
}
if len(c1.CorsAllowOrigin) != len(c2.CorsAllowOrigin) {
return false
}
for i, v := range c1.CorsAllowOrigin {
if v != c2.CorsAllowOrigin[i] {
return false
}
}
return true
}
// Parse parses the annotations contained in the ingress
// rule used to indicate if the location/s should allows CORS
func (c cors) Parse(ing *networking.Ingress) (interface{}, error) {
var err error
config := &Config{}
config.CorsEnabled, err = parser.GetBoolAnnotation("enable-cors", ing)
if err != nil {
config.CorsEnabled = false
}
unparsedOrigins, err := parser.GetStringAnnotation("cors-allow-origin", ing)
if err == nil {
config.CorsAllowOrigin = strings.Split(unparsedOrigins, ",")
for i, origin := range config.CorsAllowOrigin {
origin = strings.TrimSpace(origin)
if origin == "*" {
config.CorsAllowOrigin = []string{"*"}
break
}
if !corsOriginRegex.MatchString(origin) {
klog.Errorf("Error parsing cors-allow-origin parameters. Supplied incorrect origin: %s. Skipping.", origin)
config.CorsAllowOrigin = append(config.CorsAllowOrigin[:i], config.CorsAllowOrigin[i+1:]...)
}
klog.Infof("Current config.corsAllowOrigin %v", config.CorsAllowOrigin)
}
} else {
config.CorsAllowOrigin = []string{"*"}
}
config.CorsAllowHeaders, err = parser.GetStringAnnotation("cors-allow-headers", ing)
if err != nil || !corsHeadersRegex.MatchString(config.CorsAllowHeaders) {
config.CorsAllowHeaders = defaultCorsHeaders
}
config.CorsAllowMethods, err = parser.GetStringAnnotation("cors-allow-methods", ing)
if err != nil || !corsMethodsRegex.MatchString(config.CorsAllowMethods) {
config.CorsAllowMethods = defaultCorsMethods
}
config.CorsAllowCredentials, err = parser.GetBoolAnnotation("cors-allow-credentials", ing)
if err != nil {
config.CorsAllowCredentials = true
}
config.CorsExposeHeaders, err = parser.GetStringAnnotation("cors-expose-headers", ing)
if err != nil || !corsExposeHeadersRegex.MatchString(config.CorsExposeHeaders) {
config.CorsExposeHeaders = ""
}
config.CorsMaxAge, err = parser.GetIntAnnotation("cors-max-age", ing)
if err != nil {
config.CorsMaxAge = defaultCorsMaxAge
}
return config, nil
}