Skip to content

Commit

Permalink
Merge pull request #1358 from binbin-li/multi-tenancy-pr-2
Browse files Browse the repository at this point in the history
feat: add verifiers interface to wrap up operations on namespaced verifiers [multi-tenancy PR 2]
  • Loading branch information
binbin-li authored Apr 10, 2024
2 parents 034f5ec + 73ef709 commit 6a93bbf
Show file tree
Hide file tree
Showing 11 changed files with 312 additions and 80 deletions.
11 changes: 6 additions & 5 deletions config/configManager.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ limitations under the License.
package config

import (
"context"
"os"
"time"

Expand All @@ -25,7 +26,7 @@ import (
"github.com/sirupsen/logrus"
)

type GetExecutor func() *ef.Executor
type GetExecutor func(context.Context) *ef.Executor

var (
configHash string
Expand All @@ -38,15 +39,15 @@ func GetExecutorAndWatchForUpdate(configFilePath string) (GetExecutor, error) {
cf, err := Load(configFilePath)

if err != nil {
return func() *ef.Executor { return &ef.Executor{} }, err
return func(context.Context) *ef.Executor { return &ef.Executor{} }, err
}

configHash = cf.fileHash

stores, verifiers, policyEnforcer, err := CreateFromConfig(cf)

if err != nil {
return func() *ef.Executor { return &ef.Executor{} }, err
return func(context.Context) *ef.Executor { return &ef.Executor{} }, err
}

executor = ef.Executor{
Expand All @@ -59,12 +60,12 @@ func GetExecutorAndWatchForUpdate(configFilePath string) (GetExecutor, error) {
err = watchForConfigurationChange(configFilePath)

if err != nil {
return func() *ef.Executor { return &ef.Executor{} }, err
return func(context.Context) *ef.Executor { return &ef.Executor{} }, err
}

logrus.Info("configuration successfully loaded.")

return func() *ef.Executor { return &executor }, nil
return func(context.Context) *ef.Executor { return &executor }, nil
}

func reloadExecutor(configFilePath string) {
Expand Down
39 changes: 21 additions & 18 deletions httpserver/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,11 +83,6 @@ func (server *Server) verify(ctx context.Context, w http.ResponseWriter, r *http
results = append(results, returnItem)
mu.Unlock()
}()
if err := server.validateComponents(verifyComponents); err != nil {
logger.GetLogger(ctx, server.LogOption).Error(err)
returnItem.Error = err.Error()
return
}
requestKey, err := pkgUtils.ParseRequestKey(key)
if err != nil {
returnItem.Error = err.Error()
Expand All @@ -100,6 +95,12 @@ func (server *Server) verify(ctx context.Context, w http.ResponseWriter, r *http
}
ctx = ctxUtils.SetContextWithNamespace(ctx, requestKey.Namespace)

if err := server.validateComponents(ctx, verifyComponents); err != nil {
logger.GetLogger(ctx, server.LogOption).Error(err)
returnItem.Error = err.Error()
return
}

if subjectReference.Digest.String() == "" {
logger.GetLogger(ctx, server.LogOption).Warn("Digest should be used instead of tagged reference. The resolved digest may not point to the same signed artifact, since tags are mutable.")
}
Expand Down Expand Up @@ -129,7 +130,7 @@ func (server *Server) verify(ctx context.Context, w http.ResponseWriter, r *http
verifyParameters := executor.VerifyParameters{
Subject: resolvedSubjectReference,
}
if result, err = server.GetExecutor().VerifySubject(ctx, verifyParameters); err != nil {
if result, err = server.GetExecutor(ctx).VerifySubject(ctx, verifyParameters); err != nil {
returnItem.Error = errors.ErrorCodeExecutorFailure.WithError(err).WithComponentType(errors.Executor).Error()
return
}
Expand All @@ -145,7 +146,7 @@ func (server *Server) verify(ctx context.Context, w http.ResponseWriter, r *http
logger.GetLogger(ctx, server.LogOption).Infof("verify result for subject %s: %s", resolvedSubjectReference, string(res))
}
}
returnItem.Value = fromVerifyResult(result, server.GetExecutor().PolicyEnforcer.GetPolicyType(ctx))
returnItem.Value = fromVerifyResult(result, server.GetExecutor(ctx).PolicyEnforcer.GetPolicyType(ctx))
logger.GetLogger(ctx, server.LogOption).Debugf("verification: execution time for image %s: %dms", resolvedSubjectReference, time.Since(routineStartTime).Milliseconds())
}(utils.SanitizeString(key), ctx)
}
Expand Down Expand Up @@ -192,11 +193,6 @@ func (server *Server) mutate(ctx context.Context, w http.ResponseWriter, r *http
results = append(results, returnItem)
mu.Unlock()
}()
if err := server.validateComponents(mutateComponents); err != nil {
logger.GetLogger(ctx, server.LogOption).Error(err)
returnItem.Error = err.Error()
return
}
requestKey, err := pkgUtils.ParseRequestKey(image)
if err != nil {
returnItem.Error = err.Error()
Expand All @@ -209,11 +205,18 @@ func (server *Server) mutate(ctx context.Context, w http.ResponseWriter, r *http
returnItem.Error = err.Error()
return
}

ctx = ctxUtils.SetContextWithNamespace(ctx, requestKey.Namespace)

if err := server.validateComponents(ctx, mutateComponents); err != nil {
logger.GetLogger(ctx, server.LogOption).Error(err)
returnItem.Error = err.Error()
return
}

if parsedReference.Digest == "" {
var selectedStore referrerstore.ReferrerStore
for _, store := range server.GetExecutor().ReferrerStores {
for _, store := range server.GetExecutor(ctx).ReferrerStores {
if store.Name() == server.MutationStoreName {
selectedStore = store
break
Expand Down Expand Up @@ -243,20 +246,20 @@ func (server *Server) mutate(ctx context.Context, w http.ResponseWriter, r *http
return sendResponse(&results, "", w, http.StatusOK, true)
}

func (server *Server) validateComponents(handlerComponents string) error {
func (server *Server) validateComponents(ctx context.Context, handlerComponents string) error {
if handlerComponents == mutateComponents {
if len(server.GetExecutor().ReferrerStores) == 0 {
if len(server.GetExecutor(ctx).ReferrerStores) == 0 {
return errors.ErrorCodeConfigInvalid.WithComponentType(errors.ReferrerStore).WithDetail("referrer store config should have at least one store")
}
}
if handlerComponents == verifyComponents {
if len(server.GetExecutor().ReferrerStores) == 0 {
if len(server.GetExecutor(ctx).ReferrerStores) == 0 {
return errors.ErrorCodeConfigInvalid.WithComponentType(errors.ReferrerStore).WithDetail("referrer store config should have at least one store")
}
if server.GetExecutor().PolicyEnforcer == nil {
if server.GetExecutor(ctx).PolicyEnforcer == nil {
return errors.ErrorCodeConfigInvalid.WithComponentType(errors.PolicyProvider).WithDetail("policy provider config must be specified")
}
if len(server.GetExecutor().Verifiers) == 0 {
if len(server.GetExecutor(ctx).Verifiers) == 0 {
return errors.ErrorCodeConfigInvalid.WithComponentType(errors.Verifier).WithDetail("verifiers config should have at least one verifier")
}
}
Expand Down
4 changes: 2 additions & 2 deletions httpserver/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -178,13 +178,13 @@ func (server *Server) registerHandlers() error {
if err != nil {
return err
}
server.register(http.MethodPost, verifyPath, processTimeout(server.verify, server.GetExecutor().GetVerifyRequestTimeout(), false))
server.register(http.MethodPost, verifyPath, processTimeout(server.verify, server.GetExecutor(server.Context).GetVerifyRequestTimeout(), false))

mutatePath, err := url.JoinPath(ServerRootURL, "mutate")
if err != nil {
return err
}
server.register(http.MethodPost, mutatePath, processTimeout(server.mutate, server.GetExecutor().GetMutationRequestTimeout(), true))
server.register(http.MethodPost, mutatePath, processTimeout(server.mutate, server.GetExecutor(server.Context).GetMutationRequestTimeout(), true))

return nil
}
Expand Down
34 changes: 17 additions & 17 deletions httpserver/server_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ import (
const testArtifactType string = "test-type1"
const testImageNameTagged string = "localhost:5000/net-monitor:v1"

func testGetExecutor() *core.Executor {
func testGetExecutor(context.Context) *core.Executor {
return &core.Executor{
Verifiers: []verifier.ReferenceVerifier{},
ReferrerStores: []referrerstore.ReferrerStore{},
Expand Down Expand Up @@ -138,7 +138,7 @@ func TestServer_Timeout_Failed(t *testing.T) {
Verifiers: []verifier.ReferenceVerifier{ver},
}

getExecutor := func() *core.Executor {
getExecutor := func(context.Context) *core.Executor {
return ex
}

Expand All @@ -151,7 +151,7 @@ func TestServer_Timeout_Failed(t *testing.T) {

handler := contextHandler{
context: server.Context,
handler: processTimeout(server.verify, server.GetExecutor().GetVerifyRequestTimeout(), false),
handler: processTimeout(server.verify, server.GetExecutor(nil).GetVerifyRequestTimeout(), false),
}

handler.ServeHTTP(responseRecorder, request)
Expand Down Expand Up @@ -209,7 +209,7 @@ func TestServer_MultipleSubjects_Success(t *testing.T) {
},
}

getExecutor := func() *core.Executor {
getExecutor := func(context.Context) *core.Executor {
return ex
}

Expand All @@ -222,7 +222,7 @@ func TestServer_MultipleSubjects_Success(t *testing.T) {

handler := contextHandler{
context: server.Context,
handler: processTimeout(server.verify, server.GetExecutor().GetVerifyRequestTimeout(), false),
handler: processTimeout(server.verify, server.GetExecutor(nil).GetVerifyRequestTimeout(), false),
}

handler.ServeHTTP(responseRecorder, request)
Expand Down Expand Up @@ -280,7 +280,7 @@ func TestServer_Mutation_Success(t *testing.T) {
Verifiers: []verifier.ReferenceVerifier{ver},
}

getExecutor := func() *core.Executor {
getExecutor := func(context.Context) *core.Executor {
return ex
}

Expand All @@ -294,7 +294,7 @@ func TestServer_Mutation_Success(t *testing.T) {

handler := contextHandler{
context: server.Context,
handler: processTimeout(server.mutate, server.GetExecutor().GetMutationRequestTimeout(), true),
handler: processTimeout(server.mutate, server.GetExecutor(nil).GetMutationRequestTimeout(), true),
}

handler.ServeHTTP(responseRecorder, request)
Expand Down Expand Up @@ -356,7 +356,7 @@ func TestServer_Mutation_ReferrerStoreConfigInvalid_Failure(t *testing.T) {
Verifiers: []verifier.ReferenceVerifier{ver},
}

getExecutor := func() *core.Executor {
getExecutor := func(context.Context) *core.Executor {
return ex
}

Expand All @@ -370,7 +370,7 @@ func TestServer_Mutation_ReferrerStoreConfigInvalid_Failure(t *testing.T) {

handler := contextHandler{
context: server.Context,
handler: processTimeout(server.mutate, server.GetExecutor().GetMutationRequestTimeout(), true),
handler: processTimeout(server.mutate, server.GetExecutor(nil).GetMutationRequestTimeout(), true),
}

handler.ServeHTTP(responseRecorder, request)
Expand Down Expand Up @@ -439,7 +439,7 @@ func TestServer_MultipleRequestsForSameSubject_Success(t *testing.T) {
},
}

getExecutor := func() *core.Executor {
getExecutor := func(context.Context) *core.Executor {
return ex
}

Expand All @@ -452,7 +452,7 @@ func TestServer_MultipleRequestsForSameSubject_Success(t *testing.T) {

handler := contextHandler{
context: server.Context,
handler: processTimeout(server.verify, server.GetExecutor().GetVerifyRequestTimeout(), false),
handler: processTimeout(server.verify, server.GetExecutor(nil).GetVerifyRequestTimeout(), false),
}

handler.ServeHTTP(responseRecorder, request)
Expand Down Expand Up @@ -491,7 +491,7 @@ func TestServer_Verify_ParseReference_Failure(t *testing.T) {
},
}

getExecutor := func() *core.Executor {
getExecutor := func(context.Context) *core.Executor {
return ex
}

Expand All @@ -504,7 +504,7 @@ func TestServer_Verify_ParseReference_Failure(t *testing.T) {

handler := contextHandler{
context: server.Context,
handler: processTimeout(server.verify, server.GetExecutor().GetVerifyRequestTimeout(), false),
handler: processTimeout(server.verify, server.GetExecutor(nil).GetVerifyRequestTimeout(), false),
}

handler.ServeHTTP(responseRecorder, request)
Expand Down Expand Up @@ -564,7 +564,7 @@ func TestServer_Verify_PolicyEnforcerConfigInvalid_Failure(t *testing.T) {
Verifiers: []verifier.ReferenceVerifier{ver},
}

getExecutor := func() *core.Executor {
getExecutor := func(context.Context) *core.Executor {
return ex
}

Expand All @@ -578,7 +578,7 @@ func TestServer_Verify_PolicyEnforcerConfigInvalid_Failure(t *testing.T) {

handler := contextHandler{
context: server.Context,
handler: processTimeout(server.verify, server.GetExecutor().GetVerifyRequestTimeout(), false),
handler: processTimeout(server.verify, server.GetExecutor(nil).GetVerifyRequestTimeout(), false),
}

handler.ServeHTTP(responseRecorder, request)
Expand Down Expand Up @@ -633,7 +633,7 @@ func TestServer_Verify_VerifierConfigInvalid_Failure(t *testing.T) {
Verifiers: []verifier.ReferenceVerifier{},
}

getExecutor := func() *core.Executor {
getExecutor := func(context.Context) *core.Executor {
return ex
}

Expand All @@ -647,7 +647,7 @@ func TestServer_Verify_VerifierConfigInvalid_Failure(t *testing.T) {

handler := contextHandler{
context: server.Context,
handler: processTimeout(server.verify, server.GetExecutor().GetVerifyRequestTimeout(), false),
handler: processTimeout(server.verify, server.GetExecutor(nil).GetVerifyRequestTimeout(), false),
}

handler.ServeHTTP(responseRecorder, request)
Expand Down
18 changes: 18 additions & 0 deletions pkg/controllers/resource_map.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/*
Copyright The Ratify 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 controllers

import "github.com/deislabs/ratify/pkg/customresources/verifiers"

var VerifierMap = verifiers.NewActiveVerifiers()
18 changes: 5 additions & 13 deletions pkg/controllers/verifier_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ import (
configv1beta1 "github.com/deislabs/ratify/api/v1beta1"
"github.com/deislabs/ratify/config"
re "github.com/deislabs/ratify/errors"
"github.com/deislabs/ratify/internal/constants"
"github.com/deislabs/ratify/pkg/utils"
vr "github.com/deislabs/ratify/pkg/verifier"
vc "github.com/deislabs/ratify/pkg/verifier/config"
vf "github.com/deislabs/ratify/pkg/verifier/factory"
"github.com/deislabs/ratify/pkg/verifier/types"
Expand All @@ -43,11 +43,6 @@ type VerifierReconciler struct {
Scheme *runtime.Scheme
}

var (
// a map to track of active verifiers
VerifierMap = map[string]vr.ReferenceVerifier{}
)

//+kubebuilder:rbac:groups=config.ratify.deislabs.io,resources=verifiers,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=config.ratify.deislabs.io,resources=verifiers/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=config.ratify.deislabs.io,resources=verifiers/finalizers,verbs=update
Expand All @@ -72,7 +67,8 @@ func (r *VerifierReconciler) Reconcile(ctx context.Context, req ctrl.Request) (c
if err := r.Get(ctx, req.NamespacedName, &verifier); err != nil {
if apierrors.IsNotFound(err) {
verifierLogger.Infof("delete event detected, removing verifier %v", resource)
verifierRemove(resource)
// TODO: pass the actual namespace once multi-tenancy is supported.
VerifierMap.DeleteVerifier(constants.EmptyNamespace, resource)
} else {
verifierLogger.Error(err, "unable to fetch verifier")
}
Expand Down Expand Up @@ -122,17 +118,13 @@ func verifierAddOrReplace(spec configv1beta1.VerifierSpec, objectName string, na
logrus.Error(err, "unable to create verifier from verifier config")
return err
}
VerifierMap[objectName] = referenceVerifier
// TODO: pass the actual namespace once multi-tenancy is supported.
VerifierMap.AddVerifier(constants.EmptyNamespace, objectName, referenceVerifier)
logrus.Infof("verifier '%v' added to verifier map", referenceVerifier.Name())

return nil
}

// remove verifier from map
func verifierRemove(objectName string) {
delete(VerifierMap, objectName)
}

// returns a verifier reference from spec
func specToVerifierConfig(verifierSpec configv1beta1.VerifierSpec, verifierName string) (vc.VerifierConfig, error) {
verifierConfig := vc.VerifierConfig{}
Expand Down
Loading

0 comments on commit 6a93bbf

Please sign in to comment.