Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

admission-openstack: Adapt Secrets webhook to rely on the provider label #452

Merged
merged 2 commits into from
May 30, 2022
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
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ rules:
- apiGroups:
- core.gardener.cloud
resources:
- shoots
- cloudprofiles
- secretbindings
verbs:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ webhooks:
- UPDATE
resources:
- cloudprofiles
- secretbindings
- shoots
failurePolicy: Fail
timeoutSeconds: 10
Expand Down Expand Up @@ -49,7 +50,9 @@ webhooks:
resources:
- secrets
failurePolicy: Fail
objectSelector: {}
objectSelector:
matchLabels:
provider.shoot.gardener.cloud/openstack: "true"
namespaceSelector: {}
sideEffects: None
admissionReviewVersions:
Expand Down
10 changes: 0 additions & 10 deletions cmd/gardener-extension-admission-openstack/app/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,8 @@ import (

controllercmd "github.com/gardener/gardener/extensions/pkg/controller/cmd"
"github.com/gardener/gardener/extensions/pkg/util"
"github.com/gardener/gardener/extensions/pkg/util/index"
webhookcmd "github.com/gardener/gardener/extensions/pkg/webhook/cmd"
"github.com/gardener/gardener/pkg/apis/core/install"
gardencorev1beta1 "github.com/gardener/gardener/pkg/apis/core/v1beta1"
gardenerhealthz "github.com/gardener/gardener/pkg/healthz"
"github.com/spf13/cobra"
componentbaseconfig "k8s.io/component-base/config"
Expand Down Expand Up @@ -84,14 +82,6 @@ func NewAdmissionCommand(ctx context.Context) *cobra.Command {
return fmt.Errorf("could not update manager scheme: %w", err)
}

if err := mgr.GetFieldIndexer().IndexField(ctx, &gardencorev1beta1.SecretBinding{}, index.SecretRefNamespaceField, index.SecretRefNamespaceIndexerFunc); err != nil {
return err
}

if err := mgr.GetFieldIndexer().IndexField(ctx, &gardencorev1beta1.Shoot{}, index.SecretBindingNameField, index.SecretBindingNameIndexerFunc); err != nil {
return err
}

log.Info("Setting up webhook server")
if err := webhookOptions.Completed().AddToManager(mgr); err != nil {
return err
Expand Down
5 changes: 4 additions & 1 deletion example/40-validatingwebhookconfiguration.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ webhooks:
- UPDATE
resources:
- cloudprofiles
- secretbindings
- shoots
failurePolicy: Fail
timeoutSeconds: 10
Expand All @@ -41,7 +42,9 @@ webhooks:
resources:
- secrets
failurePolicy: Fail
objectSelector: {}
objectSelector:
matchLabels:
provider.shoot.gardener.cloud/openstack: "true"
namespaceSelector: {}
sideEffects: None
admissionReviewVersions:
Expand Down
76 changes: 76 additions & 0 deletions pkg/admission/validator/secretbinding.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
// Copyright (c) 2022 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// 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 validator

import (
"context"
"fmt"

openstackvalidation "github.com/gardener/gardener-extension-provider-openstack/pkg/apis/openstack/validation"

extensionswebhook "github.com/gardener/gardener/extensions/pkg/webhook"
"github.com/gardener/gardener/pkg/apis/core"
kutil "github.com/gardener/gardener/pkg/utils/kubernetes"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
"sigs.k8s.io/controller-runtime/pkg/client"
)

type secretBinding struct {
apiReader client.Reader
}

// InjectAPIReader injects the given apiReader into the validator.
func (sb *secretBinding) InjectAPIReader(apiReader client.Reader) error {
sb.apiReader = apiReader
return nil
}

// NewSecretBindingValidator returns a new instance of a secret binding validator.
func NewSecretBindingValidator() extensionswebhook.Validator {
return &secretBinding{}
}

// Validate checks whether the given SecretBinding refers to a Secret with valid OpenStack credentials.
func (sb *secretBinding) Validate(ctx context.Context, newObj, oldObj client.Object) error {
secretBinding, ok := newObj.(*core.SecretBinding)
if !ok {
return fmt.Errorf("wrong object type %T", newObj)
}

if oldObj != nil {
oldSecretBinding, ok := oldObj.(*core.SecretBinding)
if !ok {
return fmt.Errorf("wrong object type %T for old object", oldObj)
}

// If the provider type did not change, we exit early.
if oldSecretBinding.Provider != nil && equality.Semantic.DeepEqual(secretBinding.Provider.Type, oldSecretBinding.Provider.Type) {
return nil
}
}

var (
secret = &corev1.Secret{}
secretKey = kutil.Key(secretBinding.SecretRef.Namespace, secretBinding.SecretRef.Name)
)
// Explicitly use the client.Reader to prevent controller-runtime to start Informer for Secrets
// under the hood. The latter increases the memory usage of the component.
if err := sb.apiReader.Get(ctx, secretKey, secret); err != nil {
return err
}

return openstackvalidation.ValidateCloudProviderSecret(secret)
}
121 changes: 121 additions & 0 deletions pkg/admission/validator/secretbinding_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
// Copyright (c) 2022 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// 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 validator_test

import (
"context"
"fmt"

"github.com/gardener/gardener-extension-provider-openstack/pkg/admission/validator"
"github.com/gardener/gardener-extension-provider-openstack/pkg/openstack"

extensionswebhook "github.com/gardener/gardener/extensions/pkg/webhook"
"github.com/gardener/gardener/pkg/apis/core"
mockclient "github.com/gardener/gardener/pkg/mock/controller-runtime/client"
"github.com/golang/mock/gomock"
. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/runtime/inject"
)

var _ = Describe("SecretBinding validator", func() {

Describe("#Validate", func() {
const (
namespace = "garden-dev"
name = "my-provider-account"
)

var (
secretBindingValidator extensionswebhook.Validator

ctrl *gomock.Controller
apiReader *mockclient.MockReader

ctx = context.TODO()
secretBinding = &core.SecretBinding{
SecretRef: corev1.SecretReference{
Name: name,
Namespace: namespace,
},
}
fakeErr = fmt.Errorf("fake err")
)

BeforeEach(func() {
ctrl = gomock.NewController(GinkgoT())

secretBindingValidator = validator.NewSecretBindingValidator()
apiReader = mockclient.NewMockReader(ctrl)

err := secretBindingValidator.(inject.APIReader).InjectAPIReader(apiReader)
Expect(err).NotTo(HaveOccurred())
})

AfterEach(func() {
ctrl.Finish()
})

It("should return err when obj is not a SecretBinding", func() {
err := secretBindingValidator.Validate(ctx, &corev1.Secret{}, nil)
Expect(err).To(MatchError("wrong object type *v1.Secret"))
})

It("should return err when oldObj is not a SecretBinding", func() {
err := secretBindingValidator.Validate(ctx, &core.SecretBinding{}, &corev1.Secret{})
Expect(err).To(MatchError("wrong object type *v1.Secret for old object"))
})

It("should return err if it fails to get the corresponding Secret", func() {
apiReader.EXPECT().Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, gomock.AssignableToTypeOf(&corev1.Secret{})).Return(fakeErr)

err := secretBindingValidator.Validate(ctx, secretBinding, nil)
Expect(err).To(MatchError(fakeErr))
})

It("should return err when the corresponding Secret is not valid", func() {
apiReader.EXPECT().Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, gomock.AssignableToTypeOf(&corev1.Secret{})).
DoAndReturn(func(_ context.Context, _ client.ObjectKey, obj *corev1.Secret) error {
secret := &corev1.Secret{Data: map[string][]byte{
"foo": []byte("bar"),
}}
*obj = *secret
return nil
})

err := secretBindingValidator.Validate(ctx, secretBinding, nil)
Expect(err).To(HaveOccurred())
})

It("should return nil when the corresponding Secret is valid", func() {
apiReader.EXPECT().Get(ctx, client.ObjectKey{Namespace: namespace, Name: name}, gomock.AssignableToTypeOf(&corev1.Secret{})).
DoAndReturn(func(_ context.Context, _ client.ObjectKey, obj *corev1.Secret) error {
secret := &corev1.Secret{Data: map[string][]byte{
openstack.DomainName: []byte("domain"),
openstack.TenantName: []byte("tenant"),
openstack.UserName: []byte("user"),
openstack.Password: []byte("password"),
}}
*obj = *secret
return nil
})

err := secretBindingValidator.Validate(ctx, secretBinding, nil)
Expect(err).NotTo(HaveOccurred())
})
})
})
24 changes: 2 additions & 22 deletions pkg/admission/validator/secrets.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,32 +19,21 @@ import (
"fmt"

openstackvalidation "github.com/gardener/gardener-extension-provider-openstack/pkg/apis/openstack/validation"
"github.com/gardener/gardener-extension-provider-openstack/pkg/openstack"

secretutil "github.com/gardener/gardener/extensions/pkg/util/secret"
extensionswebhook "github.com/gardener/gardener/extensions/pkg/webhook"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
"sigs.k8s.io/controller-runtime/pkg/client"
)

type secret struct {
client client.Client
}
type secret struct{}

// NewSecretValidator returns a new instance of a secret validator.
func NewSecretValidator() extensionswebhook.Validator {
return &secret{}
}

// InjectClient injects the given client into the validator.
func (s *secret) InjectClient(client client.Client) error {
s.client = client
return nil
}

// Validate checks whether the given new secret is in use by Shoot with provider.type=openstack
// and if yes, it check whether the new secret contains valid access keys.
// Validate checks whether the given new secret contains valid OpenStack credentials.
func (s *secret) Validate(ctx context.Context, newObj, oldObj client.Object) error {
secret, ok := newObj.(*corev1.Secret)
if !ok {
Expand All @@ -62,14 +51,5 @@ func (s *secret) Validate(ctx context.Context, newObj, oldObj client.Object) err
}
}

isInUse, err := secretutil.IsSecretInUseByShoot(ctx, s.client, secret, openstack.Type)
if err != nil {
return err
}

if !isInUse {
return nil
}

return openstackvalidation.ValidateCloudProviderSecret(secret)
}
27 changes: 27 additions & 0 deletions pkg/admission/validator/validator_suite_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Copyright (c) 2022 SAP SE or an SAP affiliate company. All rights reserved. This file is licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
//
// 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 validator_test

import (
"testing"

. "github.com/onsi/ginkgo/v2"
. "github.com/onsi/gomega"
)

func TestValidator(t *testing.T) {
RegisterFailHandler(Fail)
RunSpecs(t, "Validator Suite")
}
5 changes: 3 additions & 2 deletions pkg/admission/validator/webhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,9 @@ func New(mgr manager.Manager) (*extensionswebhook.Webhook, error) {
Path: extensionswebhook.ValidatorPath,
Predicates: []predicate.Predicate{extensionspredicate.GardenCoreProviderType(openstack.Type)},
Validators: map[extensionswebhook.Validator][]extensionswebhook.Type{
NewShootValidator(): {{Obj: &core.Shoot{}}},
NewCloudProfileValidator(): {{Obj: &core.CloudProfile{}}},
NewShootValidator(): {{Obj: &core.Shoot{}}},
NewCloudProfileValidator(): {{Obj: &core.CloudProfile{}}},
NewSecretBindingValidator(): {{Obj: &core.SecretBinding{}}},
},
})
}
Expand Down
Loading