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: enables CRL configuration #1941

Merged
merged 27 commits into from
Jan 6, 2025
Merged
Show file tree
Hide file tree
Changes from 22 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
2 changes: 2 additions & 0 deletions cmd/ratify/cmd/verify.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ func verify(opts verifyCmdOptions) error {
logger.GetLogger(context.Background(), logOpt).Warn(taggedReferenceWarning)
}

config.CRLConf = cf.CRLConfig

stores, err := sf.CreateStoresFromConfig(cf.StoresConfig, config.GetDefaultPluginPath())

if err != nil {
Expand Down
1 change: 1 addition & 0 deletions config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ type Config struct {
PoliciesConfig pcConfig.PoliciesConfig `json:"policy,omitempty"`
VerifiersConfig vfConfig.VerifiersConfig `json:"verifier,omitempty"`
ExecutorConfig exConfig.ExecutorConfig `json:"executor,omitempty"`
CRLConfig CRLConfig `json:"crl,omitempty"`
LoggerConfig logger.Config `json:"logger,omitempty"`
fileHash string `json:"-"`
}
Expand Down
2 changes: 2 additions & 0 deletions config/configManager.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
var (
configHash string
executor ef.Executor
CRLConf CRLConfig
)

// Create a executor from configurationFile and setup config file watcher
junczhu marked this conversation as resolved.
Show resolved Hide resolved
Expand All @@ -43,6 +44,7 @@
}

configHash = cf.fileHash
CRLConf = cf.CRLConfig

Check warning on line 47 in config/configManager.go

View check run for this annotation

Codecov / codecov/patch

config/configManager.go#L47

Added line #L47 was not covered by tests

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

Expand Down
20 changes: 20 additions & 0 deletions config/crl_config.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
/*
junczhu marked this conversation as resolved.
Show resolved Hide resolved
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 config

type CRLConfig struct {
CacheEnabled bool `json:"cacheEnabled,omitempty"`
}
2 changes: 1 addition & 1 deletion pkg/keymanagementprovider/refresh/kubeRefresh.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,6 @@ func (kr *KubeRefresher) Create(config RefresherConfig) (Refresher, error) {
ProviderType: config.ProviderType,
ProviderRefreshInterval: config.ProviderRefreshInterval,
Resource: config.Resource,
CRLHandler: nv.NewCRLHandler(),
CRLHandler: nv.CreateCRLHandlerFromConfig(),
}, nil
}
24 changes: 12 additions & 12 deletions pkg/keymanagementprovider/refresh/kubeRefresh_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func TestKubeRefresher_Refresh(t *testing.T) {
providerRawParameters: []byte(`{"contentType": "certificate", "value": "-----BEGIN CERTIFICATE-----\nMIID2jCCAsKgAwIBAgIQXy2VqtlhSkiZKAGhsnkjbDANBgkqhkiG9w0BAQsFADBvMRswGQYDVQQD\nExJyYXRpZnkuZXhhbXBsZS5jb20xDzANBgNVBAsTBk15IE9yZzETMBEGA1UEChMKTXkgQ29tcGFu\neTEQMA4GA1UEBxMHUmVkbW9uZDELMAkGA1UECBMCV0ExCzAJBgNVBAYTAlVTMB4XDTIzMDIwMTIy\nNDUwMFoXDTI0MDIwMTIyNTUwMFowbzEbMBkGA1UEAxMScmF0aWZ5LmV4YW1wbGUuY29tMQ8wDQYD\nVQQLEwZNeSBPcmcxEzARBgNVBAoTCk15IENvbXBhbnkxEDAOBgNVBAcTB1JlZG1vbmQxCzAJBgNV\nBAgTAldBMQswCQYDVQQGEwJVUzCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAL10bM81\npPAyuraORABsOGS8M76Bi7Guwa3JlM1g2D8CuzSfSTaaT6apy9GsccxUvXd5cmiP1ffna5z+EFmc\nizFQh2aq9kWKWXDvKFXzpQuhyqD1HeVlRlF+V0AfZPvGt3VwUUjNycoUU44ctCWmcUQP/KShZev3\n6SOsJ9q7KLjxxQLsUc4mg55eZUThu8mGB8jugtjsnLUYvIWfHhyjVpGrGVrdkDMoMn+u33scOmrt\nsBljvq9WVo4T/VrTDuiOYlAJFMUae2Ptvo0go8XTN3OjLblKeiK4C+jMn9Dk33oGIT9pmX0vrDJV\nX56w/2SejC1AxCPchHaMuhlwMpftBGkCAwEAAaNyMHAwDgYDVR0PAQH/BAQDAgeAMAkGA1UdEwQC\nMAAwEwYDVR0lBAwwCgYIKwYBBQUHAwMwHwYDVR0jBBgwFoAU0eaKkZj+MS9jCp9Dg1zdv3v/aKww\nHQYDVR0OBBYEFNHmipGY/jEvYwqfQ4Nc3b97/2isMA0GCSqGSIb3DQEBCwUAA4IBAQBNDcmSBizF\nmpJlD8EgNcUCy5tz7W3+AAhEbA3vsHP4D/UyV3UgcESx+L+Nye5uDYtTVm3lQejs3erN2BjW+ds+\nXFnpU/pVimd0aYv6mJfOieRILBF4XFomjhrJOLI55oVwLN/AgX6kuC3CJY2NMyJKlTao9oZgpHhs\nLlxB/r0n9JnUoN0Gq93oc1+OLFjPI7gNuPXYOP1N46oKgEmAEmNkP1etFrEjFRgsdIFHksrmlOlD\nIed9RcQ087VLjmuymLgqMTFX34Q3j7XgN2ENwBSnkHotE9CcuGRW+NuiOeJalL8DBmFXXWwHTKLQ\nPp5g6m1yZXylLJaFLKz7tdMmO355\n-----END CERTIFICATE-----\n"}`),
providerType: "inline",
IsRefreshableFunc: func() bool { return false },
NewCRLHandler: nv.NewCRLHandler(),
NewCRLHandler: nv.CreateCRLHandlerFromConfig(),
expectedResult: ctrl.Result{},
expectedError: false,
},
Expand All @@ -64,7 +64,7 @@ func TestKubeRefresher_Refresh(t *testing.T) {
providerRawParameters: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`),
providerType: "test-kmp",
providerRefreshInterval: "",
NewCRLHandler: nv.NewCRLHandler(),
NewCRLHandler: nv.CreateCRLHandlerFromConfig(),
IsRefreshableFunc: func() bool { return true },
expectedResult: ctrl.Result{},
expectedError: false,
Expand All @@ -74,7 +74,7 @@ func TestKubeRefresher_Refresh(t *testing.T) {
providerRawParameters: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`),
providerType: "test-kmp",
providerRefreshInterval: "1m",
NewCRLHandler: nv.NewCRLHandler(),
NewCRLHandler: nv.CreateCRLHandlerFromConfig(),
IsRefreshableFunc: func() bool { return true },
expectedResult: ctrl.Result{RequeueAfter: time.Minute},
expectedError: false,
Expand All @@ -84,7 +84,7 @@ func TestKubeRefresher_Refresh(t *testing.T) {
providerRawParameters: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`),
providerType: "test-kmp",
providerRefreshInterval: "1mm",
NewCRLHandler: nv.NewCRLHandler(),
NewCRLHandler: nv.CreateCRLHandlerFromConfig(),
IsRefreshableFunc: func() bool { return true },
expectedResult: ctrl.Result{},
expectedError: true,
Expand All @@ -98,7 +98,7 @@ func TestKubeRefresher_Refresh(t *testing.T) {
providerRawParameters: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`),
providerType: "test-kmp-error",
IsRefreshableFunc: func() bool { return true },
NewCRLHandler: nv.NewCRLHandler(),
NewCRLHandler: nv.CreateCRLHandlerFromConfig(),
expectedError: true,
},
{
Expand All @@ -110,7 +110,7 @@ func TestKubeRefresher_Refresh(t *testing.T) {
providerRawParameters: []byte(`{"vaultURI": "https://yourkeyvault.vault.azure.net/", "certificates": [{"name": "cert1", "version": "1"}], "tenantID": "yourtenantID", "clientID": "yourclientID"}`),
providerType: "test-kmp-error",
IsRefreshableFunc: func() bool { return true },
NewCRLHandler: nv.NewCRLHandler(),
NewCRLHandler: nv.CreateCRLHandlerFromConfig(),
expectedError: true,
},
{
Expand All @@ -124,7 +124,7 @@ func TestKubeRefresher_Refresh(t *testing.T) {
providerType: "test-kmp",
providerRefreshInterval: "1m",
IsRefreshableFunc: func() bool { return true },
NewCRLHandler: &MockCRLHandler{CacheEnabled: true, httpClient: &http.Client{}},
NewCRLHandler: &MockCRLHandler{CacheDisabled: false, httpClient: &http.Client{}},
expectedResult: ctrl.Result{RequeueAfter: time.Minute},
expectedError: false,
},
Expand Down Expand Up @@ -172,8 +172,8 @@ func TestKubeRefresher_Refresh(t *testing.T) {
}

type MockCRLHandler struct {
CacheEnabled bool
httpClient *http.Client
CacheDisabled bool
httpClient *http.Client
}

func (h *MockCRLHandler) NewFetcher() (corecrl.Fetcher, error) {
Expand All @@ -187,7 +187,7 @@ func (h *MockCRLHandler) NewValidator(_ revocation.Options) (revocation.Validato
func TestKubeRefresher_GetResult(t *testing.T) {
kr := &KubeRefresher{
Result: ctrl.Result{RequeueAfter: time.Minute},
CRLHandler: nv.NewCRLHandler(),
CRLHandler: nv.CreateCRLHandlerFromConfig(),
}

result := kr.GetResult()
Expand All @@ -203,7 +203,7 @@ func TestKubeRefresher_GetStatus(t *testing.T) {
"attribute1": "value1",
"attribute2": "value2",
},
CRLHandler: nv.NewCRLHandler(),
CRLHandler: nv.CreateCRLHandlerFromConfig(),
}

status := kr.GetStatus()
Expand Down Expand Up @@ -252,7 +252,7 @@ func TestKubeRefresher_Create(t *testing.T) {

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
kr := &KubeRefresher{CRLHandler: nv.NewCRLHandler()}
kr := &KubeRefresher{CRLHandler: nv.CreateCRLHandlerFromConfig()}
refresher, err := kr.Create(tt.config)
if err != nil {
t.Fatalf("Expected no error, but got %v", err)
Expand Down
2 changes: 1 addition & 1 deletion pkg/manager/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@
logrus.Errorf("server start failed %v", fmt.Errorf("error loading config %w", err))
os.Exit(1)
}

config.CRLConf = cf.CRLConfig

Check warning on line 85 in pkg/manager/manager.go

View check run for this annotation

Codecov / codecov/patch

pkg/manager/manager.go#L85

Added line #L85 was not covered by tests
// initialize server
server, err := httpserver.NewServer(context.Background(), httpServerAddress, func(ctx context.Context) *ef.Executor {
namespace := ctxUtils.GetNamespace(ctx)
Expand Down
2 changes: 1 addition & 1 deletion pkg/verifier/notation/notation.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ func (f *notationPluginVerifierFactory) Create(_ string, verifierConfig config.V
if err != nil {
return nil, re.ErrorCodePluginInitFailure.WithDetail("Failed to create the Notation Verifier").WithError(err)
}
verifyService, err := getVerifierService(ctx, conf, pluginDirectory, NewCRLHandler())
verifyService, err := getVerifierService(ctx, conf, pluginDirectory, CreateCRLHandlerFromConfig())
if err != nil {
return nil, re.ErrorCodePluginInitFailure.WithDetail("Failed to create the Notation Verifier").WithError(err)
}
Expand Down
24 changes: 7 additions & 17 deletions pkg/verifier/notation/notationrevocationfactory.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import (
"github.com/notaryproject/notation-core-go/revocation"
corecrl "github.com/notaryproject/notation-core-go/revocation/crl"
"github.com/notaryproject/notation-go/dir"
"github.com/ratify-project/ratify/config"
re "github.com/ratify-project/ratify/errors"
)

Expand All @@ -33,9 +34,12 @@ var (
globalFetcher corecrl.Fetcher
)

// NewCRLHandler returns a new NewCRLHandler instance. Enable cache by default.
func NewCRLHandler() RevocationFactory {
return &CRLHandler{CacheEnabled: true, httpClient: &http.Client{}}
// CreateCRLHandlerFromConfig creates a new instance of CRLHandler using the configuration
// provided in config.CRLConf. It returns a RevocationFactory interface.
// The CRLHandler will have its CacheDisabled field set based on the configuration,
// and it will use a default HTTP client.
func CreateCRLHandlerFromConfig() RevocationFactory {
junczhu marked this conversation as resolved.
Show resolved Hide resolved
return &CRLHandler{CacheEnabled: config.CRLConf.CacheEnabled, httpClient: &http.Client{}}
}

// NewFetcher creates a new instance of a Fetcher if it doesn't already exist.
Expand All @@ -46,9 +50,6 @@ func (h *CRLHandler) NewFetcher() (corecrl.Fetcher, error) {
var err error
fetcherOnce.Do(func() {
globalFetcher, err = CreateCRLFetcher(h.httpClient, dir.PathCRLCache)
if err == nil {
h.configureCache(globalFetcher)
}
})
if err != nil {
return nil, err
Expand All @@ -66,14 +67,3 @@ func (h *CRLHandler) NewFetcher() (corecrl.Fetcher, error) {
func (h *CRLHandler) NewValidator(opts revocation.Options) (revocation.Validator, error) {
return revocation.NewWithOptions(opts)
}

// configureCache disables the cache for the HTTPFetcher if caching is not enabled.
// If the EnableCache field is set to false, this method sets the Cache field of the
// HTTPFetcher to nil, effectively disabling caching for HTTP fetch operations.
func (h *CRLHandler) configureCache(f corecrl.Fetcher) {
if !h.CacheEnabled {
if httpFetcher, ok := f.(*corecrl.HTTPFetcher); ok {
httpFetcher.Cache = nil
}
}
}
58 changes: 2 additions & 56 deletions pkg/verifier/notation/notationrevocationfactory_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,21 +14,18 @@
package notation

import (
"context"
"net/http"
"runtime"
"testing"

"github.com/notaryproject/notation-core-go/revocation"
corecrl "github.com/notaryproject/notation-core-go/revocation/crl"
"github.com/notaryproject/notation-go/dir"
"github.com/notaryproject/notation-go/verifier/crl"
re "github.com/ratify-project/ratify/errors"
"github.com/stretchr/testify/assert"
)

func TestNewRevocationFactoryImpl(t *testing.T) {
factory := NewCRLHandler()
factory := CreateCRLHandlerFromConfig()
assert.NotNil(t, factory)
}

Expand Down Expand Up @@ -76,7 +73,7 @@ func TestNewFetcher(t *testing.T) {
}

func TestNewValidator(t *testing.T) {
factory := NewCRLHandler()
factory := CreateCRLHandlerFromConfig()
opts := revocation.Options{}

validator, err := factory.NewValidator(opts)
Expand Down Expand Up @@ -112,54 +109,3 @@ func TestNewFileCache(t *testing.T) {
})
}
}
func TestConfigureCache(t *testing.T) {
testCache, _ := crl.NewFileCache(dir.PathCRLCache)
tests := []struct {
name string
cacheEnabled bool
fetcher corecrl.Fetcher
expectCache bool
}{
{
name: "cache enabled",
cacheEnabled: true,
fetcher: &corecrl.HTTPFetcher{Cache: testCache},
expectCache: true,
},
{
name: "cache disabled",
cacheEnabled: false,
fetcher: &corecrl.HTTPFetcher{Cache: testCache},
expectCache: false,
},
{
name: "non-HTTP fetcher",
cacheEnabled: false,
fetcher: &mockFetcher{},
expectCache: false,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
handler := &CRLHandler{
CacheEnabled: tt.cacheEnabled,
}
handler.configureCache(tt.fetcher)

if httpFetcher, ok := tt.fetcher.(*corecrl.HTTPFetcher); ok {
if tt.expectCache {
assert.NotNil(t, httpFetcher.Cache)
} else {
assert.Nil(t, httpFetcher.Cache)
}
}
})
}
}

type mockFetcher struct{}

func (m *mockFetcher) Fetch(_ context.Context, _ string) (*corecrl.Bundle, error) {
return nil, nil
}
7 changes: 6 additions & 1 deletion pkg/verifier/notation/revocationfactory.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
corecrl "github.com/notaryproject/notation-core-go/revocation/crl"
"github.com/notaryproject/notation-go/dir"
"github.com/notaryproject/notation-go/verifier/crl"
"github.com/ratify-project/ratify/config"
"github.com/ratify-project/ratify/internal/logger"
)

Expand All @@ -43,10 +44,14 @@
if err != nil {
return nil, err
}
crlFetcher.Cache, err = newFileCache(cacheRoot)
if !config.CRLConf.CacheEnabled {
return crlFetcher, nil
}
cache, err := newFileCache(cacheRoot)

Check warning on line 50 in pkg/verifier/notation/revocationfactory.go

View check run for this annotation

Codecov / codecov/patch

pkg/verifier/notation/revocationfactory.go#L50

Added line #L50 was not covered by tests
if err != nil {
return nil, err
}
crlFetcher.Cache = cache

Check warning on line 54 in pkg/verifier/notation/revocationfactory.go

View check run for this annotation

Codecov / codecov/patch

pkg/verifier/notation/revocationfactory.go#L54

Added line #L54 was not covered by tests
return crlFetcher, nil
}

Expand Down
6 changes: 3 additions & 3 deletions test/bats/cli-test.bats
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,14 @@ load helpers
assert_cmd_verify_failure

delete_crl_cache

check_crl_cache_deleted
unrevoke_crl

run bin/ratify verify -c $RATIFY_DIR/config_notation_crl.json -s $TEST_REGISTRY/notation:crl
assert_cmd_verify_success

check_crl_cache
junczhu marked this conversation as resolved.
Show resolved Hide resolved
assert_success
check_crl_cache_deleted
junczhu marked this conversation as resolved.
Show resolved Hide resolved
assert_failure
}

@test "notation verifier with type test" {
Expand Down
9 changes: 6 additions & 3 deletions test/bats/helpers.bash
Original file line number Diff line number Diff line change
Expand Up @@ -130,8 +130,11 @@ delete_crl_cache() {
rm -rf $HOME/.cache/notation/crl
}

check_crl_cache() {
if [[ -d "$HOME/.cache/notation/crl" ]]; then
return 0
check_crl_cache_deleted() {
if [[ -z "$(ls -A $HOME/.cache/notation/crl)" ]]; then
echo "The directory is empty."
else
echo "The directory is not empty."
return 1
fi
}
3 changes: 3 additions & 0 deletions test/bats/tests/config/config_notation_crl.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,8 @@
}
}
]
},
"crl": {
"cacheEnabled": true
}
}
Loading