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

feat: add verifiers interface to wrap up operations on namespaced verifiers [multi-tenancy PR 2] #1358

Merged
merged 5 commits into from
Apr 10, 2024
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
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 @@
package config

import (
"context"
"os"
"time"

Expand All @@ -25,7 +26,7 @@
"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 @@
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

Check warning on line 42 in config/configManager.go

View check run for this annotation

Codecov / codecov/patch

config/configManager.go#L42

Added line #L42 was not covered by tests
}

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

Check warning on line 50 in config/configManager.go

View check run for this annotation

Codecov / codecov/patch

config/configManager.go#L50

Added line #L50 was not covered by tests
}

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

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

Check warning on line 63 in config/configManager.go

View check run for this annotation

Codecov / codecov/patch

config/configManager.go#L63

Added line #L63 was not covered by tests
}

logrus.Info("configuration successfully loaded.")

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

Check warning on line 68 in config/configManager.go

View check run for this annotation

Codecov / codecov/patch

config/configManager.go#L68

Added line #L68 was not covered by tests
}

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),
binbin-li marked this conversation as resolved.
Show resolved Hide resolved
}

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 @@
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 @@
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 @@
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)

Check warning on line 71 in pkg/controllers/verifier_controller.go

View check run for this annotation

Codecov / codecov/patch

pkg/controllers/verifier_controller.go#L71

Added line #L71 was not covered by tests
} else {
verifierLogger.Error(err, "unable to fetch verifier")
}
Expand Down Expand Up @@ -122,17 +118,13 @@
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)
binbin-li marked this conversation as resolved.
Show resolved Hide resolved
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
Loading