diff --git a/.changeset/minor-bump-1789496222.md b/.changeset/minor-bump-1790100824.md similarity index 100% rename from .changeset/minor-bump-1789496222.md rename to .changeset/minor-bump-1790100824.md diff --git a/.changeset/new-ants-hide.md b/.changeset/new-ants-hide.md deleted file mode 100644 index d5d95415177..00000000000 --- a/.changeset/new-ants-hide.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"chainlink": patch ---- - -Removing deprecated Cosmos support #nops #removed diff --git a/.changeset/sharp-garlics-cry.md b/.changeset/sharp-garlics-cry.md deleted file mode 100644 index 6ffbcd2e7ea..00000000000 --- a/.changeset/sharp-garlics-cry.md +++ /dev/null @@ -1,5 +0,0 @@ ---- -"chainlink": patch ---- - -#added add bridge-cache fallback for UseConnectionManager bridge tasks diff --git a/CHANGELOG.md b/CHANGELOG.md index b499253ba03..4269f8935b1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog Chainlink Core +## 2.66.0 + +### Minor Changes + +- [#23751](https://github.com/smartcontractkit/chainlink/pull/23751) [`5a65b1d`](https://github.com/smartcontractkit/chainlink/commit/5a65b1d26d7dce35596330fb56bc8c70b02a202c) - Minor bump to start next version + +### Patch Changes + +- [#23734](https://github.com/smartcontractkit/chainlink/pull/23734) [`fa897c3`](https://github.com/smartcontractkit/chainlink/commit/fa897c3d55f584de6ece6255c061b8ef6904d0d5) - Removing deprecated Cosmos support #nops #removed + +- [#23695](https://github.com/smartcontractkit/chainlink/pull/23695) [`ea1ed53`](https://github.com/smartcontractkit/chainlink/commit/ea1ed53b9b16645c4a5da40baeaac30760f58292) - #added add bridge-cache fallback for UseConnectionManager bridge tasks + ## 2.65.0 ### Minor Changes diff --git a/config_docs_test.go b/config_docs_test.go index c9576cf10cd..c0a3a8181da 100644 --- a/config_docs_test.go +++ b/config_docs_test.go @@ -5,6 +5,7 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink/v2/core/config/docs" ) @@ -18,10 +19,10 @@ var ( func TestConfigDocs(t *testing.T) { config, err := docs.GenerateConfig() - assert.NoError(t, err, "invalid config docs") + require.NoError(t, err, "invalid config docs") assert.Equal(t, configMD, config, "docs/CONFIG.md is out of date. Run 'make config-docs' to regenerate.") secrets, err := docs.GenerateSecrets() - assert.NoError(t, err, "invalid secrets docs") + require.NoError(t, err, "invalid secrets docs") assert.Equal(t, secretsMD, secrets, "docs/SECRETS.md is out of date. Run 'make config-docs' to regenerate.") } diff --git a/core/auth/auth.go b/core/auth/auth.go index 6a414b01119..dc0a6262756 100644 --- a/core/auth/auth.go +++ b/core/auth/auth.go @@ -3,19 +3,23 @@ package auth import ( "crypto/sha3" "encoding/hex" + "errors" "fmt" "hash" - pkgerrors "github.com/pkg/errors" - "github.com/smartcontractkit/chainlink/v2/core/utils" ) var ( - // ErrorAuthFailed is a generic authentication failed - but not because of + // ErrAuthFailed is a generic authentication failed - but not because of // some system failure on our behalf (i.e. HTTP 5xx), more detail is not // given - ErrorAuthFailed = pkgerrors.New("Authentication failed") + ErrAuthFailed = errors.New("authentication failed") + + // ErrorAuthFailed is retained for backward compatibility. + // + // Deprecated: use ErrAuthFailed instead. + ErrorAuthFailed = ErrAuthFailed //nolint:errname // backward compatibility ) // Token is used for API authentication. @@ -58,7 +62,7 @@ func HashedSecret(ta *Token, salt string) (string, error) { hasher := hash.Hash(sha3.New256()) _, err := hasher.Write(hashInput(ta, salt)) if err != nil { - return "", pkgerrors.Wrap(err, "error writing external initiator authentication to hasher") + return "", fmt.Errorf("error writing external initiator authentication to hasher: %w", err) } return hex.EncodeToString(hasher.Sum(nil)), nil } diff --git a/core/bridges/bridge_type.go b/core/bridges/bridge_type.go index 235b66e17d9..96a48cd67f2 100644 --- a/core/bridges/bridge_type.go +++ b/core/bridges/bridge_type.go @@ -25,12 +25,12 @@ type BridgeTypeRequest struct { } // GetID returns the ID of this structure for jsonapi serialization. -func (bt BridgeTypeRequest) GetID() string { +func (bt *BridgeTypeRequest) GetID() string { return bt.Name.String() } // GetName returns the pluralized "type" of this structure for jsonapi serialization. -func (bt BridgeTypeRequest) GetName() string { +func (bt *BridgeTypeRequest) GetName() string { return "bridges" } diff --git a/core/bridges/bridge_type_test.go b/core/bridges/bridge_type_test.go index f23be5dc40b..d6ef7e7fe11 100644 --- a/core/bridges/bridge_type_test.go +++ b/core/bridges/bridge_type_test.go @@ -32,7 +32,7 @@ func TestBridgeTypeRequest(t *testing.T) { assert.Equal(t, "bridges", r.GetName()) assert.Equal(t, "test-bridge-name", r.GetID()) const validID = "abc123foo_bar-test" - assert.NoError(t, r.SetID(validID)) + require.NoError(t, r.SetID(validID)) assert.Equal(t, validID, r.GetID()) assert.Error(t, r.SetID("abc123.,<>/.foobar")) } diff --git a/core/bridges/cache.go b/core/bridges/cache.go index c5c4527df23..6907cb540e8 100644 --- a/core/bridges/cache.go +++ b/core/bridges/cache.go @@ -150,21 +150,21 @@ func (c *Cache) UpdateBridgeType(ctx context.Context, bt *BridgeType, btr *Bridg return nil } -func (c *Cache) GetCachedResponse(ctx context.Context, dotId string, specId int32, maxElapsed time.Duration) ([]byte, error) { +func (c *Cache) GetCachedResponse(ctx context.Context, dotID string, specID int32, maxElapsed time.Duration) ([]byte, error) { // prefer to get latest value from cache - cached, inCache := c.latestValue(dotId, specId) + cached, inCache := c.latestValue(dotID, specID) if inCache && cached.FinishedAt.After(time.Now().Add(-maxElapsed)) { return cached.Value, nil } - response, finishedAt, err := c.GetCachedResponseWithFinished(ctx, dotId, specId, maxElapsed) + response, finishedAt, err := c.GetCachedResponseWithFinished(ctx, dotID, specID, maxElapsed) if err != nil { return nil, err } - c.setValue(dotId, specId, BridgeResponse{ - DotID: dotId, - SpecID: specId, + c.setValue(dotID, specID, BridgeResponse{ + DotID: dotID, + SpecID: specID, Value: response, FinishedAt: finishedAt, }) @@ -172,18 +172,18 @@ func (c *Cache) GetCachedResponse(ctx context.Context, dotId string, specId int3 return response, nil } -func (c *Cache) UpsertBridgeResponse(ctx context.Context, dotId string, specId int32, response []byte) error { +func (c *Cache) UpsertBridgeResponse(ctx context.Context, dotID string, specID int32, response []byte) error { upsertTime := time.Now() // catch the rare case of a save race - cached, inCache := c.latestValue(dotId, specId) + cached, inCache := c.latestValue(dotID, specID) if inCache && cached.FinishedAt.After(upsertTime) { return nil } - c.setValue(dotId, specId, BridgeResponse{ - DotID: dotId, - SpecID: specId, + c.setValue(dotID, specID, BridgeResponse{ + DotID: dotID, + SpecID: specID, Value: response, FinishedAt: upsertTime, }) @@ -215,22 +215,22 @@ func (c *Cache) doBulkUpsert(ctx context.Context) { } } -func (c *Cache) latestValue(dotId string, specId int32) (BridgeResponse, bool) { +func (c *Cache) latestValue(dotID string, specID int32) (BridgeResponse, bool) { c.mu.RLock() defer c.mu.RUnlock() - cached, inCache := c.bridgeLastValueCache[responseKey(dotId, specId)] + cached, inCache := c.bridgeLastValueCache[responseKey(dotID, specID)] return cached, inCache } -func (c *Cache) setValue(dotId string, specId int32, resp BridgeResponse) { +func (c *Cache) setValue(dotID string, specID int32, resp BridgeResponse) { c.mu.Lock() defer c.mu.Unlock() - c.bridgeLastValueCache[responseKey(dotId, specId)] = resp + c.bridgeLastValueCache[responseKey(dotID, specID)] = resp } -func responseKey(dotId string, specId int32) string { - return fmt.Sprintf("%s||%d", dotId, specId) +func responseKey(dotID string, specID int32) string { + return fmt.Sprintf("%s||%d", dotID, specID) } diff --git a/core/bridges/cache_test.go b/core/bridges/cache_test.go index d85a9aa2cc9..6183a2b7bfe 100644 --- a/core/bridges/cache_test.go +++ b/core/bridges/cache_test.go @@ -55,10 +55,12 @@ func TestBridgeCache_Type(t *testing.T) { nameB := bridges.BridgeName("B") nameC := bridges.BridgeName("C") - initialExpected := []bridges.BridgeType{ - {Name: nameA}, - {Name: nameB}, - } + initialExpected := make([]bridges.BridgeType, 0, 3) + initialExpected = append(initialExpected, + bridges.BridgeType{Name: nameA}, + bridges.BridgeType{Name: nameB}, + ) + //nolint:gocritic // append into a separate slice so initialExpected stays len 2 finalExpected := append(initialExpected, bridges.BridgeType{Name: nameC}) mORM.On("FindBridges", mock.Anything, []bridges.BridgeName{nameA, nameB}).Return(initialExpected, nil) @@ -92,7 +94,7 @@ func TestBridgeCache_Type(t *testing.T) { } mORM.On("CreateBridgeType", mock.Anything, expected).Return(nil) - assert.NoError(t, cache.CreateBridgeType(ctx, expected)) + require.NoError(t, cache.CreateBridgeType(ctx, expected)) result, err := cache.FindBridge(ctx, bridge) @@ -142,19 +144,19 @@ func TestBridgeCache_Response(t *testing.T) { cache := bridges.NewCache(mORM, lggr, bridges.DefaultUpsertInterval) ctx := t.Context() - dotId := "test" - specId := int32(42) + dotID := "test" + specID := int32(42) responseData := []byte("test") - mORM.On("GetCachedResponseWithFinished", mock.Anything, dotId, specId, time.Second). + mORM.On("GetCachedResponseWithFinished", mock.Anything, dotID, specID, time.Second). Return(responseData, time.Now(), nil) - response, err := cache.GetCachedResponse(ctx, dotId, specId, time.Second) + response, err := cache.GetCachedResponse(ctx, dotID, specID, time.Second) require.NoError(t, err) assert.Equal(t, responseData, response) - response, err = cache.GetCachedResponse(ctx, dotId, specId, time.Second) + response, err = cache.GetCachedResponse(ctx, dotID, specID, time.Second) require.NoError(t, err) assert.Equal(t, responseData, response) @@ -174,8 +176,8 @@ func TestBridgeCache_Response(t *testing.T) { require.NoError(t, cache.Start(t.Context())) ctx := t.Context() - dotId := "test" - specId := int32(42) + dotID := "test" + specID := int32(42) expected := []byte("test") chBulkUpsertCalled := make(chan struct{}, 1) @@ -183,9 +185,9 @@ func TestBridgeCache_Response(t *testing.T) { chBulkUpsertCalled <- struct{}{} }) - require.NoError(t, cache.UpsertBridgeResponse(ctx, dotId, specId, expected)) + require.NoError(t, cache.UpsertBridgeResponse(ctx, dotID, specID, expected)) - response, err := cache.GetCachedResponse(ctx, dotId, specId, time.Second) + response, err := cache.GetCachedResponse(ctx, dotID, specID, time.Second) require.NoError(t, err) assert.Equal(t, expected, response) diff --git a/core/bridges/external_initiator_test.go b/core/bridges/external_initiator_test.go index 9534c7a55a8..20616720ac8 100644 --- a/core/bridges/external_initiator_test.go +++ b/core/bridges/external_initiator_test.go @@ -25,7 +25,7 @@ func TestNewExternalInitiator(t *testing.T) { URL: &url, } ei, err := bridges.NewExternalInitiator(eia, eir) - assert.NoError(t, err) + require.NoError(t, err) assert.NotEqual(t, ei.HashedSecret, eia.Secret) assert.Equal(t, ei.AccessKey, eia.AccessKey) } diff --git a/core/bridges/mocks/orm.go b/core/bridges/mocks/orm.go index 616843f6f2f..719feb6aecf 100644 --- a/core/bridges/mocks/orm.go +++ b/core/bridges/mocks/orm.go @@ -629,9 +629,9 @@ func (_c *ORM_FindExternalInitiatorByName_Call) RunAndReturn(run func(context.Co return _c } -// GetCachedResponse provides a mock function with given fields: ctx, dotId, specId, maxElapsed -func (_m *ORM) GetCachedResponse(ctx context.Context, dotId string, specId int32, maxElapsed time.Duration) ([]byte, error) { - ret := _m.Called(ctx, dotId, specId, maxElapsed) +// GetCachedResponse provides a mock function with given fields: ctx, dotID, specID, maxElapsed +func (_m *ORM) GetCachedResponse(ctx context.Context, dotID string, specID int32, maxElapsed time.Duration) ([]byte, error) { + ret := _m.Called(ctx, dotID, specID, maxElapsed) if len(ret) == 0 { panic("no return value specified for GetCachedResponse") @@ -640,10 +640,10 @@ func (_m *ORM) GetCachedResponse(ctx context.Context, dotId string, specId int32 var r0 []byte var r1 error if rf, ok := ret.Get(0).(func(context.Context, string, int32, time.Duration) ([]byte, error)); ok { - return rf(ctx, dotId, specId, maxElapsed) + return rf(ctx, dotID, specID, maxElapsed) } if rf, ok := ret.Get(0).(func(context.Context, string, int32, time.Duration) []byte); ok { - r0 = rf(ctx, dotId, specId, maxElapsed) + r0 = rf(ctx, dotID, specID, maxElapsed) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) @@ -651,7 +651,7 @@ func (_m *ORM) GetCachedResponse(ctx context.Context, dotId string, specId int32 } if rf, ok := ret.Get(1).(func(context.Context, string, int32, time.Duration) error); ok { - r1 = rf(ctx, dotId, specId, maxElapsed) + r1 = rf(ctx, dotID, specID, maxElapsed) } else { r1 = ret.Error(1) } @@ -666,14 +666,14 @@ type ORM_GetCachedResponse_Call struct { // GetCachedResponse is a helper method to define mock.On call // - ctx context.Context -// - dotId string -// - specId int32 +// - dotID string +// - specID int32 // - maxElapsed time.Duration -func (_e *ORM_Expecter) GetCachedResponse(ctx interface{}, dotId interface{}, specId interface{}, maxElapsed interface{}) *ORM_GetCachedResponse_Call { - return &ORM_GetCachedResponse_Call{Call: _e.mock.On("GetCachedResponse", ctx, dotId, specId, maxElapsed)} +func (_e *ORM_Expecter) GetCachedResponse(ctx interface{}, dotID interface{}, specID interface{}, maxElapsed interface{}) *ORM_GetCachedResponse_Call { + return &ORM_GetCachedResponse_Call{Call: _e.mock.On("GetCachedResponse", ctx, dotID, specID, maxElapsed)} } -func (_c *ORM_GetCachedResponse_Call) Run(run func(ctx context.Context, dotId string, specId int32, maxElapsed time.Duration)) *ORM_GetCachedResponse_Call { +func (_c *ORM_GetCachedResponse_Call) Run(run func(ctx context.Context, dotID string, specID int32, maxElapsed time.Duration)) *ORM_GetCachedResponse_Call { _c.Call.Run(func(args mock.Arguments) { run(args[0].(context.Context), args[1].(string), args[2].(int32), args[3].(time.Duration)) }) @@ -690,9 +690,9 @@ func (_c *ORM_GetCachedResponse_Call) RunAndReturn(run func(context.Context, str return _c } -// GetCachedResponseWithFinished provides a mock function with given fields: ctx, dotId, specId, maxElapsed -func (_m *ORM) GetCachedResponseWithFinished(ctx context.Context, dotId string, specId int32, maxElapsed time.Duration) ([]byte, time.Time, error) { - ret := _m.Called(ctx, dotId, specId, maxElapsed) +// GetCachedResponseWithFinished provides a mock function with given fields: ctx, dotID, specID, maxElapsed +func (_m *ORM) GetCachedResponseWithFinished(ctx context.Context, dotID string, specID int32, maxElapsed time.Duration) ([]byte, time.Time, error) { + ret := _m.Called(ctx, dotID, specID, maxElapsed) if len(ret) == 0 { panic("no return value specified for GetCachedResponseWithFinished") @@ -702,10 +702,10 @@ func (_m *ORM) GetCachedResponseWithFinished(ctx context.Context, dotId string, var r1 time.Time var r2 error if rf, ok := ret.Get(0).(func(context.Context, string, int32, time.Duration) ([]byte, time.Time, error)); ok { - return rf(ctx, dotId, specId, maxElapsed) + return rf(ctx, dotID, specID, maxElapsed) } if rf, ok := ret.Get(0).(func(context.Context, string, int32, time.Duration) []byte); ok { - r0 = rf(ctx, dotId, specId, maxElapsed) + r0 = rf(ctx, dotID, specID, maxElapsed) } else { if ret.Get(0) != nil { r0 = ret.Get(0).([]byte) @@ -713,13 +713,13 @@ func (_m *ORM) GetCachedResponseWithFinished(ctx context.Context, dotId string, } if rf, ok := ret.Get(1).(func(context.Context, string, int32, time.Duration) time.Time); ok { - r1 = rf(ctx, dotId, specId, maxElapsed) + r1 = rf(ctx, dotID, specID, maxElapsed) } else { r1 = ret.Get(1).(time.Time) } if rf, ok := ret.Get(2).(func(context.Context, string, int32, time.Duration) error); ok { - r2 = rf(ctx, dotId, specId, maxElapsed) + r2 = rf(ctx, dotID, specID, maxElapsed) } else { r2 = ret.Error(2) } @@ -734,14 +734,14 @@ type ORM_GetCachedResponseWithFinished_Call struct { // GetCachedResponseWithFinished is a helper method to define mock.On call // - ctx context.Context -// - dotId string -// - specId int32 +// - dotID string +// - specID int32 // - maxElapsed time.Duration -func (_e *ORM_Expecter) GetCachedResponseWithFinished(ctx interface{}, dotId interface{}, specId interface{}, maxElapsed interface{}) *ORM_GetCachedResponseWithFinished_Call { - return &ORM_GetCachedResponseWithFinished_Call{Call: _e.mock.On("GetCachedResponseWithFinished", ctx, dotId, specId, maxElapsed)} +func (_e *ORM_Expecter) GetCachedResponseWithFinished(ctx interface{}, dotID interface{}, specID interface{}, maxElapsed interface{}) *ORM_GetCachedResponseWithFinished_Call { + return &ORM_GetCachedResponseWithFinished_Call{Call: _e.mock.On("GetCachedResponseWithFinished", ctx, dotID, specID, maxElapsed)} } -func (_c *ORM_GetCachedResponseWithFinished_Call) Run(run func(ctx context.Context, dotId string, specId int32, maxElapsed time.Duration)) *ORM_GetCachedResponseWithFinished_Call { +func (_c *ORM_GetCachedResponseWithFinished_Call) Run(run func(ctx context.Context, dotID string, specID int32, maxElapsed time.Duration)) *ORM_GetCachedResponseWithFinished_Call { _c.Call.Run(func(args mock.Arguments) { run(args[0].(context.Context), args[1].(string), args[2].(int32), args[3].(time.Duration)) }) @@ -806,9 +806,9 @@ func (_c *ORM_UpdateBridgeType_Call) RunAndReturn(run func(context.Context, *bri return _c } -// UpsertBridgeResponse provides a mock function with given fields: ctx, dotId, specId, response -func (_m *ORM) UpsertBridgeResponse(ctx context.Context, dotId string, specId int32, response []byte) error { - ret := _m.Called(ctx, dotId, specId, response) +// UpsertBridgeResponse provides a mock function with given fields: ctx, dotID, specID, response +func (_m *ORM) UpsertBridgeResponse(ctx context.Context, dotID string, specID int32, response []byte) error { + ret := _m.Called(ctx, dotID, specID, response) if len(ret) == 0 { panic("no return value specified for UpsertBridgeResponse") @@ -816,7 +816,7 @@ func (_m *ORM) UpsertBridgeResponse(ctx context.Context, dotId string, specId in var r0 error if rf, ok := ret.Get(0).(func(context.Context, string, int32, []byte) error); ok { - r0 = rf(ctx, dotId, specId, response) + r0 = rf(ctx, dotID, specID, response) } else { r0 = ret.Error(0) } @@ -831,14 +831,14 @@ type ORM_UpsertBridgeResponse_Call struct { // UpsertBridgeResponse is a helper method to define mock.On call // - ctx context.Context -// - dotId string -// - specId int32 +// - dotID string +// - specID int32 // - response []byte -func (_e *ORM_Expecter) UpsertBridgeResponse(ctx interface{}, dotId interface{}, specId interface{}, response interface{}) *ORM_UpsertBridgeResponse_Call { - return &ORM_UpsertBridgeResponse_Call{Call: _e.mock.On("UpsertBridgeResponse", ctx, dotId, specId, response)} +func (_e *ORM_Expecter) UpsertBridgeResponse(ctx interface{}, dotID interface{}, specID interface{}, response interface{}) *ORM_UpsertBridgeResponse_Call { + return &ORM_UpsertBridgeResponse_Call{Call: _e.mock.On("UpsertBridgeResponse", ctx, dotID, specID, response)} } -func (_c *ORM_UpsertBridgeResponse_Call) Run(run func(ctx context.Context, dotId string, specId int32, response []byte)) *ORM_UpsertBridgeResponse_Call { +func (_c *ORM_UpsertBridgeResponse_Call) Run(run func(ctx context.Context, dotID string, specID int32, response []byte)) *ORM_UpsertBridgeResponse_Call { _c.Call.Run(func(args mock.Arguments) { run(args[0].(context.Context), args[1].(string), args[2].(int32), args[3].([]byte)) }) diff --git a/core/bridges/orm.go b/core/bridges/orm.go index 9030623fde9..fac46d24476 100644 --- a/core/bridges/orm.go +++ b/core/bridges/orm.go @@ -7,7 +7,6 @@ import ( "time" "github.com/jmoiron/sqlx" - pkgerrors "github.com/pkg/errors" "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink/v2/core/auth" @@ -17,20 +16,20 @@ type ORM interface { FindBridge(ctx context.Context, name BridgeName) (bt BridgeType, err error) FindBridges(ctx context.Context, name []BridgeName) (bts []BridgeType, err error) DeleteBridgeType(ctx context.Context, bt *BridgeType) error - BridgeTypes(ctx context.Context, offset int, limit int) ([]BridgeType, int, error) + BridgeTypes(ctx context.Context, offset, limit int) ([]BridgeType, int, error) CreateBridgeType(ctx context.Context, bt *BridgeType) error UpdateBridgeType(ctx context.Context, bt *BridgeType, btr *BridgeTypeRequest) error - GetCachedResponse(ctx context.Context, dotId string, specId int32, maxElapsed time.Duration) ([]byte, error) - UpsertBridgeResponse(ctx context.Context, dotId string, specId int32, response []byte) error + GetCachedResponse(ctx context.Context, dotID string, specID int32, maxElapsed time.Duration) ([]byte, error) + UpsertBridgeResponse(ctx context.Context, dotID string, specID int32, response []byte) error - ExternalInitiators(ctx context.Context, offset int, limit int) ([]ExternalInitiator, int, error) + ExternalInitiators(ctx context.Context, offset, limit int) ([]ExternalInitiator, int, error) CreateExternalInitiator(ctx context.Context, externalInitiator *ExternalInitiator) error DeleteExternalInitiator(ctx context.Context, name string) error FindExternalInitiator(ctx context.Context, eia *auth.Token) (*ExternalInitiator, error) FindExternalInitiatorByName(ctx context.Context, iname string) (exi ExternalInitiator, err error) - GetCachedResponseWithFinished(ctx context.Context, dotId string, specId int32, maxElapsed time.Duration) ([]byte, time.Time, error) + GetCachedResponseWithFinished(ctx context.Context, dotID string, specID int32, maxElapsed time.Duration) ([]byte, time.Time, error) BulkUpsertBridgeResponse(ctx context.Context, responses []BridgeResponse) error WithDataSource(sqlutil.DataSource) ORM @@ -59,7 +58,7 @@ func (o *orm) FindBridge(ctx context.Context, name BridgeName) (bt BridgeType, e stmt := "SELECT * FROM bridge_types WHERE name = $1" err = o.ds.GetContext(ctx, &bt, stmt, name.String()) - return + return bt, err } // FindBridges looks up multiple bridges in a single query. @@ -79,7 +78,7 @@ func (o *orm) FindBridges(ctx context.Context, names []BridgeName) ([]BridgeType } if len(bts) != len(names) { - return nil, pkgerrors.Errorf("not all bridges exist, asked for %v, exists %v", names, bts) + return nil, fmt.Errorf("not all bridges exist, asked for %v, exists %v", names, bts) } return bts, nil @@ -107,19 +106,19 @@ func (o *orm) DeleteBridgeType(ctx context.Context, bt *BridgeType) error { // BridgeTypes returns bridge types ordered by name filtered limited by the // passed params. -func (o *orm) BridgeTypes(ctx context.Context, offset int, limit int) (bridges []BridgeType, count int, err error) { +func (o *orm) BridgeTypes(ctx context.Context, offset, limit int) (bridges []BridgeType, count int, err error) { err = o.transact(ctx, true, func(tx *orm) error { if err = tx.ds.GetContext(ctx, &count, "SELECT COUNT(*) FROM bridge_types"); err != nil { - return pkgerrors.Wrap(err, "BridgeTypes failed to get count") + return fmt.Errorf("BridgeTypes failed to get count: %w", err) } sql := `SELECT * FROM bridge_types ORDER BY name asc LIMIT $1 OFFSET $2;` if err = tx.ds.SelectContext(ctx, &bridges, sql, limit, offset); err != nil { - return pkgerrors.Wrap(err, "BridgeTypes failed to load bridge_types") + return fmt.Errorf("BridgeTypes failed to load bridge_types: %w", err) } return nil }) - return + return bridges, count, err } // CreateBridgeType saves the bridge type. @@ -135,8 +134,10 @@ func (o *orm) CreateBridgeType(ctx context.Context, bt *BridgeType) error { defer stmt.Close() return stmt.GetContext(ctx, bt, bt) }) - - return pkgerrors.Wrap(err, "CreateBridgeType failed") + if err != nil { + return fmt.Errorf("CreateBridgeType failed: %w", err) + } + return nil } // UpdateBridgeType updates the bridge type. @@ -147,8 +148,8 @@ func (o *orm) UpdateBridgeType(ctx context.Context, bt *BridgeType, btr *BridgeT return err } -func (o *orm) GetCachedResponse(ctx context.Context, dotId string, specId int32, maxElapsed time.Duration) ([]byte, error) { - response, _, err := o.GetCachedResponseWithFinished(ctx, dotId, specId, maxElapsed) +func (o *orm) GetCachedResponse(ctx context.Context, dotID string, specID int32, maxElapsed time.Duration) ([]byte, error) { + response, _, err := o.GetCachedResponseWithFinished(ctx, dotID, specID, maxElapsed) if err != nil { return nil, err } @@ -156,13 +157,13 @@ func (o *orm) GetCachedResponse(ctx context.Context, dotId string, specId int32, return response, nil } -func (o *orm) GetCachedResponseWithFinished(ctx context.Context, dotId string, specId int32, maxElapsed time.Duration) ([]byte, time.Time, error) { +func (o *orm) GetCachedResponseWithFinished(ctx context.Context, dotID string, specID int32, maxElapsed time.Duration) ([]byte, time.Time, error) { stalenessThreshold := time.Now().Add(-maxElapsed) sql := `SELECT value, finished_at FROM bridge_last_value WHERE - dot_id = $1 AND - spec_id = $2 AND - finished_at > ($3) - ORDER BY finished_at + dot_id = $1 AND + spec_id = $2 AND + finished_at > ($3) + ORDER BY finished_at DESC LIMIT 1;` type responseType struct { @@ -172,29 +173,26 @@ func (o *orm) GetCachedResponseWithFinished(ctx context.Context, dotId string, s var result responseType - if err := pkgerrors.Wrap( - o.ds.GetContext(ctx, &result, sql, dotId, specId, stalenessThreshold), - fmt.Sprintf("failed to fetch last good value for task %s spec %d", dotId, specId), - ); err != nil { - return nil, time.Now(), err + if err := o.ds.GetContext(ctx, &result, sql, dotID, specID, stalenessThreshold); err != nil { + return nil, time.Now(), fmt.Errorf("failed to fetch last good value for task %s spec %d: %w", dotID, specID, err) } return result.Value, result.FinishedAt, nil } -func (o *orm) UpsertBridgeResponse(ctx context.Context, dotId string, specId int32, response []byte) error { - sql := `INSERT INTO bridge_last_value(dot_id, spec_id, value, finished_at) +func (o *orm) UpsertBridgeResponse(ctx context.Context, dotID string, specID int32, response []byte) error { + sql := `INSERT INTO bridge_last_value(dot_id, spec_id, value, finished_at) VALUES($1, $2, $3, $4) ON CONFLICT ON CONSTRAINT bridge_last_value_pkey DO UPDATE SET value = $3, finished_at = $4;` - _, err := o.ds.ExecContext(ctx, sql, dotId, specId, response, time.Now()) + _, err := o.ds.ExecContext(ctx, sql, dotID, specID, response, time.Now()) return err } func (o *orm) BulkUpsertBridgeResponse(ctx context.Context, responses []BridgeResponse) error { - sql := `INSERT INTO bridge_last_value(dot_id, spec_id, value, finished_at) + sql := `INSERT INTO bridge_last_value(dot_id, spec_id, value, finished_at) VALUES (:dot_id, :spec_id, :value, :finished_at) ON CONFLICT ON CONSTRAINT bridge_last_value_pkey DO UPDATE SET value = excluded.value, finished_at = excluded.finished_at;` @@ -209,19 +207,19 @@ func (o *orm) BulkUpsertBridgeResponse(ctx context.Context, responses []BridgeRe // --- External Initiator // ExternalInitiators returns a list of external initiators sorted by name -func (o *orm) ExternalInitiators(ctx context.Context, offset int, limit int) (initiators []ExternalInitiator, count int, err error) { +func (o *orm) ExternalInitiators(ctx context.Context, offset, limit int) (initiators []ExternalInitiator, count int, err error) { err = o.transact(ctx, true, func(tx *orm) error { if err = tx.ds.GetContext(ctx, &count, "SELECT COUNT(*) FROM external_initiators"); err != nil { - return pkgerrors.Wrap(err, "ExternalInitiators failed to get count") + return fmt.Errorf("ExternalInitiators failed to get count: %w", err) } sql := `SELECT * FROM external_initiators ORDER BY name asc LIMIT $1 OFFSET $2;` if err = tx.ds.SelectContext(ctx, &initiators, sql, limit, offset); err != nil { - return pkgerrors.Wrap(err, "ExternalInitiators failed to load external_initiators") + return fmt.Errorf("ExternalInitiators failed to load external_initiators: %w", err) } return nil }) - return + return initiators, count, err } // CreateExternalInitiator inserts a new external initiator @@ -234,12 +232,18 @@ func (o *orm) CreateExternalInitiator(ctx context.Context, externalInitiator *Ex var stmt *sqlx.NamedStmt stmt, err = tx.ds.PrepareNamedContext(ctx, query) if err != nil { - return pkgerrors.Wrap(err, "failed to prepare named stmt") + return fmt.Errorf("failed to prepare named stmt: %w", err) } defer stmt.Close() - return pkgerrors.Wrap(stmt.GetContext(ctx, externalInitiator, externalInitiator), "failed to load external_initiator") + if gerr := stmt.GetContext(ctx, externalInitiator, externalInitiator); gerr != nil { + return fmt.Errorf("failed to load external_initiator: %w", gerr) + } + return nil }) - return pkgerrors.Wrap(err, "CreateExternalInitiator failed") + if err != nil { + return fmt.Errorf("CreateExternalInitiator failed: %w", err) + } + return nil } // DeleteExternalInitiator removes an external initiator @@ -269,5 +273,5 @@ func (o *orm) FindExternalInitiator(ctx context.Context, eia *auth.Token) (*Exte // FindExternalInitiatorByName finds an external initiator given an authentication request func (o *orm) FindExternalInitiatorByName(ctx context.Context, iname string) (exi ExternalInitiator, err error) { err = o.ds.GetContext(ctx, &exi, `SELECT * FROM external_initiators WHERE lower(name) = lower($1)`, iname) - return + return exi, err } diff --git a/core/bridges/orm_test.go b/core/bridges/orm_test.go index 7f9f622fdbd..7aba548bec3 100644 --- a/core/bridges/orm_test.go +++ b/core/bridges/orm_test.go @@ -6,7 +6,6 @@ import ( "github.com/google/uuid" "github.com/jmoiron/sqlx" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" @@ -37,12 +36,12 @@ func TestORM_FindBridges(t *testing.T) { URL: cltest.WebURL(t, "https://bridge1.com"), } ctx := t.Context() - assert.NoError(t, orm.CreateBridgeType(ctx, &bt)) + require.NoError(t, orm.CreateBridgeType(ctx, &bt)) bt2 := bridges.BridgeType{ Name: "bridge2", URL: cltest.WebURL(t, "https://bridge2.com"), } - assert.NoError(t, orm.CreateBridgeType(ctx, &bt2)) + require.NoError(t, orm.CreateBridgeType(ctx, &bt2)) bts, err := orm.FindBridges(ctx, []bridges.BridgeName{"bridge2", "bridge1"}) require.NoError(t, err) require.Len(t, bts, 2) @@ -74,7 +73,7 @@ func TestORM_FindBridge(t *testing.T) { bt := bridges.BridgeType{} bt.Name = bridges.MustParseBridgeName("solargridreporting") bt.URL = cltest.WebURL(t, "https://denergy.eth") - assert.NoError(t, orm.CreateBridgeType(ctx, &bt)) + require.NoError(t, orm.CreateBridgeType(ctx, &bt)) cases := []struct { description string diff --git a/core/capabilities/confidentialrelay/handler.go b/core/capabilities/confidentialrelay/handler.go index f405bf99d78..6833146e4f9 100644 --- a/core/capabilities/confidentialrelay/handler.go +++ b/core/capabilities/confidentialrelay/handler.go @@ -998,7 +998,7 @@ func (h *Handler) signSecretsResponse( // Keep populating Signatures too: there are still readers of the array. The // cleanup order is readers first, then writers (this), then the field itself, // or builds go red. - Signatures: []confidentialrelaytypes.RelayResponseSignature{sig}, + Signatures: []confidentialrelaytypes.RelayResponseSignature{sig}, //nolint:staticcheck // SA1019 backward compatibility }, nil } @@ -1029,7 +1029,7 @@ func (h *Handler) signCapabilityResponse( // Keep populating Signatures too: there are still readers of the array. The // cleanup order is readers first, then writers (this), then the field itself, // or builds go red. - Signatures: []confidentialrelaytypes.RelayResponseSignature{sig}, + Signatures: []confidentialrelaytypes.RelayResponseSignature{sig}, //nolint:staticcheck // SA1019 backward compatibility }, nil } diff --git a/core/capabilities/confidentialrelay/handler_test.go b/core/capabilities/confidentialrelay/handler_test.go index 602434245d7..a62ae5e35ef 100644 --- a/core/capabilities/confidentialrelay/handler_test.go +++ b/core/capabilities/confidentialrelay/handler_test.go @@ -104,6 +104,7 @@ func (m *mockGatewayConnector) AddHandler(_ context.Context, methods []string, _ m.addedMethods = methods return nil } + func (m *mockGatewayConnector) RemoveHandler(_ context.Context, _ []string) error { m.removed = true return nil @@ -152,12 +153,14 @@ func (m *mockCapRegistry) ConfigForCapability(_ context.Context, capID string, _ } return capabilities.CapabilityConfiguration{}, fmt.Errorf("config not found: %s", capID) } + func (m *mockCapRegistry) DONsForCapability(_ context.Context, capID string) ([]capabilities.DONWithNodes, error) { if dons, ok := m.dons[capID]; ok { return dons, nil } return nil, fmt.Errorf("no DONs found for: %s", capID) } + func (m *mockCapRegistry) LocalNode(_ context.Context) (capabilities.Node, error) { return m.localNode, nil } @@ -450,7 +453,8 @@ func TestHandler_HandleGatewayMessage(t *testing.T) { } var result confidentialrelaytypes.SignedCapabilityResponseResult require.NoError(t, json.Unmarshal(*resp.Result, &result)) - require.Len(t, result.Signatures, 1) + require.NotEmpty(t, result.Signature.Signature) + require.Len(t, result.Signatures, 1) //nolint:staticcheck // SA1019 still populated for legacy readers assertValidCapabilitySignature(t, params, result) decoded, err := base64.StdEncoding.DecodeString(result.Result.Payload) @@ -558,7 +562,8 @@ func TestHandler_HandleGatewayMessage(t *testing.T) { } var result confidentialrelaytypes.SignedCapabilityResponseResult require.NoError(t, json.Unmarshal(*resp.Result, &result)) - require.Len(t, result.Signatures, 1) + require.NotEmpty(t, result.Signature.Signature) + require.Len(t, result.Signatures, 1) //nolint:staticcheck // SA1019 still populated for legacy readers assertValidCapabilitySignature(t, params, result) assert.Equal(t, "execution failed", result.Result.Error) assert.Empty(t, result.Result.Payload) @@ -579,7 +584,8 @@ func TestHandler_HandleGatewayMessage(t *testing.T) { params.Attestation = "" var result confidentialrelaytypes.SignedSecretsResponseResult require.NoError(t, json.Unmarshal(*resp.Result, &result)) - require.Len(t, result.Signatures, 1) + require.NotEmpty(t, result.Signature.Signature) + require.Len(t, result.Signatures, 1) //nolint:staticcheck // SA1019 still populated for legacy readers assertValidSecretsSignature(t, params, result) require.Len(t, result.Result.Secrets, 1) assert.Equal(t, "API_KEY", result.Result.Secrets[0].ID.Key) @@ -760,8 +766,8 @@ func assertValidCapabilitySignature( hash, err := result.Result.Hash(params) require.NoError(t, err) payload := confidentialrelaytypes.RelayResponseSignaturePayload(hash) - pubKey := ed25519.PublicKey(result.Signatures[0].Signer) - require.True(t, ed25519.Verify(pubKey, payload, result.Signatures[0].Signature)) + pubKey := ed25519.PublicKey(result.Signature.Signer) + require.True(t, ed25519.Verify(pubKey, payload, result.Signature.Signature)) } func assertValidSecretsSignature( @@ -773,8 +779,8 @@ func assertValidSecretsSignature( hash, err := result.Result.Hash(params) require.NoError(t, err) payload := confidentialrelaytypes.RelayResponseSignaturePayload(hash) - pubKey := ed25519.PublicKey(result.Signatures[0].Signer) - require.True(t, ed25519.Verify(pubKey, payload, result.Signatures[0].Signature)) + pubKey := ed25519.PublicKey(result.Signature.Signer) + require.True(t, ed25519.Verify(pubKey, payload, result.Signature.Signature)) } func TestHandler_Lifecycle(t *testing.T) { diff --git a/core/capabilities/fakes/confidential_http_action.go b/core/capabilities/fakes/confidential_http_action.go index 85153de6ac3..ea0986c6d18 100644 --- a/core/capabilities/fakes/confidential_http_action.go +++ b/core/capabilities/fakes/confidential_http_action.go @@ -68,7 +68,7 @@ func NewDirectConfidentialHTTPAction(lggr logger.Logger, secretsPath string) *Di secretsFile = envFile } - if data, err := os.ReadFile(secretsFile); err == nil { + if data, err := os.ReadFile(secretsFile); err == nil { //nolint:gosec // secrets path is trusted config, not untrusted user input if marshalErr := yaml.Unmarshal(data, &fc.secretsConfig); marshalErr != nil { lggr.Warnf("Failed to parse secrets file %s: %v", secretsFile, marshalErr) } else { diff --git a/core/capabilities/fakes/consensus_nodag_test.go b/core/capabilities/fakes/consensus_nodag_test.go index 0d4b9b51cb9..b10f647df5c 100644 --- a/core/capabilities/fakes/consensus_nodag_test.go +++ b/core/capabilities/fakes/consensus_nodag_test.go @@ -26,7 +26,7 @@ const ( func Test_Simple_EVMEncoder(t *testing.T) { nSigners := 4 - signers := []ocr2key.KeyBundle{} + signers := make([]ocr2key.KeyBundle, 0, nSigners) for range nSigners { signers = append(signers, ocr2key.MustNewInsecure(SeedForKeys(), corekeys.EVM)) } diff --git a/core/capabilities/fakes/http_action.go b/core/capabilities/fakes/http_action.go index 9f53ab0cf91..f0b81bb98f9 100644 --- a/core/capabilities/fakes/http_action.go +++ b/core/capabilities/fakes/http_action.go @@ -173,7 +173,7 @@ func (fh *DirectHTTPAction) SendRequest(ctx context.Context, metadata commonCap. // Create response response := &customhttp.Response{ StatusCode: uint32(resp.StatusCode), //nolint:gosec // status code is always in valid range - Headers: headers, + Headers: headers, //nolint:staticcheck // SA1019 MultiHeaders: multiHeaders, Body: respBody, } diff --git a/core/capabilities/fakes/http_action_test.go b/core/capabilities/fakes/http_action_test.go index d3ff584698c..da744d495a6 100644 --- a/core/capabilities/fakes/http_action_test.go +++ b/core/capabilities/fakes/http_action_test.go @@ -67,7 +67,7 @@ func TestDirectHTTPAction_RequestHeaders(t *testing.T) { input := &customhttp.Request{ Url: srv.URL, Method: "GET", - Headers: map[string]string{"Authorization": "Basic legacy-auth"}, + Headers: map[string]string{"Authorization": "Basic legacy-auth"}, //nolint:staticcheck // SA1019 } metadata := commonCap.RequestMetadata{} diff --git a/core/capabilities/gateway_connector/service_wrapper.go b/core/capabilities/gateway_connector/service_wrapper.go index 38bed84670c..0e1c230742d 100644 --- a/core/capabilities/gateway_connector/service_wrapper.go +++ b/core/capabilities/gateway_connector/service_wrapper.go @@ -105,7 +105,7 @@ func (e *ServiceWrapper) Start(ctx context.Context) error { return fmt.Errorf("gateway connector keystore check failed (chainID %s): %w", e.chainID, err) } - translated := connector.ConnectorConfig{}.From(conf) + translated := connector.Config{}.From(conf) // Override NodeAddress in translated config if we auto-discovered it if translated.NodeAddress == "" { translated.NodeAddress = nodeAddress diff --git a/core/capabilities/launcher.go b/core/capabilities/launcher.go index b6b6c1867c1..24bf8c5adb7 100644 --- a/core/capabilities/launcher.go +++ b/core/capabilities/launcher.go @@ -286,7 +286,6 @@ func (w *launcher) onNewRegistry(ctx context.Context, metadataRegistry *registry remoteWorkflowDONs := []registry.DON{} myDONs := map[uint32]bool{} myDONFamiliesSet := map[string]bool{} - myDONFamilies := []string{} for _, id := range allDONIDs { d := metadataRegistry.IDsToDONs[id] for _, peerID := range d.Members { @@ -306,6 +305,7 @@ func (w *launcher) onNewRegistry(ctx context.Context, metadataRegistry *registry } } } + myDONFamilies := make([]string, 0, len(myDONFamiliesSet)) for family := range myDONFamiliesSet { myDONFamilies = append(myDONFamilies, family) } diff --git a/core/capabilities/remote/trigger_publisher.go b/core/capabilities/remote/trigger_publisher.go index 2be976b6641..2ae1b02989d 100644 --- a/core/capabilities/remote/trigger_publisher.go +++ b/core/capabilities/remote/trigger_publisher.go @@ -103,8 +103,10 @@ type TriggerPublisher interface { SetConfig(config *commoncap.RemoteTriggerConfig, underlying commoncap.TriggerCapability, capDonInfo commoncap.DON, workflowDONs map[uint32]commoncap.DON) error } -var _ TriggerPublisher = &triggerPublisher{} -var _ types.ReceiverService = &triggerPublisher{} +var ( + _ TriggerPublisher = &triggerPublisher{} + _ types.ReceiverService = &triggerPublisher{} +) const ( minAllowedBatchCollectionPeriod = 10 * time.Millisecond @@ -112,7 +114,7 @@ const ( defaultMaxParallelRegisters = 100 // TODO: make this configurable https://smartcontract-it.atlassian.net/browse/PLEX-3266 ) -func NewTriggerPublisher(capabilityID string, capMethodName string, dispatcher types.Dispatcher, lggr logger.Logger) *triggerPublisher { +func NewTriggerPublisher(capabilityID, capMethodName string, dispatcher types.Dispatcher, lggr logger.Logger) *triggerPublisher { slotUsageAttrs := []attribute.KeyValue{ attribute.String("capabilityID", capabilityID), attribute.String("capMethodName", capMethodName), @@ -496,8 +498,8 @@ func (p *triggerPublisher) Receive(ctx context.Context, msg *types.MessageBody) p.messageCache.Delete(key) p.mu.Unlock() - ctx, cancel := p.stopCh.NewCtx() - err = p.cfg.Load().underlying.UnregisterTrigger(ctx, reg.request) + unregisterCtx, cancel := p.stopCh.NewCtx() + err = p.cfg.Load().underlying.UnregisterTrigger(unregisterCtx, reg.request) if err != nil { unregisterOutcome = "error" p.lggr.Errorw("failed to unregister trigger on underlying", "workflowID", key.workflowID, "triggerID", key.triggerID, "err", err) diff --git a/core/capabilities/vault/gw_handler.go b/core/capabilities/vault/gw_handler.go index 22cfae0b01b..d47f1080d42 100644 --- a/core/capabilities/vault/gw_handler.go +++ b/core/capabilities/vault/gw_handler.go @@ -15,11 +15,11 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/beholder" vaultcommon "github.com/smartcontractkit/chainlink-common/pkg/capabilities/actions/vault" jsonrpc "github.com/smartcontractkit/chainlink-common/pkg/jsonrpc2" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/services" "github.com/smartcontractkit/chainlink-common/pkg/settings/limits" "github.com/smartcontractkit/chainlink-common/pkg/types/core" "github.com/smartcontractkit/chainlink/v2/core/capabilities/vault/vaulttypes" - "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/gateway/api" "github.com/smartcontractkit/chainlink/v2/core/services/gateway/connector" workflowsyncerv2 "github.com/smartcontractkit/chainlink/v2/core/services/workflows/syncer/v2" @@ -130,7 +130,7 @@ func NewGatewayHandler( gatewayConnector: connector, requestProcessor: requestProcessor, jwtAuthService: jwtAuthService, - lggr: lggr.Named(HandlerName), + lggr: logger.Named(lggr, HandlerName), metrics: metrics, } gh.Service, gh.eng = services.Config{ @@ -174,7 +174,7 @@ func (h *GatewayHandler) Methods() []string { } func (h *GatewayHandler) requestLogger(req *jsonrpc.Request[json.RawMessage], gatewayID string) logger.Logger { - return h.lggr.With("requestID", req.ID, "method", req.Method, "gatewayID", gatewayID) + return logger.With(h.lggr, "requestID", req.ID, "method", req.Method, "gatewayID", gatewayID) } func (h *GatewayHandler) HandleGatewayMessage(ctx context.Context, gatewayID string, req *jsonrpc.Request[json.RawMessage]) (err error) { diff --git a/core/capabilities/vault/request_replay_guard_test.go b/core/capabilities/vault/request_replay_guard_test.go index 07e4b1ee6a5..69a155b79eb 100644 --- a/core/capabilities/vault/request_replay_guard_test.go +++ b/core/capabilities/vault/request_replay_guard_test.go @@ -137,7 +137,7 @@ func TestRequestReplayGuard_ConcurrentDifferentDigests(t *testing.T) { for i := range goroutines { go func(idx int) { defer wg.Done() - digest := "digest-" + string(rune('A'+idx)) + digest := "digest-" + string(rune('A'+idx)) //nolint:gosec // idx bounded 0..49, within rune range errors[idx] = guard.CheckAndRecord(digest, futureExpiry) }(i) } diff --git a/core/capabilities/vault/validator.go b/core/capabilities/vault/validator.go index 33dd79f256a..ddf72df6ac4 100644 --- a/core/capabilities/vault/validator.go +++ b/core/capabilities/vault/validator.go @@ -19,7 +19,9 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/capabilities/vault/vaultutils" ) -var isValidIDComponent = regexp.MustCompile(`^[a-zA-Z0-9_]+$`).MatchString +var ( + isValidIDComponent = regexp.MustCompile(`^[a-zA-Z0-9_]+$`).MatchString +) type RequestValidator struct { MaxRequestBatchSizeLimiter limits.BoundLimiter[int] @@ -104,7 +106,7 @@ func (r *RequestValidator) validateWriteRequest(ctx context.Context, publicKey * return nil } -func (r *RequestValidator) ValidateCiphertextSize(ctx context.Context, owner, encryptedValue string) error { +func (r *RequestValidator) ValidateCiphertextSize(ctx context.Context, owner string, encryptedValue string) error { rawCiphertext, err := hex.DecodeString(encryptedValue) if err != nil { return fmt.Errorf("failed to decode encrypted value: %w", err) @@ -139,7 +141,7 @@ func (r *RequestValidator) ValidateCiphertextSizes(ctx context.Context, owner st return nil } -func (r *RequestValidator) ValidateSecretIdentifier(ctx context.Context, idKey, idOwner, idNamespace string) error { +func (r *RequestValidator) ValidateSecretIdentifier(ctx context.Context, idKey string, idOwner string, idNamespace string) error { if idKey == "" { return errors.New("key cannot be empty") } @@ -321,7 +323,7 @@ func NewRequestValidatorFromLimitsFactory(limitsFactory limits.Factory) (*Reques // owner label (Ethereum address, left-padded to 32 bytes). owner must be non-empty; // when the public key is nil, verification is skipped for the same reasons as // verifyEncryptedSecret. -func EnsureRightLabelOnSecret(publicKey *tdh2easy.PublicKey, secret, owner string) error { +func EnsureRightLabelOnSecret(publicKey *tdh2easy.PublicKey, secret string, owner string) error { cipherText, err := verifyEncryptedSecret(publicKey, secret) if err != nil { return err diff --git a/core/capabilities/webapi/outgoing_connector_handler_test.go b/core/capabilities/webapi/outgoing_connector_handler_test.go index 62f70a3c3c2..b44d33b8ff1 100644 --- a/core/capabilities/webapi/outgoing_connector_handler_test.go +++ b/core/capabilities/webapi/outgoing_connector_handler_test.go @@ -3,11 +3,11 @@ package webapi import ( "context" "encoding/json" + "errors" "testing" "github.com/ethereum/go-ethereum/crypto" "github.com/pelletier/go-toml" - "github.com/pkg/errors" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" @@ -436,7 +436,7 @@ func TestOutgoingConnectorHandler_HandleGatewayMessage_InvalidMessage(t *testing ) invalidMsg := api.Message{ Body: api.MessageBody{ - // MessageId is empty, which should fail Validate() + // MessageID is empty, which should fail Validate() Method: "some-method", }, } diff --git a/core/cbor/cbor_test.go b/core/cbor/cbor_test.go index c1eb8ec3c0b..d49a3c2d8c0 100644 --- a/core/cbor/cbor_test.go +++ b/core/cbor/cbor_test.go @@ -138,13 +138,13 @@ func Test_ParseCBOR(t *testing.T) { for _, test := range tests { t.Run(test.name, func(t *testing.T) { b, err := hexutil.Decode(test.in) - assert.NoError(t, err) + require.NoError(t, err) json, err := ParseDietCBOR(b) if test.wantErrored { assert.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, test.want, json) } }) @@ -156,16 +156,16 @@ func Test_ParseCBORToStruct_Success(t *testing.T) { hexCBOR := `0xbf6375726c781a68747470733a2f2f657468657270726963652e636f6d2f61706964706174689f66726563656e7463757364ffff000000` bytesCBOR, err := hexutil.Decode(hexCBOR) - assert.NoError(t, err) + require.NoError(t, err) parsed := struct { - Url string `cbor:"url"` + URL string `cbor:"url"` Path []string `cbor:"path"` }{} err = ParseDietCBORToStruct(bytesCBOR, &parsed) require.NoError(t, err) - require.Equal(t, "https://etherprice.com/api", parsed.Url) + require.Equal(t, "https://etherprice.com/api", parsed.URL) require.Equal(t, []string{"recent", "usd"}, parsed.Path) } @@ -174,10 +174,10 @@ func Test_ParseCBORToStruct_WrongFieldType(t *testing.T) { hexCBOR := `0xbf6375726c781a68747470733a2f2f657468657270726963652e636f6d2f61706964706174689f66726563656e7463757364ffff000000` bytesCBOR, err := hexutil.Decode(hexCBOR) - assert.NoError(t, err) + require.NoError(t, err) parsed := struct { - Url string `cbor:"url"` + URL string `cbor:"url"` Path []int `cbor:"path"` // expect int but get string }{} err = ParseDietCBORToStruct(bytesCBOR, &parsed) @@ -191,7 +191,7 @@ func Test_ParseCBORToStruct_BinaryStringOfWrongType(t *testing.T) { // {"key":"value"} but with last byte replaced with invalid unicode (0x88) hexCBOR := `0x636B65796576616C7588` bytesCBOR, err := hexutil.Decode(hexCBOR) - assert.NoError(t, err) + require.NoError(t, err) parsed := struct { Key string `cbor:"key"` @@ -276,12 +276,12 @@ func TestCoerceInterfaceMapToStringMap(t *testing.T) { {"simple map", map[any]any{"key": "value"}, map[string]any{"key": "value"}}, {"int map", map[int]any{1: "value"}, map[int]any{1: "value"}}, { - "nested string map map", + "nested string map", map[string]any{"key": map[any]any{"nk": "nv"}}, map[string]any{"key": map[string]any{"nk": "nv"}}, }, { - "nested map map", + "nested map", map[any]any{"key": map[any]any{"nk": "nv"}}, map[string]any{"key": map[string]any{"nk": "nv"}}, }, diff --git a/core/cmd/app.go b/core/cmd/app.go index 9f31b8d4b2b..ee0e378ecb1 100644 --- a/core/cmd/app.go +++ b/core/cmd/app.go @@ -2,6 +2,7 @@ package cmd import ( "cmp" + "errors" "fmt" "net/url" "os" @@ -9,7 +10,6 @@ import ( "regexp" "slices" - "github.com/pkg/errors" "github.com/prometheus/client_golang/prometheus" "github.com/urfave/cli" @@ -107,7 +107,7 @@ func NewApp(s *Shell) *cli.App { urlStr := c.String("remote-node-url") remoteNodeURL, err := url.Parse(urlStr) if err != nil { - return errors.Wrapf(err, "%s is not a valid URL", urlStr) + return fmt.Errorf("%s is not a valid URL: %w", urlStr, err) } insecureSkipVerify := c.Bool("insecure-skip-verify") @@ -117,8 +117,8 @@ func NewApp(s *Shell) *cli.App { credentialsFile := c.String("admin-credentials-file") sr, err := sessionRequestBuilder.Build(credentialsFile) - if err != nil && !errors.Is(errors.Cause(err), ErrNoCredentialFile) && !os.IsNotExist(err) { - return errors.Wrapf(err, "failed to load API credentials from file %s", credentialsFile) + if err != nil && !errors.Is(err, ErrNoCredentialFile) && !os.IsNotExist(err) { + return fmt.Errorf("failed to load API credentials from file %s: %w", credentialsFile, err) } s.HTTP = NewAuthenticatedHTTPClient(s.Logger, clientOpts, cookieAuth, sr) @@ -270,7 +270,7 @@ func NewApp(s *Shell) *cli.App { lggrCfg := logger.Config{ LogLevel: s.Config.Log().Level(), Dir: s.Config.Log().File().Dir(), - JsonConsole: s.Config.Log().JSONConsole(), + JSONConsole: s.Config.Log().JSONConsole(), UnixTS: s.Config.Log().UnixTimestamps(), //nolint:gosec // filemaxsizesmb won't exceed max int FileMaxSizeMB: int(logFileMaxSizeMB), diff --git a/core/cmd/shell.go b/core/cmd/shell.go index f37140046f7..42057d37e8b 100644 --- a/core/cmd/shell.go +++ b/core/cmd/shell.go @@ -290,7 +290,8 @@ func (n ChainlinkAppFactory) NewApplication(ctx context.Context, cfg chainlink.G // Configure and optionally start the audit log forwarder service auditLogger, err := audit.NewAuditLogger(appLggr, cfg.AuditLogger()) if err != nil { - return nil, err + appLggr.Criticalf("Failed to initialize audit logger: %v. In a future release, this error will prevent node startup.", err) + auditLogger = audit.NoopLogger } creOpts := cre.Opts{ diff --git a/core/config/config_internal_test.go b/core/config/config_internal_test.go index 41c6a4bb19d..e82988b2f70 100644 --- a/core/config/config_internal_test.go +++ b/core/config/config_internal_test.go @@ -14,33 +14,33 @@ import ( func TestStore_bigIntParser(t *testing.T) { val, err := parse.BigInt("0") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, new(big.Int).SetInt64(0), val) val, err = parse.BigInt("15") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, new(big.Int).SetInt64(15), val) val, err = parse.BigInt("x") - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, val) val, err = parse.BigInt("") - assert.Error(t, err) + require.Error(t, err) assert.Nil(t, val) } func TestStore_levelParser(t *testing.T) { val, err := parse.LogLevel("ERROR") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, zapcore.ErrorLevel, val) val, err = parse.LogLevel("") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, zapcore.InfoLevel, val) val, err = parse.LogLevel("primus sucks") - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, val, zapcore.Level(0)) } @@ -73,11 +73,11 @@ func TestStore_urlParser(t *testing.T) { func TestStore_boolParser(t *testing.T) { val, err := parse.Bool("true") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, true, val) val, err = parse.Bool("false") - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, false, val) _, err = parse.Bool("") diff --git a/core/config/toml/types.go b/core/config/toml/types.go index dac2de6244f..2a37aa3c9b7 100644 --- a/core/config/toml/types.go +++ b/core/config/toml/types.go @@ -126,16 +126,16 @@ func (c *Core) SetFrom(f *Core) { func (c *Core) ValidateConfig() (err error) { _, verr := parse.HomeDir(*c.RootDir) if verr != nil { - err = errors.Join(err, configutils.ErrInvalid{Name: "RootDir", Value: true, Msg: fmt.Sprintf("Failed to expand RootDir. Please use an explicit path: %s", verr)}) + err = errors.Join(err, configutils.InvalidError{Name: "RootDir", Value: true, Msg: fmt.Sprintf("Failed to expand RootDir. Please use an explicit path: %s", verr)}) } if (*c.OCR.Enabled || *c.OCR2.Enabled) && !*c.P2P.V2.Enabled { - err = errors.Join(err, configutils.ErrInvalid{Name: "P2P.V2.Enabled", Value: false, Msg: "P2P required for OCR or OCR2. Please enable P2P or disable OCR/OCR2."}) + err = errors.Join(err, configutils.InvalidError{Name: "P2P.V2.Enabled", Value: false, Msg: "P2P required for OCR or OCR2. Please enable P2P or disable OCR/OCR2."}) } if *c.Tracing.Enabled && *c.Telemetry.Enabled { if c.Tracing.CollectorTarget == c.Telemetry.Endpoint { - err = errors.Join(err, configutils.ErrInvalid{Name: "Tracing.CollectorTarget", Value: *c.Tracing.CollectorTarget, Msg: "Same as Telemetry.Endpoint. Must be different or disabled."}) + err = errors.Join(err, configutils.InvalidError{Name: "Tracing.CollectorTarget", Value: *c.Tracing.CollectorTarget, Msg: "Same as Telemetry.Endpoint. Must be different or disabled."}) } } @@ -200,7 +200,7 @@ func (s *SolKeys) validateMerge(f *SolKeys) (err error) { continue // a missing ID is a validation error, not a merge conflict } if _, ok := have[*solKey.ID]; ok { - err = errors.Join(err, configutils.ErrOverride{Name: "SolKeys: " + *solKey.ID}) + err = errors.Join(err, configutils.OverrideError{Name: "SolKeys: " + *solKey.ID}) } } } @@ -210,7 +210,7 @@ func (s *SolKeys) validateMerge(f *SolKeys) (err error) { func (s *SolKeys) ValidateConfig() (err error) { for i, solKey := range s.Keys { if err2 := solKey.ValidateConfig(); err2 != nil { - err = errors.Join(err, configutils.ErrInvalid{Name: fmt.Sprintf("SolKeys[%d]", i), Value: solKey, Msg: "invalid SolKey"}) + err = errors.Join(err, configutils.InvalidError{Name: fmt.Sprintf("SolKeys[%d]", i), Value: solKey, Msg: "invalid SolKey"}) } } return err @@ -235,26 +235,26 @@ func (e *SolKey) SetFrom(f *SolKey) (err error) { func (e *SolKey) validateMerge(f *SolKey) (err error) { if e.JSON != nil && f.JSON != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "PrivateKey"}) + err = errors.Join(err, configutils.OverrideError{Name: "PrivateKey"}) } if e.ID != nil && f.ID != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "Selector"}) + err = errors.Join(err, configutils.OverrideError{Name: "Selector"}) } if e.Password != nil && f.Password != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "Password"}) + err = errors.Join(err, configutils.OverrideError{Name: "Password"}) } return err } func (e *SolKey) ValidateConfig() (err error) { if (e.JSON != nil) != (e.Password != nil) || (e.Password != nil) != (e.ID != nil) { - err = errors.Join(err, configutils.ErrInvalid{Name: "SolKey", Value: e.JSON, Msg: "all fields must be nil or non-nil"}) + err = errors.Join(err, configutils.InvalidError{Name: "SolKey", Value: e.JSON, Msg: "all fields must be nil or non-nil"}) } // require valid id if e.ID != nil { _, err2 := chain_selectors.SolanaNameFromChainId(*e.ID) if err2 != nil { - err = errors.Join(err, configutils.ErrInvalid{Name: "ChainID", Value: e.ID, Msg: "invalid chain id"}) + err = errors.Join(err, configutils.InvalidError{Name: "ChainID", Value: e.ID, Msg: "invalid chain id"}) } } return err @@ -298,7 +298,7 @@ func (a *AptosKeys) validateMerge(f *AptosKeys) (err error) { continue // a missing ID is a validation error, not a merge conflict } if _, ok := have[*aptosKey.ID]; ok { - err = errors.Join(err, configutils.ErrOverride{Name: fmt.Sprintf("AptosKeys: %d", *aptosKey.ID)}) + err = errors.Join(err, configutils.OverrideError{Name: fmt.Sprintf("AptosKeys: %d", *aptosKey.ID)}) } } } @@ -308,7 +308,7 @@ func (a *AptosKeys) validateMerge(f *AptosKeys) (err error) { func (a *AptosKeys) ValidateConfig() (err error) { for i, aptosKey := range a.Keys { if err2 := aptosKey.ValidateConfig(); err2 != nil { - err = errors.Join(err, configutils.ErrInvalid{Name: fmt.Sprintf("AptosKeys[%d]", i), Value: aptosKey, Msg: "invalid AptosKey"}) + err = errors.Join(err, configutils.InvalidError{Name: fmt.Sprintf("AptosKeys[%d]", i), Value: aptosKey, Msg: "invalid AptosKey"}) } } return err @@ -333,24 +333,24 @@ func (p *AptosKey) SetFrom(f *AptosKey) (err error) { func (p *AptosKey) validateMerge(f *AptosKey) (err error) { if p.JSON != nil && f.JSON != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "JSON"}) + err = errors.Join(err, configutils.OverrideError{Name: "JSON"}) } if p.ID != nil && f.ID != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "ID"}) + err = errors.Join(err, configutils.OverrideError{Name: "ID"}) } if p.Password != nil && f.Password != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "Password"}) + err = errors.Join(err, configutils.OverrideError{Name: "Password"}) } return err } func (p *AptosKey) ValidateConfig() (err error) { if (p.JSON != nil) != (p.Password != nil) || (p.Password != nil) != (p.ID != nil) { - err = errors.Join(err, configutils.ErrInvalid{Name: "AptosKey", Value: p.JSON, Msg: "all fields must be nil or non-nil"}) + err = errors.Join(err, configutils.InvalidError{Name: "AptosKey", Value: p.JSON, Msg: "all fields must be nil or non-nil"}) } if p.ID != nil { if _, ok := chain_selectors.AptosChainIdToChainSelector()[*p.ID]; !ok { - err = errors.Join(err, configutils.ErrInvalid{Name: "ID", Value: p.ID, Msg: "invalid chain id"}) + err = errors.Join(err, configutils.InvalidError{Name: "ID", Value: p.ID, Msg: "invalid chain id"}) } } return err @@ -394,7 +394,7 @@ func (s *StellarKeys) validateMerge(f *StellarKeys) (err error) { continue // a missing ID is a validation error, not a merge conflict } if _, ok := have[*stellarKey.ID]; ok { - err = errors.Join(err, configutils.ErrOverride{Name: "StellarKeys: " + *stellarKey.ID}) + err = errors.Join(err, configutils.OverrideError{Name: "StellarKeys: " + *stellarKey.ID}) } } } @@ -404,7 +404,7 @@ func (s *StellarKeys) validateMerge(f *StellarKeys) (err error) { func (s *StellarKeys) ValidateConfig() (err error) { for i, stellarKey := range s.Keys { if err2 := stellarKey.ValidateConfig(); err2 != nil { - err = errors.Join(err, configutils.ErrInvalid{Name: fmt.Sprintf("StellarKeys[%d]", i), Value: stellarKey, Msg: "invalid StellarKey"}) + err = errors.Join(err, configutils.InvalidError{Name: fmt.Sprintf("StellarKeys[%d]", i), Value: stellarKey, Msg: "invalid StellarKey"}) } } return err @@ -429,24 +429,24 @@ func (s *StellarKey) SetFrom(f *StellarKey) (err error) { func (s *StellarKey) validateMerge(f *StellarKey) (err error) { if s.JSON != nil && f.JSON != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "JSON"}) + err = errors.Join(err, configutils.OverrideError{Name: "JSON"}) } if s.ID != nil && f.ID != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "ID"}) + err = errors.Join(err, configutils.OverrideError{Name: "ID"}) } if s.Password != nil && f.Password != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "Password"}) + err = errors.Join(err, configutils.OverrideError{Name: "Password"}) } return err } func (s *StellarKey) ValidateConfig() (err error) { if (s.JSON != nil) != (s.Password != nil) || (s.Password != nil) != (s.ID != nil) { - err = errors.Join(err, configutils.ErrInvalid{Name: "StellarKey", Value: s.JSON, Msg: "all fields must be nil or non-nil"}) + err = errors.Join(err, configutils.InvalidError{Name: "StellarKey", Value: s.JSON, Msg: "all fields must be nil or non-nil"}) } if s.ID != nil { if _, err2 := chain_selectors.StellarNameFromChainId(*s.ID); err2 != nil { - err = errors.Join(err, configutils.ErrInvalid{Name: "ID", Value: s.ID, Msg: "invalid chain id"}) + err = errors.Join(err, configutils.InvalidError{Name: "ID", Value: s.ID, Msg: "invalid chain id"}) } } return err @@ -484,7 +484,7 @@ func (e *EthKeys) validateMerge(f *EthKeys) (err error) { continue // a missing ID is a validation error, not a merge conflict } if _, ok := have[*ethKey.ID]; ok { - err = errors.Join(err, configutils.ErrOverride{Name: fmt.Sprintf("EthKeys: %d", *ethKey.ID)}) + err = errors.Join(err, configutils.OverrideError{Name: fmt.Sprintf("EthKeys: %d", *ethKey.ID)}) } } } @@ -494,7 +494,7 @@ func (e *EthKeys) validateMerge(f *EthKeys) (err error) { func (e *EthKeys) ValidateConfig() (err error) { for i, ethKey := range e.Keys { if err2 := ethKey.ValidateConfig(); err2 != nil { - err = errors.Join(err, configutils.ErrInvalid{Name: fmt.Sprintf("EthKeys[%d]", i), Value: ethKey, Msg: "invalid EthKey"}) + err = errors.Join(err, configutils.InvalidError{Name: fmt.Sprintf("EthKeys[%d]", i), Value: ethKey, Msg: "invalid EthKey"}) } } return err @@ -552,18 +552,19 @@ func (d *DatabaseSecrets) ValidateConfig() (err error) { } func (d *DatabaseSecrets) validateConfig(buildMode string) (err error) { - if d.URL == nil || (*url.URL)(d.URL).String() == "" { - err = errors.Join(err, configutils.ErrEmpty{Name: "URL", Msg: "must be provided and non-empty"}) - } else if *d.AllowSimplePasswords && buildMode == build.Prod { - err = errors.Join(err, configutils.ErrInvalid{Name: "AllowSimplePasswords", Value: true, Msg: "insecure configs are not allowed on secure builds"}) - } else if !*d.AllowSimplePasswords { - if verr := validateDBURL((url.URL)(*d.URL)); verr != nil { - err = errors.Join(err, configutils.ErrInvalid{Name: "URL", Value: "*****", Msg: dbURLPasswordComplexity(verr)}) + switch { + case d.URL == nil || (*url.URL)(d.URL).String() == "": + err = errors.Join(err, configutils.EmptyError{Name: "URL", Msg: "must be provided and non-empty"}) + case *d.AllowSimplePasswords && buildMode == build.Prod: + err = errors.Join(err, configutils.InvalidError{Name: "AllowSimplePasswords", Value: true, Msg: "insecure configs are not allowed on secure builds"}) + case !*d.AllowSimplePasswords: + if verr := validateDBURL(url.URL(*d.URL)); verr != nil { + err = errors.Join(err, configutils.InvalidError{Name: "URL", Value: "*****", Msg: dbURLPasswordComplexity(verr)}) } } if d.BackupURL != nil && !*d.AllowSimplePasswords { - if verr := validateDBURL((url.URL)(*d.BackupURL)); verr != nil { - err = errors.Join(err, configutils.ErrInvalid{Name: "BackupURL", Value: "*****", Msg: dbURLPasswordComplexity(verr)}) + if verr := validateDBURL(url.URL(*d.BackupURL)); verr != nil { + err = errors.Join(err, configutils.InvalidError{Name: "BackupURL", Value: "*****", Msg: dbURLPasswordComplexity(verr)}) } } return err @@ -589,15 +590,15 @@ func (d *DatabaseSecrets) SetFrom(f *DatabaseSecrets) (err error) { func (d *DatabaseSecrets) validateMerge(f *DatabaseSecrets) (err error) { if d.AllowSimplePasswords != nil && f.AllowSimplePasswords != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "AllowSimplePasswords"}) + err = errors.Join(err, configutils.OverrideError{Name: "AllowSimplePasswords"}) } if d.BackupURL != nil && f.BackupURL != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "BackupURL"}) + err = errors.Join(err, configutils.OverrideError{Name: "BackupURL"}) } if d.URL != nil && f.URL != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "URL"}) + err = errors.Join(err, configutils.OverrideError{Name: "URL"}) } return err @@ -628,26 +629,26 @@ func (e *EthKey) SetFrom(f *EthKey) (err error) { func (e *EthKey) validateMerge(f *EthKey) (err error) { if e.JSON != nil && f.JSON != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "PrivateKey"}) + err = errors.Join(err, configutils.OverrideError{Name: "PrivateKey"}) } if e.ID != nil && f.ID != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "Selector"}) + err = errors.Join(err, configutils.OverrideError{Name: "Selector"}) } if e.Password != nil && f.Password != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "Password"}) + err = errors.Join(err, configutils.OverrideError{Name: "Password"}) } return err } func (e *EthKey) ValidateConfig() (err error) { if (e.JSON != nil) != (e.Password != nil) || (e.Password != nil) != (e.ID != nil) { - err = errors.Join(err, configutils.ErrInvalid{Name: "EthKey", Value: e.JSON, Msg: "all fields must be nil or non-nil"}) + err = errors.Join(err, configutils.InvalidError{Name: "EthKey", Value: e.JSON, Msg: "all fields must be nil or non-nil"}) } // require valid id if e.ID != nil { _, ok := chain_selectors.ChainByEvmChainID(uint64(*e.ID)) //nolint:gosec // disable G115 if !ok { - err = errors.Join(err, configutils.ErrInvalid{Name: "ChainSelector", Value: e.ID, Msg: "invalid chain selector"}) + err = errors.Join(err, configutils.InvalidError{Name: "ChainSelector", Value: e.ID, Msg: "invalid chain selector"}) } } return err @@ -674,17 +675,17 @@ func (p *P2PKey) SetFrom(f *P2PKey) (err error) { func (p *P2PKey) validateMerge(f *P2PKey) (err error) { if p.JSON != nil && f.JSON != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "JSON"}) + err = errors.Join(err, configutils.OverrideError{Name: "JSON"}) } if p.Password != nil && f.Password != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "Password"}) + err = errors.Join(err, configutils.OverrideError{Name: "Password"}) } return err } func (p *P2PKey) ValidateConfig() (err error) { if (p.JSON != nil) != (p.Password != nil) { - err = errors.Join(err, configutils.ErrInvalid{Name: "P2PKey", Value: p.JSON, Msg: "all fields must be nil or non-nil"}) + err = errors.Join(err, configutils.InvalidError{Name: "P2PKey", Value: p.JSON, Msg: "all fields must be nil or non-nil"}) } return err } @@ -710,17 +711,17 @@ func (p *DKGRecipientKey) SetFrom(f *DKGRecipientKey) (err error) { func (p *DKGRecipientKey) validateMerge(f *DKGRecipientKey) (err error) { if p.JSON != nil && f.JSON != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "JSON"}) + err = errors.Join(err, configutils.OverrideError{Name: "JSON"}) } if p.Password != nil && f.Password != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "Password"}) + err = errors.Join(err, configutils.OverrideError{Name: "Password"}) } return err } func (p *DKGRecipientKey) ValidateConfig() (err error) { if (p.JSON != nil) != (p.Password != nil) { - err = errors.Join(err, configutils.ErrInvalid{Name: "DKGRecipientKey", Value: p.JSON, Msg: "all fields must be nil or non-nil"}) + err = errors.Join(err, configutils.InvalidError{Name: "DKGRecipientKey", Value: p.JSON, Msg: "all fields must be nil or non-nil"}) } return err } @@ -748,11 +749,11 @@ func (p *Passwords) SetFrom(f *Passwords) (err error) { func (p *Passwords) validateMerge(f *Passwords) (err error) { if p.Keystore != nil && f.Keystore != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "Keystore"}) + err = errors.Join(err, configutils.OverrideError{Name: "Keystore"}) } if p.VRF != nil && f.VRF != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "VRF"}) + err = errors.Join(err, configutils.OverrideError{Name: "VRF"}) } return err @@ -760,7 +761,7 @@ func (p *Passwords) validateMerge(f *Passwords) (err error) { func (p *Passwords) ValidateConfig() (err error) { if p.Keystore == nil || *p.Keystore == "" { - err = errors.Join(err, configutils.ErrEmpty{Name: "Keystore", Msg: "must be provided and non-empty"}) + err = errors.Join(err, configutils.EmptyError{Name: "Keystore", Msg: "must be provided and non-empty"}) } return err } @@ -784,7 +785,7 @@ func (p *PyroscopeSecrets) SetFrom(f *PyroscopeSecrets) (err error) { func (p *PyroscopeSecrets) validateMerge(f *PyroscopeSecrets) (err error) { if p.AuthToken != nil && f.AuthToken != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "AuthToken"}) + err = errors.Join(err, configutils.OverrideError{Name: "AuthToken"}) } return err @@ -809,7 +810,7 @@ func (p *PrometheusSecrets) SetFrom(f *PrometheusSecrets) (err error) { func (p *PrometheusSecrets) validateMerge(f *PrometheusSecrets) (err error) { if p.AuthToken != nil && f.AuthToken != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "AuthToken"}) + err = errors.Join(err, configutils.OverrideError{Name: "AuthToken"}) } return err @@ -917,12 +918,12 @@ func (l *DatabaseLock) Mode() string { func (l *DatabaseLock) ValidateConfig() (err error) { if l.LeaseRefreshInterval.Duration() > l.LeaseDuration.Duration()/2 { - err = errors.Join(err, configutils.ErrInvalid{ + err = errors.Join(err, configutils.InvalidError{ Name: "LeaseRefreshInterval", Value: l.LeaseRefreshInterval, Msg: fmt.Sprintf("must be less than or equal to half of LeaseDuration (%s)", l.LeaseDuration), }) } - return + return err } func (l *DatabaseLock) setFrom(f *DatabaseLock) { @@ -1013,8 +1014,8 @@ func (t *TelemetryIngress) setFrom(f *TelemetryIngress) { type AuditLogger struct { Enabled *bool - ForwardToUrl *commonconfig.URL - JsonWrapperKey *string + ForwardToUrl *commonconfig.URL //nolint:revive // TOML key compatibility + JsonWrapperKey *string //nolint:revive // TOML key compatibility Headers *[]models.ServiceHeader } @@ -1179,63 +1180,63 @@ func (w *WebServer) ValidateConfig() (err error) { case string(sessions.LDAPAuth): // Assert LDAP fields when AuthMethod set to LDAP if *w.LDAP.BaseDN == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "LDAP.BaseDN", Msg: "LDAP BaseDN can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "LDAP.BaseDN", Msg: "LDAP BaseDN can not be empty"}) } if *w.LDAP.BaseUserAttr == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "LDAP.BaseUserAttr", Msg: "LDAP BaseUserAttr can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "LDAP.BaseUserAttr", Msg: "LDAP BaseUserAttr can not be empty"}) } if *w.LDAP.UsersDN == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "LDAP.UsersDN", Msg: "LDAP UsersDN can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "LDAP.UsersDN", Msg: "LDAP UsersDN can not be empty"}) } if *w.LDAP.GroupsDN == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "LDAP.GroupsDN", Msg: "LDAP GroupsDN can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "LDAP.GroupsDN", Msg: "LDAP GroupsDN can not be empty"}) } if *w.LDAP.AdminUserGroupCN == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "LDAP.AdminUserGroupCN", Msg: "LDAP AdminUserGroupCN can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "LDAP.AdminUserGroupCN", Msg: "LDAP AdminUserGroupCN can not be empty"}) } if *w.LDAP.EditUserGroupCN == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "LDAP.RunUserGroupCN", Msg: "LDAP ReadUserGroupCN can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "LDAP.RunUserGroupCN", Msg: "LDAP ReadUserGroupCN can not be empty"}) } if *w.LDAP.RunUserGroupCN == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "LDAP.RunUserGroupCN", Msg: "LDAP RunUserGroupCN can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "LDAP.RunUserGroupCN", Msg: "LDAP RunUserGroupCN can not be empty"}) } if *w.LDAP.ReadUserGroupCN == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "LDAP.ReadUserGroupCN", Msg: "LDAP ReadUserGroupCN can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "LDAP.ReadUserGroupCN", Msg: "LDAP ReadUserGroupCN can not be empty"}) } return err case string(sessions.OIDCAuth): if w.OIDC.ClientID == nil || *w.OIDC.ClientID == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "OIDC.ClientID", Msg: "OIDC ClientID can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "OIDC.ClientID", Msg: "OIDC ClientID can not be empty"}) } if w.OIDC.ProviderURL == nil || *w.OIDC.ProviderURL == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "OIDC.ProviderURL", Msg: "OIDC ProviderURL can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "OIDC.ProviderURL", Msg: "OIDC ProviderURL can not be empty"}) } if w.OIDC.RedirectURL == nil || *w.OIDC.RedirectURL == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "OIDC.RedirectURL", Msg: "OIDC RedirectURL can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "OIDC.RedirectURL", Msg: "OIDC RedirectURL can not be empty"}) } if w.OIDC.ClaimName == nil || *w.OIDC.ClaimName == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "OIDC.ClaimName", Msg: "OIDC ClaimName can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "OIDC.ClaimName", Msg: "OIDC ClaimName can not be empty"}) } if w.OIDC.AdminClaim == nil || *w.OIDC.AdminClaim == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "OIDC.AdminClaim", Msg: "OIDC AdminClaim can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "OIDC.AdminClaim", Msg: "OIDC AdminClaim can not be empty"}) } if w.OIDC.EditClaim == nil || *w.OIDC.EditClaim == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "OIDC.EditClaim", Msg: "OIDC EditClaim can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "OIDC.EditClaim", Msg: "OIDC EditClaim can not be empty"}) } if w.OIDC.RunClaim == nil || *w.OIDC.RunClaim == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "OIDC.RunClaim", Msg: "OIDC RunClaim can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "OIDC.RunClaim", Msg: "OIDC RunClaim can not be empty"}) } if w.OIDC.ReadClaim == nil || *w.OIDC.ReadClaim == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "OIDC.ReadClaim", Msg: "OIDC ReadClaim can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "OIDC.ReadClaim", Msg: "OIDC ReadClaim can not be empty"}) } if w.OIDC.SessionTimeout == commonconfig.MustNewDuration(0) { - err = errors.Join(err, configutils.ErrInvalid{Name: "OIDC.SessionTimeout", Msg: "OIDC SessionTimeout can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "OIDC.SessionTimeout", Msg: "OIDC SessionTimeout can not be empty"}) } if w.OIDC.UserAPITokenEnabled == nil { - err = errors.Join(err, configutils.ErrInvalid{Name: "OIDC.UserAPITokenEnabled", Msg: "OIDC UserAPITokenEnabled can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "OIDC.UserAPITokenEnabled", Msg: "OIDC UserAPITokenEnabled can not be empty"}) } if w.OIDC.UserAPITokenDuration == commonconfig.MustNewDuration(0) { - err = errors.Join(err, configutils.ErrInvalid{Name: "OIDC.UserAPITokenDuration", Msg: "OIDC UserAPITokenDuration can not be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "OIDC.UserAPITokenDuration", Msg: "OIDC UserAPITokenDuration can not be empty"}) } return err } @@ -1323,7 +1324,7 @@ type WebServerLDAP struct { EditUserGroupCN *string RunUserGroupCN *string ReadUserGroupCN *string - UserApiTokenEnabled *bool + UserApiTokenEnabled *bool //nolint:revive // TOML key compatibility UserAPITokenDuration *commonconfig.Duration UpstreamSyncInterval *commonconfig.Duration UpstreamSyncRateLimit *commonconfig.Duration @@ -1479,22 +1480,22 @@ func (w *WebServerSecrets) ValidateConfig() (err error) { // Validate LDAP if it has non-zero values if w.LDAP != (WebServerLDAPSecrets{}) { if w.LDAP.ServerAddress == nil || w.LDAP.ServerAddress.URL().String() == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "WebServerLDAPSecrets.ServerAddress", Msg: "WebServerLDAPSecrets ServerAddress cannot be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "WebServerLDAPSecrets.ServerAddress", Msg: "WebServerLDAPSecrets ServerAddress cannot be empty"}) } if w.LDAP.ReadOnlyUserLogin == nil || *w.LDAP.ReadOnlyUserLogin == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "w.LDAP.bServerLDAPSecrets.ReadOnlyUserLogin", Msg: "WebServerLDAPSecrets ReadOnlyUserLogin cannot be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "w.LDAP.bServerLDAPSecrets.ReadOnlyUserLogin", Msg: "WebServerLDAPSecrets ReadOnlyUserLogin cannot be empty"}) } if w.LDAP.ReadOnlyUserPass == nil || *w.LDAP.ReadOnlyUserPass == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "w.LDAP.bServerLDAPSecrets.ReadOnlyUserPass", Msg: "WebServerLDAPSecrets ReadOnlyUserPass cannot be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "w.LDAP.bServerLDAPSecrets.ReadOnlyUserPass", Msg: "WebServerLDAPSecrets ReadOnlyUserPass cannot be empty"}) } } // Validate OIDC if it has non-zero values if w.OIDC != (WebServerOIDCSecrets{}) { if w.OIDC.ClientSecret.String() == "" { - err = errors.Join(err, configutils.ErrInvalid{Name: "WebServerOIDCSecrets.ClientSecret", Msg: "WebServerOIDCSecrets ClientSecret cannot be empty"}) + err = errors.Join(err, configutils.InvalidError{Name: "WebServerOIDCSecrets.ClientSecret", Msg: "WebServerOIDCSecrets ClientSecret cannot be empty"}) } } @@ -1856,20 +1857,20 @@ func (ins *Insecure) ValidateConfig() (err error) { func (ins *Insecure) validateConfig(buildMode string) (err error) { if buildMode == build.Dev { - return + return err } if ins.DevWebServer != nil && *ins.DevWebServer { - err = errors.Join(err, configutils.ErrInvalid{Name: "DevWebServer", Value: *ins.DevWebServer, Msg: "insecure configs are not allowed on secure builds"}) + err = errors.Join(err, configutils.InvalidError{Name: "DevWebServer", Value: *ins.DevWebServer, Msg: "insecure configs are not allowed on secure builds"}) } // OCRDevelopmentMode is allowed on dev/test builds. if ins.OCRDevelopmentMode != nil && *ins.OCRDevelopmentMode && buildMode == build.Prod { - err = errors.Join(err, configutils.ErrInvalid{Name: "OCRDevelopmentMode", Value: *ins.OCRDevelopmentMode, Msg: "insecure configs are not allowed on secure builds"}) + err = errors.Join(err, configutils.InvalidError{Name: "OCRDevelopmentMode", Value: *ins.OCRDevelopmentMode, Msg: "insecure configs are not allowed on secure builds"}) } if ins.InfiniteDepthQueries != nil && *ins.InfiniteDepthQueries { - err = errors.Join(err, configutils.ErrInvalid{Name: "InfiniteDepthQueries", Value: *ins.InfiniteDepthQueries, Msg: "insecure configs are not allowed on secure builds"}) + err = errors.Join(err, configutils.InvalidError{Name: "InfiniteDepthQueries", Value: *ins.InfiniteDepthQueries, Msg: "insecure configs are not allowed on secure builds"}) } if ins.DisableRateLimiting != nil && *ins.DisableRateLimiting { - err = errors.Join(err, configutils.ErrInvalid{Name: "DisableRateLimiting", Value: *ins.DisableRateLimiting, Msg: "insecure configs are not allowed on secure builds"}) + err = errors.Join(err, configutils.InvalidError{Name: "DisableRateLimiting", Value: *ins.DisableRateLimiting, Msg: "insecure configs are not allowed on secure builds"}) } return err } @@ -1920,10 +1921,10 @@ func (m *MercuryTLS) setFrom(f *MercuryTLS) { func (m *MercuryTLS) ValidateConfig() (err error) { if *m.CertFile != "" { if !isValidFilePath(*m.CertFile) { - err = errors.Join(err, configutils.ErrInvalid{Name: "CertFile", Value: *m.CertFile, Msg: "must be a valid file path"}) + err = errors.Join(err, configutils.InvalidError{Name: "CertFile", Value: *m.CertFile, Msg: "must be a valid file path"}) } } - return + return err } type MercuryTransmitter struct { @@ -2010,7 +2011,7 @@ func (m *MercurySecrets) validateMerge(f *MercurySecrets) (err error) { if m.Credentials != nil && f.Credentials != nil { for k := range f.Credentials { if _, exists := m.Credentials[k]; exists { - err = errors.Join(err, configutils.ErrOverride{Name: fmt.Sprintf("Credentials[\"%s\"]", k)}) + err = errors.Join(err, configutils.OverrideError{Name: fmt.Sprintf("Credentials[\"%s\"]", k)}) } } } @@ -2022,14 +2023,14 @@ func (m *MercurySecrets) ValidateConfig() (err error) { urls := make(map[string]struct{}, len(m.Credentials)) for name, creds := range m.Credentials { if name == "" { - err = errors.Join(err, configutils.ErrEmpty{Name: "Name", Msg: "must be provided and non-empty"}) + err = errors.Join(err, configutils.EmptyError{Name: "Name", Msg: "must be provided and non-empty"}) } if creds.URL == nil || creds.URL.URL() == nil { - err = errors.Join(err, configutils.ErrMissing{Name: "URL", Msg: "must be provided and non-empty"}) + err = errors.Join(err, configutils.MissingError{Name: "URL", Msg: "must be provided and non-empty"}) continue } if creds.LegacyURL != nil && creds.LegacyURL.URL() == nil { - err = errors.Join(err, configutils.ErrMissing{Name: "Legacy URL", Msg: "must be a valid URL"}) + err = errors.Join(err, configutils.MissingError{Name: "Legacy URL", Msg: "must be a valid URL"}) continue } s := creds.URL.URL().String() @@ -2167,11 +2168,11 @@ func (w *WorkflowFetcherConfig) ValidateConfig() error { u, err := url.Parse(*w.URL) if err != nil { - return configutils.ErrInvalid{Name: "URL", Value: *w.URL, Msg: "must be a valid URL"} + return configutils.InvalidError{Name: "URL", Value: *w.URL, Msg: "must be a valid URL"} } if u.Scheme != "file" && u.Scheme != "http" && u.Scheme != "https" { - return configutils.ErrInvalid{Name: "URL", Value: *w.URL, Msg: "scheme must be one of: file, http, https"} + return configutils.InvalidError{Name: "URL", Value: *w.URL, Msg: "scheme must be one of: file, http, https"} } return nil @@ -2189,7 +2190,7 @@ func (l *LinkingConfig) ValidateConfig() error { if l.RequestTimeout == nil { l.RequestTimeout = commonconfig.MustNewDuration(2 * time.Second) } else if l.RequestTimeout.Duration() <= 0 { - return configutils.ErrInvalid{Name: "RequestTimeout", Value: l.RequestTimeout.String(), Msg: "must be positive"} + return configutils.InvalidError{Name: "RequestTimeout", Value: l.RequestTimeout.String(), Msg: "must be positive"} } if l.DurableCacheEnabled == nil { val := true @@ -2261,17 +2262,17 @@ func (a *CCVSecrets) validateMerge(f *CCVSecrets) (err error) { for _, aggregatorSecret := range a.AggregatorSecrets { for _, fAggregatorSecret := range f.AggregatorSecrets { if aggregatorSecret.VerifierID == fAggregatorSecret.VerifierID { - err = errors.Join(err, configutils.ErrOverride{Name: "CCV.AggregatorSecrets.VerifierID"}) + err = errors.Join(err, configutils.OverrideError{Name: "CCV.AggregatorSecrets.VerifierID"}) } } } } if a.IndexerSecret != nil && f.IndexerSecret != nil { if a.IndexerSecret.APIKey != nil && f.IndexerSecret.APIKey != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "CCV.IndexerSecret.APIKey"}) + err = errors.Join(err, configutils.OverrideError{Name: "CCV.IndexerSecret.APIKey"}) } if a.IndexerSecret.APISecret != nil && f.IndexerSecret.APISecret != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "CCV.IndexerSecret.APISecret"}) + err = errors.Join(err, configutils.OverrideError{Name: "CCV.IndexerSecret.APISecret"}) } } return err @@ -2332,14 +2333,14 @@ func (c *CreSecrets) SetFrom(f *CreSecrets) (err error) { func (c *CreSecrets) validateMerge(f *CreSecrets) (err error) { if c.Streams != nil && f.Streams != nil { if c.Streams.APIKey != nil && f.Streams.APIKey != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "Streams.APIKey"}) + err = errors.Join(err, configutils.OverrideError{Name: "Streams.APIKey"}) } if c.Streams.APISecret != nil && f.Streams.APISecret != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "Streams.APISecret"}) + err = errors.Join(err, configutils.OverrideError{Name: "Streams.APISecret"}) } } if len(c.LocalSecretOverrides) > 0 && len(f.LocalSecretOverrides) > 0 { - err = errors.Join(err, configutils.ErrOverride{Name: "LocalSecretOverrides"}) + err = errors.Join(err, configutils.OverrideError{Name: "LocalSecretOverrides"}) } return err } @@ -2442,7 +2443,7 @@ func (s *WorkflowStorage) ValidateConfig() error { URLIsSet := s.URL != nil && *s.URL != "" ArtifactStorageHostIsSet := s.ArtifactStorageHost != nil && *s.ArtifactStorageHost != "" if URLIsSet && !ArtifactStorageHostIsSet { - return configutils.ErrInvalid{Name: "ArtifactStorageHost", Value: "", Msg: "workflow storage service artifact storage host must be set"} + return configutils.InvalidError{Name: "ArtifactStorageHost", Value: "", Msg: "workflow storage service artifact storage host must be set"} } if s.TLSEnabled == nil { @@ -2603,7 +2604,7 @@ func (r *WorkflowRegistry) ValidateConfig() error { } if len(r.AdditionalSourcesConfig) > MaxAdditionalSources { - return configutils.ErrInvalid{ + return configutils.InvalidError{ Name: "AdditionalSources", Value: len(r.AdditionalSourcesConfig), Msg: fmt.Sprintf("maximum %d additional sources supported", MaxAdditionalSources), @@ -2617,18 +2618,18 @@ func (r *WorkflowRegistry) ValidateConfig() error { // Validate each source has a URL and unique Name for i, src := range r.AdditionalSourcesConfig { if src.URL == nil || *src.URL == "" { - return configutils.ErrMissing{Name: fmt.Sprintf("AdditionalSources[%d].URL", i)} + return configutils.MissingError{Name: fmt.Sprintf("AdditionalSources[%d].URL", i)} } // Require Name field if src.Name == nil || *src.Name == "" { - return configutils.ErrMissing{Name: fmt.Sprintf("AdditionalSources[%d].Name", i)} + return configutils.MissingError{Name: fmt.Sprintf("AdditionalSources[%d].Name", i)} } name := *src.Name // Check reserved names if reservedNames[name] { - return configutils.ErrInvalid{ + return configutils.InvalidError{ Name: fmt.Sprintf("AdditionalSources[%d].Name", i), Value: name, Msg: "name is reserved for internal use", @@ -2637,7 +2638,7 @@ func (r *WorkflowRegistry) ValidateConfig() error { // Check uniqueness if seenNames[name] { - return configutils.ErrInvalid{ + return configutils.InvalidError{ Name: fmt.Sprintf("AdditionalSources[%d].Name", i), Value: name, Msg: "duplicate source name; each additional source must have a unique name", @@ -2651,7 +2652,7 @@ func (r *WorkflowRegistry) ValidateConfig() error { // AdditionalSources returns the list of additional workflow sources. // Implements config.CapabilitiesWorkflowRegistry. -func (r WorkflowRegistry) AdditionalSources() []config.AdditionalWorkflowSource { +func (r *WorkflowRegistry) AdditionalSources() []config.AdditionalWorkflowSource { result := make([]config.AdditionalWorkflowSource, len(r.AdditionalSourcesConfig)) for i := range r.AdditionalSourcesConfig { result[i] = r.AdditionalSourcesConfig[i] @@ -2881,7 +2882,7 @@ var capabilityIDRegex = regexp.MustCompile(`^[a-z][a-z0-9-]*@[0-9]+\.[0-9]+\.[0- // ValidateCapabilityID validates that a capability ID matches the expected format "name@version". func ValidateCapabilityID(capID string) error { if !capabilityIDRegex.MatchString(capID) { - return configutils.ErrInvalid{ + return configutils.InvalidError{ Name: "CapabilityID", Value: capID, Msg: "must be in format 'name@version' (e.g., 'http-action@1.0.0')", @@ -2923,7 +2924,7 @@ func (t *ThresholdKeyShareSecrets) SetFrom(f *ThresholdKeyShareSecrets) (err err func (t *ThresholdKeyShareSecrets) validateMerge(f *ThresholdKeyShareSecrets) (err error) { if t.ThresholdKeyShare != nil && f.ThresholdKeyShare != nil { - err = errors.Join(err, configutils.ErrOverride{Name: "ThresholdKeyShare"}) + err = errors.Join(err, configutils.OverrideError{Name: "ThresholdKeyShare"}) } return err @@ -2970,7 +2971,7 @@ func (t *Tracing) ValidateConfig() (err error) { if t.SamplingRatio != nil { if *t.SamplingRatio < 0 || *t.SamplingRatio > 1 { - err = errors.Join(err, configutils.ErrInvalid{Name: "SamplingRatio", Value: *t.SamplingRatio, Msg: "must be between 0 and 1"}) + err = errors.Join(err, configutils.InvalidError{Name: "SamplingRatio", Value: *t.SamplingRatio, Msg: "must be between 0 and 1"}) } } @@ -2979,18 +2980,18 @@ func (t *Tracing) ValidateConfig() (err error) { case "tls": // TLSCertPath must be set if t.TLSCertPath == nil { - err = errors.Join(err, configutils.ErrMissing{Name: "TLSCertPath", Msg: "must be set when Tracing.Mode is tls"}) + err = errors.Join(err, configutils.MissingError{Name: "TLSCertPath", Msg: "must be set when Tracing.Mode is tls"}) } else { ok := isValidFilePath(*t.TLSCertPath) if !ok { - err = errors.Join(err, configutils.ErrInvalid{Name: "TLSCertPath", Value: *t.TLSCertPath, Msg: "must be a valid file path"}) + err = errors.Join(err, configutils.InvalidError{Name: "TLSCertPath", Value: *t.TLSCertPath, Msg: "must be a valid file path"}) } } case "unencrypted": // no-op default: // Mode must be either "tls" or "unencrypted" - err = errors.Join(err, configutils.ErrInvalid{Name: "Mode", Value: *t.Mode, Msg: "must be either 'tls' or 'unencrypted'"}) + err = errors.Join(err, configutils.InvalidError{Name: "Mode", Value: *t.Mode, Msg: "must be either 'tls' or 'unencrypted'"}) } } @@ -2998,12 +2999,12 @@ func (t *Tracing) ValidateConfig() (err error) { switch *t.Mode { case "tls": if !isValidURI(*t.CollectorTarget) { - err = errors.Join(err, configutils.ErrInvalid{Name: "CollectorTarget", Value: *t.CollectorTarget, Msg: "must be a valid URI"}) + err = errors.Join(err, configutils.InvalidError{Name: "CollectorTarget", Value: *t.CollectorTarget, Msg: "must be a valid URI"}) } case "unencrypted": // Unencrypted traces can not be sent to external networks if !isValidLocalURI(*t.CollectorTarget) { - err = errors.Join(err, configutils.ErrInvalid{Name: "CollectorTarget", Value: *t.CollectorTarget, Msg: "must be a valid local URI"}) + err = errors.Join(err, configutils.InvalidError{Name: "CollectorTarget", Value: *t.CollectorTarget, Msg: "must be a valid local URI"}) } default: // no-op @@ -3163,37 +3164,37 @@ func (b *Telemetry) ValidateConfig() (err error) { return nil } if b.Endpoint == nil || *b.Endpoint == "" { - err = errors.Join(err, configutils.ErrMissing{Name: "Endpoint", Msg: "must be set when Telemetry is enabled"}) + err = errors.Join(err, configutils.MissingError{Name: "Endpoint", Msg: "must be set when Telemetry is enabled"}) } if b.InsecureConnection == nil || !*b.InsecureConnection { // InsecureConnection is set and false if b.CACertFile == nil || *b.CACertFile == "" { - err = errors.Join(err, configutils.ErrMissing{Name: "CACertFile", Msg: "must be set, unless InsecureConnection is used"}) + err = errors.Join(err, configutils.MissingError{Name: "CACertFile", Msg: "must be set, unless InsecureConnection is used"}) } } if ratio := b.TraceSampleRatio; ratio != nil && (*ratio < 0 || *ratio > 1) { - err = errors.Join(err, configutils.ErrInvalid{Name: "TraceSampleRatio", Value: *ratio, Msg: "must be between 0 and 1"}) + err = errors.Join(err, configutils.InvalidError{Name: "TraceSampleRatio", Value: *ratio, Msg: "must be between 0 and 1"}) } if v := b.ChipIngressBufferSize; v != nil && *v == 0 { - err = errors.Join(err, configutils.ErrInvalid{Name: "ChipIngressBufferSize", Value: *v, Msg: "must be greater than 0"}) + err = errors.Join(err, configutils.InvalidError{Name: "ChipIngressBufferSize", Value: *v, Msg: "must be greater than 0"}) } if v := b.ChipIngressMaxBatchSize; v != nil && *v == 0 { - err = errors.Join(err, configutils.ErrInvalid{Name: "ChipIngressMaxBatchSize", Value: *v, Msg: "must be greater than 0"}) + err = errors.Join(err, configutils.InvalidError{Name: "ChipIngressMaxBatchSize", Value: *v, Msg: "must be greater than 0"}) } if v := b.ChipIngressMaxConcurrentSends; v != nil && *v <= 0 { - err = errors.Join(err, configutils.ErrInvalid{Name: "ChipIngressMaxConcurrentSends", Value: *v, Msg: "must be greater than 0"}) + err = errors.Join(err, configutils.InvalidError{Name: "ChipIngressMaxConcurrentSends", Value: *v, Msg: "must be greater than 0"}) } if v := b.ChipIngressSendInterval; v != nil && v.Duration() <= 0 { - err = errors.Join(err, configutils.ErrInvalid{Name: "ChipIngressSendInterval", Value: v.Duration(), Msg: "must be greater than 0"}) + err = errors.Join(err, configutils.InvalidError{Name: "ChipIngressSendInterval", Value: v.Duration(), Msg: "must be greater than 0"}) } if v := b.ChipIngressSendTimeout; v != nil && v.Duration() <= 0 { - err = errors.Join(err, configutils.ErrInvalid{Name: "ChipIngressSendTimeout", Value: v.Duration(), Msg: "must be greater than 0"}) + err = errors.Join(err, configutils.InvalidError{Name: "ChipIngressSendTimeout", Value: v.Duration(), Msg: "must be greater than 0"}) } if v := b.ChipIngressDrainTimeout; v != nil && v.Duration() <= 0 { - err = errors.Join(err, configutils.ErrInvalid{Name: "ChipIngressDrainTimeout", Value: v.Duration(), Msg: "must be greater than 0"}) + err = errors.Join(err, configutils.InvalidError{Name: "ChipIngressDrainTimeout", Value: v.Duration(), Msg: "must be greater than 0"}) } if v := b.ChipIngressMaxGRPCRequestSize; v != nil && *v <= 0 { - err = errors.Join(err, configutils.ErrInvalid{Name: "ChipIngressMaxGRPCRequestSize", Value: *v, Msg: "must be greater than 0"}) + err = errors.Join(err, configutils.InvalidError{Name: "ChipIngressMaxGRPCRequestSize", Value: *v, Msg: "must be greater than 0"}) } return err } @@ -3251,14 +3252,14 @@ func (b *Metering) setFrom(f *Metering) { func (b *Metering) ValidateConfig() (err error) { if b.MeterSnapshotsEnabled != nil && *b.MeterSnapshotsEnabled && (b.MeterRecordsEnabled == nil || !*b.MeterRecordsEnabled) { - err = errors.Join(err, configutils.ErrInvalid{ + err = errors.Join(err, configutils.InvalidError{ Name: "MeterSnapshotsEnabled", Value: true, Msg: "requires MeterRecordsEnabled to be true", }) } if b.MeterRecordsEnabled != nil && *b.MeterRecordsEnabled && (b.NodeID == nil || *b.NodeID == "") { - err = errors.Join(err, configutils.ErrInvalid{ + err = errors.Join(err, configutils.InvalidError{ Name: "NodeID", Value: "", Msg: "must be non-empty when MeterRecordsEnabled is true (an empty NodeID collapses per-node snapshot dedup scope DON-wide)", @@ -3340,7 +3341,7 @@ func (b *Billing) setFrom(f *Billing) { func (b *Billing) ValidateConfig() error { if b.URL == nil || *b.URL == "" { - return configutils.ErrInvalid{Name: "URL", Value: "", Msg: "billing service url must be set"} + return configutils.InvalidError{Name: "URL", Value: "", Msg: "billing service url must be set"} } if b.TLSEnabled == nil { @@ -3389,11 +3390,11 @@ func (e *BridgeStatusReporter) ValidateConfig() error { } if e.PollingInterval == nil { - return configutils.ErrInvalid{Name: "PollingInterval", Value: nil, Msg: "must be set"} + return configutils.InvalidError{Name: "PollingInterval", Value: nil, Msg: "must be set"} } if e.PollingInterval.Duration() < config.MinimumPollingInterval { - return configutils.ErrInvalid{Name: "PollingInterval", Value: e.PollingInterval.Duration(), Msg: "must be greater than or equal to: " + config.MinimumPollingInterval.String()} + return configutils.InvalidError{Name: "PollingInterval", Value: e.PollingInterval.Duration(), Msg: "must be greater than or equal to: " + config.MinimumPollingInterval.String()} } if e.IgnoreInvalidBridges == nil { @@ -3438,7 +3439,7 @@ func (e *JobSpecReporter) ValidateConfig() error { } if e.PollingInterval.Duration() < config.MinimumPollingInterval { - return configutils.ErrInvalid{Name: "PollingInterval", Value: e.PollingInterval.Duration(), Msg: "must be greater than or equal to: " + config.MinimumPollingInterval.String()} + return configutils.InvalidError{Name: "PollingInterval", Value: e.PollingInterval.Duration(), Msg: "must be greater than or equal to: " + config.MinimumPollingInterval.String()} } if e.EnabledOCR2PluginTypes == nil { @@ -3519,7 +3520,7 @@ func (s *Sharding) ValidateConfig() (err error) { } if mode != ShardAssignmentModeManualOnly { if s.ShardOrchestratorAddress == nil || s.ShardOrchestratorAddress.URL() == nil { - err = errors.Join(err, configutils.ErrInvalid{ + err = errors.Join(err, configutils.InvalidError{ Name: "ShardOrchestratorAddress", Value: s.ShardOrchestratorAddress, Msg: "must be specified when ShardingEnabled is true and ShardIndex > 0", diff --git a/core/config/toml/types_test.go b/core/config/toml/types_test.go index a5252a2552e..5095f697249 100644 --- a/core/config/toml/types_test.go +++ b/core/config/toml/types_test.go @@ -63,7 +63,7 @@ func TestMercurySecrets_duplicateURLs(t *testing.T) { } err := ms.ValidateConfig() - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, "URL: invalid value (https://GOOGLE.COM): duplicate - must be unique", err.Error()) } @@ -79,7 +79,7 @@ func TestMercurySecrets_emptyURL(t *testing.T) { } err := ms.ValidateConfig() - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, "URL: missing: must be provided and non-empty", err.Error()) } @@ -116,11 +116,11 @@ func Test_validateDBURL(t *testing.T) { } func TestDatabaseSecrets_ValidateConfig(t *testing.T) { - validUrl := commonconfig.URL(url.URL{Scheme: "https", Host: "localhost"}) - validSecretURL := *models.NewSecretURL(&validUrl) + validURL := commonconfig.URL(url.URL{Scheme: "https", Host: "localhost"}) + validSecretURL := *models.NewSecretURL(&validURL) - invalidEmptyUrl := commonconfig.URL(url.URL{}) - invalidEmptySecretURL := *models.NewSecretURL(&invalidEmptyUrl) + invalidEmptyURL := commonconfig.URL(url.URL{}) + invalidEmptySecretURL := *models.NewSecretURL(&invalidEmptyURL) invalidBackupURL := commonconfig.URL(url.URL{Scheme: "http", Host: "localhost"}) invalidBackupSecretURL := *models.NewSecretURL(&invalidBackupURL) @@ -188,6 +188,7 @@ func TestDatabaseSecrets_ValidateConfig(t *testing.T) { }) } } + func TestTracing_ValidateCollectorTarget(t *testing.T) { tests := []struct { name string @@ -307,7 +308,7 @@ func TestTracing_ValidateCollectorTarget(t *testing.T) { err := tracing.ValidateConfig() if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, tt.errMsg, err.Error()) } else { assert.NoError(t, err) @@ -342,13 +343,13 @@ func TestTracing_ValidateSamplingRatio(t *testing.T) { name: "invalid negative value", samplingRatio: new(-0.1), wantErr: true, - errMsg: configutils.ErrInvalid{Name: "SamplingRatio", Value: -0.1, Msg: "must be between 0 and 1"}.Error(), + errMsg: configutils.InvalidError{Name: "SamplingRatio", Value: -0.1, Msg: "must be between 0 and 1"}.Error(), }, { name: "invalid value greater than 1", samplingRatio: new(1.1), wantErr: true, - errMsg: configutils.ErrInvalid{Name: "SamplingRatio", Value: 1.1, Msg: "must be between 0 and 1"}.Error(), + errMsg: configutils.InvalidError{Name: "SamplingRatio", Value: 1.1, Msg: "must be between 0 and 1"}.Error(), }, { name: "nil SamplingRatio", @@ -367,7 +368,7 @@ func TestTracing_ValidateSamplingRatio(t *testing.T) { err := tracing.ValidateConfig() if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, tt.errMsg, err.Error()) } else { assert.NoError(t, err) @@ -378,7 +379,7 @@ func TestTracing_ValidateSamplingRatio(t *testing.T) { func TestTracing_ValidateTLSCertPath(t *testing.T) { // tests for Tracing.Mode = 'tls' - tls_tests := []struct { + tlsTests := []struct { name string tlsCertPath *string wantErr bool @@ -409,7 +410,7 @@ func TestTracing_ValidateTLSCertPath(t *testing.T) { } // tests for Tracing.Mode = 'unencrypted' - unencrypted_tests := []struct { + unencryptedTests := []struct { name string tlsCertPath *string wantErr bool @@ -437,7 +438,7 @@ func TestTracing_ValidateTLSCertPath(t *testing.T) { }, } - for _, tt := range tls_tests { + for _, tt := range tlsTests { t.Run(tt.name, func(t *testing.T) { tracing := &Tracing{ Mode: new("tls"), @@ -448,7 +449,7 @@ func TestTracing_ValidateTLSCertPath(t *testing.T) { err := tracing.ValidateConfig() if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, tt.errMsg, err.Error()) } else { assert.NoError(t, err) @@ -456,7 +457,8 @@ func TestTracing_ValidateTLSCertPath(t *testing.T) { }) } - for _, tt := range unencrypted_tests { + //nolint:paralleltest // TODO: Fix these in upcoming refactoring + for _, tt := range unencryptedTests { t.Run(tt.name, func(t *testing.T) { tracing := &Tracing{ Mode: new("unencrypted"), @@ -467,7 +469,7 @@ func TestTracing_ValidateTLSCertPath(t *testing.T) { err := tracing.ValidateConfig() if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, tt.errMsg, err.Error()) } else { assert.NoError(t, err) @@ -529,7 +531,7 @@ func TestTracing_ValidateMode(t *testing.T) { err := tracing.ValidateConfig() if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, tt.errMsg, err.Error()) } else { assert.NoError(t, err) @@ -574,7 +576,7 @@ func TestMercuryTLS_ValidateTLSCertPath(t *testing.T) { err := mercury.ValidateConfig() if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) assert.Equal(t, tt.errMsg, err.Error()) } else { assert.NoError(t, err) diff --git a/core/internal/cltest/cltest.go b/core/internal/cltest/cltest.go index 385fbf7bbfb..e3ae5141ed6 100644 --- a/core/internal/cltest/cltest.go +++ b/core/internal/cltest/cltest.go @@ -179,7 +179,7 @@ func FormatWithPrefixedChainID(chainID, id string) string { // TestApplication holds the test application and test servers type TestApplication struct { t testing.TB - *chainlink.ChainlinkApplication + *chainlink.Node Logger logger.Logger Server *httptest.Server Started bool @@ -230,8 +230,7 @@ func NewApplicationWithConfigAndKey(t testing.TB, c chainlink.GeneralConfig, fla chainID := *sqlutil.New(&FixtureChainID) for _, dep := range flagsAndDeps { - switch v := dep.(type) { - case *sqlutil.Big: + if v, ok := dep.(*sqlutil.Big); ok { chainID = *v } } @@ -271,9 +270,9 @@ func NewApplicationWithConfig(t testing.TB, cfg chainlink.GeneralConfig, flagsAn lggr = logger.TestLogger(t) } - var auditLogger audit.AuditLogger + var auditLogger audit.Logger for _, dep := range flagsAndDeps { - audLgger, is := dep.(audit.AuditLogger) + audLgger, is := dep.(audit.Logger) if is { auditLogger = audLgger break @@ -420,11 +419,11 @@ func NewApplicationWithConfig(t testing.TB, cfg chainlink.GeneralConfig, flagsAn }) require.NoError(t, err) - app := appInstance.(*chainlink.ChainlinkApplication) + app := appInstance.(*chainlink.Node) ta := &TestApplication{ - t: t, - ChainlinkApplication: app, - Logger: lggr, + t: t, + Node: app, + Logger: lggr, } for _, dep := range flagsAndDeps { if k, ok := dep.(ethkey.KeyV2); ok { @@ -444,73 +443,73 @@ func logPubKeys(t testing.TB, kr keystore.Master) { ctx := t.Context() csas, err := kr.CSA().GetAll() require.NoError(t, err) - csaIDs := make([]string, len(csas)) + csaIDs := make([]string, 0, len(csas)) for _, CSAKey := range csas { csaIDs = append(csaIDs, CSAKey.ID()) } eths, err := kr.Eth().GetAll(ctx) require.NoError(t, err) - ethIDs := make([]string, len(eths)) + ethIDs := make([]string, 0, len(eths)) for _, ETHKey := range eths { ethIDs = append(ethIDs, ETHKey.ID()) } ocrs, err := kr.OCR().GetAll() require.NoError(t, err) - ocrIDs := make([]string, len(ocrs)) + ocrIDs := make([]string, 0, len(ocrs)) for _, OCRKey := range ocrs { ocrIDs = append(ocrIDs, OCRKey.ID()) } ocr2s, err := kr.OCR2().GetAll() require.NoError(t, err) - ocr2IDs := make([]string, len(ocr2s)) + ocr2IDs := make([]string, 0, len(ocr2s)) for _, OCR2Key := range ocr2s { ocr2IDs = append(ocr2IDs, OCR2Key.ID()) } p2ps, err := kr.P2P().GetAll() require.NoError(t, err) - p2pIDs := make([]string, len(p2ps)) + p2pIDs := make([]string, 0, len(p2ps)) for _, P2PKey := range p2ps { p2pIDs = append(p2pIDs, P2PKey.ID()) } solanas, err := kr.Solana().GetAll() require.NoError(t, err) - solanaIDs := make([]string, len(solanas)) + solanaIDs := make([]string, 0, len(solanas)) for _, solanaKey := range solanas { solanaIDs = append(solanaIDs, solanaKey.ID()) } starknets, err := kr.StarkNet().GetAll() require.NoError(t, err) - starknetIDs := make([]string, len(starknets)) + starknetIDs := make([]string, 0, len(starknets)) for _, starkkey := range starknets { starknetIDs = append(starknetIDs, starkkey.ID()) } aptoses, err := kr.Aptos().GetAll() require.NoError(t, err) - aptosIDs := make([]string, len(aptoses)) + aptosIDs := make([]string, 0, len(aptoses)) for _, aptosKey := range aptoses { aptosIDs = append(aptosIDs, aptosKey.ID()) } trons, err := kr.Tron().GetAll() require.NoError(t, err) - tronIDs := make([]string, len(trons)) + tronIDs := make([]string, 0, len(trons)) for _, tronKey := range trons { tronIDs = append(tronIDs, tronKey.ID()) } tons, err := kr.TON().GetAll() require.NoError(t, err) - tonIDs := make([]string, len(tons)) + tonIDs := make([]string, 0, len(tons)) for _, tonKey := range tons { tonIDs = append(tonIDs, tonKey.ID()) } suies, err := kr.Sui().GetAll() require.NoError(t, err) - suiIDs := make([]string, len(suies)) + suiIDs := make([]string, 0, len(suies)) for _, suiKey := range suies { suiIDs = append(suiIDs, suiKey.ID()) } vrfs, err := kr.VRF().GetAll() require.NoError(t, err) - vrfIDs := make([]string, len(vrfs)) + vrfIDs := make([]string, 0, len(vrfs)) for _, VRFKey := range vrfs { vrfIDs = append(vrfIDs, VRFKey.ID()) } @@ -568,7 +567,7 @@ func NewEthMocksWithDefaultChain(t testing.TB) (c *clienttest.Client) { testutils.SkipShortDB(t) c = NewEthMocks(t) c.On("ConfiguredChainID").Return(&FixtureChainID).Maybe() - return + return c } func NewEthMocks(t testing.TB) *clienttest.Client { @@ -653,7 +652,7 @@ func (ta *TestApplication) Start(ctx context.Context) error { return err } - err = ta.ChainlinkApplication.Start(ctx) + err = ta.Node.Start(ctx) if err != nil { return err } @@ -749,7 +748,7 @@ func (ta *TestApplication) NewShellAndRenderer() (*cmd.Shell, *RendererMock) { Renderer: r, Config: ta.GetConfig(), Logger: lggr, - AppFactory: seededAppFactory{ta.ChainlinkApplication}, + AppFactory: seededAppFactory{ta.Node}, FallbackAPIInitializer: NewMockAPIInitializer(ta.t), Runner: EmptyRunner{}, HTTP: hc.HTTPClient, @@ -768,7 +767,7 @@ func (ta *TestApplication) NewAuthenticatingShell(prompter cmd.Prompter) *cmd.Sh Renderer: &RendererMock{}, Config: ta.GetConfig(), Logger: lggr, - AppFactory: seededAppFactory{ta.ChainlinkApplication}, + AppFactory: seededAppFactory{ta.Node}, FallbackAPIInitializer: NewMockAPIInitializer(ta.t), Runner: EmptyRunner{}, HTTP: cmd.NewAuthenticatedHTTPClient(ta.Logger, ta.NewClientOpts(), cookieAuth, clsessions.SessionRequest{}), @@ -902,7 +901,7 @@ func CreateJobViaWeb(t testing.TB, app *TestApplication, request []byte) job.Job t.Helper() client := app.NewHTTPClient(nil) - resp, cleanup := client.Post("/v2/jobs", bytes.NewBuffer(request)) + resp, cleanup := client.Post("/v2/jobs", bytes.NewBuffer(request)) //nolint:bodyclose // body closed via deferred cleanup() defer cleanup() AssertServerResponse(t, resp, http.StatusOK) @@ -915,7 +914,7 @@ func CreateJobViaWeb2(t testing.TB, app *TestApplication, spec string) webpresen t.Helper() client := app.NewHTTPClient(nil) - resp, cleanup := client.Post("/v2/jobs", bytes.NewBufferString(spec)) + resp, cleanup := client.Post("/v2/jobs", bytes.NewBufferString(spec)) //nolint:bodyclose // body closed via deferred cleanup() defer cleanup() AssertServerResponse(t, resp, http.StatusOK) @@ -928,7 +927,7 @@ func DeleteJobViaWeb(t testing.TB, app *TestApplication, jobID int32) { t.Helper() client := app.NewHTTPClient(nil) - resp, cleanup := client.Delete(fmt.Sprintf("/v2/jobs/%v", jobID)) + resp, cleanup := client.Delete(fmt.Sprintf("/v2/jobs/%v", jobID)) //nolint:bodyclose // body closed via deferred cleanup() defer cleanup() AssertServerResponse(t, resp, http.StatusNoContent) } @@ -951,7 +950,7 @@ func CreateJobRunViaUserByID( bodyBuf := bytes.NewBufferString(body) client := app.NewHTTPClient(nil) - resp, cleanup := client.Post("/v2/jobs/"+strconv.Itoa(int(jobID))+"/runs", bodyBuf) + resp, cleanup := client.Post("/v2/jobs/"+strconv.Itoa(int(jobID))+"/runs", bodyBuf) //nolint:bodyclose // body closed via deferred cleanup() defer cleanup() AssertServerResponse(t, resp, 200) var pr webpresenters.PipelineRunResource @@ -969,7 +968,7 @@ func CreateExternalInitiatorViaWeb( t.Helper() client := app.NewHTTPClient(nil) - resp, cleanup := client.Post("/v2/external_initiators", bytes.NewBufferString(payload)) + resp, cleanup := client.Post("/v2/external_initiators", bytes.NewBufferString(payload)) //nolint:bodyclose // body closed via deferred cleanup() defer cleanup() AssertServerResponse(t, resp, http.StatusCreated) ei := &webpresenters.ExternalInitiatorAuthentication{} @@ -1003,16 +1002,17 @@ func WaitForSpecErrorV2(t *testing.T, ds sqlutil.DataSource, jobID int32, count return jse } -func WaitForPipelineError(t testing.TB, nodeID int, jobID int32, expectedPipelineRuns int, expectedTaskRuns int, jo job.ORM, timeout, poll time.Duration) []pipeline.Run { +func WaitForPipelineError(t testing.TB, nodeID int, jobID int32, expectedPipelineRuns, expectedTaskRuns int, jo job.ORM, timeout, poll time.Duration) []pipeline.Run { t.Helper() return WaitForPipeline(t, nodeID, jobID, expectedPipelineRuns, expectedTaskRuns, jo, timeout, poll, pipeline.RunStatusErrored) } -func WaitForPipelineComplete(t testing.TB, nodeID int, jobID int32, expectedPipelineRuns int, expectedTaskRuns int, jo job.ORM, timeout, poll time.Duration) []pipeline.Run { + +func WaitForPipelineComplete(t testing.TB, nodeID int, jobID int32, expectedPipelineRuns, expectedTaskRuns int, jo job.ORM, timeout, poll time.Duration) []pipeline.Run { t.Helper() return WaitForPipeline(t, nodeID, jobID, expectedPipelineRuns, expectedTaskRuns, jo, timeout, poll, pipeline.RunStatusCompleted) } -func WaitForPipeline(t testing.TB, nodeID int, jobID int32, expectedPipelineRuns int, expectedTaskRuns int, jo job.ORM, timeout, poll time.Duration, state pipeline.RunStatus) []pipeline.Run { +func WaitForPipeline(t testing.TB, nodeID int, jobID int32, expectedPipelineRuns, expectedTaskRuns int, jo job.ORM, timeout, poll time.Duration, state pipeline.RunStatus) []pipeline.Run { t.Helper() var pr []pipeline.Run @@ -1069,13 +1069,13 @@ func AssertPipelineRunsStays(t testing.TB, pipelineSpecID int32, db sqlutil.Data func AssertEthTxAttemptCountStays(t testing.TB, txStore txmgr.TestEvmTxStore, want int) []int64 { g := gomega.NewWithT(t) - var txaIds []int64 + var txaIDs []int64 g.Consistently(func() []txmgr.TxAttempt { attempts, err := txStore.GetAllTxAttempts(t.Context()) assert.NoError(t, err) return attempts }, AssertNoActionTimeout, DBPollingInterval).Should(gomega.HaveLen(want)) - return txaIds + return txaIDs } // Head return a new head with the given number. @@ -1188,7 +1188,7 @@ func UnauthenticatedGet(t testing.TB, url string, headers map[string]string) (*h return unauthenticatedHTTP(t, "GET", url, nil, headers) } -func unauthenticatedHTTP(t testing.TB, method string, url string, body io.Reader, headers map[string]string) (*http.Response, func()) { +func unauthenticatedHTTP(t testing.TB, method, url string, body io.Reader, headers map[string]string) (*http.Response, func()) { t.Helper() client := clhttptest.NewTestLocalOnlyHTTPClient() diff --git a/core/internal/cltest/contract_mock_receiver.go b/core/internal/cltest/contract_mock_receiver.go index bac12562aed..166bbd7f577 100644 --- a/core/internal/cltest/contract_mock_receiver.go +++ b/core/internal/cltest/contract_mock_receiver.go @@ -104,11 +104,12 @@ func (receiver contractMockReceiver) mustEncodeResponse(funcName string, respons firstArg := responseArgs[0] isStruct := reflect.TypeOf(firstArg).Kind() == reflect.Struct - if isStruct && len(responseArgs) > 1 { + switch { + case isStruct && len(responseArgs) > 1: receiver.t.Fatal("cannot encode response with struct and multiple return values") - } else if isStruct { + case isStruct: outputList = structToInterfaceSlice(firstArg) - } else { + default: outputList = responseArgs } @@ -120,7 +121,7 @@ func (receiver contractMockReceiver) mustEncodeResponse(funcName string, respons func structToInterfaceSlice(structArg any) []any { v := reflect.ValueOf(structArg) values := make([]any, v.NumField()) - for i := 0; i < v.NumField(); i++ { + for i := range v.NumField() { values[i] = v.Field(i).Interface() } return values diff --git a/core/internal/cltest/mocks.go b/core/internal/cltest/mocks.go index 477465cef0f..3a6af54bc19 100644 --- a/core/internal/cltest/mocks.go +++ b/core/internal/cltest/mocks.go @@ -60,13 +60,13 @@ func (mes *MockSubscription) Unsubscribe() { return } mes.unsubscribed = true - switch mes.channel.(type) { + switch c := mes.channel.(type) { case chan struct{}: - close(mes.channel.(chan struct{})) + close(c) case chan gethTypes.Log: - close(mes.channel.(chan gethTypes.Log)) + close(c) case chan *evmtypes.Head: - close(mes.channel.(chan *evmtypes.Head)) + close(c) default: logger.TestLogger(mes.t).Fatalf("Unable to close MockSubscription channel of type %T", mes.channel) } @@ -322,7 +322,7 @@ func NewMockAPIInitializer(t testing.TB) *MockAPIInitializer { func (m *MockAPIInitializer) Initialize(ctx context.Context, orm sessions.BasicAdminUsersORM, lggr logger.Logger) (sessions.User, error) { if user, err := orm.FindUser(ctx, APIEmailAdmin); err == nil { - return user, err + return user, nil } m.Count++ user := MustRandomUser(m.t) diff --git a/core/internal/features/features_test.go b/core/internal/features/features_test.go index f25ac4fcf3a..5ad5c033877 100644 --- a/core/internal/features/features_test.go +++ b/core/internal/features/features_test.go @@ -87,6 +87,7 @@ func TestIntegration_AuthToken(t *testing.T) { headers[webauth.APISecret] = secret resp, cleanup := cltest.UnauthenticatedGet(t, url, headers) + defer resp.Body.Close() defer cleanup() cltest.AssertServerResponse(t, resp, http.StatusOK) } diff --git a/core/internal/features/ocr2/features_ocr2_helper.go b/core/internal/features/ocr2/features_ocr2_helper.go index 3a1982dbf80..1fde8778990 100644 --- a/core/internal/features/ocr2/features_ocr2_helper.go +++ b/core/internal/features/ocr2/features_ocr2_helper.go @@ -37,6 +37,7 @@ import ( "github.com/smartcontractkit/chainlink-common/keystore/corekeys/ocr2key" "github.com/smartcontractkit/chainlink-common/keystore/corekeys/p2pkey" commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink-evm/gethwrappers/generated/link_token_interface" "github.com/smartcontractkit/chainlink-evm/gethwrappers/operatorforwarder/generated/authorized_forwarder" @@ -51,7 +52,6 @@ import ( "github.com/smartcontractkit/chainlink/v2/core/bridges" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" - "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/chainlink" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/testhelpers" @@ -238,7 +238,7 @@ func RunTestIntegrationOCR2(t *testing.T) { t.Parallel() owner, b, ocrContractAddress, ocrContract, nodeConfig := SetupOCR2Contracts(t) - lggr := logger.TestLogger(t) + lggr := logger.Test(t) bootstrapNodePort := freeport.GetOne(t) bootstrapNode := SetupNodeOCR2(t, owner, bootstrapNodePort, false /* useForwarders */, b, nil, nodeConfig) diff --git a/core/internal/features/ocr2/features_ocr2_test.go b/core/internal/features/ocr2/features_ocr2_test.go index 4038cdcfd62..249d9cd8a2e 100644 --- a/core/internal/features/ocr2/features_ocr2_test.go +++ b/core/internal/features/ocr2/features_ocr2_test.go @@ -25,12 +25,12 @@ import ( ocrtypes2 "github.com/smartcontractkit/libocr/offchainreporting2plus/types" "github.com/smartcontractkit/chainlink-common/keystore/corekeys/ocr2key" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-evm/pkg/keys" "github.com/smartcontractkit/chainlink-evm/pkg/transmitter" "github.com/smartcontractkit/chainlink/v2/core/bridges" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" - "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/services/keystore" "github.com/smartcontractkit/chainlink/v2/core/services/ocr2/validate" "github.com/smartcontractkit/chainlink/v2/core/store/models" @@ -45,7 +45,7 @@ func TestIntegration_OCR2_ForwarderFlow(t *testing.T) { t.Parallel() owner, b, ocrContractAddress, ocrContract, nodeConfig := SetupOCR2Contracts(t) - lggr := logger.TestLogger(t) + lggr := logger.Test(t) bootstrapNodePort := freeport.GetOne(t) bootstrapNode := SetupNodeOCR2(t, owner, bootstrapNodePort, true /* useForwarders */, b, nil, nodeConfig) @@ -102,7 +102,7 @@ chainID = 1337 }() jids := make([]int32, 0, 4) - var servers, slowServers = make([]*httptest.Server, 4), make([]*httptest.Server, 4) + servers, slowServers := make([]*httptest.Server, 4), make([]*httptest.Server, 4) // We expect metadata of: // latestAnswer:nil // First call // latestAnswer:0 diff --git a/core/internal/mocks/application.go b/core/internal/mocks/application.go index d5e6e1a87b1..92c7c68fe58 100644 --- a/core/internal/mocks/application.go +++ b/core/internal/mocks/application.go @@ -400,19 +400,19 @@ func (_c *Application_FindLCA_Call) RunAndReturn(run func(context.Context, *big. } // GetAuditLogger provides a mock function with no fields -func (_m *Application) GetAuditLogger() audit.AuditLogger { +func (_m *Application) GetAuditLogger() audit.Logger { ret := _m.Called() if len(ret) == 0 { panic("no return value specified for GetAuditLogger") } - var r0 audit.AuditLogger - if rf, ok := ret.Get(0).(func() audit.AuditLogger); ok { + var r0 audit.Logger + if rf, ok := ret.Get(0).(func() audit.Logger); ok { r0 = rf() } else { if ret.Get(0) != nil { - r0 = ret.Get(0).(audit.AuditLogger) + r0 = ret.Get(0).(audit.Logger) } } @@ -436,12 +436,12 @@ func (_c *Application_GetAuditLogger_Call) Run(run func()) *Application_GetAudit return _c } -func (_c *Application_GetAuditLogger_Call) Return(_a0 audit.AuditLogger) *Application_GetAuditLogger_Call { +func (_c *Application_GetAuditLogger_Call) Return(_a0 audit.Logger) *Application_GetAuditLogger_Call { _c.Call.Return(_a0) return _c } -func (_c *Application_GetAuditLogger_Call) RunAndReturn(run func() audit.AuditLogger) *Application_GetAuditLogger_Call { +func (_c *Application_GetAuditLogger_Call) RunAndReturn(run func() audit.Logger) *Application_GetAuditLogger_Call { _c.Call.Return(run) return _c } diff --git a/core/internal/testutils/configtest/general_config.go b/core/internal/testutils/configtest/general_config.go index 0f8bb39e60e..b343c0bb23b 100644 --- a/core/internal/testutils/configtest/general_config.go +++ b/core/internal/testutils/configtest/general_config.go @@ -12,7 +12,6 @@ import ( "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" pgcommon "github.com/smartcontractkit/chainlink-common/pkg/sqlutil/pg" "github.com/smartcontractkit/chainlink-evm/pkg/client" - evmclient "github.com/smartcontractkit/chainlink-evm/pkg/client" "github.com/smartcontractkit/chainlink-evm/pkg/config/toml" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils" "github.com/smartcontractkit/chainlink/v2/core/services/chainlink" @@ -21,14 +20,14 @@ import ( const DefaultPeerID = "12D3KooWPjceQrSwdWXPyLLeABRXmuqt69Rg3sBYbU1Nft9HyQ6X" -// NewTestGeneralConfig returns a new chainlink.GeneralConfig with default test overrides and one chain with evmclient.NullClientChainID. +// NewTestGeneralConfig returns a new chainlink.GeneralConfig with default test overrides and one chain with client.NullClientChainID. func NewTestGeneralConfig(t testing.TB) chainlink.GeneralConfig { return NewGeneralConfig(t, nil) } // NewGeneralConfig returns a new chainlink.GeneralConfig with overrides. -// The default test overrides are applied before overrideFn, and include one chain with evmclient.NullClientChainID. +// The default test overrides are applied before overrideFn, and include one chain with client.NullClientChainID. func NewGeneralConfig(t testing.TB, overrideFn func(*chainlink.Config, *chainlink.Secrets)) chainlink.GeneralConfig { tempDir := t.TempDir() - g, err := chainlink.GeneralConfigOpts{ + opts := chainlink.GeneralConfigOpts{ OverrideFn: func(c *chainlink.Config, s *chainlink.Secrets) { overrides(c, s) c.RootDir = &tempDir @@ -36,12 +35,13 @@ func NewGeneralConfig(t testing.TB, overrideFn func(*chainlink.Config, *chainlin fn(c, s) } }, - }.New() + } + g, err := opts.New() require.NoError(t, err) return g } -// overrides applies some test config settings and adds a default chain with evmclient.NullClientChainID. +// overrides applies some test config settings and adds a default chain with client.NullClientChainID. func overrides(c *chainlink.Config, s *chainlink.Secrets) { s.Password.Keystore = models.NewSecret("dummy-to-pass-validation") @@ -69,7 +69,7 @@ func overrides(c *chainlink.Config, s *chainlink.Secrets) { c.WebServer.ListenIP = &testIP c.WebServer.TLS.ListenIP = &testIP - chainID := sqlutil.NewI(evmclient.NullClientChainID) + chainID := sqlutil.NewI(client.NullClientChainID) chainCfg := toml.Defaults(chainID) chainCfg.LogPollInterval = commonconfig.MustNewDuration(1 * time.Second) // speed it up from the standard 15s for tests @@ -92,7 +92,7 @@ func overrides(c *chainlink.Config, s *chainlink.Secrets) { // NewGeneralConfigSimulated returns a new chainlink.GeneralConfig with overrides, including the simulated EVM chain. // The default test overrides are applied before overrideFn. -// The simulated chain (testutils.SimulatedChainID) replaces the null chain (evmclient.NullClientChainID). +// The simulated chain (testutils.SimulatedChainID) replaces the null chain (client.NullClientChainID). func NewGeneralConfigSimulated(t testing.TB, overrideFn func(*chainlink.Config, *chainlink.Secrets)) chainlink.GeneralConfig { return NewGeneralConfig(t, func(c *chainlink.Config, s *chainlink.Secrets) { simulated(c, s) diff --git a/core/internal/testutils/evmtest/evmtest.go b/core/internal/testutils/evmtest/evmtest.go index bc9f6090756..8a723f40511 100644 --- a/core/internal/testutils/evmtest/evmtest.go +++ b/core/internal/testutils/evmtest/evmtest.go @@ -68,7 +68,7 @@ type TestChainOpts struct { // allows to mock client/config on that chain func NewLegacyChains(t testing.TB, testopts TestChainOpts) *legacyevm.LegacyChains { lggr, ks, opts := NewChainOpts(t, testopts) - cc, err := evmrelay.NewLegacyChainsAndConfig(lggr, ks, opts) + cc, err := evmrelay.NewLegacyChainsAndConfig(lggr, ks, opts) //nolint:staticcheck // test-only legacy default chain helper require.NoError(t, err) for _, c := range cc.Slice() { servicetest.Run(t, c) @@ -122,7 +122,7 @@ func NewChainOpts(t testing.TB, testopts TestChainOpts) (logger.Logger, keystore const NullClientChainID = evmclient.NullClientChainID -// Deprecated, this is a replacement function for tests for now removed default evmChainID logic +// MustGetDefaultChainID is a replacement function for tests for now removed default evmChainID logic func MustGetDefaultChainID(t testing.TB, evmCfgs configtoml.EVMConfigs) *big.Int { if len(evmCfgs) == 0 { t.Fatalf("at least one evm chain config must be defined") @@ -135,7 +135,7 @@ func MustGetDefaultChainID(t testing.TB, evmCfgs configtoml.EVMConfigs) *big.Int return chainID } -// Deprecated, this is a replacement function for tests for now removed default chain logic +// MustGetDefaultChain is a replacement function for tests for now removed default chain logic func MustGetDefaultChain(t testing.TB, cc legacyevm.LegacyChainContainer) legacyevm.Chain { if len(cc.Slice()) == 0 { t.Fatalf("at least one evm chain container must be defined") diff --git a/core/internal/testutils/httptest/httptest.go b/core/internal/testutils/httptest/httptest.go index 69549ae3e45..66d3e04520f 100644 --- a/core/internal/testutils/httptest/httptest.go +++ b/core/internal/testutils/httptest/httptest.go @@ -2,11 +2,10 @@ package httptest import ( "context" + "fmt" "net" "net/http" "time" - - pkgerrors "github.com/pkg/errors" ) // NewTestHTTPClient returns a real HTTP client that may only make requests to @@ -25,14 +24,13 @@ func testDialContext(ctx context.Context, network, address string) (net.Conn, er // https://golang.org/pkg/net/http/#RoundTripper Timeout: 30 * time.Second, KeepAlive: 30 * time.Second, - DualStack: true, }).DialContext(ctx, network, address) if err != nil { return con, err } a := con.RemoteAddr().(*net.TCPAddr) if a != nil && !a.IP.IsLoopback() { - return nil, pkgerrors.Errorf("Test HTTP client may only dial localhost, got address: %v", a.String()) + return nil, fmt.Errorf("test HTTP client may only dial localhost, got address: %v", a.String()) } return con, err } diff --git a/core/internal/testutils/logger.go b/core/internal/testutils/logger.go index f3db412c0db..78787b897b0 100644 --- a/core/internal/testutils/logger.go +++ b/core/internal/testutils/logger.go @@ -9,7 +9,7 @@ import ( "go.uber.org/zap/zapcore" "go.uber.org/zap/zaptest/observer" - "github.com/smartcontractkit/chainlink/v2/core/logger" + "github.com/smartcontractkit/chainlink-common/pkg/logger" ) // LoggerAssertMaxLevel returns a test logger which is observed on cleanup @@ -18,7 +18,7 @@ func LoggerAssertMaxLevel(t *testing.T, lvl zapcore.Level) logger.Logger { if lvl >= zapcore.FatalLevel { t.Fatalf("no levels exist after %s", zapcore.FatalLevel) } - lggr, o := logger.TestLoggerObserved(t, lvl+1) + lggr, o := logger.TestObserved(t, lvl+1) t.Cleanup(func() { assert.Empty(t, o.Len(), "logger contains entries with levels above %q:\n%s", lvl, loggedEntries(o.All())) }) diff --git a/core/internal/testutils/pgtest/txdb_test.go b/core/internal/testutils/pgtest/txdb_test.go index af386fc5481..b87e71f3ee6 100644 --- a/core/internal/testutils/pgtest/txdb_test.go +++ b/core/internal/testutils/pgtest/txdb_test.go @@ -19,18 +19,18 @@ func TestTxDBDriver(t *testing.T) { } // clean up, if previous tests failed err := dropTable() - assert.NoError(t, err) + require.NoError(t, err) _, err = db.Exec(`CREATE TABLE txdb_test (id TEXT NOT NULL)`) - assert.NoError(t, err) + require.NoError(t, err) t.Cleanup(func() { _ = dropTable() }) _, err = db.Exec(`INSERT INTO txdb_test VALUES ($1)`, uuid.New().String()) - assert.NoError(t, err) + require.NoError(t, err) ensureValuesPresent := func(t *testing.T, db *sqlx.DB) { var ids []string err = db.Select(&ids, `SELECT id from txdb_test`) - assert.NoError(t, err) + require.NoError(t, err) assert.Len(t, ids, 1) } @@ -49,7 +49,7 @@ func TestTxDBDriver(t *testing.T) { t.Run("Cancel of tx's context does not trigger rollback of driver's tx", func(t *testing.T) { ctx, cancel := context.WithCancel(t.Context()) _, err := db.BeginTx(ctx, nil) - assert.NoError(t, err) + require.NoError(t, err) cancel() // BeginTx spawns separate goroutine that rollbacks the tx and tries to close underlying connection, unless // db driver says that connection is still active. diff --git a/core/internal/testutils/testutils.go b/core/internal/testutils/testutils.go index b42a6689b20..a433bfe8e84 100644 --- a/core/internal/testutils/testutils.go +++ b/core/internal/testutils/testutils.go @@ -123,6 +123,7 @@ func WaitTimeoutCustom(t *testing.T, requested time.Duration) time.Duration { // // Deprecated: use [testing.TB.Context] directly // + //go:fix inline func Context(tb testing.TB) context.Context { return tb.Context() diff --git a/core/logger/audit/audit_logger.go b/core/logger/audit/audit_logger.go index 6e9e25202dd..5f2eee17911 100644 --- a/core/logger/audit/audit_logger.go +++ b/core/logger/audit/audit_logger.go @@ -14,9 +14,9 @@ import ( "time" commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/services" "github.com/smartcontractkit/chainlink/v2/core/config" - "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/store/models" ) @@ -27,20 +27,25 @@ const ( type Data = map[string]any -type AuditLogger interface { +type Logger interface { services.Service Audit(eventID EventID, data Data) } +// AuditLogger is an alias for Logger retained for backward compatibility. +// +//nolint:revive // backward compatibility alias +type AuditLogger = Logger + type HTTPAuditLoggerInterface interface { Do(req *http.Request) (*http.Response, error) } -type AuditLoggerService struct { +type LoggerService struct { logger logger.Logger // The standard logger configured in the node enabled bool // Whether the audit logger is enabled or not - forwardToUrl commonconfig.URL // Location we are going to send logs to + forwardToURL commonconfig.URL // Location we are going to send logs to headers []models.ServiceHeader // Headers to be sent along with logs for identification/authentication jsonWrapperKey string // Wrap audit data as a map under this key if present environmentName string // Decorate the environment this is coming from @@ -53,23 +58,28 @@ type AuditLoggerService struct { chDone chan struct{} } +// AuditLoggerService is an alias for LoggerService retained for backward compatibility. +// +//nolint:revive // backward compatibility alias +type AuditLoggerService = LoggerService + type wrappedAuditLog struct { eventID EventID data Data } -var NoopLogger AuditLogger = &AuditLoggerService{} +var NoopLogger Logger = &LoggerService{} // NewAuditLogger returns a buffer push system that ingests audit log events and // asynchronously pushes them up to an HTTP log service. // Parses and validates the AUDIT_LOGS_* environment values and returns an enabled // AuditLogger instance. If the environment variables are not set, the logger // is disabled and short circuits execution via enabled flag. -func NewAuditLogger(logger logger.Logger, config config.AuditLogger) (AuditLogger, error) { +func NewAuditLogger(lggr logger.Logger, config config.AuditLogger) (Logger, error) { // If the unverified config is nil, then we assume this came from the // configuration system and return a nil logger. if config == nil || !config.Enabled() { - return &AuditLoggerService{}, nil + return &LoggerService{}, nil } hostname, err := os.Hostname() @@ -77,23 +87,23 @@ func NewAuditLogger(logger logger.Logger, config config.AuditLogger) (AuditLogge return nil, fmt.Errorf("initialization error - unable to get hostname: %w", err) } - forwardToUrl, err := config.ForwardToUrl() + forwardToURL, err := config.ForwardToUrl() if err != nil { - return &AuditLoggerService{}, nil + return nil, fmt.Errorf("initialization error - unable to get forward URL: %w", err) } headers, err := config.Headers() if err != nil { - return &AuditLoggerService{}, nil + return nil, fmt.Errorf("initialization error - unable to get headers: %w", err) } loggingChannel := make(chan wrappedAuditLog, bufferCapacity) - // Create new AuditLoggerService - auditLogger := AuditLoggerService{ - logger: logger.Helper(1), + // Create new LoggerService + auditLogger := LoggerService{ + logger: logger.Helper(lggr, 1), enabled: true, - forwardToUrl: forwardToUrl, + forwardToURL: forwardToURL, headers: headers, jsonWrapperKey: config.JsonWrapperKey(), environmentName: config.Environment(), @@ -109,16 +119,16 @@ func NewAuditLogger(logger logger.Logger, config config.AuditLogger) (AuditLogge return &auditLogger, nil } -func (l *AuditLoggerService) SetLoggingClient(newClient HTTPAuditLoggerInterface) { +func (l *LoggerService) SetLoggingClient(newClient HTTPAuditLoggerInterface) { l.loggingClient = newClient } // Entrypoint for new audit logs. This buffers all logs that come in they will -// sent out by the goroutine that was started when the AuditLoggerService was +// sent out by the goroutine that was started when the LoggerService was // created. If this service was not enabled, this immediately returns. // // This function never blocks. -func (l *AuditLoggerService) Audit(eventID EventID, data Data) { +func (l *LoggerService) Audit(eventID EventID, data Data) { if !l.enabled { return } @@ -136,9 +146,9 @@ func (l *AuditLoggerService) Audit(eventID EventID, data Data) { } // Start the audit logger and begin processing logs on the channel -func (l *AuditLoggerService) Start(context.Context) error { +func (l *LoggerService) Start(context.Context) error { if !l.enabled { - return errors.New("The audit logger is not enabled") + return errors.New("the audit logger is not enabled") } go l.runLoop() @@ -146,9 +156,9 @@ func (l *AuditLoggerService) Start(context.Context) error { } // Stops the logger and will close the channel. -func (l *AuditLoggerService) Close() error { +func (l *LoggerService) Close() error { if !l.enabled { - return errors.New("The audit logger is not enabled") + return errors.New("the audit logger is not enabled") } l.logger.Warnf("Disabled the audit logger service") @@ -158,11 +168,11 @@ func (l *AuditLoggerService) Close() error { return nil } -func (l *AuditLoggerService) Name() string { +func (l *LoggerService) Name() string { return l.logger.Name() } -func (l *AuditLoggerService) HealthReport() map[string]error { +func (l *LoggerService) HealthReport() map[string]error { var err error if !l.enabled { err = errors.New("the audit logger is not enabled") @@ -172,7 +182,7 @@ func (l *AuditLoggerService) HealthReport() map[string]error { return map[string]error{l.Name(): err} } -func (l *AuditLoggerService) Ready() error { +func (l *LoggerService) Ready() error { if !l.enabled { return errors.New("the audit logger is not enabled") } @@ -184,7 +194,7 @@ func (l *AuditLoggerService) Ready() error { // logs as they come in. // // This function calls postLogToLogService which blocks. -func (l *AuditLoggerService) runLoop() { +func (l *LoggerService) runLoop() { defer close(l.chDone) for { @@ -204,7 +214,7 @@ func (l *AuditLoggerService) runLoop() { // due to transient network errors. // // This function blocks when called. -func (l *AuditLoggerService) postLogToLogService(eventID EventID, data Data) { +func (l *LoggerService) postLogToLogService(eventID EventID, data Data) { // Audit log JSON data logItem := map[string]any{ "eventID": eventID, @@ -228,7 +238,7 @@ func (l *AuditLoggerService) postLogToLogService(eventID EventID, data Data) { defer cancel() // Send to remote service - req, err := http.NewRequestWithContext(ctx, http.MethodPost, (*url.URL)(&l.forwardToUrl).String(), bytes.NewReader(serializedLog)) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, (*url.URL)(&l.forwardToURL).String(), bytes.NewReader(serializedLog)) if err != nil { l.logger.Error("failed to create request to remote logging service!") } @@ -240,6 +250,9 @@ func (l *AuditLoggerService) postLogToLogService(eventID EventID, data Data) { l.logger.Errorw("failed to send audit log to HTTP log service", "err", err, "logItem", logItem) return } + if resp.Body != nil { + defer resp.Body.Close() + } if resp.StatusCode != http.StatusOK { if resp.Body == nil { l.logger.Errorw("no body to read. Possibly an error occurred sending", "logItem", logItem) diff --git a/core/logger/audit/audit_logger_test.go b/core/logger/audit/audit_logger_test.go index 34a92074bd8..2b42121f437 100644 --- a/core/logger/audit/audit_logger_test.go +++ b/core/logger/audit/audit_logger_test.go @@ -2,6 +2,7 @@ package audit_test import ( "encoding/json" + "errors" "flag" "io" "net/http" @@ -13,8 +14,8 @@ import ( "github.com/urfave/cli" commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" - "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/logger/audit" "github.com/smartcontractkit/chainlink/v2/core/store/models" ) @@ -41,7 +42,6 @@ type LoginLogItem struct { func (mock *MockHTTPClient) Do(req *http.Request) (*http.Response, error) { b, err := io.ReadAll(req.Body) - if err != nil { return nil, err } @@ -65,7 +65,7 @@ func (c Config) Environment() string { return "test" } -func (c Config) ForwardToUrl() (commonconfig.URL, error) { +func (c Config) ForwardToUrl() (commonconfig.URL, error) { //nolint:revive // method name required by interface url, err := commonconfig.ParseURL("http://localhost:9898") if err != nil { return commonconfig.URL{}, err @@ -77,10 +77,48 @@ func (c Config) Headers() (models.ServiceHeaders, error) { return make(models.ServiceHeaders, 0), nil } -func (c Config) JsonWrapperKey() string { +func (c Config) JsonWrapperKey() string { //nolint:revive // method name required by interface return "" } +// badForwardToURLConfig fails ForwardToUrl(), all other methods delegate to Config. +type badForwardToURLConfig struct { + Config +} + +func (c badForwardToURLConfig) ForwardToUrl() (commonconfig.URL, error) { //nolint:revive // method name required by interface + return commonconfig.URL{}, errors.New("bad forward-to url") +} + +// badHeadersConfig fails Headers(), all other methods delegate to Config. +type badHeadersConfig struct { + Config +} + +func (c badHeadersConfig) Headers() (models.ServiceHeaders, error) { + return nil, errors.New("bad headers") +} + +func TestNewAuditLogger_ConfigErrors(t *testing.T) { + t.Parallel() + + lggr := logger.TestSugared(t) + + t.Run("returns error when ForwardToUrl fails", func(t *testing.T) { + t.Parallel() + + _, err := audit.NewAuditLogger(lggr, badForwardToURLConfig{}) + require.ErrorContains(t, err, "bad forward-to url") + }) + + t.Run("returns error when Headers fails", func(t *testing.T) { + t.Parallel() + + _, err := audit.NewAuditLogger(lggr, badHeadersConfig{}) + require.ErrorContains(t, err, "bad headers") + }) +} + func TestCheckLoginAuditLog(t *testing.T) { t.Parallel() @@ -94,25 +132,25 @@ func TestCheckLoginAuditLog(t *testing.T) { // Create a test logger because the audit logger relies on this logger // as well - logger := logger.TestLogger(t) + lggr := logger.TestSugared(t) auditLoggerTestConfig := Config{} // Create new AuditLoggerService - auditLogger, err := audit.NewAuditLogger(logger.Named("AuditLogger"), &auditLoggerTestConfig) - assert.NoError(t, err) + auditLogger, err := audit.NewAuditLogger(lggr.Named("AuditLogger"), &auditLoggerTestConfig) + require.NoError(t, err) // Cast to concrete type so we can swap out the internals - auditLoggerService, ok := auditLogger.(*audit.AuditLoggerService) + auditLoggerService, ok := auditLogger.(*audit.LoggerService) assert.True(t, ok) // Swap the internals with a testing handler auditLoggerService.SetLoggingClient(&mockHTTPClient) - assert.NoError(t, auditLoggerService.Ready()) + require.NoError(t, auditLoggerService.Ready()) // Create a new chainlink test application passing in our test logger // and audit logger - app := cltest.NewApplication(t, logger, auditLogger) + app := cltest.NewApplication(t, lggr, auditLogger) require.NoError(t, app.Start(t.Context())) enteredStrings := []string{cltest.APIEmailAdmin, cltest.Password} @@ -126,12 +164,12 @@ func TestCheckLoginAuditLog(t *testing.T) { // Login err = client.RemoteLogin(c) - assert.NoError(t, err) + require.NoError(t, err) select { case event := <-loggingChannel: deserialized := &LoginLogItem{} - assert.NoError(t, json.Unmarshal([]byte(event.body), deserialized)) + require.NoError(t, json.Unmarshal([]byte(event.body), deserialized)) assert.Equal(t, cltest.APIEmailAdmin, deserialized.Data.Email) assert.Equal(t, "test", deserialized.Env) @@ -141,5 +179,5 @@ func TestCheckLoginAuditLog(t *testing.T) { case <-time.After(5 * time.Second): } - assert.True(t, false) + assert.Fail(t, "timed out waiting for login audit log event") } diff --git a/core/logger/audit/audit_types.go b/core/logger/audit/audit_types.go index c12ed574d5a..0f5b2f1523a 100644 --- a/core/logger/audit/audit_types.go +++ b/core/logger/audit/audit_types.go @@ -62,8 +62,13 @@ const ( ChainSpecUpdated EventID = "CHAIN_SPEC_UPDATED" ChainDeleted EventID = "CHAIN_DELETED" - ChainRpcNodeAdded EventID = "CHAIN_RPC_NODE_ADDED" - ChainRpcNodeDeleted EventID = "CHAIN_RPC_NODE_DELETED" + ChainRPCNodeAdded EventID = "CHAIN_RPC_NODE_ADDED" + ChainRPCNodeDeleted EventID = "CHAIN_RPC_NODE_DELETED" + + // ChainRpcNodeAdded is an alias retained for backward compatibility. + ChainRpcNodeAdded = ChainRPCNodeAdded //nolint:revive // backward compatibility + // ChainRpcNodeDeleted is an alias retained for backward compatibility. + ChainRpcNodeDeleted = ChainRPCNodeDeleted //nolint:revive // backward compatibility BridgeCreated EventID = "BRIDGE_CREATED" BridgeUpdated EventID = "BRIDGE_UPDATED" @@ -81,10 +86,15 @@ const ( JobProposalSpecRejected EventID = "JOB_PROPOSAL_SPEC_REJECTED" ConfigUpdated EventID = "CONFIG_UPDATED" - ConfigSqlLoggingEnabled EventID = "CONFIG_SQL_LOGGING_ENABLED" - ConfigSqlLoggingDisabled EventID = "CONFIG_SQL_LOGGING_DISABLED" + ConfigSQLLoggingEnabled EventID = "CONFIG_SQL_LOGGING_ENABLED" + ConfigSQLLoggingDisabled EventID = "CONFIG_SQL_LOGGING_DISABLED" GlobalLogLevelSet EventID = "GLOBAL_LOG_LEVEL_SET" + // ConfigSqlLoggingEnabled is an alias retained for backward compatibility. + ConfigSqlLoggingEnabled = ConfigSQLLoggingEnabled //nolint:revive // backward compatibility + // ConfigSqlLoggingDisabled is an alias retained for backward compatibility. + ConfigSqlLoggingDisabled = ConfigSQLLoggingDisabled //nolint:revive // backward compatibility + JobErrorDismissed EventID = "JOB_ERROR_DISMISSED" JobRunSet EventID = "JOB_RUN_SET" diff --git a/core/logger/disk_stats_test.go b/core/logger/disk_stats_test.go index ee0e5bbf99a..7538ddbcd59 100644 --- a/core/logger/disk_stats_test.go +++ b/core/logger/disk_stats_test.go @@ -4,13 +4,14 @@ import ( "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_diskSpaceAvailable(t *testing.T) { t.Parallel() size, err := diskSpaceAvailable(".") - assert.NoError(t, err) + require.NoError(t, err) assert.NotZero(t, size) _, err = diskSpaceAvailable("") diff --git a/core/logger/fields_test.go b/core/logger/fields_test.go index 511756cfc13..f797248b867 100644 --- a/core/logger/fields_test.go +++ b/core/logger/fields_test.go @@ -76,7 +76,7 @@ func TestFields_With(t *testing.T) { t.Parallel() assert.Panics(t, func() { - //lint:ignore SA5012 we expect panic here + //nolint:staticcheck // intentional: odd number of key/value args triggers panic _ = f.With("xyz") }, "expected even number of arguments") }) diff --git a/core/logger/logger.go b/core/logger/logger.go index 9cae2d3e50f..8abcd608e0c 100644 --- a/core/logger/logger.go +++ b/core/logger/logger.go @@ -72,7 +72,8 @@ var _ common.Logger = (Logger)(nil) // - Trace: Only included if compiled with the trace tag. For example: go test -tags trace ... // // Node Operator Docs: https://docs.chain.link/docs/configuration-variables/#log_level -// Deprecated: use [common.Logger] & [common.SugaredLogger] +// +// Note: prefer [common.Logger] & [common.SugaredLogger] type Logger interface { // With creates a new Logger with the given arguments With(args ...any) Logger @@ -159,7 +160,7 @@ func NewLogger() (Logger, func() error) { type Config struct { LogLevel zapcore.Level Dir string - JsonConsole bool + JSONConsole bool UnixTS bool FileMaxSizeMB int FileMaxAgeDays int @@ -187,7 +188,7 @@ func (c *Config) NewWithCores(cores ...zapcore.Core) (Logger, func() error) { c.diskPollConfig = newDiskPollConfig(diskPollInterval) } - cfg := newZapConfigProd(c.JsonConsole, c.UnixTS) + cfg := newZapConfigProd(c.JSONConsole, c.UnixTS) cfg.Level.SetLevel(c.LogLevel) var ( l Logger @@ -212,12 +213,12 @@ func (c *Config) NewWithCores(cores ...zapcore.Core) (Logger, func() error) { } // DebugLogsToDisk returns whether debug logs should be stored in disk -func (c Config) DebugLogsToDisk() bool { +func (c *Config) DebugLogsToDisk() bool { return c.FileMaxSizeMB > 0 } // RequiredDiskSpace returns the required disk space in order to allow debug logs to be stored in disk -func (c Config) RequiredDiskSpace() utils.FileSize { +func (c *Config) RequiredDiskSpace() utils.FileSize { return utils.FileSize(c.FileMaxSizeMB * utils.MB * (c.FileMaxBackups + 1)) //nolint:gosec // G115 } @@ -229,7 +230,7 @@ func (c *Config) DiskSpaceAvailable(path string) (utils.FileSize, error) { return c.diskSpaceAvailableFn(path) } -func (c Config) LogsFile() string { +func (c *Config) LogsFile() string { return filepath.Join(c.Dir, logsFile) } diff --git a/core/logger/logger_test.go b/core/logger/logger_test.go index cf300920255..96192c31b91 100644 --- a/core/logger/logger_test.go +++ b/core/logger/logger_test.go @@ -65,10 +65,9 @@ func TestOtelCore(t *testing.T) { otelCore := otelzap.NewCore(noopLogger, otelzap.WithLevel(zapcore.DebugLevel)) logger, closeFn = cfg.NewWithCores(otelCore) - defer func() { - err := closeFn() - require.NoError(t, err) - }() + t.Cleanup(func() { + require.NoError(t, closeFn()) + }) require.NotNil(t, logger) // Test that logger works with otel core @@ -76,10 +75,9 @@ func TestOtelCore(t *testing.T) { } else { // Test that regular logger works logger, closeFn = cfg.NewWithCores() - defer func() { - err := closeFn() - require.NoError(t, err) - }() + t.Cleanup(func() { + require.NoError(t, closeFn()) + }) require.NotNil(t, logger) logger.Info("test log message without otel") @@ -98,7 +96,7 @@ func TestAtomicCoreSwap(t *testing.T) { lggrCfg := Config{ LogLevel: zapcore.InfoLevel, - JsonConsole: true, + JSONConsole: true, UnixTS: false, FileMaxSizeMB: 0, FileMaxAgeDays: 0, @@ -107,10 +105,10 @@ func TestAtomicCoreSwap(t *testing.T) { } lggr, closeFn := lggrCfg.NewWithCores(ac.root) - defer func() { + t.Cleanup(func() { ac.Close() require.NoError(t, closeFn()) - }() + }) // Create observer to capture logs otelCore, otelLogs := observer.New(zapcore.InfoLevel) diff --git a/core/logger/logger_unix.go b/core/logger/logger_unix.go index 41c0b2ff133..ab8437619da 100644 --- a/core/logger/logger_unix.go +++ b/core/logger/logger_unix.go @@ -10,6 +10,6 @@ func registerOSSinks() error { // logFileURI returns the full path to the file the // NewLogger logs to, and uses zap's built in default file sink. -func (c Config) logFileURI() string { +func (c *Config) logFileURI() string { return filepath.ToSlash(c.LogsFile()) } diff --git a/core/logger/logger_windows.go b/core/logger/logger_windows.go index 0de01e87b31..b7f4eecf2b1 100644 --- a/core/logger/logger_windows.go +++ b/core/logger/logger_windows.go @@ -14,7 +14,7 @@ import ( // directory, with a custom scheme winfile:/// specifically tailored for // Windows to get around their handling of the file:// schema in uber.org/zap. // https://github.com/uber-go/zap/issues/621 -func (c Config) logFileURI() string { +func (c *Config) logFileURI() string { return "winfile:///" + filepath.ToSlash(c.LogsFile()) } diff --git a/core/logger/passthrough_test.go b/core/logger/passthrough_test.go index b56880ccd45..241159e0fb8 100644 --- a/core/logger/passthrough_test.go +++ b/core/logger/passthrough_test.go @@ -4,7 +4,6 @@ import ( "errors" "testing" - "github.com/stretchr/testify/assert" "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" "go.uber.org/zap/zapcore" @@ -65,7 +64,7 @@ func TestLogger_Passthrough(t *testing.T) { require.Equal(t, "mockLogger", nm) err := l.Sync() - assert.ErrorIs(t, err, errTest) + require.ErrorIs(t, err, errTest) l.Recover(errTest) }) diff --git a/core/logger/prometheus_test.go b/core/logger/prometheus_test.go index e1763678122..e469554a5e0 100644 --- a/core/logger/prometheus_test.go +++ b/core/logger/prometheus_test.go @@ -9,6 +9,7 @@ import ( "github.com/prometheus/client_golang/prometheus/promauto" io_prometheus_client "github.com/prometheus/client_model/go" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestPrometheusLogger_Counters(t *testing.T) { @@ -89,7 +90,7 @@ func TestPrometheusLogger_Counters(t *testing.T) { func assertCounterValue(t *testing.T, c prometheus.Counter, v int) { var m io_prometheus_client.Metric err := c.Write(&m) - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, v, int(m.GetCounter().GetValue())) } diff --git a/core/logger/pyroscope.go b/core/logger/pyroscope.go index d18487f467c..2b5e0f4310e 100644 --- a/core/logger/pyroscope.go +++ b/core/logger/pyroscope.go @@ -31,7 +31,7 @@ func StartPyroscope(pyroConfig config.Pyroscope, pprofConfig PprofConfig) (*pyro ApplicationName: "chainlink-node", ServerAddress: pyroConfig.ServerAddress(), - AuthToken: pyroConfig.AuthToken(), + AuthToken: pyroConfig.AuthToken(), //nolint:staticcheck // SA1019 // We disable logging the profiling info, it will be in the Pyroscope instance anyways... Logger: nil, diff --git a/core/logger/sentry.go b/core/logger/sentry.go index e556f4be81c..61242d1913a 100644 --- a/core/logger/sentry.go +++ b/core/logger/sentry.go @@ -247,19 +247,14 @@ func (s *sentryLogger) Helper(add int) Logger { func toMap(args []any) (m map[string]any) { m = make(map[string]any, len(args)/2) - for i := 0; i < len(args); { - // Make sure this element isn't a dangling key - if i == len(args)-1 { - break - } - - // Consume this value and the next, treating them as a key-value pair. If the - // key isn't a string ignore it + // Consume this value and the next, treating them as a key-value pair. If the + // key isn't a string ignore it. The `i+1 < len(args)` guard skips any dangling + // trailing key on odd-length input. + for i := 0; i+1 < len(args); i += 2 { key, val := args[i], args[i+1] if keyStr, ok := key.(string); ok { m[keyStr] = val } - i += 2 } return m } diff --git a/core/logger/test_logger.go b/core/logger/test_logger.go index 2f018432f66..227f3993ae4 100644 --- a/core/logger/test_logger.go +++ b/core/logger/test_logger.go @@ -34,7 +34,8 @@ func TestLoggerObserved(tb testing.TB, lvl zapcore.Level) (Logger, *observer.Obs // testLogger returns a new SugaredLogger for tests. core is optional. func testLogger(tb testing.TB, core zapcore.Core, lvl zapcore.Level) SugaredLogger { a := zap.NewAtomicLevelAt(lvl) - opts := []zaptest.LoggerOption{zaptest.Level(a)} + opts := make([]zaptest.LoggerOption, 0, 2) + opts = append(opts, zaptest.Level(a)) zapOpts := []zap.Option{zap.AddCaller(), zap.AddStacktrace(zapcore.ErrorLevel)} if core != nil { zapOpts = append(zapOpts, zap.WrapCore(func(c zapcore.Core) zapcore.Core { diff --git a/core/logger/test_logger_test.go b/core/logger/test_logger_test.go index 07baaff307f..db1c3e625c0 100644 --- a/core/logger/test_logger_test.go +++ b/core/logger/test_logger_test.go @@ -53,10 +53,10 @@ func TestTestLogger(t *testing.T) { const ( workerName = "WorkerName" workerMessage = "Did some work" - idKey, workerId = "workerId", "42" + idKey, workerID = "workerId", "42" resultKey, resultVal = "result", "success" ) - workLgr := srvLgr.Named(workerName).With(idKey, workerId) + workLgr := srvLgr.Named(workerName).With(idKey, workerID) workLgr.Infow(workerMessage, resultKey, resultVal) // [INFO] Did some work logger/test_logger_test.go:49 version=unset@unset logger=ServiceName.WorkerName result=success workerId=42 logs = observed.TakeAll() @@ -65,7 +65,7 @@ func TestTestLogger(t *testing.T) { assert.Equal(t, zap.InfoLevel, log.Level) assert.Equal(t, workerMessage, log.Message) assert.Equal(t, fmt.Sprintf("%s.%s", serviceName, workerName), log.LoggerName) - assert.Equal(t, workerId, log.ContextMap()[idKey]) + assert.Equal(t, workerID, log.ContextMap()[idKey]) assert.Equal(t, resultVal, log.ContextMap()[resultKey]) const ( diff --git a/core/logger/zap_test.go b/core/logger/zap_test.go index 7f055b4cfc1..3f074ae7bb8 100644 --- a/core/logger/zap_test.go +++ b/core/logger/zap_test.go @@ -29,12 +29,12 @@ func TestZapLogger_OutOfDiskSpace(t *testing.T) { logsDir := t.TempDir() tmpFile, err := os.CreateTemp(logsDir, "*") - assert.NoError(t, err) - defer func() { assert.NoError(t, tmpFile.Close()) }() + require.NoError(t, err) + t.Cleanup(func() { assert.NoError(t, tmpFile.Close()) }) var logFileSize utils.FileSize err = logFileSize.UnmarshalText([]byte("100mb")) - assert.NoError(t, err) + require.NoError(t, err) pollCfg := newDiskPollConfig(1 * time.Second) @@ -140,7 +140,7 @@ func TestZapLogger_OutOfDiskSpace(t *testing.T) { logFile := local.LogsFile() b, err := os.ReadFile(logFile) - assert.NoError(t, err) + require.NoError(t, err) logs := string(b) lines := strings.Split(logs, "\n") @@ -191,7 +191,7 @@ func TestZapLogger_OutOfDiskSpace(t *testing.T) { logFile := local.LogsFile() b, err := os.ReadFile(logFile) - assert.NoError(t, err) + require.NoError(t, err) logs := string(b) lines := strings.Split(logs, "\n") @@ -213,12 +213,12 @@ func TestZapLogger_LogCaller(t *testing.T) { logsDir := t.TempDir() tmpFile, err := os.CreateTemp(logsDir, "*") - assert.NoError(t, err) - defer func() { assert.NoError(t, tmpFile.Close()) }() + require.NoError(t, err) + t.Cleanup(func() { assert.NoError(t, tmpFile.Close()) }) var logFileSize utils.FileSize err = logFileSize.UnmarshalText([]byte("100mb")) - assert.NoError(t, err) + require.NoError(t, err) pollChan := make(chan time.Time) stop := func() { @@ -254,7 +254,7 @@ func TestZapLogger_LogCaller(t *testing.T) { logFile := local.LogsFile() b, err := os.ReadFile(logFile) - assert.NoError(t, err) + require.NoError(t, err) logs := string(b) lines := strings.Split(logs, "\n") @@ -278,7 +278,7 @@ func TestLogger_Leak(t *testing.T) { } ac := NewUpdatableCore() - defer ac.Close() + t.Cleanup(func() { ac.Close() }) startObjectsNum := heapObjects() aLggr := ac.root.With([]zapcore.Field{}) bLggr := aLggr.With([]zapcore.Field{}) diff --git a/core/services/job/models.go b/core/services/job/models.go index 7bf49ea202f..ad71d7d3997 100644 --- a/core/services/job/models.go +++ b/core/services/job/models.go @@ -4,6 +4,7 @@ import ( "database/sql" "database/sql/driver" "encoding/json" + "errors" "fmt" "strconv" "strings" @@ -12,7 +13,6 @@ import ( "github.com/ethereum/go-ethereum/common" "github.com/google/uuid" "github.com/lib/pq" - "github.com/pkg/errors" "gopkg.in/guregu/null.v4" "github.com/smartcontractkit/chainlink-common/keystore/corekeys" @@ -308,7 +308,7 @@ func (s *OCROracleSpec) SetID(value string) error { // JSONConfig is a map for config properties which are encoded as JSON in the database by implementing // sql.Scanner and driver.Valuer. -type JSONConfig map[string]any //nolint:recvcheck // Scan requires pointer receiver to unmarshal into map, Value requires value receiver for driver.Valuer +type JSONConfig map[string]any // Bytes returns the raw bytes func (r JSONConfig) Bytes() []byte { @@ -325,7 +325,7 @@ func (r JSONConfig) Value() (driver.Value, error) { func (r *JSONConfig) Scan(value any) error { b, ok := value.([]byte) if !ok { - return errors.Errorf("expected bytes got %T", b) + return fmt.Errorf("expected bytes got %T", b) } return json.Unmarshal(b, &r) } @@ -857,7 +857,7 @@ type StandardCapabilitiesConfig struct { OracleFactory OracleFactoryConfig `toml:"oracle_factory"` } -type OracleFactoryConfig struct { //nolint:recvcheck // Scan requires pointer receiver to unmarshal into struct, Value requires value receiver for driver.Valuer +type OracleFactoryConfig struct { Enabled bool `toml:"enabled"` BootstrapPeers []string `toml:"bootstrap_peers"` OCRContractAddress string `toml:"ocr_contract_address"` @@ -880,7 +880,7 @@ func (ofc *OracleFactoryConfig) Scan(value any) error { b, ok := value.([]byte) if !ok { - return errors.Errorf("expected bytes got %T", value) + return fmt.Errorf("expected bytes got %T", value) } return json.Unmarshal(b, &ofc) } diff --git a/core/services/llo/observation/observation_context.go b/core/services/llo/observation/observation_context.go index c49925308ca..86751af6a28 100644 --- a/core/services/llo/observation/observation_context.go +++ b/core/services/llo/observation/observation_context.go @@ -147,15 +147,15 @@ func (oc *observationContext) enqueueObservationTelemetry(ctx context.Context, s } if val != nil { ot.StreamValueType = int32(val.Type()) - b, err := val.MarshalBinary() - if err != nil { - oc.l.Errorw("failed to MarshalBinary on stream value", "error", err) + b, bErr := val.MarshalBinary() + if bErr != nil { + oc.l.Errorw("failed to MarshalBinary on stream value", "error", bErr) } else { ot.StreamValueBinary = b } - s, err := val.MarshalText() - if err != nil { - oc.l.Errorw("failed to MarshalText on stream value", "error", err) + s, sErr := val.MarshalText() + if sErr != nil { + oc.l.Errorw("failed to MarshalText on stream value", "error", sErr) } else { ot.StreamValueText = string(s) } diff --git a/core/services/pipeline/models.go b/core/services/pipeline/models.go index 23a308f5f64..f37b9858c48 100644 --- a/core/services/pipeline/models.go +++ b/core/services/pipeline/models.go @@ -3,14 +3,13 @@ package pipeline import ( "database/sql/driver" "encoding/json" - stderrors "errors" + "errors" "fmt" "math/big" "strconv" "time" "github.com/google/uuid" - "github.com/pkg/errors" "github.com/shopspring/decimal" "gopkg.in/guregu/null.v4" @@ -202,7 +201,7 @@ func (r *Run) StringAllErrors() []*string { return allErrors } -type RunErrors []null.String //nolint:recvcheck // Scan requires pointer receiver to unmarshal, Value requires value receiver for driver.Valuer +type RunErrors []null.String func (re *RunErrors) Scan(value any) error { if value == nil { @@ -211,7 +210,7 @@ func (re *RunErrors) Scan(value any) error { } bytes, ok := value.([]byte) if !ok { - return errors.Errorf("RunErrors#Scan received unsupported value %v of type %T", value, value) + return fmt.Errorf("RunErrors#Scan received unsupported value %v of type %T", value, value) } if len(bytes) == 0 { *re = nil @@ -247,7 +246,7 @@ func (re RunErrors) ToError() error { for _, e := range re { errs = append(errs, toErr(e)) } - return stderrors.Join(errs...) + return errors.Join(errs...) } type ResumeRequest struct { diff --git a/core/services/workflows/cmd/cre/utils/standard_capabilities.go b/core/services/workflows/cmd/cre/utils/standard_capabilities.go index 275a04def55..1593d64fd49 100644 --- a/core/services/workflows/cmd/cre/utils/standard_capabilities.go +++ b/core/services/workflows/cmd/cre/utils/standard_capabilities.go @@ -30,9 +30,6 @@ var ( Config: `{"fastestScheduleIntervalSeconds": 1}`, Enabled: true, }, - "readcontract": {}, - "kvstore": {}, - "workflowevent": {}, } ) diff --git a/core/sessions/ldapauth/helpers_test.go b/core/sessions/ldapauth/helpers_test.go index 1bb4abf6341..9837b5366f7 100644 --- a/core/sessions/ldapauth/helpers_test.go +++ b/core/sessions/ldapauth/helpers_test.go @@ -4,9 +4,9 @@ import ( "time" commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink/v2/core/config" - "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/logger/audit" ) @@ -15,13 +15,13 @@ func NewTestLDAPAuthenticator( ds sqlutil.DataSource, ldapCfg config.LDAP, lggr logger.Logger, - auditLogger audit.AuditLogger, + auditLogger audit.Logger, ) (*ldapAuthenticator, error) { ldapAuth := ldapAuthenticator{ ds: ds, ldapClient: newLDAPClient(ldapCfg), config: ldapCfg, - lggr: lggr.Named("LDAPAuthenticationProvider"), + lggr: logger.Sugared(lggr).Named("LDAPAuthenticationProvider"), auditLogger: auditLogger, } @@ -42,8 +42,7 @@ func (l *ldapAuthenticator) SetLDAPClient(newClient LDAPClient) { } // Implements config.LDAP -type TestConfig struct { -} +type TestConfig struct{} func (t *TestConfig) ServerAddress() string { return "ldaps://MOCK" @@ -113,7 +112,7 @@ func (t *TestConfig) ReadUserGroupCN() string { return NodeReadOnlyGroupCN } -func (t *TestConfig) UserApiTokenEnabled() bool { +func (t *TestConfig) UserApiTokenEnabled() bool { //nolint:revive // method name required by interface return true } diff --git a/core/sessions/ldapauth/ldap.go b/core/sessions/ldapauth/ldap.go index 8a622bf8214..445e60cbf99 100644 --- a/core/sessions/ldapauth/ldap.go +++ b/core/sessions/ldapauth/ldap.go @@ -35,12 +35,12 @@ import ( "github.com/gin-gonic/gin" "github.com/go-ldap/ldap/v3" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink-common/pkg/utils/mathutil" "github.com/smartcontractkit/chainlink/v2/core/auth" "github.com/smartcontractkit/chainlink/v2/core/bridges" "github.com/smartcontractkit/chainlink/v2/core/config" - "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/logger/audit" "github.com/smartcontractkit/chainlink/v2/core/sessions" "github.com/smartcontractkit/chainlink/v2/core/utils" @@ -50,15 +50,17 @@ const ( UniqueMemberAttribute = "uniqueMember" ) -var ErrUserNotInUpstream = errors.New("LDAP query returned no matching users") -var ErrUserNoLDAPGroups = errors.New("user present in directory, but matching no role groups assigned") +var ( + ErrUserNotInUpstream = errors.New("LDAP query returned no matching users") + ErrUserNoLDAPGroups = errors.New("user present in directory, but matching no role groups assigned") +) type ldapAuthenticator struct { ds sqlutil.DataSource ldapClient LDAPClient config config.LDAP - lggr logger.Logger - auditLogger audit.AuditLogger + lggr logger.SugaredLogger + auditLogger audit.Logger } // ldapAuthenticator implements sessions.AuthenticationProvider interface @@ -69,7 +71,7 @@ func NewLDAPAuthenticator( ldapCfg config.LDAP, dev bool, lggr logger.Logger, - auditLogger audit.AuditLogger, + auditLogger audit.Logger, ) (*ldapAuthenticator, error) { // If not chainlink dev and not tls, error if !dev && !ldapCfg.ServerTLS() { @@ -92,7 +94,7 @@ func NewLDAPAuthenticator( ds: ds, ldapClient: newLDAPClient(ldapCfg), config: ldapCfg, - lggr: lggr.Named("LDAPAuthenticationProvider"), + lggr: logger.Sugared(lggr).Named("LDAPAuthenticationProvider"), auditLogger: auditLogger, } @@ -238,13 +240,12 @@ func (l *ldapAuthenticator) FindUserByAPIToken(ctx context.Context, apiToken str // ListUsers will load and return all active users in applicable LDAP groups, extended with local admin users as well func (l *ldapAuthenticator) ListUsers(ctx context.Context) ([]sessions.User, error) { // For each defined role/group, query for the list of group members to gather the full list of possible users - users := []sessions.User{} var err error conn, err := l.ldapClient.CreateEphemeralConnection() if err != nil { l.lggr.Errorf("error in LDAP dial: %v", err) - return users, errors.New("unable to establish connection to LDAP server with provided URL and credentials") + return nil, errors.New("unable to establish connection to LDAP server with provided URL and credentials") } defer conn.Close() @@ -252,28 +253,29 @@ func (l *ldapAuthenticator) ListUsers(ctx context.Context) ([]sessions.User, err adminUsers, err := l.ldapGroupMembersListToUser(conn, l.config.AdminUserGroupCN(), sessions.UserRoleAdmin) if err != nil { l.lggr.Errorf("error in ldapGroupMembersListToUser: %v", err) - return users, errors.New("unable to list group users") + return nil, errors.New("unable to list group users") } // Query for list of uniqueMember IDs present in Edit group editUsers, err := l.ldapGroupMembersListToUser(conn, l.config.EditUserGroupCN(), sessions.UserRoleEdit) if err != nil { l.lggr.Error("error in ldapGroupMembersListToUser: ", err) - return users, errors.New("unable to list group users") + return nil, errors.New("unable to list group users") } // Query for list of uniqueMember IDs present in Run group runUsers, err := l.ldapGroupMembersListToUser(conn, l.config.RunUserGroupCN(), sessions.UserRoleRun) if err != nil { l.lggr.Error("error in ldapGroupMembersListToUser: ", err) - return users, errors.New("unable to list group users") + return nil, errors.New("unable to list group users") } // Query for list of uniqueMember IDs present in Read group readUsers, err := l.ldapGroupMembersListToUser(conn, l.config.ReadUserGroupCN(), sessions.UserRoleView) if err != nil { l.lggr.Error("error in ldapGroupMembersListToUser: ", err) - return users, errors.New("unable to list group users") + return nil, errors.New("unable to list group users") } // Aggregate full list + users := make([]sessions.User, 0, len(adminUsers)+len(editUsers)+len(runUsers)+len(readUsers)) users = append(users, adminUsers...) users = append(users, editUsers...) users = append(users, runUsers...) @@ -501,7 +503,7 @@ func (l *ldapAuthenticator) SetPassword(ctx context.Context, user *sessions.User } // TestPassword tests if an LDAP login bind can be performed with provided credentials, returns nil if success -func (l *ldapAuthenticator) TestPassword(ctx context.Context, email string, password string) error { +func (l *ldapAuthenticator) TestPassword(ctx context.Context, email, password string) error { conn, err := l.ldapClient.CreateEphemeralConnection() if err != nil { return errors.New("unable to establish connection to LDAP server with provided URL and credentials") @@ -607,7 +609,7 @@ func (l *ldapAuthenticator) Sessions(ctx context.Context, offset, limit int) ([] var sessions []sessions.Session sql := `SELECT * FROM ldap_sessions ORDER BY created_at, id LIMIT $1 OFFSET $2;` if err := l.ds.SelectContext(ctx, &sessions, sql, limit, offset); err != nil { - return sessions, nil + return nil, err } return sessions, nil } @@ -782,7 +784,7 @@ func (l *ldapAuthenticator) groupSearchResultsToUserRole(ldapGroups []*ldap.Entr ) } -func GroupSearchResultsToUserRole(ldapGroups []*ldap.Entry, adminCN string, editCN string, runCN string, readCN string) (sessions.UserRole, error) { +func GroupSearchResultsToUserRole(ldapGroups []*ldap.Entry, adminCN, editCN, runCN, readCN string) (sessions.UserRole, error) { // If defined Admin group name is present in groups search result, return UserRoleAdmin for _, group := range ldapGroups { if group.GetAttributeValue("cn") == adminCN { diff --git a/core/sessions/ldapauth/ldap_test.go b/core/sessions/ldapauth/ldap_test.go index 8b736f8f785..821b00213e6 100644 --- a/core/sessions/ldapauth/ldap_test.go +++ b/core/sessions/ldapauth/ldap_test.go @@ -12,9 +12,9 @@ import ( "github.com/stretchr/testify/mock" "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" - "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/logger/audit" "github.com/smartcontractkit/chainlink/v2/core/sessions" "github.com/smartcontractkit/chainlink/v2/core/sessions/ldapauth" @@ -27,7 +27,7 @@ func setupAuthenticationProvider(t *testing.T, ldapClient ldapauth.LDAPClient) ( cfg := ldapauth.TestConfig{} db := pgtest.NewSqlxDB(t) - ldapAuthProvider, err := ldapauth.NewTestLDAPAuthenticator(db, &cfg, logger.TestLogger(t), &audit.AuditLoggerService{}) + ldapAuthProvider, err := ldapauth.NewTestLDAPAuthenticator(db, &cfg, logger.TestSugared(t), &audit.LoggerService{}) if err != nil { t.Fatalf("Error constructing NewTestLDAPAuthenticator: %v\n", err) } diff --git a/core/sessions/ldapauth/sync.go b/core/sessions/ldapauth/sync.go index 813080e71c5..782f797ee14 100644 --- a/core/sessions/ldapauth/sync.go +++ b/core/sessions/ldapauth/sync.go @@ -10,10 +10,10 @@ import ( "github.com/go-ldap/ldap/v3" "github.com/lib/pq" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/services" "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink/v2/core/config" - "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/sessions" ) @@ -21,7 +21,7 @@ type LDAPServerStateSyncer struct { ds sqlutil.DataSource ldapClient LDAPClient config config.LDAP - lggr logger.Logger + lggr logger.SugaredLogger nextSyncTime time.Time done chan struct{} stopCh services.StopChan @@ -37,7 +37,7 @@ func NewLDAPServerStateSyncer( ds: ds, ldapClient: newLDAPClient(config), config: config, - lggr: lggr.Named("LDAPServerStateSync"), + lggr: logger.Sugared(lggr).Named("LDAPServerStateSync"), done: make(chan struct{}), stopCh: make(services.StopChan), } @@ -116,7 +116,6 @@ func (l *LDAPServerStateSyncer) Work(ctx context.Context) { l.lggr.Info("Begin Upstream LDAP provider state sync after checking time against config UpstreamSyncInterval and UpstreamSyncRateLimit") // For each defined role/group, query for the list of group members to gather the full list of possible users - users := []sessions.User{} conn, err := l.ldapClient.CreateEphemeralConnection() if err != nil { @@ -155,6 +154,7 @@ func (l *LDAPServerStateSyncer) Work(ctx context.Context) { return } + users := make([]sessions.User, 0, len(adminUsers)+len(editUsers)+len(runUsers)+len(readUsers)) users = append(users, adminUsers...) users = append(users, editUsers...) users = append(users, runUsers...) diff --git a/core/sessions/localauth/orm.go b/core/sessions/localauth/orm.go index 28a88ef1b0a..d3477079ed0 100644 --- a/core/sessions/localauth/orm.go +++ b/core/sessions/localauth/orm.go @@ -4,17 +4,18 @@ import ( "context" "crypto/subtle" "encoding/json" + "errors" + "fmt" "strings" "time" "github.com/gin-gonic/gin" - pkgerrors "github.com/pkg/errors" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink-common/pkg/utils/mathutil" "github.com/smartcontractkit/chainlink/v2/core/auth" "github.com/smartcontractkit/chainlink/v2/core/bridges" - "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/logger/audit" "github.com/smartcontractkit/chainlink/v2/core/sessions" "github.com/smartcontractkit/chainlink/v2/core/utils" @@ -23,23 +24,29 @@ import ( type orm struct { ds sqlutil.DataSource sessionDuration time.Duration - lggr logger.Logger - auditLogger audit.AuditLogger + lggr logger.SugaredLogger + auditLogger audit.Logger } // orm implements sessions.AuthenticationProvider and sessions.BasicAdminUsersORM interfaces -var _ sessions.AuthenticationProvider = (*orm)(nil) -var _ sessions.BasicAdminUsersORM = (*orm)(nil) +var ( + _ sessions.AuthenticationProvider = (*orm)(nil) + _ sessions.BasicAdminUsersORM = (*orm)(nil) +) -func NewORM(ds sqlutil.DataSource, sd time.Duration, lggr logger.Logger, auditLogger audit.AuditLogger) sessions.AuthenticationProvider { +func NewORM(ds sqlutil.DataSource, sd time.Duration, lggr logger.Logger, auditLogger audit.Logger) sessions.AuthenticationProvider { return &orm{ ds: ds, sessionDuration: sd, - lggr: lggr.Named("LocalAuthAuthenticationProviderORM"), + lggr: logger.Sugared(lggr).Named("LocalAuthAuthenticationProviderORM"), auditLogger: auditLogger, } } +// ErrMFAFailed is returned when any step of the MFA/WebAuthn login flow fails. +// The generic message deliberately avoids leaking why MFA failed. +var ErrMFAFailed = errors.New("MFA error") + // FindUser will attempt to return an API user by email. func (o *orm) FindUser(ctx context.Context, email string) (sessions.User, error) { return o.findUser(ctx, email) @@ -49,27 +56,27 @@ func (o *orm) FindUser(ctx context.Context, email string) (sessions.User, error) func (o *orm) FindUserByAPIToken(ctx context.Context, apiToken string) (user sessions.User, err error) { sql := "SELECT * FROM users WHERE token_key = $1" err = o.ds.GetContext(ctx, &user, sql, apiToken) - return + return user, err } func (o *orm) findUser(ctx context.Context, email string) (user sessions.User, err error) { sql := "SELECT * FROM users WHERE lower(email) = lower($1)" err = o.ds.GetContext(ctx, &user, sql, email) - return + return user, err } // ListUsers will load and return all user rows from the db. func (o *orm) ListUsers(ctx context.Context) (users []sessions.User, err error) { sql := "SELECT * FROM users ORDER BY email ASC;" err = o.ds.SelectContext(ctx, &users, sql) - return + return users, err } // findValidSession finds an unexpired session by its ID and returns the associated email. func (o *orm) findValidSession(ctx context.Context, sessionID string) (email string, err error) { if err := o.ds.GetContext(ctx, &email, "SELECT email FROM sessions WHERE id = $1 AND last_used + $2 >= now() FOR UPDATE", sessionID, o.sessionDuration); err != nil { o.lggr.Infof("query result: %v", email) - return email, pkgerrors.Wrap(err, "no matching user for provided session token") + return email, fmt.Errorf("no matching user for provided session token: %w", err) } return email, nil } @@ -153,12 +160,12 @@ func (o *orm) CreateSession(ctx context.Context, sr sessions.SessionRequest) (st // for MFA tokens leaking if an account has MFA tokens or not. if !constantTimeEmailCompare(strings.ToLower(sr.Email), strings.ToLower(user.Email)) { o.auditLogger.Audit(audit.AuthLoginFailedEmail, map[string]any{"email": sr.Email}) - return "", pkgerrors.New("Invalid email") + return "", errors.New("invalid email") } if !utils.CheckPasswordHash(sr.Password, string(user.HashedPassword)) { o.auditLogger.Audit(audit.AuthLoginFailedPassword, map[string]any{"email": sr.Email}) - return "", pkgerrors.New("Invalid password") + return "", errors.New("invalid password") } // Load all valid MFA tokens associated with user's email @@ -166,7 +173,7 @@ func (o *orm) CreateSession(ctx context.Context, sr sessions.SessionRequest) (st if err != nil { // There was an error with the database query lggr.Errorf("Could not fetch user's MFA data: %v", err) - return "", pkgerrors.New("MFA Error") + return "", ErrMFAFailed } // No webauthn tokens registered for the current user, so normal authentication is now complete @@ -186,28 +193,27 @@ func (o *orm) CreateSession(ctx context.Context, sr sessions.SessionRequest) (st options, webauthnError := sessions.BeginWebAuthnLogin(user, uwas, sr) if webauthnError != nil { lggr.Errorf("Could not begin WebAuthn verification: %v", webauthnError) - return "", pkgerrors.New("MFA Error") + return "", ErrMFAFailed } j, jsonError := json.Marshal(options) if jsonError != nil { lggr.Errorf("Could not serialize WebAuthn challenge: %v", jsonError) - return "", pkgerrors.New("MFA Error") + return "", ErrMFAFailed } - return "", pkgerrors.New(string(j)) + return "", errors.New(string(j)) } // The user is at the final stage of logging in with MFA. We have an // attestation back from the user, we now need to verify that it is // correct. err = sessions.FinishWebAuthnLogin(user, uwas, sr) - if err != nil { // The user does have WebAuthn enabled but failed the check o.auditLogger.Audit(audit.AuthLoginFailed2FA, map[string]any{"email": sr.Email, "error": err}) lggr.Errorf("User sent an invalid attestation: %v", err) - return "", pkgerrors.New("MFA Error") + return "", ErrMFAFailed } lggr.Infof("User passed MFA authentication and login will proceed") @@ -261,13 +267,13 @@ func (o *orm) UpdateRole(ctx context.Context, email, newRole string) (sessions.U var userToEdit sessions.User if newRole == "" { - return userToEdit, pkgerrors.New("user role must be specified") + return userToEdit, errors.New("user role must be specified") } err := sqlutil.TransactDataSource(ctx, o.ds, nil, func(tx sqlutil.DataSource) error { // First, attempt to load specified user by email if err := tx.GetContext(ctx, &userToEdit, "SELECT * FROM users WHERE lower(email) = lower($1)", email); err != nil { - return pkgerrors.New("no matching user for provided email") + return errors.New("no matching user for provided email") } // Patch validated role @@ -280,13 +286,13 @@ func (o *orm) UpdateRole(ctx context.Context, email, newRole string) (sessions.U _, err = tx.ExecContext(ctx, "DELETE FROM sessions WHERE email = lower($1)", email) if err != nil { o.lggr.Errorw("Failed to purge user sessions for UpdateRole", "err", err) - return pkgerrors.New("error updating API user") + return errors.New("error updating API user") } sql := "UPDATE users SET role = $1, updated_at = now() WHERE lower(email) = lower($2) RETURNING *" if err := tx.GetContext(ctx, &userToEdit, sql, userToEdit.Role, email); err != nil { o.lggr.Errorw("Error updating API user", "err", err) - return pkgerrors.New("error updating API user") + return errors.New("error updating API user") } return nil @@ -306,13 +312,13 @@ func (o *orm) SetPassword(ctx context.Context, user *sessions.User, newPassword } // TestPassword checks plaintext user provided password with hashed database password, returns nil if matched -func (o *orm) TestPassword(ctx context.Context, email string, password string) error { +func (o *orm) TestPassword(ctx context.Context, email, password string) error { var hashedPassword string if err := o.ds.GetContext(ctx, &hashedPassword, "SELECT hashed_password FROM users WHERE lower(email) = lower($1)", email); err != nil { - return pkgerrors.New("no matching user for provided email") + return errors.New("no matching user for provided email") } if !utils.CheckPasswordHash(password, hashedPassword) { - return pkgerrors.New("passwords don't match") + return errors.New("passwords don't match") } return nil } @@ -333,7 +339,7 @@ func (o *orm) SetAuthToken(ctx context.Context, user *sessions.User, token *auth salt := utils.NewSecret(utils.DefaultSecretSize) hashedSecret, err := auth.HashedSecret(token, salt) if err != nil { - return pkgerrors.Wrap(err, "user") + return fmt.Errorf("user: %w", err) } sql := "UPDATE users SET token_salt = $1, token_key = $2, token_hashed_secret = $3, updated_at = now() WHERE email = $4 RETURNING *" return o.ds.GetContext(ctx, user, sql, salt, token.AccessKey, hashedSecret, user.Email) @@ -356,9 +362,9 @@ func (o *orm) SaveWebAuthn(ctx context.Context, token *sessions.WebAuthn) error func (o *orm) Sessions(ctx context.Context, offset, limit int) (sessions []sessions.Session, err error) { sql := `SELECT * FROM sessions ORDER BY created_at, id LIMIT $1 OFFSET $2;` if err = o.ds.SelectContext(ctx, &sessions, sql, limit, offset); err != nil { - return + return sessions, err } - return + return sessions, err } // NOTE: this is duplicated from the bridges ORM to appease the AuthStorer interface diff --git a/core/sessions/localauth/orm_test.go b/core/sessions/localauth/orm_test.go index 07ee6199197..1ea50bb4317 100644 --- a/core/sessions/localauth/orm_test.go +++ b/core/sessions/localauth/orm_test.go @@ -11,10 +11,10 @@ import ( "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink/v2/core/auth" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" - "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/logger/audit" "github.com/smartcontractkit/chainlink/v2/core/sessions" "github.com/smartcontractkit/chainlink/v2/core/sessions/localauth" @@ -25,7 +25,7 @@ func setupORM(t *testing.T) (*sqlx.DB, sessions.AuthenticationProvider) { t.Helper() db := pgtest.NewSqlxDB(t) - orm := localauth.NewORM(db, time.Minute, logger.TestLogger(t), &audit.AuditLoggerService{}) + orm := localauth.NewORM(db, time.Minute, logger.TestSugared(t), &audit.LoggerService{}) return db, orm } @@ -68,7 +68,7 @@ func TestORM_AuthorizedUserWithSession(t *testing.T) { t.Run(test.name, func(t *testing.T) { ctx := t.Context() db := pgtest.NewSqlxDB(t) - orm := localauth.NewORM(db, test.sessionDuration, logger.TestLogger(t), &audit.AuditLoggerService{}) + orm := localauth.NewORM(db, test.sessionDuration, logger.TestSugared(t), &audit.LoggerService{}) user := cltest.MustRandomUser(t) require.NoError(t, orm.CreateUser(ctx, &user)) @@ -129,7 +129,7 @@ func TestORM_DeleteUserSession(t *testing.T) { require.NoError(t, err) sessions, err := orm.Sessions(ctx, 0, 10) - assert.NoError(t, err) + require.NoError(t, err) require.Empty(t, sessions) } @@ -151,7 +151,7 @@ func TestORM_DeleteUserCascade(t *testing.T) { require.Error(t, err) sessions, err := orm.Sessions(ctx, 0, 10) - assert.NoError(t, err) + require.NoError(t, err) require.Empty(t, sessions) } @@ -266,7 +266,7 @@ func TestORM_WebAuthn(t *testing.T) { Password: cltest.Password, }) require.Error(t, err) - require.ErrorContains(t, err, "MFA Error") + require.ErrorIs(t, err, localauth.ErrMFAFailed) ss := sessions.NewWebAuthnSessionStore() _, err = orm.CreateSession(ctx, sessions.SessionRequest{ @@ -294,7 +294,7 @@ func TestORM_WebAuthn(t *testing.T) { WebAuthnData: "invalid-format", }) require.Error(t, err) - require.ErrorContains(t, err, "MFA Error") + require.ErrorIs(t, err, localauth.ErrMFAFailed) challengeResp, err := json.Marshal(protocol.CredentialAssertionResponse{ PublicKeyCredential: protocol.PublicKeyCredential{ diff --git a/core/sessions/localauth/reaper.go b/core/sessions/localauth/reaper.go index 6f2bfe732c5..eee05a8f876 100644 --- a/core/sessions/localauth/reaper.go +++ b/core/sessions/localauth/reaper.go @@ -5,15 +5,15 @@ import ( "time" commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink-common/pkg/utils" - "github.com/smartcontractkit/chainlink/v2/core/logger" ) type sessionReaper struct { ds sqlutil.DataSource config SessionReaperConfig - lggr logger.Logger + lggr logger.SugaredLogger } type SessionReaperConfig interface { @@ -26,7 +26,7 @@ func NewSessionReaper(ds sqlutil.DataSource, config SessionReaperConfig, lggr lo return utils.NewSleeperTaskCtx(&sessionReaper{ ds, config, - lggr.Named("SessionReaper"), + logger.Sugared(lggr).Named("SessionReaper"), }) } @@ -34,7 +34,8 @@ func (sr *sessionReaper) Name() string { return sr.lggr.Name() } func (sr *sessionReaper) Work(ctx context.Context) { recordCreationStaleThreshold := sr.config.SessionReaperExpiration().Before( - sr.config.SessionTimeout().Before(time.Now())) + sr.config.SessionTimeout().Before(time.Now()), + ) err := sr.deleteStaleSessions(ctx, recordCreationStaleThreshold) if err != nil { sr.lggr.Error("unable to reap stale sessions: ", err) diff --git a/core/sessions/localauth/reaper_test.go b/core/sessions/localauth/reaper_test.go index 65631998553..89ad77b4482 100644 --- a/core/sessions/localauth/reaper_test.go +++ b/core/sessions/localauth/reaper_test.go @@ -9,9 +9,9 @@ import ( "github.com/stretchr/testify/require" commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" - "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/logger/audit" "github.com/smartcontractkit/chainlink/v2/core/sessions" "github.com/smartcontractkit/chainlink/v2/core/sessions/localauth" @@ -32,7 +32,7 @@ func TestSessionReaper_ReapSessions(t *testing.T) { db := pgtest.NewSqlxDB(t) config := sessionReaperConfig{} - lggr := logger.TestLogger(t) + lggr := logger.TestSugared(t) orm := localauth.NewORM(db, config.SessionTimeout().Duration(), lggr, audit.NoopLogger) r := localauth.NewSessionReaper(db, config, lggr) diff --git a/core/sessions/oidcauth/helpers_test.go b/core/sessions/oidcauth/helpers_test.go index 742009c1750..ac6ffc696a2 100644 --- a/core/sessions/oidcauth/helpers_test.go +++ b/core/sessions/oidcauth/helpers_test.go @@ -9,9 +9,9 @@ import ( "golang.org/x/oauth2" commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink/v2/core/config" - "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/logger/audit" ) @@ -20,7 +20,7 @@ func NewTestOIDCAuthenticator( ds sqlutil.DataSource, oidcCfg config.OIDC, lggr logger.Logger, - auditLogger audit.AuditLogger, + auditLogger audit.Logger, ) (*oidcAuthenticator, error) { var provider *oidc.Provider var oidcConfig *oidc.Config @@ -51,7 +51,7 @@ func NewTestOIDCAuthenticator( provider: provider, oidcConfig: oidcConfig, oauth2Config: oauth2Config, - lggr: lggr.Named("OIDCAuthenticationProvider"), + lggr: logger.Sugared(lggr).Named("OIDCAuthenticationProvider"), auditLogger: auditLogger, } @@ -82,8 +82,7 @@ const ( ) // Implements config.OIDC -type TestConfig struct { -} +type TestConfig struct{} func (t *TestConfig) ClientID() string { return "abcd1234" diff --git a/core/sessions/oidcauth/oidc.go b/core/sessions/oidcauth/oidc.go index bc66a344dc1..cc7dd40eefb 100644 --- a/core/sessions/oidcauth/oidc.go +++ b/core/sessions/oidcauth/oidc.go @@ -23,12 +23,12 @@ import ( "github.com/gin-gonic/gin" "golang.org/x/oauth2" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink-common/pkg/utils/mathutil" "github.com/smartcontractkit/chainlink/v2/core/auth" "github.com/smartcontractkit/chainlink/v2/core/bridges" "github.com/smartcontractkit/chainlink/v2/core/config" - "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/logger/audit" clsessions "github.com/smartcontractkit/chainlink/v2/core/sessions" "github.com/smartcontractkit/chainlink/v2/core/utils" @@ -47,8 +47,8 @@ type oidcAuthenticator struct { provider *oidc.Provider oidcConfig *oidc.Config oauth2Config *oauth2.Config - lggr logger.Logger - auditLogger audit.AuditLogger + lggr logger.SugaredLogger + auditLogger audit.Logger } // ExchangeTokenRequest represents the expected JSON payload from the frontend @@ -70,7 +70,7 @@ func NewOIDCAuthenticator( ds sqlutil.DataSource, oidcCfg config.OIDC, lggr logger.Logger, - auditLogger audit.AuditLogger, + auditLogger audit.Logger, ) (*oidcAuthenticator, error) { // Ensure all RBAC role mappings to OIDC Id claims are defined, and required fields populated, or error on startup lggr.Debugf("OIDC CFG:\n %#v\n", oidcCfg) @@ -124,7 +124,7 @@ func NewOIDCAuthenticator( provider: provider, oidcConfig: oidcConfig, oauth2Config: oauth2Config, - lggr: lggr.Named("OIDCAuthenticationProvider"), + lggr: logger.Sugared(lggr).Named("OIDCAuthenticationProvider"), auditLogger: auditLogger, } @@ -454,7 +454,7 @@ func (oi *oidcAuthenticator) CreateUser(ctx context.Context, user *clsessions.Us } // UpdateRole is not supported for read only OIDC -func (oi *oidcAuthenticator) UpdateRole(ctx context.Context, email string, newRole string) (clsessions.User, error) { +func (oi *oidcAuthenticator) UpdateRole(ctx context.Context, email, newRole string) (clsessions.User, error) { return clsessions.User{}, clsessions.ErrNotSupported } @@ -485,7 +485,7 @@ func (oi *oidcAuthenticator) SetPassword(ctx context.Context, user *clsessions.U } // TestPassword only supports the potential local admin user, as there is no queryable identity server for the OIDC implementation -func (oi *oidcAuthenticator) TestPassword(ctx context.Context, email string, password string) error { +func (oi *oidcAuthenticator) TestPassword(ctx context.Context, email, password string) error { // Fall back to test local users table in case of supported local CLI users as well var hashedPassword string if err := oi.ds.GetContext(ctx, &hashedPassword, "SELECT hashed_password FROM users WHERE lower(email) = lower($1)", email); err != nil { @@ -563,7 +563,7 @@ func (oi *oidcAuthenticator) Sessions(ctx context.Context, offset, limit int) ([ var sessions []clsessions.Session sql := `SELECT * FROM oidc_sessions ORDER BY created_at, id LIMIT $1 OFFSET $2;` if err := oi.ds.SelectContext(ctx, &sessions, sql, limit, offset); err != nil { - return sessions, nil + return nil, err } return sessions, nil } @@ -596,7 +596,7 @@ func (oi *oidcAuthenticator) localLoginFallback(ctx context.Context, sr clsessio return user, nil } -func (oi *oidcAuthenticator) IDClaimsToUserRole(idClaims []string, adminClaim string, editClaim string, runClaim string, readClaim string) (clsessions.UserRole, error) { +func (oi *oidcAuthenticator) IDClaimsToUserRole(idClaims []string, adminClaim, editClaim, runClaim, readClaim string) (clsessions.UserRole, error) { // If defined Admin group name is present in id claims, return UserRoleAdmin if slices.Contains(idClaims, adminClaim) { return clsessions.UserRoleAdmin, nil diff --git a/core/sessions/oidcauth/oidc_test.go b/core/sessions/oidcauth/oidc_test.go index 3d935c2efd1..ccfbc4c81f0 100644 --- a/core/sessions/oidcauth/oidc_test.go +++ b/core/sessions/oidcauth/oidc_test.go @@ -11,9 +11,9 @@ import ( "github.com/jmoiron/sqlx" "github.com/stretchr/testify/require" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink/v2/core/internal/cltest" "github.com/smartcontractkit/chainlink/v2/core/internal/testutils/pgtest" - "github.com/smartcontractkit/chainlink/v2/core/logger" "github.com/smartcontractkit/chainlink/v2/core/logger/audit" "github.com/smartcontractkit/chainlink/v2/core/sessions" "github.com/smartcontractkit/chainlink/v2/core/sessions/oidcauth" @@ -25,7 +25,7 @@ func setupAuthenticationProvider(t *testing.T) (*sqlx.DB, sessions.Authenticatio cfg := oidcauth.TestConfig{} db := pgtest.NewSqlxDB(t) - oidcAuthProvider, err := oidcauth.NewTestOIDCAuthenticator(db, &cfg, logger.TestLogger(t), &audit.AuditLoggerService{}) + oidcAuthProvider, err := oidcauth.NewTestOIDCAuthenticator(db, &cfg, logger.TestSugared(t), &audit.LoggerService{}) if err != nil { t.Fatalf("Error constructing NewTestoidcAuthenticator: %v\n", err) } @@ -343,7 +343,7 @@ func Test_IDClaimsToUserRole(t *testing.T) { t.Parallel() cfg := oidcauth.TestConfig{} db := pgtest.NewSqlxDB(t) - oidcAuthProvider, err := oidcauth.NewTestOIDCAuthenticator(db, &cfg, logger.TestLogger(t), &audit.AuditLoggerService{}) + oidcAuthProvider, err := oidcauth.NewTestOIDCAuthenticator(db, &cfg, logger.TestSugared(t), &audit.LoggerService{}) require.NoError(t, err) tests := []struct { @@ -416,7 +416,7 @@ func Test_ExtractIDClaimValues(t *testing.T) { t.Parallel() cfg := oidcauth.TestConfig{} db := pgtest.NewSqlxDB(t) - oidcAuthProvider, err := oidcauth.NewTestOIDCAuthenticator(db, &cfg, logger.TestLogger(t), &audit.AuditLoggerService{}) + oidcAuthProvider, err := oidcauth.NewTestOIDCAuthenticator(db, &cfg, logger.TestSugared(t), &audit.LoggerService{}) require.NoError(t, err) tests := []struct { name string diff --git a/core/sessions/oidcauth/reaper.go b/core/sessions/oidcauth/reaper.go index eca436eb6bb..6210e6252e1 100644 --- a/core/sessions/oidcauth/reaper.go +++ b/core/sessions/oidcauth/reaper.go @@ -5,15 +5,15 @@ import ( "time" commonconfig "github.com/smartcontractkit/chainlink-common/pkg/config" + "github.com/smartcontractkit/chainlink-common/pkg/logger" "github.com/smartcontractkit/chainlink-common/pkg/sqlutil" "github.com/smartcontractkit/chainlink-common/pkg/utils" - "github.com/smartcontractkit/chainlink/v2/core/logger" ) type sessionReaper struct { ds sqlutil.DataSource config SessionReaperConfig - lggr logger.Logger + lggr logger.SugaredLogger } type SessionReaperConfig interface { @@ -26,7 +26,7 @@ func NewSessionReaper(ds sqlutil.DataSource, config SessionReaperConfig, lggr lo return utils.NewSleeperTaskCtx(&sessionReaper{ ds, config, - lggr.Named("OIDCSessionReaper"), + logger.Sugared(lggr).Named("OIDCSessionReaper"), }) } @@ -36,7 +36,8 @@ func (sr *sessionReaper) Name() string { func (sr *sessionReaper) Work(ctx context.Context) { recordCreationStaleThreshold := sr.config.SessionReaperExpiration().Before( - sr.config.SessionTimeout().Before(time.Now())) + sr.config.SessionTimeout().Before(time.Now()), + ) err := sr.deleteStaleSessions(ctx, recordCreationStaleThreshold) if err != nil { sr.lggr.Error("unable to reap stale sessions: ", err) diff --git a/core/sessions/user_test.go b/core/sessions/user_test.go index 962f8770639..280c90dea53 100644 --- a/core/sessions/user_test.go +++ b/core/sessions/user_test.go @@ -41,7 +41,7 @@ func TestNewUser(t *testing.T) { if test.wantError { assert.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) assert.Equal(t, test.email, user.Email) assert.Equal(t, test.role, user.Role) assert.NotEmpty(t, user.HashedPassword) @@ -64,13 +64,13 @@ func TestAuthenticateUserByToken(t *testing.T) { var user sessions.User token, err := user.GenerateAuthToken() - assert.NoError(t, err, "failed when generate auth token") + require.NoError(t, err, "failed when generate auth token") ok, err := sessions.AuthenticateUserByToken(token, &user) require.NoError(t, err) assert.True(t, ok, "authentication must be successful") _, err = user.GenerateAuthToken() - assert.NoError(t, err, "failed to generate auth token") + require.NoError(t, err, "failed to generate auth token") ok, err = sessions.AuthenticateUserByToken(token, &user) require.NoError(t, err) assert.False(t, ok, "authentication must fail with past token") diff --git a/core/sessions/webauthn.go b/core/sessions/webauthn.go index cb362b0903d..28ec6a5a9a2 100644 --- a/core/sessions/webauthn.go +++ b/core/sessions/webauthn.go @@ -3,6 +3,7 @@ package sessions import ( "context" "encoding/json" + "errors" "fmt" "net/http" "strings" @@ -11,7 +12,6 @@ import ( "github.com/go-webauthn/webauthn/protocol" "github.com/go-webauthn/webauthn/webauthn" sqlxTypes "github.com/jmoiron/sqlx/types" - pkgerrors "github.com/pkg/errors" ) // WebAuthn holds the credentials for API user. @@ -32,13 +32,24 @@ type WebAuthnConfiguration struct { RPOrigin string } +// rpOrigins converts a single configured origin into the []string form the +// go-webauthn library now requires (RPOrigin is deprecated), preserving the +// library's own validation: an empty origin still results in a construction- +// time error from webauthn.New rather than silently accepting an empty +// string as a valid origin entry. +func rpOrigins(origin string) []string { + if origin == "" { + return nil + } + return []string{origin} +} + func (store *WebAuthnSessionStore) BeginWebAuthnRegistration(user User, uwas []WebAuthn, config WebAuthnConfiguration) (*protocol.CredentialCreation, error) { webAuthn, err := webauthn.New(&webauthn.Config{ - RPDisplayName: "Chainlink Operator", // Display Name - RPID: config.RPID, // Generally the domain name - RPOrigin: config.RPOrigin, // The origin URL for WebAuthn requests + RPDisplayName: "Chainlink Operator", // Display Name + RPID: config.RPID, // Generally the domain name + RPOrigins: rpOrigins(config.RPOrigin), // The origin URLs for WebAuthn requests }) - if err != nil { return nil, err } @@ -57,7 +68,6 @@ func (store *WebAuthnSessionStore) BeginWebAuthnRegistration(user User, uwas []W waUser, registerOptions, ) - if err != nil { return nil, err } @@ -73,9 +83,9 @@ func (store *WebAuthnSessionStore) BeginWebAuthnRegistration(user User, uwas []W func (store *WebAuthnSessionStore) FinishWebAuthnRegistration(user User, uwas []WebAuthn, response *http.Request, config WebAuthnConfiguration) (*webauthn.Credential, error) { webAuthn, err := webauthn.New(&webauthn.Config{ - RPDisplayName: "Chainlink Operator", // Display Name - RPID: config.RPID, // Generally the domain name - RPOrigin: config.RPOrigin, // The origin URL for WebAuthn requests + RPDisplayName: "Chainlink Operator", // Display Name + RPID: config.RPID, // Generally the domain name + RPOrigins: rpOrigins(config.RPOrigin), // The origin URLs for WebAuthn requests }) if err != nil { return nil, err @@ -94,7 +104,7 @@ func (store *WebAuthnSessionStore) FinishWebAuthnRegistration(user User, uwas [] credential, err := webAuthn.FinishRegistration(waUser, sessionData, response) if err != nil { - return nil, pkgerrors.Wrap(err, "failed to FinishRegistration") + return nil, fmt.Errorf("failed to FinishRegistration: %w", err) } return credential, nil @@ -102,11 +112,10 @@ func (store *WebAuthnSessionStore) FinishWebAuthnRegistration(user User, uwas [] func BeginWebAuthnLogin(user User, uwas []WebAuthn, sr SessionRequest) (*protocol.CredentialAssertion, error) { webAuthn, err := webauthn.New(&webauthn.Config{ - RPDisplayName: "Chainlink Operator", // Display Name - RPID: sr.WebAuthnConfig.RPID, // Generally the domain name - RPOrigin: sr.WebAuthnConfig.RPOrigin, // The origin URL for WebAuthn requests + RPDisplayName: "Chainlink Operator", // Display Name + RPID: sr.WebAuthnConfig.RPID, // Generally the domain name + RPOrigins: rpOrigins(sr.WebAuthnConfig.RPOrigin), // The origin URLs for WebAuthn requests }) - if err != nil { return nil, err } @@ -132,13 +141,12 @@ func BeginWebAuthnLogin(user User, uwas []WebAuthn, sr SessionRequest) (*protoco func FinishWebAuthnLogin(user User, uwas []WebAuthn, sr SessionRequest) error { webAuthn, err := webauthn.New(&webauthn.Config{ - RPDisplayName: "Chainlink Operator", // Display Name - RPID: sr.WebAuthnConfig.RPID, // Generally the domain name - RPOrigin: sr.WebAuthnConfig.RPOrigin, // The origin URL for WebAuthn requests + RPDisplayName: "Chainlink Operator", // Display Name + RPID: sr.WebAuthnConfig.RPID, // Generally the domain name + RPOrigins: rpOrigins(sr.WebAuthnConfig.RPOrigin), // The origin URLs for WebAuthn requests }) - if err != nil { - return pkgerrors.Wrapf(err, "failed to create webAuthn structure with RPID: %s and RPOrigin: %s", sr.WebAuthnConfig.RPID, sr.WebAuthnConfig.RPOrigin) + return fmt.Errorf("failed to create webAuthn structure with RPID: %s and RPOrigin: %s: %w", sr.WebAuthnConfig.RPID, sr.WebAuthnConfig.RPOrigin, err) } credential, err := protocol.ParseCredentialRequestResponseBody(strings.NewReader(sr.WebAuthnData)) @@ -162,37 +170,37 @@ func FinishWebAuthnLogin(user User, uwas []WebAuthn, sr SessionRequest) error { } // WebAuthnID returns the user's ID -func (u WebAuthnUser) WebAuthnID() []byte { +func (u *WebAuthnUser) WebAuthnID() []byte { return []byte(u.Email) } // WebAuthnName returns the user's email -func (u WebAuthnUser) WebAuthnName() string { +func (u *WebAuthnUser) WebAuthnName() string { return u.Email } // WebAuthnDisplayName returns the user's display name. // In this case we just return the email -func (u WebAuthnUser) WebAuthnDisplayName() string { +func (u *WebAuthnUser) WebAuthnDisplayName() string { return u.Email } // WebAuthnIcon should be the logo in some form. How it should // be is currently unclear to me. -func (u WebAuthnUser) WebAuthnIcon() string { +func (u *WebAuthnUser) WebAuthnIcon() string { return "" } // WebAuthnCredentials returns credentials owned by the user -func (u WebAuthnUser) WebAuthnCredentials() []webauthn.Credential { +func (u *WebAuthnUser) WebAuthnCredentials() []webauthn.Credential { return u.WACredentials } // CredentialExcludeList returns a CredentialDescriptor array filled // with all the user's credentials to prevent them from re-registering // keys -func (u WebAuthnUser) CredentialExcludeList() []protocol.CredentialDescriptor { - credentialExcludeList := []protocol.CredentialDescriptor{} +func (u *WebAuthnUser) CredentialExcludeList() []protocol.CredentialDescriptor { + credentialExcludeList := make([]protocol.CredentialDescriptor, 0, len(u.WACredentials)) for _, cred := range u.WACredentials { descriptor := protocol.CredentialDescriptor{ @@ -217,13 +225,13 @@ func (u *WebAuthnUser) LoadWebAuthnCredentials(uwas []WebAuthn) error { return nil } -func duoWebAuthUserFromUser(user User, uwas []WebAuthn) (WebAuthnUser, error) { +func duoWebAuthUserFromUser(user User, uwas []WebAuthn) (*WebAuthnUser, error) { waUser := WebAuthnUser{ Email: user.Email, } err := waUser.LoadWebAuthnCredentials(uwas) - return waUser, err + return &waUser, err } // WebAuthnSessionStore is a wrapper around an in memory key value store which provides some helper @@ -265,7 +273,7 @@ func (store *WebAuthnSessionStore) take(key string) (val string, ok bool) { if ok { delete(store.inProgressRegistrations, key) } - return + return val, ok } // GetWebauthnSession unmarshals and returns the webauthn session information @@ -273,11 +281,11 @@ func (store *WebAuthnSessionStore) take(key string) (val string, ok bool) { func (store *WebAuthnSessionStore) GetWebauthnSession(key string) (data webauthn.SessionData, err error) { assertion, ok := store.take(key) if !ok { - err = pkgerrors.New("assertion not in challenge store") - return + err = errors.New("assertion not in challenge store") + return data, err } err = json.Unmarshal([]byte(assertion), &data) - return + return data, err } func AddCredentialToUser(ctx context.Context, ap AuthenticationProvider, email string, credential *webauthn.Credential) error { diff --git a/core/sessions/webauthn_test.go b/core/sessions/webauthn_test.go index 34797738492..6bc72041927 100644 --- a/core/sessions/webauthn_test.go +++ b/core/sessions/webauthn_test.go @@ -44,7 +44,7 @@ func TestWebAuthnSessionStore(t *testing.T) { require.False(t, ok) _, err = s.GetWebauthnSession(key) - assert.ErrorContains(t, err, "assertion not in challenge store") + require.ErrorContains(t, err, "assertion not in challenge store") user := mustRandomUser(t) cred := webauthn.Credential{ @@ -72,6 +72,20 @@ func TestWebAuthnSessionStore(t *testing.T) { require.Error(t, err) } +func TestBeginWebAuthnRegistration_EmptyRPOrigin(t *testing.T) { + t.Parallel() + + s := NewWebAuthnSessionStore() + user := mustRandomUser(t) + + // An empty RPOrigin must still fail at construction time, matching + // go-webauthn's own validation, rather than silently producing a + // RelyingParty with no allowed origins. + wcfg := WebAuthnConfiguration{RPID: "test-rpid", RPOrigin: ""} + _, err := s.BeginWebAuthnRegistration(user, nil, wcfg) + require.ErrorContains(t, err, "RPOrigins") +} + func mustRandomUser(t testing.TB) User { email := fmt.Sprintf("user-%v@chainlink.test", mrand.Int63()) r, err := NewUser(email, testutils.Password, UserRoleAdmin) diff --git a/core/store/doc.go b/core/store/doc.go index e3032901b5e..749519ed5a4 100644 --- a/core/store/doc.go +++ b/core/store/doc.go @@ -24,7 +24,7 @@ // # Store // // The Store is the persistence layer for the application. It saves the -// the application state and most interaction with the node needs to occur +// application state and most interaction with the node needs to occur // through the store. // // # Tx Manager diff --git a/core/store/migrate/migrate.go b/core/store/migrate/migrate.go index 80c8e319859..ceef05b46cb 100644 --- a/core/store/migrate/migrate.go +++ b/core/store/migrate/migrate.go @@ -4,13 +4,14 @@ import ( "context" "database/sql" "embed" + "errors" "fmt" "io/fs" "os" "strconv" "strings" - pkgerrors "github.com/pkg/errors" + "github.com/jackc/pgx/v5/pgconn" "github.com/pressly/goose/v3" "github.com/pressly/goose/v3/database" "gopkg.in/guregu/null.v4" @@ -90,8 +91,12 @@ func ensureMigrated(ctx context.Context, db *sql.DB, p *goose.Provider, provider var names []string err = sqlxDB.SelectContext(ctx, &names, `SELECT id FROM migrations`) if err != nil { - // already migrated - return nil + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) && pgErr.Code == "42P01" { + // legacy migrations table absent: already migrated (or fresh DB) + return nil + } + return fmt.Errorf("failed to read legacy migrations table: %w", err) } // ensure that no legacy job specs are present: we _must_ bail out early if // so because otherwise we run the risk of dropping working jobs if the @@ -109,7 +114,7 @@ func ensureMigrated(ctx context.Context, db *sql.DB, p *goose.Provider, provider } } if !found { - return pkgerrors.New("database state is too old. Need to migrate to chainlink version 0.9.10 first before upgrading to this version. This upgrade is NOT REVERSIBLE, so it is STRONGLY RECOMMENDED that you take a database backup before continuing") + return errors.New("database state is too old. Need to migrate to chainlink version 0.9.10 first before upgrading to this version. This upgrade is NOT REVERSIBLE, so it is STRONGLY RECOMMENDED that you take a database backup before continuing") } // ensure a goose migrations table exists with it's initial v0 @@ -134,7 +139,7 @@ func ensureMigrated(ctx context.Context, db *sql.DB, p *goose.Provider, provider id, err = strconv.ParseInt(before, 10, 64) if err == nil && id <= 0 { - return pkgerrors.New("migration IDs must be greater than zero") + return errors.New("migration IDs must be greater than zero") } } @@ -202,7 +207,7 @@ func SetMigrationENVVars(generalConfig toml.EVMConfigs) error { if generalConfig.Enabled() { err := os.Setenv(env.EVMChainIDNotNullMigration0195, generalConfig[0].ChainID.String()) if err != nil { - panic(pkgerrors.Wrap(err, "failed to set migrations env variables")) + panic(fmt.Errorf("failed to set migrations env variables: %w", err)) } } return nil diff --git a/core/store/migrate/migrate_test.go b/core/store/migrate/migrate_test.go index 57e9f16156b..c5da283da48 100644 --- a/core/store/migrate/migrate_test.go +++ b/core/store/migrate/migrate_test.go @@ -207,10 +207,10 @@ func TestMigrate_0100_BootstrapConfigs(t *testing.T) { require.NoError(t, err) sql = `INSERT INTO bootstrap_specs (contract_id, relay, relay_config, monitoring_endpoint, - blockchain_timeout, contract_config_tracker_poll_interval, + blockchain_timeout, contract_config_tracker_poll_interval, contract_config_confirmations, created_at, updated_at) - VALUES ( :contract_id, :relay, :relay_config, :monitoring_endpoint, - :blockchain_timeout, :contract_config_tracker_poll_interval, + VALUES ( :contract_id, :relay, :relay_config, :monitoring_endpoint, + :blockchain_timeout, :contract_config_tracker_poll_interval, :contract_config_confirmations, NOW(), NOW()) RETURNING id;` @@ -328,8 +328,8 @@ func TestMigrate_0100_BootstrapConfigs(t *testing.T) { var jobsAndContracts []jobIDAndContractID sql = `SELECT jobs.id, ocr2.contract_id -FROM jobs -INNER JOIN offchainreporting2_oracle_specs as ocr2 +FROM jobs +INNER JOIN offchainreporting2_oracle_specs as ocr2 ON jobs.offchainreporting2_oracle_spec_id = ocr2.id` err = db.Select(&jobsAndContracts, sql) require.NoError(t, err) @@ -505,7 +505,7 @@ func BenchmarkBackfillingRecordsWithMigration202(b *testing.B) { _, err = db.NamedExecContext(ctx, ` INSERT INTO evm.log_poller_blocks (evm_chain_id, block_hash, block_number, finalized_block_number, block_timestamp, created_at) - VALUES + VALUES (:evm_chain_id, :block_hash, :block_number, :finalized_block_number, NOW(), NOW()) ON CONFLICT DO NOTHING`, blocks[start:end]) require.NoError(b, err) diff --git a/core/store/models/common.go b/core/store/models/common.go index 5c05686b08a..a04d1e0d151 100644 --- a/core/store/models/common.go +++ b/core/store/models/common.go @@ -4,7 +4,7 @@ import ( "bytes" "database/sql/driver" "encoding/json" - stderrors "errors" + "errors" "fmt" "maps" "net/url" @@ -13,7 +13,6 @@ import ( "time" "github.com/ethereum/go-ethereum/common" - "github.com/pkg/errors" "github.com/robfig/cron/v3" "github.com/tidwall/gjson" @@ -307,7 +306,7 @@ func (sh *ServiceHeaders) UnmarshalText(input []byte) error { for header := range headerLines { keyValue := strings.Split(header, "||") if len(keyValue) != 2 { - return errors.Errorf("invalid headers provided for the audit logger. Value, single pair split on || required, got: %s", keyValue) + return fmt.Errorf("invalid headers provided for the audit logger. Value, single pair split on || required, got: %s", keyValue) } h := ServiceHeader{ Header: keyValue[0], @@ -356,13 +355,13 @@ var ( headerValueRegex = regexp.MustCompile("^[A-Za-z_ :;.,\\/\"'?!(){}[\\]@<>=\\-+*#$&`|~^%]+$") ) -func (h ServiceHeader) Validate() (err error) { +func (h *ServiceHeader) Validate() (err error) { if !headerNameRegex.MatchString(h.Header) { - err = stderrors.Join(err, errors.Errorf("invalid header name: %s", h.Header)) + err = errors.Join(err, fmt.Errorf("invalid header name: %s", h.Header)) } if !headerValueRegex.MatchString(h.Value) { - err = stderrors.Join(err, errors.Errorf("invalid header value: %s", h.Value)) + err = errors.Join(err, fmt.Errorf("invalid header value: %s", h.Value)) } - return + return err } diff --git a/core/utils/config/validate.go b/core/utils/config/validate.go index da3fa57d742..9bae4efb748 100644 --- a/core/utils/config/validate.go +++ b/core/utils/config/validate.go @@ -43,17 +43,27 @@ func (e DeprecatedError) Error() string { return fmt.Sprintf("%s: is deprecated and will be removed in %s", e.Name, when) } +// ErrInvalid is retained for backward compatibility. +// // Deprecated: use InvalidError instead. type ErrInvalid = InvalidError //nolint:errname // backward compatibility +// ErrMissing is retained for backward compatibility. +// // Deprecated: use MissingError instead. type ErrMissing = MissingError //nolint:errname // backward compatibility +// ErrEmpty is retained for backward compatibility. +// // Deprecated: use EmptyError instead. type ErrEmpty = EmptyError //nolint:errname // backward compatibility +// ErrOverride is retained for backward compatibility. +// // Deprecated: use OverrideError instead. type ErrOverride = OverrideError //nolint:errname // backward compatibility +// ErrDeprecated is retained for backward compatibility. +// // Deprecated: use DeprecatedError instead. type ErrDeprecated = DeprecatedError //nolint:errname // backward compatibility diff --git a/core/web/log_controller.go b/core/web/log_controller.go index 0a6a4e51a7d..71dc9021f50 100644 --- a/core/web/log_controller.go +++ b/core/web/log_controller.go @@ -97,9 +97,9 @@ func (cc *LogController) Patch(c *gin.Context) { if request.Level == "debug" { if request.SQLEnabled != nil && *request.SQLEnabled { - cc.App.GetAuditLogger().Audit(audit.ConfigSqlLoggingEnabled, map[string]any{}) + cc.App.GetAuditLogger().Audit(audit.ConfigSQLLoggingEnabled, map[string]any{}) } else { - cc.App.GetAuditLogger().Audit(audit.ConfigSqlLoggingDisabled, map[string]any{}) + cc.App.GetAuditLogger().Audit(audit.ConfigSQLLoggingDisabled, map[string]any{}) } } diff --git a/core/web/resolver/mutation.go b/core/web/resolver/mutation.go index bbd83b37915..c6e1355458c 100644 --- a/core/web/resolver/mutation.go +++ b/core/web/resolver/mutation.go @@ -4,12 +4,12 @@ import ( "context" "database/sql" "encoding/json" + "errors" "fmt" "net/url" "time" "github.com/graph-gophers/graphql-go" - "github.com/pkg/errors" "go.uber.org/zap/zapcore" "gopkg.in/guregu/null.v4" @@ -135,7 +135,8 @@ func (r *Resolver) CreateCSAKey(ctx context.Context) (*CreateCSAKeyPayloadResolv func (r *Resolver) DeleteCSAKey(ctx context.Context, args struct { ID graphql.ID -}) (*DeleteCSAKeyPayloadResolver, error) { +}, +) (*DeleteCSAKeyPayloadResolver, error) { if err := authenticateUserIsAdmin(ctx); err != nil { return nil, err } @@ -178,7 +179,8 @@ type createFeedsManagerChainConfigInput struct { func (r *Resolver) CreateFeedsManagerChainConfig(ctx context.Context, args struct { Input *createFeedsManagerChainConfigInput -}) (*CreateFeedsManagerChainConfigPayloadResolver, error) { +}, +) (*CreateFeedsManagerChainConfigPayloadResolver, error) { if err := authenticateUserCanEdit(ctx); err != nil { return nil, err } @@ -263,7 +265,8 @@ func (r *Resolver) CreateFeedsManagerChainConfig(ctx context.Context, args struc func (r *Resolver) DeleteFeedsManagerChainConfig(ctx context.Context, args struct { ID string -}) (*DeleteFeedsManagerChainConfigPayloadResolver, error) { +}, +) (*DeleteFeedsManagerChainConfigPayloadResolver, error) { if err := authenticateUserCanEdit(ctx); err != nil { return nil, err } @@ -319,7 +322,8 @@ type updateFeedsManagerChainConfigInput struct { func (r *Resolver) UpdateFeedsManagerChainConfig(ctx context.Context, args struct { ID string Input *updateFeedsManagerChainConfigInput -}) (*UpdateFeedsManagerChainConfigPayloadResolver, error) { +}, +) (*UpdateFeedsManagerChainConfigPayloadResolver, error) { if err := authenticateUserCanEdit(ctx); err != nil { return nil, err } @@ -403,7 +407,8 @@ type createFeedsManagerInput struct { func (r *Resolver) CreateFeedsManager(ctx context.Context, args struct { Input *createFeedsManagerInput -}) (*CreateFeedsManagerPayloadResolver, error) { +}, +) (*CreateFeedsManagerPayloadResolver, error) { if err := authenticateUserCanEdit(ctx); err != nil { return nil, err } @@ -457,7 +462,8 @@ type updateBridgeInput struct { func (r *Resolver) UpdateBridge(ctx context.Context, args struct { ID graphql.ID Input updateBridgeInput -}) (*UpdateBridgePayloadResolver, error) { +}, +) (*UpdateBridgePayloadResolver, error) { if err := authenticateUserCanEdit(ctx); err != nil { return nil, err } @@ -526,7 +532,8 @@ type updateFeedsManagerInput struct { func (r *Resolver) UpdateFeedsManager(ctx context.Context, args struct { ID graphql.ID Input *updateFeedsManagerInput -}) (*UpdateFeedsManagerPayloadResolver, error) { +}, +) (*UpdateFeedsManagerPayloadResolver, error) { if err := authenticateUserCanEdit(ctx); err != nil { return nil, err } @@ -635,7 +642,8 @@ func (r *Resolver) CreateOCRKeyBundle(ctx context.Context) (*CreateOCRKeyBundleP func (r *Resolver) DeleteOCRKeyBundle(ctx context.Context, args struct { ID string -}) (*DeleteOCRKeyBundlePayloadResolver, error) { +}, +) (*DeleteOCRKeyBundlePayloadResolver, error) { if err := authenticateUserIsAdmin(ctx); err != nil { return nil, err } @@ -654,7 +662,8 @@ func (r *Resolver) DeleteOCRKeyBundle(ctx context.Context, args struct { func (r *Resolver) DeleteBridge(ctx context.Context, args struct { ID graphql.ID -}) (*DeleteBridgePayloadResolver, error) { +}, +) (*DeleteBridgePayloadResolver, error) { if err := authenticateUserCanEdit(ctx); err != nil { return nil, err } @@ -714,7 +723,8 @@ func (r *Resolver) CreateP2PKey(ctx context.Context) (*CreateP2PKeyPayloadResolv func (r *Resolver) DeleteP2PKey(ctx context.Context, args struct { ID graphql.ID -}) (*DeleteP2PKeyPayloadResolver, error) { +}, +) (*DeleteP2PKeyPayloadResolver, error) { if err := authenticateUserIsAdmin(ctx); err != nil { return nil, err } @@ -762,14 +772,15 @@ func (r *Resolver) CreateVRFKey(ctx context.Context) (*CreateVRFKeyPayloadResolv func (r *Resolver) DeleteVRFKey(ctx context.Context, args struct { ID graphql.ID -}) (*DeleteVRFKeyPayloadResolver, error) { +}, +) (*DeleteVRFKeyPayloadResolver, error) { if err := authenticateUserIsAdmin(ctx); err != nil { return nil, err } key, err := r.App.GetKeyStore().VRF().Delete(ctx, string(args.ID)) if err != nil { - if errors.Is(errors.Cause(err), keystore.ErrMissingVRFKey) { + if errors.Is(err, keystore.ErrMissingVRFKey) { return NewDeleteVRFKeyPayloadResolver(vrfkey.KeyV2{}, err), nil } return nil, err @@ -787,7 +798,8 @@ func (r *Resolver) DeleteVRFKey(ctx context.Context, args struct { func (r *Resolver) ApproveJobProposalSpec(ctx context.Context, args struct { ID graphql.ID Force *bool -}) (*ApproveJobProposalSpecPayloadResolver, error) { +}, +) (*ApproveJobProposalSpecPayloadResolver, error) { if err := authenticateUserCanEdit(ctx); err != nil { return nil, err } @@ -826,7 +838,8 @@ func (r *Resolver) ApproveJobProposalSpec(ctx context.Context, args struct { // CancelJobProposalSpec cancels the job proposal spec. func (r *Resolver) CancelJobProposalSpec(ctx context.Context, args struct { ID graphql.ID -}) (*CancelJobProposalSpecPayloadResolver, error) { +}, +) (*CancelJobProposalSpecPayloadResolver, error) { if err := authenticateUserCanEdit(ctx); err != nil { return nil, err } @@ -861,7 +874,8 @@ func (r *Resolver) CancelJobProposalSpec(ctx context.Context, args struct { // RejectJobProposalSpec rejects the job proposal spec. func (r *Resolver) RejectJobProposalSpec(ctx context.Context, args struct { ID graphql.ID -}) (*RejectJobProposalSpecPayloadResolver, error) { +}, +) (*RejectJobProposalSpecPayloadResolver, error) { if err := authenticateUserCanEdit(ctx); err != nil { return nil, err } @@ -897,7 +911,8 @@ func (r *Resolver) RejectJobProposalSpec(ctx context.Context, args struct { func (r *Resolver) UpdateJobProposalSpecDefinition(ctx context.Context, args struct { ID graphql.ID Input *struct{ Definition string } -}) (*UpdateJobProposalSpecDefinitionPayloadResolver, error) { +}, +) (*UpdateJobProposalSpecDefinitionPayloadResolver, error) { if err := authenticateUserCanEdit(ctx); err != nil { return nil, err } @@ -933,7 +948,8 @@ func (r *Resolver) UpdateJobProposalSpecDefinition(ctx context.Context, args str func (r *Resolver) UpdateUserPassword(ctx context.Context, args struct { Input UpdatePasswordInput -}) (*UpdatePasswordPayloadResolver, error) { +}, +) (*UpdatePasswordPayloadResolver, error) { if err := authenticateUser(ctx); err != nil { return nil, err } @@ -971,7 +987,8 @@ func (r *Resolver) UpdateUserPassword(ctx context.Context, args struct { func (r *Resolver) SetSQLLogging(ctx context.Context, args struct { Input struct{ Enabled bool } -}) (*SetSQLLoggingPayloadResolver, error) { +}, +) (*SetSQLLoggingPayloadResolver, error) { if err := authenticateUserIsAdmin(ctx); err != nil { return nil, err } @@ -979,9 +996,9 @@ func (r *Resolver) SetSQLLogging(ctx context.Context, args struct { r.App.GetConfig().SetLogSQL(args.Input.Enabled) if args.Input.Enabled { - r.App.GetAuditLogger().Audit(audit.ConfigSqlLoggingEnabled, map[string]any{}) + r.App.GetAuditLogger().Audit(audit.ConfigSQLLoggingEnabled, map[string]any{}) } else { - r.App.GetAuditLogger().Audit(audit.ConfigSqlLoggingDisabled, map[string]any{}) + r.App.GetAuditLogger().Audit(audit.ConfigSQLLoggingDisabled, map[string]any{}) } return NewSetSQLLoggingPayload(args.Input.Enabled), nil @@ -989,7 +1006,8 @@ func (r *Resolver) SetSQLLogging(ctx context.Context, args struct { func (r *Resolver) CreateAPIToken(ctx context.Context, args struct { Input struct{ Password string } -}) (*CreateAPITokenPayloadResolver, error) { +}, +) (*CreateAPITokenPayloadResolver, error) { if err := authenticateUser(ctx); err != nil { return nil, err } @@ -1023,7 +1041,8 @@ func (r *Resolver) CreateAPIToken(ctx context.Context, args struct { func (r *Resolver) DeleteAPIToken(ctx context.Context, args struct { Input struct{ Password string } -}) (*DeleteAPITokenPayloadResolver, error) { +}, +) (*DeleteAPITokenPayloadResolver, error) { if err := authenticateUser(ctx); err != nil { return nil, err } @@ -1062,7 +1081,8 @@ func (r *Resolver) CreateJob(ctx context.Context, args struct { Input struct { TOML string } -}) (*CreateJobPayloadResolver, error) { +}, +) (*CreateJobPayloadResolver, error) { if err := authenticateUserCanEdit(ctx); err != nil { return nil, err } @@ -1070,7 +1090,7 @@ func (r *Resolver) CreateJob(ctx context.Context, args struct { jbt, err := job.ValidateSpec(args.Input.TOML) if err != nil { return NewCreateJobPayload(r.App, nil, map[string]string{ - "TOML spec": errors.Wrap(err, "failed to parse TOML").Error(), + "TOML spec": fmt.Errorf("failed to parse TOML: %w", err).Error(), }), nil } @@ -1144,7 +1164,8 @@ func (r *Resolver) CreateJob(ctx context.Context, args struct { func (r *Resolver) DeleteJob(ctx context.Context, args struct { ID graphql.ID -}) (*DeleteJobPayloadResolver, error) { +}, +) (*DeleteJobPayloadResolver, error) { if err := authenticateUserCanEdit(ctx); err != nil { return nil, err } @@ -1178,7 +1199,8 @@ func (r *Resolver) DeleteJob(ctx context.Context, args struct { func (r *Resolver) DismissJobError(ctx context.Context, args struct { ID graphql.ID -}) (*DismissJobErrorPayloadResolver, error) { +}, +) (*DismissJobErrorPayloadResolver, error) { if err := authenticateUserCanEdit(ctx); err != nil { return nil, err } @@ -1212,7 +1234,8 @@ func (r *Resolver) DismissJobError(ctx context.Context, args struct { func (r *Resolver) RunJob(ctx context.Context, args struct { ID graphql.ID -}) (*RunJobPayloadResolver, error) { +}, +) (*RunJobPayloadResolver, error) { if err := authenticateUserCanRun(ctx); err != nil { return nil, err } @@ -1238,7 +1261,8 @@ func (r *Resolver) RunJob(ctx context.Context, args struct { func (r *Resolver) SetGlobalLogLevel(ctx context.Context, args struct { Level LogLevel -}) (*SetGlobalLogLevelPayloadResolver, error) { +}, +) (*SetGlobalLogLevelPayloadResolver, error) { if err := authenticateUserIsAdmin(ctx); err != nil { return nil, err } @@ -1264,7 +1288,8 @@ func (r *Resolver) SetGlobalLogLevel(ctx context.Context, args struct { // CreateOCR2KeyBundle resolves a create OCR2 Key bundle mutation func (r *Resolver) CreateOCR2KeyBundle(ctx context.Context, args struct { ChainType OCR2ChainType -}) (*CreateOCR2KeyBundlePayloadResolver, error) { +}, +) (*CreateOCR2KeyBundlePayloadResolver, error) { if err := authenticateUserCanEdit(ctx); err != nil { return nil, err } @@ -1292,7 +1317,8 @@ func (r *Resolver) CreateOCR2KeyBundle(ctx context.Context, args struct { // DeleteOCR2KeyBundle resolves a create OCR2 Key bundle mutation func (r *Resolver) DeleteOCR2KeyBundle(ctx context.Context, args struct { ID graphql.ID -}) (*DeleteOCR2KeyBundlePayloadResolver, error) { +}, +) (*DeleteOCR2KeyBundlePayloadResolver, error) { if err := authenticateUserIsAdmin(ctx); err != nil { return nil, err } diff --git a/main_test.go b/main_test.go index 78445157c1a..354d4bd3924 100644 --- a/main_test.go +++ b/main_test.go @@ -1,7 +1,11 @@ package main import ( + "errors" + "flag" "fmt" + "io/fs" + "log" "os" "path/filepath" "strconv" @@ -36,22 +40,25 @@ const ( integrationBuildName = "go:build.integration" ) +// updateScripts enables updating testscript golden files, like `go test . -update` +var updateScripts = flag.Bool("update", false, "update testscript golden files") + func TestMain(m *testing.M) { + // keep GOTMPDIR short: osx default is too long for go-plugin sockets. + // Not removed afterwards because testscript.Main never returns (os.Exit). + tmp, err := os.MkdirTemp("", "chainlink-testscripts") + if err != nil { + log.Fatalf("failed to create temp dir: %v", err) + } + os.Setenv("GOTMPDIR", tmp) + testscript.Main(m, map[string]func(){ "chainlink": func() { os.Exit(core.Main()) }, }) } -var ( - // Temporary workaround for skipping flaky tests as we improve our tracking process - skipFlakyTests = map[string]string{ // test name: issue number - // "TestScripts/nodes/evm/list/list": "https://smartcontract-it.atlassian.net/browse/DX-107", - // "TestScripts/keys/eth/list/unavailable": "https://smartcontract-it.atlassian.net/browse/DX-110", - } -) - -// TestScripts walks through the testdata/scripts directory and runs all tests that end in -// .txt or .txtar with the testscripts library. To run an individual test, specify it in the +// TestScripts walks through the testdata/scripts directory and runs all .txtar +// files with the testscripts library. To run an individual test, specify it in the // -run param of go test without the txtar or txt suffix, like so: // go test . -run TestScripts/node/validate/default func TestScripts(t *testing.T) { @@ -59,43 +66,24 @@ func TestScripts(t *testing.T) { t.Skip("skipping testscript") } - tmp := t.TempDir() - require.NoError(t, os.Setenv("GOTMPDIR", tmp)) - t.Cleanup(func() { - require.NoError(t, os.Unsetenv("GOTMPDIR")) - }) t.Parallel() visitor := txtar.NewDirVisitor("testdata/scripts", txtar.Recurse, func(path string) error { t.Run(strings.TrimPrefix(path, "testdata/scripts/"), func(t *testing.T) { t.Parallel() - // Check each .txtar file against skipFlakyTests matches, err := filepath.Glob(filepath.Join(path, "*.txtar")) require.NoError(t, err) - - var filesToRun []string - for _, match := range matches { - scriptName := strings.TrimSuffix(filepath.Base(match), ".txtar") - fullTestName := t.Name() + "/" + scriptName - - if message, shouldSkip := skipFlakyTests[fullTestName]; shouldSkip { - t.Logf("Skipping Flaky Test: %s - %s", fullTestName, message) - continue - } - filesToRun = append(filesToRun, match) - } - - if len(filesToRun) == 0 { - t.Skip("all scripts in directory skipped") + if len(matches) == 0 { + t.Skip("no scripts found") } testscript.Run(t, testscript.Params{ - Files: filesToRun, - Setup: commonEnv(t), + Files: matches, + Setup: commonEnv(), ContinueOnError: true, RequireExplicitExec: true, - // UpdateScripts: true, // uncomment to update golden files + UpdateScripts: *updateScripts, }) }) return nil @@ -107,21 +95,25 @@ func TestScripts(t *testing.T) { // isIntegrationBuild is toggled true by a func init() with a //go:build integration gate var isIntegrationBuild = false -func commonEnv(t testing.TB) func(*testscript.Env) error { +func commonEnv() func(*testscript.Env) error { return func(te *testscript.Env) error { if _, err := os.Stat(filepath.Join(te.WorkDir, integrationBuildName)); err == nil && !isIntegrationBuild { te.T().Skip("integration test") return nil } - te.Setenv("HOME", "$WORK/home") + home := filepath.Join(te.WorkDir, "home") + if err := os.MkdirAll(home, 0o777); err != nil { + return fmt.Errorf("failed to create home dir %s: %w", home, err) + } + te.Setenv("HOME", home) te.Setenv("VERSION", static.Version) te.Setenv("VERSION_TAG", static.VersionTag) te.Setenv("COMMIT_SHA", static.Sha) te.Setenv("TMPDIR", "/tmp") // osx default is too long for go-plugin sockets b, err := os.ReadFile(filepath.Join(te.WorkDir, testPortName)) - if err != nil && !os.IsNotExist(err) { + if err != nil && !errors.Is(err, fs.ErrNotExist) { return fmt.Errorf("failed to read file %s: %w", testPortName, err) } else if err == nil { envVarName := strings.TrimSpace(string(b)) @@ -137,13 +129,19 @@ func commonEnv(t testing.TB) func(*testscript.Env) error { } b, err = os.ReadFile(filepath.Join(te.WorkDir, testDBName)) - if err != nil && !os.IsNotExist(err) { + if err != nil && !errors.Is(err, fs.ErrNotExist) { return fmt.Errorf("failed to read file %s: %w", testDBName, err) } else if err == nil { envVarName := strings.TrimSpace(string(b)) te.T().Log("test database requested:", envVarName) - u2 := testdb.New(t, true).String() + // Env.T implements testing.TB when started via testscript.Run + // (it wraps the per-script *testing.T), so its Cleanup runs when + // this script ends — not when the whole TestScripts suite finishes. + // Do not switch this suite to testscript.RunT. + // https://pkg.go.dev/github.com/rogpeppe/go-internal/testscript#Env.T + tb := te.T().(testing.TB) + u2 := testdb.New(tb, true).String() te.Setenv(envVarName, u2) } diff --git a/operator_ui/TAG b/operator_ui/TAG index f78dc36529a..bf057dbfd9d 100644 --- a/operator_ui/TAG +++ b/operator_ui/TAG @@ -1 +1 @@ -v0.10.0 \ No newline at end of file +v0.10.0 diff --git a/operator_ui/install.go b/operator_ui/install.go index 1a66149b8c5..e0575bc748e 100644 --- a/operator_ui/install.go +++ b/operator_ui/install.go @@ -33,7 +33,7 @@ func main() { tag := mustReadTagFile(path.Join(rootDir, tagPath)) strippedTag := stripVersionFromTag(tag) assetName := fmt.Sprintf("%s-%s-%s.tgz", owner, repo, strippedTag) - downloadUrl := fmt.Sprintf("https://github.com/%s/releases/download/%s/%s", fullRepo, tag, assetName) + downloadURL := fmt.Sprintf("https://github.com/%s/releases/download/%s/%s", fullRepo, tag, assetName) // Assuming that we're in "root/operator_ui/" unpackPath := filepath.Join(rootDir, unpackDir) @@ -43,11 +43,13 @@ func main() { } subPath := "package/artifacts/" - mustDownloadSubAsset(downloadUrl, downloadTimeoutSeconds, unpackPath, subPath) + if err := mustDownloadSubAsset(downloadURL, downloadTimeoutSeconds, unpackPath, subPath); err != nil { + log.Fatal(err) + } } func mustReadTagFile(file string) string { - tagBytes, err := os.ReadFile(file) + tagBytes, err := os.ReadFile(file) //nolint:gosec // path is constructed from the tool's own rootDir, not untrusted input if err != nil { log.Fatalln(err) } @@ -60,45 +62,43 @@ func stripVersionFromTag(tag string) string { } func rmrf(path string) error { - err := os.RemoveAll(path) + err := os.RemoveAll(path) //nolint:gosec // path is the tool's own unpack dir, not untrusted input if err != nil { return err } - err = os.Mkdir(path, 0755) + err = os.Mkdir(path, 0o755) //nolint:gosec // path is the tool's own unpack dir, not untrusted input return err } // Download a sub asset from a .tgz file and extract it to a destination path -func mustDownloadSubAsset(downloadUrl string, downloadTimeoutSeconds int, unpackPath string, subPath string) { - fmt.Println("Downloading", downloadUrl) +func mustDownloadSubAsset(downloadURL string, downloadTimeoutSeconds int, unpackPath, subPath string) error { + fmt.Println("Downloading", downloadURL) ctx, cancel := context.WithTimeout(context.Background(), time.Duration(downloadTimeoutSeconds)*time.Second) defer cancel() - /* #nosec G107 */ - req, err := http.NewRequestWithContext(ctx, http.MethodGet, downloadUrl, nil) + //nolint:gosec // downloadURL is a fixed github.com release URL, not attacker-controlled + req, err := http.NewRequestWithContext(ctx, http.MethodGet, downloadURL, nil) if err != nil { - log.Fatalln(err) + return fmt.Errorf("failed to create request: %w", err) } + //nolint:gosec // SSRF: URL is a fixed github.com release URL resp, err := http.DefaultClient.Do(req) if err != nil { - log.Fatalln(err) + return fmt.Errorf("failed to download asset: %w", err) } defer resp.Body.Close() if resp.StatusCode != http.StatusOK { - log.Fatalln(fmt.Errorf("failed to fetch asset: %s", resp.Status)) + return fmt.Errorf("failed to fetch asset: %s", resp.Status) } - err = decompressTgzSubpath(resp.Body, unpackPath, subPath) - if err != nil { - log.Fatalln(err) - } + return decompressTgzSubpath(resp.Body, unpackPath, subPath) } // Decompress a .tgz file to a destination path, only extracting files that are in the subpath // // Subpath files are extracted to the root of the destination path, rather than preserving the subpath -func decompressTgzSubpath(file io.Reader, destPath string, subPath string) error { +func decompressTgzSubpath(file io.Reader, destPath, subPath string) error { // Create a gzip reader gzr, err := gzip.NewReader(file) if err != nil { @@ -129,12 +129,16 @@ func decompressTgzSubpath(file io.Reader, destPath string, subPath string) error header.Name = strings.TrimPrefix(header.Name, subPath) // Target location where the dir/file should be created - target := fmt.Sprintf("%s/%s", destPath, header.Name) + target := filepath.Join(destPath, header.Name) //nolint:gosec // G305: traversal guarded by the HasPrefix check below + cleanDest := filepath.Clean(destPath) + if target != cleanDest && !strings.HasPrefix(target, cleanDest+string(os.PathSeparator)) { + return fmt.Errorf("tar entry %q escapes destination %q", header.Name, destPath) + } // Check the file type switch header.Typeflag { case tar.TypeDir: // Directory - if err := os.MkdirAll(target, 0755); err != nil { + if err := os.MkdirAll(target, 0o755); err != nil { //nolint:gosec // G703: target validated above, stays under destPath return fmt.Errorf("failed to create directory: %w", err) } fmt.Println("Creating directory", target) diff --git a/package.json b/package.json index 859bd015fe6..cefa619e680 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "chainlink", - "version": "2.65.0", + "version": "2.66.0", "description": "node of the decentralized oracle network, bridging on and off-chain computation", "main": "index.js", "scripts": { diff --git a/plugins/chainlink.Dockerfile b/plugins/chainlink.Dockerfile index 86994d4134f..d953d0c392a 100644 --- a/plugins/chainlink.Dockerfile +++ b/plugins/chainlink.Dockerfile @@ -71,10 +71,10 @@ RUN --mount=type=secret,id=GIT_AUTH_TOKEN \ mkdir -p /gobins "${CL_LOOPINSTALL_OUTPUT_DIR}" && \ GOBIN=/gobins CL_LOOPINSTALL_OUTPUT_DIR=${CL_LOOPINSTALL_OUTPUT_DIR} make install-plugins-public && \ if [ "${CL_INSTALL_PRIVATE_PLUGINS}" = "true" ]; then \ - GOBIN=/gobins CL_LOOPINSTALL_OUTPUT_DIR=${CL_LOOPINSTALL_OUTPUT_DIR} make install-plugins-private; \ + GOBIN=/gobins CL_LOOPINSTALL_OUTPUT_DIR=${CL_LOOPINSTALL_OUTPUT_DIR} make install-plugins-private; \ fi && \ if [ "${CL_INSTALL_TESTING_PLUGINS}" = "true" ]; then \ - GOBIN=/gobins CL_LOOPINSTALL_OUTPUT_DIR=${CL_LOOPINSTALL_OUTPUT_DIR} make install-plugins-testing; \ + GOBIN=/gobins CL_LOOPINSTALL_OUTPUT_DIR=${CL_LOOPINSTALL_OUTPUT_DIR} make install-plugins-testing; \ fi && \ mkdir -p /tmp/lib && \ ./plugins/scripts/copy_loopinstall_libs.sh \ @@ -99,10 +99,10 @@ RUN --mount=type=cache,id=go-mod-cache,target=/go/pkg/mod \ --mount=type=cache,id=go-build-cache,target=/root/.cache/go-build \ mkdir -p /gobins && \ if [ "$CL_IS_PROD_BUILD" = "false" ]; then \ - GOBIN=/gobins make install-chainlink-dev; \ - else \ - GOBIN=/gobins make install-chainlink; \ - fi + GOBIN=/gobins make install-chainlink-dev; \ + else \ + GOBIN=/gobins make install-chainlink; \ + fi ## # Final Image @@ -123,18 +123,18 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ RUN curl -fsSL https://www.postgresql.org/media/keys/ACCC4CF8.asc \ | gpg --dearmor -o /usr/share/keyrings/postgresql-archive-keyring.gpg \ && gpg --no-default-keyring \ - --keyring /usr/share/keyrings/postgresql-archive-keyring.gpg \ - --fingerprint B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8 \ + --keyring /usr/share/keyrings/postgresql-archive-keyring.gpg \ + --fingerprint B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8 \ && echo "deb [signed-by=/usr/share/keyrings/postgresql-archive-keyring.gpg] \ - https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" \ - >/etc/apt/sources.list.d/pgdg.list \ + https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" \ + >/etc/apt/sources.list.d/pgdg.list \ && apt-get update && apt-get install -y --no-install-recommends postgresql-client-17=17.10-1.pgdg24.04+1 \ && rm -rf /var/lib/apt/lists/* # Prod images (CHAINLINK_USER=chainlink) run as UID:GID 14933:14933 for deterministic ownership. RUN if [ ${CHAINLINK_USER} != root ]; then \ - groupadd --gid 14933 ${CHAINLINK_USER} && \ - useradd --uid 14933 --gid 14933 --create-home ${CHAINLINK_USER}; \ + groupadd --gid 14933 ${CHAINLINK_USER} && \ + useradd --uid 14933 --gid 14933 --create-home ${CHAINLINK_USER}; \ fi USER ${CHAINLINK_USER} diff --git a/plugins/cmd.go b/plugins/cmd.go index 9a312c53882..1e56b98d1ac 100644 --- a/plugins/cmd.go +++ b/plugins/cmd.go @@ -19,7 +19,7 @@ func NewCmdFactory(register func(id string) (*RegisteredLoop, error), lcfg CmdCo return nil, fmt.Errorf("failed to register %s LOOP plugin: %w", lcfg.ID, err) } return func() *exec.Cmd { - cmd := exec.Command(lcfg.Cmd) //#nosec G204 -- we control the value of the cmd so the lint/sec error is a false positive + cmd := exec.Command(lcfg.Cmd) //nolint:noctx,gosec // LOOP process; ctx attached by caller at execution, cmd value controlled by us cmd.Env = append(cmd.Env, lcfg.Env...) cmd.Env = append(cmd.Env, registeredLoop.EnvCfg.AsCmdEnv()...) return cmd diff --git a/plugins/loop_registry.go b/plugins/loop_registry.go index 76523a7894e..ab8d70bd956 100644 --- a/plugins/loop_registry.go +++ b/plugins/loop_registry.go @@ -47,7 +47,8 @@ type LoopRegistry struct { func NewLoopRegistry(lggr logger.Logger, appID string, featureLogPoller bool, dbConfig config.Database, mercury dataengine.Mercury, pyroscope config.Pyroscope, autoPPROF config.AutoPprof, tracing config.Tracing, telemetry config.Telemetry, - metering config.Metering, telemetryAuthHeaders map[string]string, telemetryAuthPubKeyHex string, looppCfg config.LOOPP) *LoopRegistry { + metering config.Metering, telemetryAuthHeaders map[string]string, telemetryAuthPubKeyHex string, looppCfg config.LOOPP, +) *LoopRegistry { return &LoopRegistry{ registry: map[string]*RegisteredLoop{}, lggr: logger.Named(lggr, "LoopRegistry"), @@ -228,8 +229,8 @@ func (m *LoopRegistry) Unregister(id string) { // Return slice sorted by plugin name. Safe for concurrent use. func (m *LoopRegistry) List() []*RegisteredLoop { - var registeredLoops []*RegisteredLoop m.mu.Lock() + registeredLoops := make([]*RegisteredLoop, 0, len(m.registry)) for _, known := range m.registry { registeredLoops = append(registeredLoops, known) } diff --git a/plugins/loop_registry_test.go b/plugins/loop_registry_test.go index 30f52ffa975..3278036c21d 100644 --- a/plugins/loop_registry_test.go +++ b/plugins/loop_registry_test.go @@ -274,7 +274,7 @@ func TestLoopRegistry_Register(t *testing.T) { require.True(t, envCfg.TracingEnabled) require.Equal(t, "http://localhost:9000", envCfg.TracingCollectorTarget) require.Equal(t, map[string]string{"attribute": "value"}, envCfg.TracingAttributes) - require.Equal(t, 0.1, envCfg.TracingSamplingRatio) + require.InEpsilon(t, 0.1, envCfg.TracingSamplingRatio, 1e-9) require.Equal(t, "/path/to/cert.pem", envCfg.TracingTLSCertPath) require.True(t, envCfg.TelemetryEnabled) @@ -282,7 +282,7 @@ func TestLoopRegistry_Register(t *testing.T) { require.Equal(t, "path/to/cert.pem", envCfg.TelemetryCACertFile) require.Equal(t, "http://localhost:9001", envCfg.TelemetryEndpoint) require.Equal(t, beholder.OtelAttributes{"foo": "bar"}, envCfg.TelemetryAttributes) - require.Equal(t, 0.42, envCfg.TelemetryTraceSampleRatio) + require.InEpsilon(t, 0.42, envCfg.TelemetryTraceSampleRatio, 1e-9) require.True(t, envCfg.TelemetryEmitterBatchProcessor) require.Equal(t, 1*time.Second, envCfg.TelemetryEmitterExportTimeout) require.False(t, envCfg.TelemetryLogStreamingEnabled) diff --git a/plugins/plugins.public.yaml b/plugins/plugins.public.yaml index 0368d5f6adb..653cacbcc43 100644 --- a/plugins/plugins.public.yaml +++ b/plugins/plugins.public.yaml @@ -63,29 +63,23 @@ plugins: capability-cron: - moduleURI: "github.com/smartcontractkit/capabilities/cron" - gitRef: "4d4c4ec65942cf2732b8bc0594278cd05165aec2" + gitRef: "fab9af5ab180a205dbfd5d90a1cd837815019159" installPath: "." flags: "-tags timetzdata" capability-consensus: - moduleURI: "github.com/smartcontractkit/capabilities/consensus" - gitRef: "4d4c4ec65942cf2732b8bc0594278cd05165aec2" - installPath: "." - - capability-workflowevent: - - enabled: false - moduleURI: "github.com/smartcontractkit/capabilities/workflowevent" - gitRef: "4d4c4ec65942cf2732b8bc0594278cd05165aec2" + gitRef: "fab9af5ab180a205dbfd5d90a1cd837815019159" installPath: "." capability-httpaction: - moduleURI: "github.com/smartcontractkit/capabilities/http_action" - gitRef: "4d4c4ec65942cf2732b8bc0594278cd05165aec2" + gitRef: "fab9af5ab180a205dbfd5d90a1cd837815019159" installPath: "." capability-httptrigger: - moduleURI: "github.com/smartcontractkit/capabilities/http_trigger" - gitRef: "4d4c4ec65942cf2732b8bc0594278cd05165aec2" + gitRef: "fab9af5ab180a205dbfd5d90a1cd837815019159" installPath: "." capability-evm: diff --git a/plugins/registrar.go b/plugins/registrar.go index 8523d3980cc..22920b0c5b6 100644 --- a/plugins/registrar.go +++ b/plugins/registrar.go @@ -9,7 +9,7 @@ import ( // RegistrarConfig generates contains static configuration type RegistrarConfig interface { RegisterLOOP(config CmdConfig) (func() *exec.Cmd, loop.GRPCOpts, error) - UnregisterLOOP(ID string) + UnregisterLOOP(id string) } type registarConfig struct { @@ -38,6 +38,6 @@ func (pc *registarConfig) RegisterLOOP(cfg CmdConfig) (func() *exec.Cmd, loop.GR return cmdFn, pc.grpcOpts, nil } -func (pc *registarConfig) UnregisterLOOP(ID string) { - pc.loopUnregisterFn(ID) +func (pc *registarConfig) UnregisterLOOP(id string) { + pc.loopUnregisterFn(id) } diff --git a/tools/plugout/main.go b/tools/plugout/main.go index 67768ea7508..b068ef48737 100644 --- a/tools/plugout/main.go +++ b/tools/plugout/main.go @@ -438,7 +438,7 @@ func updateGitRefInYAML(pluginPath, module string, goModMV ModuleVersion) error } newContent := strings.Join(lines, "\n") - if err := os.WriteFile(pluginPath, []byte(newContent), 0600); err != nil { + if err := os.WriteFile(pluginPath, []byte(newContent), 0600); err != nil { //nolint:gosec // pluginPath is constructed internally from module iteration return fmt.Errorf("failed to write YAML file: %w", err) } return nil