Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
100 changes: 100 additions & 0 deletions config/webhook/manifests.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,86 @@ kind: ValidatingWebhookConfiguration
metadata:
name: validating-webhook-configuration
webhooks:
- admissionReviewVersions:
- v1
clientConfig:
service:
name: webhook-service
namespace: system
path: /validate-apisix-apache-org-v2-apisixconsumer
failurePolicy: Fail
name: vapisixconsumer-v2.kb.io
rules:
- apiGroups:
- apisix.apache.org
apiVersions:
- v2
operations:
- CREATE
- UPDATE
resources:
- apisixconsumers
sideEffects: None
- admissionReviewVersions:
- v1
clientConfig:
service:
name: webhook-service
namespace: system
path: /validate-apisix-apache-org-v2-apisixroute
failurePolicy: Fail
name: vapisixroute-v2.kb.io
rules:
- apiGroups:
- apisix.apache.org
apiVersions:
- v2
operations:
- CREATE
- UPDATE
resources:
- apisixroutes
sideEffects: None
- admissionReviewVersions:
- v1
clientConfig:
service:
name: webhook-service
namespace: system
path: /validate-apisix-apache-org-v2-apisixtls
failurePolicy: Fail
name: vapisixtls-v2.kb.io
rules:
- apiGroups:
- apisix.apache.org
apiVersions:
- v2
operations:
- CREATE
- UPDATE
resources:
- apisixtlses
sideEffects: None
- admissionReviewVersions:
- v1
clientConfig:
service:
name: webhook-service
namespace: system
path: /validate-apisix-apache-org-v1alpha1-consumer
failurePolicy: Fail
name: vconsumer-v1alpha1.kb.io
rules:
- apiGroups:
- apisix.apache.org
apiVersions:
- v1alpha1
operations:
- CREATE
- UPDATE
resources:
- consumers
sideEffects: None
- admissionReviewVersions:
- v1
clientConfig:
Expand All @@ -24,6 +104,26 @@ webhooks:
resources:
- gateways
sideEffects: None
- admissionReviewVersions:
- v1
clientConfig:
service:
name: webhook-service
namespace: system
path: /validate-apisix-apache-org-v1alpha1-gatewayproxy
failurePolicy: Fail
name: vgatewayproxy-v1alpha1.kb.io
rules:
- apiGroups:
- apisix.apache.org
apiVersions:
- v1alpha1
operations:
- CREATE
- UPDATE
resources:
- gatewayproxies
sideEffects: None
- admissionReviewVersions:
- v1
clientConfig:
Expand Down
15 changes: 15 additions & 0 deletions internal/manager/webhooks.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,20 @@ func setupWebhooks(_ context.Context, mgr manager.Manager) error {
if err := webhookv1.SetupGatewayWebhookWithManager(mgr); err != nil {
return err
}
if err := webhookv1.SetupGatewayProxyWebhookWithManager(mgr); err != nil {
return err
}
if err := webhookv1.SetupApisixConsumerWebhookWithManager(mgr); err != nil {
return err
}
if err := webhookv1.SetupApisixTlsWebhookWithManager(mgr); err != nil {
return err
}
if err := webhookv1.SetupApisixRouteWebhookWithManager(mgr); err != nil {
return err
}
if err := webhookv1.SetupConsumerWebhookWithManager(mgr); err != nil {
return err
}
return nil
}
123 changes: 123 additions & 0 deletions internal/webhook/v1/apisixconsumer_webhook.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You 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 v1

import (
"context"
"fmt"

corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/types"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
logf "sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/webhook"
"sigs.k8s.io/controller-runtime/pkg/webhook/admission"

apisixv2 "github.com/apache/apisix-ingress-controller/api/v2"
"github.com/apache/apisix-ingress-controller/internal/webhook/v1/reference"
)

var apisixConsumerLog = logf.Log.WithName("apisixconsumer-resource")

func SetupApisixConsumerWebhookWithManager(mgr ctrl.Manager) error {
return ctrl.NewWebhookManagedBy(mgr).
For(&apisixv2.ApisixConsumer{}).
WithValidator(NewApisixConsumerCustomValidator(mgr.GetClient())).
Complete()
}

// +kubebuilder:webhook:path=/validate-apisix-apache-org-v2-apisixconsumer,mutating=false,failurePolicy=fail,sideEffects=None,groups=apisix.apache.org,resources=apisixconsumers,verbs=create;update,versions=v2,name=vapisixconsumer-v2.kb.io,admissionReviewVersions=v1

type ApisixConsumerCustomValidator struct {
Client client.Client
checker reference.Checker
}

var _ webhook.CustomValidator = &ApisixConsumerCustomValidator{}

func NewApisixConsumerCustomValidator(c client.Client) *ApisixConsumerCustomValidator {
return &ApisixConsumerCustomValidator{
Client: c,
checker: reference.NewChecker(c, apisixConsumerLog),
}
}

func (v *ApisixConsumerCustomValidator) ValidateCreate(ctx context.Context, obj runtime.Object) (admission.Warnings, error) {
consumer, ok := obj.(*apisixv2.ApisixConsumer)
if !ok {
return nil, fmt.Errorf("expected an ApisixConsumer object but got %T", obj)
}
apisixConsumerLog.Info("Validation for ApisixConsumer upon creation", "name", consumer.GetName(), "namespace", consumer.GetNamespace())

return v.collectWarnings(ctx, consumer), nil
}

func (v *ApisixConsumerCustomValidator) ValidateUpdate(ctx context.Context, oldObj, newObj runtime.Object) (admission.Warnings, error) {
consumer, ok := newObj.(*apisixv2.ApisixConsumer)
if !ok {
return nil, fmt.Errorf("expected an ApisixConsumer object for the newObj but got %T", newObj)
}
apisixConsumerLog.Info("Validation for ApisixConsumer upon update", "name", consumer.GetName(), "namespace", consumer.GetNamespace())

return v.collectWarnings(ctx, consumer), nil
}

func (*ApisixConsumerCustomValidator) ValidateDelete(context.Context, runtime.Object) (admission.Warnings, error) {
return nil, nil
}

func (v *ApisixConsumerCustomValidator) collectWarnings(ctx context.Context, consumer *apisixv2.ApisixConsumer) admission.Warnings {
namespace := consumer.GetNamespace()
var warnings admission.Warnings

addSecretWarning := func(ref *corev1.LocalObjectReference) {
if ref == nil || ref.Name == "" {
return
}

warnings = append(warnings, v.checker.Secret(ctx, reference.SecretRef{
Object: consumer,
NamespacedName: types.NamespacedName{
Namespace: namespace,
Name: ref.Name,
},
})...)
}

params := consumer.Spec.AuthParameter
if params.BasicAuth != nil {
addSecretWarning(params.BasicAuth.SecretRef)
}
if params.KeyAuth != nil {
addSecretWarning(params.KeyAuth.SecretRef)
}
if params.WolfRBAC != nil {
addSecretWarning(params.WolfRBAC.SecretRef)
}
if params.JwtAuth != nil {
addSecretWarning(params.JwtAuth.SecretRef)
}
if params.HMACAuth != nil {
addSecretWarning(params.HMACAuth.SecretRef)
}
if params.LDAPAuth != nil {
addSecretWarning(params.LDAPAuth.SecretRef)
}

return warnings
}
137 changes: 137 additions & 0 deletions internal/webhook/v1/apisixconsumer_webhook_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
// Licensed to the Apache Software Foundation (ASF) under one or more
// contributor license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright ownership.
// The ASF licenses this file to You 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 v1

import (
"context"
"testing"

"github.com/stretchr/testify/require"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
"sigs.k8s.io/controller-runtime/pkg/client/fake"

apisixv2 "github.com/apache/apisix-ingress-controller/api/v2"
)

func buildApisixConsumerValidator(t *testing.T, objects ...runtime.Object) *ApisixConsumerCustomValidator {
t.Helper()

scheme := runtime.NewScheme()
require.NoError(t, clientgoscheme.AddToScheme(scheme))
require.NoError(t, apisixv2.AddToScheme(scheme))

builder := fake.NewClientBuilder().WithScheme(scheme)
if len(objects) > 0 {
builder = builder.WithRuntimeObjects(objects...)
}

return NewApisixConsumerCustomValidator(builder.Build())
}

func TestApisixConsumerValidator_MissingBasicAuthSecret(t *testing.T) {
consumer := &apisixv2.ApisixConsumer{
ObjectMeta: metav1.ObjectMeta{
Name: "demo",
Namespace: "default",
},
Spec: apisixv2.ApisixConsumerSpec{
AuthParameter: apisixv2.ApisixConsumerAuthParameter{
BasicAuth: &apisixv2.ApisixConsumerBasicAuth{
SecretRef: &corev1.LocalObjectReference{Name: "basic-auth"},
},
},
},
}

validator := buildApisixConsumerValidator(t)

warnings, err := validator.ValidateCreate(context.Background(), consumer)
require.NoError(t, err)
require.Equal(t, 1, len(warnings))
require.Equal(t, "Referenced Secret 'default/basic-auth' not found", warnings[0])
}

func TestApisixConsumerValidator_MultipleSecretWarnings(t *testing.T) {
consumer := &apisixv2.ApisixConsumer{
ObjectMeta: metav1.ObjectMeta{
Name: "demo",
Namespace: "default",
},
Spec: apisixv2.ApisixConsumerSpec{
AuthParameter: apisixv2.ApisixConsumerAuthParameter{
BasicAuth: &apisixv2.ApisixConsumerBasicAuth{
SecretRef: &corev1.LocalObjectReference{Name: "basic-auth"},
},
JwtAuth: &apisixv2.ApisixConsumerJwtAuth{
SecretRef: &corev1.LocalObjectReference{Name: "jwt-auth"},
},
HMACAuth: &apisixv2.ApisixConsumerHMACAuth{
SecretRef: &corev1.LocalObjectReference{Name: "hmac-auth"},
},
},
},
}

basicAuthSecret := &corev1.Secret{
ObjectMeta: metav1.ObjectMeta{
Name: "basic-auth",
Namespace: "default",
},
}

validator := buildApisixConsumerValidator(t, basicAuthSecret)

warnings, err := validator.ValidateCreate(context.Background(), consumer)
require.NoError(t, err)
require.Len(t, warnings, 2)
require.ElementsMatch(t, []string{
"Referenced Secret 'default/jwt-auth' not found",
"Referenced Secret 'default/hmac-auth' not found",
}, warnings)
}

func TestApisixConsumerValidator_NoWarningsWhenSecretsExist(t *testing.T) {
consumer := &apisixv2.ApisixConsumer{
ObjectMeta: metav1.ObjectMeta{
Name: "demo",
Namespace: "default",
},
Spec: apisixv2.ApisixConsumerSpec{
AuthParameter: apisixv2.ApisixConsumerAuthParameter{
KeyAuth: &apisixv2.ApisixConsumerKeyAuth{
SecretRef: &corev1.LocalObjectReference{Name: "key-auth"},
},
WolfRBAC: &apisixv2.ApisixConsumerWolfRBAC{
SecretRef: &corev1.LocalObjectReference{Name: "wolf-rbac"},
},
},
},
}

secrets := []runtime.Object{
&corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "key-auth", Namespace: "default"}},
&corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "wolf-rbac", Namespace: "default"}},
}

validator := buildApisixConsumerValidator(t, secrets...)

warnings, err := validator.ValidateCreate(context.Background(), consumer)
require.NoError(t, err)
require.Empty(t, warnings)
}
Loading
Loading