feat: add annotation to allow to add custom response headers (#9742)
* add custom headers Signed-off-by: Christian Groschupp <christian@groschupp.org> * add tests Signed-off-by: Christian Groschupp <christian@groschupp.org> * add docs * update copyright * change comments * add e2e test customheaders * add custom headers validation * remove escapeLiteralDollar filter * validate value in custom headers * add regex for header value * fix annotation test * Revert "remove escapeLiteralDollar filter" This reverts commit ab48392b60dee4ce146a4c17e046849f9633c7fb. * add annotationConfig * fix test * fix golangci-lint findings * fix: add missung exp module --------- Signed-off-by: Christian Groschupp <christian@groschupp.org>
This commit is contained in:
parent
d56aacdb31
commit
1f4ee0e235
15 changed files with 537 additions and 4 deletions
124
internal/ingress/annotations/customheaders/main.go
Normal file
124
internal/ingress/annotations/customheaders/main.go
Normal file
|
|
@ -0,0 +1,124 @@
|
|||
/*
|
||||
Copyright 2023 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 customheaders
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
|
||||
"k8s.io/klog/v2"
|
||||
|
||||
networking "k8s.io/api/networking/v1"
|
||||
|
||||
"golang.org/x/exp/slices"
|
||||
"k8s.io/ingress-nginx/internal/ingress/annotations/parser"
|
||||
ing_errors "k8s.io/ingress-nginx/internal/ingress/errors"
|
||||
"k8s.io/ingress-nginx/internal/ingress/resolver"
|
||||
)
|
||||
|
||||
// Config returns the custom response headers for an Ingress rule
|
||||
type Config struct {
|
||||
Headers map[string]string `json:"headers,omitempty"`
|
||||
}
|
||||
|
||||
var (
|
||||
headerRegexp = regexp.MustCompile(`^[a-zA-Z\d\-_]+$`)
|
||||
valueRegexp = regexp.MustCompile(`^[a-zA-Z\d_ :;.,\\/"'?!(){}\[\]@<>=\-+*#$&\x60|~^%]+$`)
|
||||
)
|
||||
|
||||
// ValidHeader checks is the provided string satisfies the header's name regex
|
||||
func ValidHeader(header string) bool {
|
||||
return headerRegexp.MatchString(header)
|
||||
}
|
||||
|
||||
// ValidValue checks is the provided string satisfies the value regex
|
||||
func ValidValue(header string) bool {
|
||||
return valueRegexp.MatchString(header)
|
||||
}
|
||||
|
||||
const (
|
||||
customHeadersConfigMapAnnotation = "custom-headers"
|
||||
)
|
||||
|
||||
var customHeadersAnnotation = parser.Annotation{
|
||||
Group: "backend",
|
||||
Annotations: parser.AnnotationFields{
|
||||
customHeadersConfigMapAnnotation: {
|
||||
Validator: parser.ValidateRegex(parser.BasicCharsRegex, true),
|
||||
Scope: parser.AnnotationScopeLocation,
|
||||
Risk: parser.AnnotationRiskMedium,
|
||||
Documentation: `This annotation sets the name of a ConfigMap that specifies headers to pass to the client.
|
||||
Only ConfigMaps on the same namespace are allowed`,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
type customHeaders struct {
|
||||
r resolver.Resolver
|
||||
annotationConfig parser.Annotation
|
||||
}
|
||||
|
||||
// NewParser creates a new custom response headers annotation parser
|
||||
func NewParser(r resolver.Resolver) parser.IngressAnnotation {
|
||||
return customHeaders{r: r, annotationConfig: customHeadersAnnotation}
|
||||
}
|
||||
|
||||
func (a customHeaders) GetDocumentation() parser.AnnotationFields {
|
||||
return a.annotationConfig.Annotations
|
||||
}
|
||||
|
||||
// Parse parses the annotations contained in the ingress to use
|
||||
// custom response headers
|
||||
func (a customHeaders) Parse(ing *networking.Ingress) (interface{}, error) {
|
||||
clientHeadersConfigMapName, err := parser.GetStringAnnotation(customHeadersConfigMapAnnotation, ing, a.annotationConfig.Annotations)
|
||||
if err != nil {
|
||||
klog.V(3).InfoS("client-headers annotation is undefined and will not be set")
|
||||
}
|
||||
|
||||
var headers map[string]string
|
||||
defBackend := a.r.GetDefaultBackend()
|
||||
|
||||
if clientHeadersConfigMapName != "" {
|
||||
clientHeadersMapContents, err := a.r.GetConfigMap(clientHeadersConfigMapName)
|
||||
if err != nil {
|
||||
return nil, ing_errors.NewLocationDenied(fmt.Sprintf("unable to find configMap %q", clientHeadersConfigMapName))
|
||||
}
|
||||
|
||||
for header, value := range clientHeadersMapContents.Data {
|
||||
if !ValidHeader(header) {
|
||||
return nil, ing_errors.NewLocationDenied("invalid header name in configmap")
|
||||
}
|
||||
if !ValidValue(value) {
|
||||
return nil, ing_errors.NewLocationDenied("invalid header value in configmap")
|
||||
}
|
||||
if !slices.Contains(defBackend.AllowedResponseHeaders, header) {
|
||||
return nil, ing_errors.NewLocationDenied(fmt.Sprintf("header %s is not allowed, defined allowed headers inside global-allowed-response-headers %v", header, defBackend.AllowedResponseHeaders))
|
||||
}
|
||||
}
|
||||
|
||||
headers = clientHeadersMapContents.Data
|
||||
}
|
||||
|
||||
return &Config{
|
||||
Headers: headers,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (a customHeaders) Validate(anns map[string]string) error {
|
||||
maxrisk := parser.StringRiskToRisk(a.r.GetSecurityConfiguration().AnnotationsRiskLevel)
|
||||
return parser.CheckAnnotationRisk(anns, maxrisk, customHeadersAnnotation.Annotations)
|
||||
}
|
||||
113
internal/ingress/annotations/customheaders/main_test.go
Normal file
113
internal/ingress/annotations/customheaders/main_test.go
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
/*
|
||||
Copyright 2023 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 customheaders
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
api "k8s.io/api/core/v1"
|
||||
networking "k8s.io/api/networking/v1"
|
||||
meta_v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
|
||||
"k8s.io/ingress-nginx/internal/ingress/annotations/parser"
|
||||
"k8s.io/ingress-nginx/internal/ingress/defaults"
|
||||
"k8s.io/ingress-nginx/internal/ingress/resolver"
|
||||
)
|
||||
|
||||
func buildIngress() *networking.Ingress {
|
||||
return &networking.Ingress{
|
||||
ObjectMeta: meta_v1.ObjectMeta{
|
||||
Name: "foo",
|
||||
Namespace: api.NamespaceDefault,
|
||||
},
|
||||
Spec: networking.IngressSpec{
|
||||
DefaultBackend: &networking.IngressBackend{
|
||||
Service: &networking.IngressServiceBackend{
|
||||
Name: "default-backend",
|
||||
Port: networking.ServiceBackendPort{
|
||||
Number: 80,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
type mockBackend struct {
|
||||
resolver.Mock
|
||||
}
|
||||
|
||||
// GetDefaultBackend returns the backend that must be used as default
|
||||
func (m mockBackend) GetDefaultBackend() defaults.Backend {
|
||||
return defaults.Backend{
|
||||
AllowedResponseHeaders: []string{"Content-Type", "Access-Control-Max-Age"},
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomHeadersParseInvalidAnnotations(t *testing.T) {
|
||||
ing := buildIngress()
|
||||
configMapResolver := mockBackend{}
|
||||
configMapResolver.ConfigMaps = map[string]*api.ConfigMap{}
|
||||
|
||||
_, err := NewParser(configMapResolver).Parse(ing)
|
||||
if err != nil {
|
||||
t.Errorf("expected error parsing ingress with custom-response-headers")
|
||||
}
|
||||
|
||||
data := map[string]string{}
|
||||
data[parser.GetAnnotationWithPrefix("custom-headers")] = "custom-headers-configmap"
|
||||
ing.SetAnnotations(data)
|
||||
i, err := NewParser(&resolver.Mock{}).Parse(ing)
|
||||
if err == nil {
|
||||
t.Errorf("expected error parsing ingress with custom-response-headers")
|
||||
}
|
||||
if i != nil {
|
||||
t.Errorf("expected %v but got %v", nil, i)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCustomHeadersParseAnnotations(t *testing.T) {
|
||||
ing := buildIngress()
|
||||
|
||||
data := map[string]string{}
|
||||
data[parser.GetAnnotationWithPrefix("custom-headers")] = "custom-headers-configmap"
|
||||
ing.SetAnnotations(data)
|
||||
|
||||
configMapResolver := mockBackend{}
|
||||
configMapResolver.ConfigMaps = map[string]*api.ConfigMap{}
|
||||
|
||||
configMapResolver.ConfigMaps["custom-headers-configmap"] = &api.ConfigMap{Data: map[string]string{"Content-Type": "application/json", "Access-Control-Max-Age": "600"}}
|
||||
|
||||
i, err := NewParser(configMapResolver).Parse(ing)
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error parsing ingress with custom-response-headers: %s", err)
|
||||
}
|
||||
val, ok := i.(*Config)
|
||||
if !ok {
|
||||
t.Errorf("expected a *Config type")
|
||||
}
|
||||
|
||||
expectedResponseHeaders := map[string]string{}
|
||||
expectedResponseHeaders["Content-Type"] = "application/json"
|
||||
expectedResponseHeaders["Access-Control-Max-Age"] = "600"
|
||||
|
||||
c := &Config{expectedResponseHeaders}
|
||||
|
||||
if !reflect.DeepEqual(c, val) {
|
||||
t.Errorf("expected %v but got %v", c, val)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue