From b87624d3b59fd8eb2bce5292a1c8d7e7b5e42fff Mon Sep 17 00:00:00 2001 From: kopi-solarpunk <163832130+kopi-solarpunk@users.noreply.github.com> Date: Thu, 16 May 2024 10:03:28 +0200 Subject: [PATCH] Start refactoring for new linter rules (#39) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit refactor: refactoring to match new linter rules according to https://github.com/Solar-Punk-Ltd/bee/pull/38 Not everything is fixed, just a reference what can and needs to be improved. * implement grantee management * Add POST endpoint + fixes * Save grantees as pubkey list and fix remove error; CHG: act-handler logger names * Refactor: pass getter, putter to controller functions * Refactor: error handling in dynamicaccess; Read cache header only for download handlers * CHG: grantees ref is encrypted and added to history ref + tests * Fix nil pointer dereference panic * CHG: put actref in handlegrantees; Add: pin, tag,deferred headers * CHG: pass loadsave to handlers; check if history address is nil * FIX: re-init history so that it can be saved; only add publisher if histroy is zero * make act timestamp optional * fix revoke grantees * Fix: Act timestamp header nil check; Uploadhandler UT * refactor: start refactoring for now linter rules * refactor: revert non ACT related files * CHG: accesslogic getkeys refactor * refactor: fix errcheck and ineffassign linter errors in most cases * refactor: add headers, and change error handling * refactor: add headers --------- Co-authored-by: Kexort Co-authored-by: Bálint Ujvári --- pkg/api/dynamicaccess.go | 12 +++-- pkg/api/dynamicaccess_test.go | 48 +++++++++----------- pkg/dynamicaccess/accesslogic.go | 65 +++++++++++++++------------ pkg/dynamicaccess/accesslogic_test.go | 52 ++++++++------------- pkg/dynamicaccess/controller.go | 26 ++++++----- pkg/dynamicaccess/controller_test.go | 40 ++++++++++------- pkg/dynamicaccess/grantee.go | 20 ++++++--- pkg/dynamicaccess/grantee_test.go | 14 +++++- pkg/dynamicaccess/history.go | 42 ++++++++++------- pkg/dynamicaccess/history_test.go | 18 +++++--- pkg/dynamicaccess/mock/accesslogic.go | 3 ++ pkg/dynamicaccess/mock/controller.go | 4 +- pkg/dynamicaccess/mock/grantee.go | 4 ++ pkg/dynamicaccess/mock/session.go | 5 ++- pkg/dynamicaccess/session.go | 28 ++++++++---- pkg/dynamicaccess/session_test.go | 6 ++- pkg/kvs/kvs_test.go | 4 +- pkg/kvs/mock/kvs.go | 7 ++- pkg/manifest/mantaray/node.go | 7 +-- 19 files changed, 231 insertions(+), 174 deletions(-) diff --git a/pkg/api/dynamicaccess.go b/pkg/api/dynamicaccess.go index bbf3abbc69e..32447f905e8 100644 --- a/pkg/api/dynamicaccess.go +++ b/pkg/api/dynamicaccess.go @@ -1,3 +1,7 @@ +// Copyright 2024 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package api import ( @@ -6,6 +10,7 @@ import ( "encoding/hex" "encoding/json" "errors" + "fmt" "io" "net/http" "time" @@ -114,7 +119,6 @@ func (s *Service) actDecryptionHandler() func(h http.Handler) http.Handler { h.ServeHTTP(w, r.WithContext(setAddressInContext(ctx, reference))) }) } - } // actEncryptionHandler is a middleware that encrypts the given address using the publisher's public key @@ -133,7 +137,7 @@ func (s *Service) actEncryptionHandler( if err != nil { logger.Debug("act failed to encrypt reference", "error", err) logger.Error(nil, "act failed to encrypt reference") - return swarm.ZeroAddress, err + return swarm.ZeroAddress, fmt.Errorf("act failed to encrypt reference: %w", err) } // only need to upload history and kvs if a new history is created, // meaning that the publsher uploaded to the history for the first time @@ -142,13 +146,13 @@ func (s *Service) actEncryptionHandler( if err != nil { logger.Debug("done split keyvaluestore failed", "error", err) logger.Error(nil, "done split keyvaluestore failed") - return swarm.ZeroAddress, err + return swarm.ZeroAddress, fmt.Errorf("done split keyvaluestore failed: %w", err) } err = putter.Done(historyReference) if err != nil { logger.Debug("done split history failed", "error", err) logger.Error(nil, "done split history failed") - return swarm.ZeroAddress, err + return swarm.ZeroAddress, fmt.Errorf("done split history failed: %w", err) } } diff --git a/pkg/api/dynamicaccess_test.go b/pkg/api/dynamicaccess_test.go index a2d0cd6e4b2..79eac36327b 100644 --- a/pkg/api/dynamicaccess_test.go +++ b/pkg/api/dynamicaccess_test.go @@ -40,23 +40,23 @@ func prepareHistoryFixture(storer api.Storer) (dynamicaccess.History, swarm.Addr testActRef1 := swarm.NewAddress([]byte("39a5ea87b141fe44aa609c3327ecd891")) firstTime := time.Date(1994, time.April, 1, 0, 0, 0, 0, time.UTC).Unix() - h.Add(ctx, testActRef1, &firstTime, nil) + _ = h.Add(ctx, testActRef1, &firstTime, nil) testActRef2 := swarm.NewAddress([]byte("39a5ea87b141fe44aa609c3327ecd892")) secondTime := time.Date(2000, time.April, 1, 0, 0, 0, 0, time.UTC).Unix() - h.Add(ctx, testActRef2, &secondTime, nil) + _ = h.Add(ctx, testActRef2, &secondTime, nil) testActRef3 := swarm.NewAddress([]byte("39a5ea87b141fe44aa609c3327ecd893")) thirdTime := time.Date(2015, time.April, 1, 0, 0, 0, 0, time.UTC).Unix() - h.Add(ctx, testActRef3, &thirdTime, nil) + _ = h.Add(ctx, testActRef3, &thirdTime, nil) testActRef4 := swarm.NewAddress([]byte("39a5ea87b141fe44aa609c3327ecd894")) fourthTime := time.Date(2020, time.April, 1, 0, 0, 0, 0, time.UTC).Unix() - h.Add(ctx, testActRef4, &fourthTime, nil) + _ = h.Add(ctx, testActRef4, &fourthTime, nil) testActRef5 := swarm.NewAddress([]byte("39a5ea87b141fe44aa609c3327ecd895")) fifthTime := time.Date(2030, time.April, 1, 0, 0, 0, 0, time.UTC).Unix() - h.Add(ctx, testActRef5, &fifthTime, nil) + _ = h.Add(ctx, testActRef5, &fifthTime, nil) ref, _ := h.Store(ctx) return h, ref @@ -221,10 +221,11 @@ func TestDacEachEndpointWithAct(t *testing.T) { } } -// nolint:paralleltest,tparallel // TestDacWithoutActHeader [negative tests]: // 1. upload w/ "Swarm-Act" header then try to dowload w/o the header. // 2. upload w/o "Swarm-Act" header then try to dowload w/ the header. +// +//nolint:paralleltest,tparallel func TestDacWithoutAct(t *testing.T) { t.Parallel() var ( @@ -321,8 +322,9 @@ func TestDacWithoutAct(t *testing.T) { }) } -// nolint:paralleltest,tparallel // TestDacInvalidPath [negative test]: Expect Bad request when the path address is invalid. +// +//nolint:paralleltest,tparallel func TestDacInvalidPath(t *testing.T) { t.Parallel() var ( @@ -345,9 +347,7 @@ func TestDacInvalidPath(t *testing.T) { PublicKey: pk.PublicKey, Dac: mockdac.New(), }) - var ( - encryptedRef = "asd" - ) + encryptedRef := "asd" jsonhttptest.Request(t, client, http.MethodGet, fileDownloadResource(encryptedRef), http.StatusBadRequest, jsonhttptest.WithRequestHeader(api.SwarmActTimestampHeader, strconv.FormatInt(now, 10)), @@ -361,7 +361,8 @@ func TestDacInvalidPath(t *testing.T) { Field: "address", Error: api.HexInvalidByteError('s').Error(), }, - }}), + }, + }), jsonhttptest.WithRequestHeader(api.ContentTypeHeader, "text/html; charset=utf-8"), ) }) @@ -388,7 +389,6 @@ func TestDacHistory(t *testing.T) { fileName = "sample.html" now = time.Now().Unix() ) - fmt.Printf("bagoy now: %d\n", now) t.Run("empty-history-upload-then-download-and-check-data", func(t *testing.T) { client, _, _, _ := newTestServer(t, testServerOptions{ @@ -516,9 +516,7 @@ func TestDacHistory(t *testing.T) { PublicKey: pk.PublicKey, Dac: mockdac.New(), }) - var ( - testfile = "testfile1" - ) + testfile := "testfile1" jsonhttptest.Request(t, client, http.MethodPost, fileUploadResource+"?name="+fileName, http.StatusInternalServerError, jsonhttptest.WithRequestHeader(api.SwarmActHeader, "true"), @@ -541,9 +539,7 @@ func TestDacHistory(t *testing.T) { PublicKey: pk.PublicKey, Dac: mockdac.New(mockdac.WithHistory(h, fixtureHref.String())), }) - var ( - encryptedRef = "a5df670544eaea29e61b19d8739faa4573b19e4426e58a173e51ed0b5e7e2ade" - ) + encryptedRef := "a5df670544eaea29e61b19d8739faa4573b19e4426e58a173e51ed0b5e7e2ade" jsonhttptest.Request(t, client, http.MethodGet, fileDownloadResource(encryptedRef), http.StatusNotFound, jsonhttptest.WithRequestHeader(api.SwarmActTimestampHeader, strconv.FormatInt(now, 10)), @@ -619,9 +615,7 @@ func TestDacTimestamp(t *testing.T) { }) t.Run("download-w/o-timestamp", func(t *testing.T) { - var ( - encryptedRef = "a5df670544eaea29e61b19d8739faa4573b19e4426e58a173e51ed0b5e7e2ade" - ) + encryptedRef := "a5df670544eaea29e61b19d8739faa4573b19e4426e58a173e51ed0b5e7e2ade" client, _, _, _ := newTestServer(t, testServerOptions{ Storer: storerMock, Logger: logger, @@ -754,7 +748,8 @@ func TestDacPublisher(t *testing.T) { Field: "Swarm-Act-Publisher", Error: "malformed public key: invalid length: 32", }, - }}), + }, + }), jsonhttptest.WithRequestHeader(api.ContentTypeHeader, "text/html; charset=utf-8"), ) }) @@ -785,9 +780,7 @@ func TestDacPublisher(t *testing.T) { }) t.Run("download-w/o-publisher", func(t *testing.T) { - var ( - encryptedRef = "a5df670544eaea29e61b19d8739faa4573b19e4426e58a173e51ed0b5e7e2ade" - ) + encryptedRef := "a5df670544eaea29e61b19d8739faa4573b19e4426e58a173e51ed0b5e7e2ade" client, _, _, _ := newTestServer(t, testServerOptions{ Storer: storerMock, Logger: logger, @@ -862,7 +855,8 @@ func TestDacGrantees(t *testing.T) { Field: "address", Error: api.HexInvalidByteError('s').Error(), }, - }}), + }, + }), ) }) t.Run("add-revoke-grantees", func(t *testing.T) { @@ -904,8 +898,8 @@ func TestDacGrantees(t *testing.T) { jsonhttptest.WithRequestHeader(api.SwarmPostageBatchIdHeader, batchOkStr), jsonhttptest.WithJSONRequestBody(body), ) - }) + t.Run("create-granteelist", func(t *testing.T) { body := api.GranteesPostRequest{ GranteeList: []string{ diff --git a/pkg/dynamicaccess/accesslogic.go b/pkg/dynamicaccess/accesslogic.go index 33b8ba819ba..1cb9db8b5ba 100644 --- a/pkg/dynamicaccess/accesslogic.go +++ b/pkg/dynamicaccess/accesslogic.go @@ -1,8 +1,13 @@ +// Copyright 2024 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package dynamicaccess import ( "context" "crypto/ecdsa" + "fmt" encryption "github.com/ethersphere/bee/v2/pkg/encryption" "github.com/ethersphere/bee/v2/pkg/kvs" @@ -10,11 +15,14 @@ import ( "golang.org/x/crypto/sha3" ) -var hashFunc = sha3.NewLegacyKeccak256 -var oneByteArray = []byte{1} -var zeroByteArray = []byte{0} +//nolint:gochecknoglobals +var ( + hashFunc = sha3.NewLegacyKeccak256 + oneByteArray = []byte{1} + zeroByteArray = []byte{0} +) -// Read-only interface for the ACT +// Decryptor is a read-only interface for the ACT. type Decryptor interface { // DecryptRef will return a decrypted reference, for given encrypted reference and grantee DecryptRef(ctx context.Context, storage kvs.KeyValueStore, encryptedRef swarm.Address, publisher *ecdsa.PublicKey) (swarm.Address, error) @@ -22,13 +30,13 @@ type Decryptor interface { Session } -// Control interface for the ACT (does write operations) +// Control interface for the ACT (does write operations). type Control interface { // Embedding the Decryptor interface Decryptor - // Adds a new grantee to the ACT + // AddGrantee adds a new grantee to the ACT AddGrantee(ctx context.Context, storage kvs.KeyValueStore, publisherPubKey, granteePubKey *ecdsa.PublicKey, accessKey *encryption.Key) error - // Encrypts a Swarm reference for a given grantee + // EncryptRef encrypts a Swarm reference for a given grantee EncryptRef(ctx context.Context, storage kvs.KeyValueStore, grantee *ecdsa.PublicKey, ref swarm.Address) (swarm.Address, error) } @@ -38,14 +46,14 @@ type ActLogic struct { var _ Control = (*ActLogic)(nil) -// Adds a new publisher to an empty act +// AddPublisher adds a new publisher to an empty act. func (al ActLogic) AddPublisher(ctx context.Context, storage kvs.KeyValueStore, publisher *ecdsa.PublicKey) error { accessKey := encryption.GenerateRandomKey(encryption.KeyLength) return al.AddGrantee(ctx, storage, publisher, publisher, &accessKey) } -// Encrypts a SWARM reference for a publisher +// EncryptRef encrypts a SWARM reference for a publisher. func (al ActLogic) EncryptRef(ctx context.Context, storage kvs.KeyValueStore, publisherPubKey *ecdsa.PublicKey, ref swarm.Address) (swarm.Address, error) { accessKey, err := al.getAccessKey(ctx, storage, publisherPubKey) if err != nil { @@ -54,13 +62,13 @@ func (al ActLogic) EncryptRef(ctx context.Context, storage kvs.KeyValueStore, pu refCipher := encryption.New(accessKey, 0, uint32(0), hashFunc) encryptedRef, err := refCipher.Encrypt(ref.Bytes()) if err != nil { - return swarm.ZeroAddress, err + return swarm.ZeroAddress, fmt.Errorf("failed to encrypt reference: %w", err) } return swarm.NewAddress(encryptedRef), nil } -// Adds a new grantee to the ACT +// AddGrantee adds a new grantee to the ACT. func (al ActLogic) AddGrantee(ctx context.Context, storage kvs.KeyValueStore, publisherPubKey, granteePubKey *ecdsa.PublicKey, accessKeyPointer *encryption.Key) error { var ( accessKey encryption.Key @@ -79,61 +87,60 @@ func (al ActLogic) AddGrantee(ctx context.Context, storage kvs.KeyValueStore, pu } // Encrypt the access key for the new Grantee - keys, err := al.getKeys(granteePubKey) + lookupKey, accessKeyDecryptionKey, err := al.getKeys(granteePubKey) if err != nil { return err } - lookupKey := keys[0] - // accessKeyDecryptionKey is used for encryption of the access key - accessKeyDecryptionKey := keys[1] // Encrypt the access key for the new Grantee cipher := encryption.New(encryption.Key(accessKeyDecryptionKey), 0, uint32(0), hashFunc) granteeEncryptedAccessKey, err := cipher.Encrypt(accessKey) if err != nil { - return err + return fmt.Errorf("failed to encrypt access key: %w", err) } - // Add the new encrypted access key for the Act + // Add the new encrypted access key to the Act return storage.Put(ctx, lookupKey, granteeEncryptedAccessKey) } -// Will return the access key for a publisher (public key) +// Will return the access key for a publisher (public key). func (al *ActLogic) getAccessKey(ctx context.Context, storage kvs.KeyValueStore, publisherPubKey *ecdsa.PublicKey) ([]byte, error) { - keys, err := al.getKeys(publisherPubKey) + publisherLookupKey, publisherAKDecryptionKey, err := al.getKeys(publisherPubKey) if err != nil { return nil, err } - publisherLookupKey := keys[0] - publisherAKDecryptionKey := keys[1] - // no need to constructor call if value not found in act + // no need for constructor call if value not found in act accessKeyDecryptionCipher := encryption.New(encryption.Key(publisherAKDecryptionKey), 0, uint32(0), hashFunc) encryptedAK, err := storage.Get(ctx, publisherLookupKey) if err != nil { - return nil, err + return nil, fmt.Errorf("failed go get value from KVS: %w", err) } return accessKeyDecryptionCipher.Decrypt(encryptedAK) } // Generate lookup key and access key decryption key for a given public key -func (al *ActLogic) getKeys(publicKey *ecdsa.PublicKey) ([][]byte, error) { - return al.Session.Key(publicKey, [][]byte{zeroByteArray, oneByteArray}) +func (al *ActLogic) getKeys(publicKey *ecdsa.PublicKey) ([]byte, []byte, error) { + nonces := [][]byte{zeroByteArray, oneByteArray} + // keys := make([][]byte, 0, len(nonces)) + keys, err := al.Session.Key(publicKey, nonces) + if keys == nil { + return nil, nil, err + } + return keys[0], keys[1], err } // DecryptRef will return a decrypted reference, for given encrypted reference and publisher func (al ActLogic) DecryptRef(ctx context.Context, storage kvs.KeyValueStore, encryptedRef swarm.Address, publisher *ecdsa.PublicKey) (swarm.Address, error) { - keys, err := al.getKeys(publisher) + lookupKey, accessKeyDecryptionKey, err := al.getKeys(publisher) if err != nil { return swarm.ZeroAddress, err } - lookupKey := keys[0] - accessKeyDecryptionKey := keys[1] // Lookup encrypted access key from the ACT manifest encryptedAccessKey, err := storage.Get(ctx, lookupKey) if err != nil { - return swarm.ZeroAddress, err + return swarm.ZeroAddress, fmt.Errorf("failed to get access key from KVS: %w", err) } // Decrypt access key diff --git a/pkg/dynamicaccess/accesslogic_test.go b/pkg/dynamicaccess/accesslogic_test.go index 66a3f8930e3..8d6c146e468 100644 --- a/pkg/dynamicaccess/accesslogic_test.go +++ b/pkg/dynamicaccess/accesslogic_test.go @@ -1,3 +1,7 @@ +// Copyright 2024 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package dynamicaccess_test import ( @@ -12,6 +16,7 @@ import ( "github.com/ethersphere/bee/v2/pkg/dynamicaccess" kvsmock "github.com/ethersphere/bee/v2/pkg/kvs/mock" "github.com/ethersphere/bee/v2/pkg/swarm" + "github.com/stretchr/testify/assert" ) // Generates a new test environment with a fix private key @@ -79,7 +84,6 @@ func TestDecryptRef_Success(t *testing.T) { } if expectedRef.Compare(acutalRef) != 0 { - t.Errorf("Get gave back wrong Swarm reference!") } } @@ -123,7 +127,6 @@ func TestDecryptRefWithGrantee_Success(t *testing.T) { } if expectedRef.Compare(acutalRef) != 0 { - t.Errorf("Get gave back wrong Swarm reference!") } } @@ -135,9 +138,7 @@ func TestDecryptRef_Error(t *testing.T) { s := kvsmock.New() al := setupAccessLogic() err := al.AddPublisher(ctx, s, &id0.PublicKey) - if err != nil { - t.Errorf("AddPublisher: expected no error, got %v", err) - } + assert.NoError(t, err) expectedRef := "39a5ea87b141fe44aa609c3327ecd896c0e2122897f5f4bbacf74db1033c5559" @@ -158,19 +159,14 @@ func TestAddPublisher(t *testing.T) { al := setupAccessLogic() err := al.AddPublisher(ctx, s, &id0.PublicKey) - if err != nil { - t.Errorf("AddPublisher: expected no error, got %v", err) - } + assert.NoError(t, err) decodedSavedLookupKey, err := hex.DecodeString(savedLookupKey) - if err != nil { - t.Errorf("DecodeString: expected no error, got %v", err) - } + assert.NoError(t, err) encryptedAccessKey, err := s.Get(ctx, decodedSavedLookupKey) - if err != nil { - t.Errorf("Lookup: expected no error, got %v", err) - } + assert.NoError(t, err) + decodedEncryptedAccessKey := hex.EncodeToString(encryptedAccessKey) // A random value is returned so it is only possibly to check the length of the returned value @@ -184,7 +180,6 @@ func TestAddPublisher(t *testing.T) { } func TestAddNewGranteeToContent(t *testing.T) { - id0 := getPrivKey(0) id1 := getPrivKey(1) id2 := getPrivKey(2) @@ -197,24 +192,17 @@ func TestAddNewGranteeToContent(t *testing.T) { s := kvsmock.New() al := setupAccessLogic() err := al.AddPublisher(ctx, s, &id0.PublicKey) - if err != nil { - t.Errorf("AddNewGrantee: expected no error, got %v", err) - } + assert.NoError(t, err) err = al.AddGrantee(ctx, s, &id0.PublicKey, &id1.PublicKey, nil) - if err != nil { - t.Errorf("AddNewGrantee: expected no error, got %v", err) - } + assert.NoError(t, err) err = al.AddGrantee(ctx, s, &id0.PublicKey, &id2.PublicKey, nil) - if err != nil { - t.Errorf("AddNewGrantee: expected no error, got %v", err) - } + assert.NoError(t, err) lookupKeyAsByte, err := hex.DecodeString(publisherLookupKey) - if err != nil { - t.Errorf("AddNewGrantee: expected no error, got %v", err) - } + assert.NoError(t, err) + result, _ := s.Get(ctx, lookupKeyAsByte) hexEncodedEncryptedAK := hex.EncodeToString(result) if len(hexEncodedEncryptedAK) != 64 { @@ -222,9 +210,8 @@ func TestAddNewGranteeToContent(t *testing.T) { } lookupKeyAsByte, err = hex.DecodeString(firstAddedGranteeLookupKey) - if err != nil { - t.Errorf("AddNewGrantee: expected no error, got %v", err) - } + assert.NoError(t, err) + result, _ = s.Get(ctx, lookupKeyAsByte) hexEncodedEncryptedAK = hex.EncodeToString(result) if len(hexEncodedEncryptedAK) != 64 { @@ -232,9 +219,8 @@ func TestAddNewGranteeToContent(t *testing.T) { } lookupKeyAsByte, err = hex.DecodeString(secondAddedGranteeLookupKey) - if err != nil { - t.Errorf("AddNewGrantee: expected no error, got %v", err) - } + assert.NoError(t, err) + result, _ = s.Get(ctx, lookupKeyAsByte) hexEncodedEncryptedAK = hex.EncodeToString(result) if len(hexEncodedEncryptedAK) != 64 { diff --git a/pkg/dynamicaccess/controller.go b/pkg/dynamicaccess/controller.go index a2c9ad50d04..a8998aa12df 100644 --- a/pkg/dynamicaccess/controller.go +++ b/pkg/dynamicaccess/controller.go @@ -1,3 +1,7 @@ +// Copyright 2024 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package dynamicaccess import ( @@ -33,13 +37,13 @@ type Controller interface { io.Closer } -type controller struct { +type ControllerStruct struct { accessLogic ActLogic } -var _ Controller = (*controller)(nil) +var _ Controller = (*ControllerStruct)(nil) -func (c *controller) DownloadHandler( +func (c *ControllerStruct) DownloadHandler( ctx context.Context, ls file.LoadSaver, encryptedRef swarm.Address, @@ -63,7 +67,7 @@ func (c *controller) DownloadHandler( return c.accessLogic.DecryptRef(ctx, act, encryptedRef, publisher) } -func (c *controller) UploadHandler( +func (c *ControllerStruct) UploadHandler( ctx context.Context, ls file.LoadSaver, refrefence swarm.Address, @@ -121,13 +125,13 @@ func (c *controller) UploadHandler( return actRef, historyRef, encryptedRef, err } -func NewController(accessLogic ActLogic) Controller { - return &controller{ +func NewController(accessLogic ActLogic) *ControllerStruct { + return &ControllerStruct{ accessLogic: accessLogic, } } -func (c *controller) HandleGrantees( +func (c *ControllerStruct) HandleGrantees( ctx context.Context, ls file.LoadSaver, gls file.LoadSaver, @@ -261,7 +265,7 @@ func (c *controller) HandleGrantees( return glref, eglref, href, actref, nil } -func (c *controller) GetGrantees(ctx context.Context, ls file.LoadSaver, publisher *ecdsa.PublicKey, encryptedglref swarm.Address) ([]*ecdsa.PublicKey, error) { +func (c *ControllerStruct) GetGrantees(ctx context.Context, ls file.LoadSaver, publisher *ecdsa.PublicKey, encryptedglref swarm.Address) ([]*ecdsa.PublicKey, error) { granteeRef, err := c.decryptRefForPublisher(publisher, encryptedglref) if err != nil { return nil, err @@ -273,7 +277,7 @@ func (c *controller) GetGrantees(ctx context.Context, ls file.LoadSaver, publish return gl.Get(), nil } -func (c *controller) encryptRefForPublisher(publisherPubKey *ecdsa.PublicKey, ref swarm.Address) (swarm.Address, error) { +func (c *ControllerStruct) encryptRefForPublisher(publisherPubKey *ecdsa.PublicKey, ref swarm.Address) (swarm.Address, error) { keys, err := c.accessLogic.Session.Key(publisherPubKey, [][]byte{oneByteArray}) if err != nil { return swarm.ZeroAddress, err @@ -287,7 +291,7 @@ func (c *controller) encryptRefForPublisher(publisherPubKey *ecdsa.PublicKey, re return swarm.NewAddress(encryptedRef), nil } -func (c *controller) decryptRefForPublisher(publisherPubKey *ecdsa.PublicKey, encryptedRef swarm.Address) (swarm.Address, error) { +func (c *ControllerStruct) decryptRefForPublisher(publisherPubKey *ecdsa.PublicKey, encryptedRef swarm.Address) (swarm.Address, error) { keys, err := c.accessLogic.Session.Key(publisherPubKey, [][]byte{oneByteArray}) if err != nil { return swarm.ZeroAddress, err @@ -308,6 +312,6 @@ func requestPipelineFactory(ctx context.Context, s storage.Putter, encrypt bool, } // TODO: what to do in close ? -func (s *controller) Close() error { +func (s *ControllerStruct) Close() error { return nil } diff --git a/pkg/dynamicaccess/controller_test.go b/pkg/dynamicaccess/controller_test.go index 2b3065899a1..05b4e76db11 100644 --- a/pkg/dynamicaccess/controller_test.go +++ b/pkg/dynamicaccess/controller_test.go @@ -1,3 +1,7 @@ +// Copyright 2024 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package dynamicaccess_test import ( @@ -18,6 +22,7 @@ import ( "golang.org/x/crypto/sha3" ) +//nolint:errcheck,gosec,wrapcheck func getHistoryFixture(ctx context.Context, ls file.LoadSaver, al dynamicaccess.ActLogic, publisher *ecdsa.PublicKey) (swarm.Address, error) { h, err := dynamicaccess.NewHistory(ls) if err != nil { @@ -103,11 +108,11 @@ func TestController_PublisherDownload(t *testing.T) { c := dynamicaccess.NewController(al) ls := createLs() ref := swarm.RandAddress(t) - href, err := getHistoryFixture(ctx, ls, al, &publisher.PublicKey) - h, err := dynamicaccess.NewHistoryReference(ls, href) - entry, err := h.Lookup(ctx, time.Now().Unix()) + href, _ := getHistoryFixture(ctx, ls, al, &publisher.PublicKey) + h, _ := dynamicaccess.NewHistoryReference(ls, href) + entry, _ := h.Lookup(ctx, time.Now().Unix()) actRef := entry.Reference() - act, err := kvs.NewReference(ls, actRef) + act, _ := kvs.NewReference(ls, actRef) encRef, err := al.EncryptRef(ctx, act, &publisher.PublicKey, ref) assert.NoError(t, err) @@ -128,12 +133,12 @@ func TestController_GranteeDownload(t *testing.T) { ls := createLs() c := dynamicaccess.NewController(al) ref := swarm.RandAddress(t) - href, err := getHistoryFixture(ctx, ls, publisherAL, &publisher.PublicKey) - h, err := dynamicaccess.NewHistoryReference(ls, href) + href, _ := getHistoryFixture(ctx, ls, publisherAL, &publisher.PublicKey) + h, _ := dynamicaccess.NewHistoryReference(ls, href) ts := time.Date(2001, time.April, 1, 0, 0, 0, 0, time.UTC).Unix() - entry, err := h.Lookup(ctx, ts) + entry, _ := h.Lookup(ctx, ts) actRef := entry.Reference() - act, err := kvs.NewReference(ls, actRef) + act, _ := kvs.NewReference(ls, actRef) encRef, err := publisherAL.EncryptRef(ctx, act, &publisher.PublicKey, ref) assert.NoError(t, err) @@ -178,7 +183,7 @@ func TestController_HandleGrantees(t *testing.T) { assert.Len(t, gl.Get(), 1) addList = []*ecdsa.PublicKey{&getPrivKey(0).PublicKey} - granteeRef, _, _, _, err = c.HandleGrantees(ctx, ls, ls, eglref, href, &publisher.PublicKey, addList, nil) + granteeRef, _, _, _, _ = c.HandleGrantees(ctx, ls, ls, eglref, href, &publisher.PublicKey, addList, nil) gl, err = dynamicaccess.NewGranteeListReference(ls, granteeRef) assert.NoError(t, err) assert.Len(t, gl.Get(), 2) @@ -187,12 +192,12 @@ func TestController_HandleGrantees(t *testing.T) { addList := []*ecdsa.PublicKey{&grantee.PublicKey} revokeList := []*ecdsa.PublicKey{&grantee1.PublicKey} gl, _ := dynamicaccess.NewGranteeList(ls) - gl.Add([]*ecdsa.PublicKey{&publisher.PublicKey, &grantee1.PublicKey}) - granteeRef, err := gl.Save(ctx) + _ = gl.Add([]*ecdsa.PublicKey{&publisher.PublicKey, &grantee1.PublicKey}) + granteeRef, _ := gl.Save(ctx) eglref, _ := refCipher.Encrypt(granteeRef.Bytes()) - granteeRef, _, _, _, err = c.HandleGrantees(ctx, ls, gls, swarm.NewAddress(eglref), href, &publisher.PublicKey, addList, revokeList) - gl, err = dynamicaccess.NewGranteeListReference(ls, granteeRef) + granteeRef, _, _, _, _ = c.HandleGrantees(ctx, ls, gls, swarm.NewAddress(eglref), href, &publisher.PublicKey, addList, revokeList) + gl, err := dynamicaccess.NewGranteeListReference(ls, granteeRef) assert.NoError(t, err) assert.Len(t, gl.Get(), 2) @@ -200,8 +205,9 @@ func TestController_HandleGrantees(t *testing.T) { t.Run("add twice", func(t *testing.T) { addList := []*ecdsa.PublicKey{&grantee.PublicKey, &grantee.PublicKey} + //nolint:ineffassign,staticcheck,wastedassign granteeRef, eglref, _, _, err := c.HandleGrantees(ctx, ls, gls, swarm.ZeroAddress, href, &publisher.PublicKey, addList, nil) - granteeRef, _, _, _, err = c.HandleGrantees(ctx, ls, ls, eglref, href, &publisher.PublicKey, addList, nil) + granteeRef, _, _, _, _ = c.HandleGrantees(ctx, ls, ls, eglref, href, &publisher.PublicKey, addList, nil) gl, err := dynamicaccess.NewGranteeListReference(createLs(), granteeRef) assert.NoError(t, err) @@ -209,7 +215,7 @@ func TestController_HandleGrantees(t *testing.T) { }) t.Run("revoke non-existing", func(t *testing.T) { addList := []*ecdsa.PublicKey{&grantee.PublicKey} - granteeRef, _, _, _, err := c.HandleGrantees(ctx, ls, ls, swarm.ZeroAddress, href, &publisher.PublicKey, addList, nil) + granteeRef, _, _, _, _ := c.HandleGrantees(ctx, ls, ls, swarm.ZeroAddress, href, &publisher.PublicKey, addList, nil) gl, err := dynamicaccess.NewGranteeListReference(createLs(), granteeRef) assert.NoError(t, err) @@ -233,7 +239,7 @@ func TestController_GetGrantees(t *testing.T) { t.Run("get by publisher", func(t *testing.T) { addList := []*ecdsa.PublicKey{&grantee.PublicKey} - granteeRef, eglRef, _, _, err := c1.HandleGrantees(ctx, ls, gls, swarm.ZeroAddress, swarm.ZeroAddress, &publisher.PublicKey, addList, nil) + granteeRef, eglRef, _, _, _ := c1.HandleGrantees(ctx, ls, gls, swarm.ZeroAddress, swarm.ZeroAddress, &publisher.PublicKey, addList, nil) grantees, err := c1.GetGrantees(ctx, ls, &publisher.PublicKey, eglRef) assert.NoError(t, err) @@ -244,7 +250,7 @@ func TestController_GetGrantees(t *testing.T) { }) t.Run("get by non-publisher", func(t *testing.T) { addList := []*ecdsa.PublicKey{&grantee.PublicKey} - _, eglRef, _, _, err := c1.HandleGrantees(ctx, ls, gls, swarm.ZeroAddress, swarm.ZeroAddress, &publisher.PublicKey, addList, nil) + _, eglRef, _, _, _ := c1.HandleGrantees(ctx, ls, gls, swarm.ZeroAddress, swarm.ZeroAddress, &publisher.PublicKey, addList, nil) grantees, err := c2.GetGrantees(ctx, ls, &publisher.PublicKey, eglRef) assert.Error(t, err) assert.Nil(t, grantees) diff --git a/pkg/dynamicaccess/grantee.go b/pkg/dynamicaccess/grantee.go index 02cd8099021..57e6429f7da 100644 --- a/pkg/dynamicaccess/grantee.go +++ b/pkg/dynamicaccess/grantee.go @@ -1,9 +1,14 @@ +// Copyright 2024 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package dynamicaccess import ( "context" "crypto/ecdsa" "crypto/elliptic" + "errors" "fmt" "github.com/btcsuite/btcd/btcec/v2" @@ -76,13 +81,18 @@ func (g *GranteeListStruct) Save(ctx context.Context) (swarm.Address, error) { return swarm.NewAddress(refBytes), nil } +var ( + ErrNothingToRemove = errors.New("nothing to remove") + ErrNoGranteeFound = errors.New("no grantee found") +) + func (g *GranteeListStruct) Remove(keysToRemove []*ecdsa.PublicKey) error { if len(keysToRemove) == 0 { - return fmt.Errorf("nothing to remove") + return ErrNothingToRemove } if len(g.grantees) == 0 { - return fmt.Errorf("no grantee found") + return ErrNoGranteeFound } grantees := g.grantees @@ -99,17 +109,17 @@ func (g *GranteeListStruct) Remove(keysToRemove []*ecdsa.PublicKey) error { return nil } -func NewGranteeList(ls file.LoadSaver) (GranteeList, error) { +func NewGranteeList(ls file.LoadSaver) (*GranteeListStruct, error) { // Why is the error necessary? return &GranteeListStruct{ grantees: []*ecdsa.PublicKey{}, loadSave: ls, }, nil } -func NewGranteeListReference(ls file.LoadSaver, reference swarm.Address) (GranteeList, error) { +func NewGranteeListReference(ls file.LoadSaver, reference swarm.Address) (*GranteeListStruct, error) { data, err := ls.Load(context.Background(), reference.Bytes()) if err != nil { - return nil, err + return nil, fmt.Errorf("unable to load reference, %w", err) } grantees := deserialize(data) diff --git a/pkg/dynamicaccess/grantee_test.go b/pkg/dynamicaccess/grantee_test.go index c4ce58ac8aa..cd69aaa752c 100644 --- a/pkg/dynamicaccess/grantee_test.go +++ b/pkg/dynamicaccess/grantee_test.go @@ -1,3 +1,7 @@ +// Copyright 2024 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package dynamicaccess_test import ( @@ -33,7 +37,13 @@ func createLs() file.LoadSaver { func generateKeyListFixture() ([]*ecdsa.PublicKey, error) { key1, err := ecdsa.GenerateKey(btcec.S256(), rand.Reader) + if err != nil { + return nil, err + } key2, err := ecdsa.GenerateKey(btcec.S256(), rand.Reader) + if err != nil { + return nil, err + } key3, err := ecdsa.GenerateKey(btcec.S256(), rand.Reader) if err != nil { return nil, err @@ -216,8 +226,8 @@ func TestGranteeRemoveTwo(t *testing.T) { if err != nil { t.Errorf("key generation error: %v", err) } - err = gl.Add([]*ecdsa.PublicKey{keys[0]}) - err = gl.Add([]*ecdsa.PublicKey{keys[0]}) + _ = gl.Add([]*ecdsa.PublicKey{keys[0]}) + _ = gl.Add([]*ecdsa.PublicKey{keys[0]}) err = gl.Remove([]*ecdsa.PublicKey{keys[0]}) assert.NoError(t, err) } diff --git a/pkg/dynamicaccess/history.go b/pkg/dynamicaccess/history.go index 25193adf886..27485e95f95 100644 --- a/pkg/dynamicaccess/history.go +++ b/pkg/dynamicaccess/history.go @@ -1,3 +1,7 @@ +// Copyright 2024 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package dynamicaccess import ( @@ -20,44 +24,47 @@ type History interface { Store(ctx context.Context) (swarm.Address, error) } -var _ History = (*history)(nil) +var _ History = (*HistoryStruct)(nil) -var ErrEndIteration = errors.New("end iteration") +var ( + ErrEndIteration = errors.New("end iteration") + ErrUnexpectedType = errors.New("unexpected type") +) -type history struct { +type HistoryStruct struct { manifest *manifest.MantarayManifest ls file.LoadSaver } -func NewHistory(ls file.LoadSaver) (History, error) { +func NewHistory(ls file.LoadSaver) (*HistoryStruct, error) { m, err := manifest.NewDefaultManifest(ls, false) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to create default manifest: %w", err) } mm, ok := m.(*manifest.MantarayManifest) if !ok { - return nil, fmt.Errorf("expected MantarayManifest, got %T", m) + return nil, fmt.Errorf("%w: expected MantarayManifest, got %T", ErrUnexpectedType, m) } - return &history{manifest: mm, ls: ls}, nil + return &HistoryStruct{manifest: mm, ls: ls}, nil } -func NewHistoryReference(ls file.LoadSaver, ref swarm.Address) (History, error) { +func NewHistoryReference(ls file.LoadSaver, ref swarm.Address) (*HistoryStruct, error) { m, err := manifest.NewDefaultManifestReference(ref, ls) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to create default manifest: %w", err) } mm, ok := m.(*manifest.MantarayManifest) if !ok { - return nil, fmt.Errorf("expected MantarayManifest, got %T", m) + return nil, fmt.Errorf("%w: expected MantarayManifest, got %T", ErrUnexpectedType, m) } - return &history{manifest: mm, ls: ls}, nil + return &HistoryStruct{manifest: mm, ls: ls}, nil } -func (h *history) Add(ctx context.Context, ref swarm.Address, timestamp *int64, metadata *map[string]string) error { +func (h *HistoryStruct) Add(ctx context.Context, ref swarm.Address, timestamp *int64, metadata *map[string]string) error { mtdt := map[string]string{} if metadata != nil { mtdt = *metadata @@ -74,10 +81,12 @@ func (h *history) Add(ctx context.Context, ref swarm.Address, timestamp *int64, return h.manifest.Add(ctx, key, manifest.NewEntry(ref, mtdt)) } +var ErrInvalidTimestamp = errors.New("invalid timestamp") + // Lookup finds the entry for a path or returns error if not found -func (h *history) Lookup(ctx context.Context, timestamp int64) (manifest.Entry, error) { +func (h *HistoryStruct) Lookup(ctx context.Context, timestamp int64) (manifest.Entry, error) { if timestamp <= 0 { - return manifest.NewEntry(swarm.ZeroAddress, map[string]string{}), errors.New("invalid timestamp") + return manifest.NewEntry(swarm.ZeroAddress, map[string]string{}), ErrInvalidTimestamp } reversedTimestamp := math.MaxInt64 - timestamp @@ -93,7 +102,7 @@ func (h *history) Lookup(ctx context.Context, timestamp int64) (manifest.Entry, return manifest.NewEntry(swarm.ZeroAddress, map[string]string{}), nil } -func (h *history) lookupNode(ctx context.Context, searchedTimestamp int64) (*mantaray.Node, error) { +func (h *HistoryStruct) lookupNode(ctx context.Context, searchedTimestamp int64) (*mantaray.Node, error) { // before node's timestamp is the closest one that is less than or equal to the searched timestamp // for instance: 2030, 2020, 1994 -> search for 2021 -> before is 2020 var beforeNode *mantaray.Node @@ -134,12 +143,11 @@ func (h *history) lookupNode(ctx context.Context, searchedTimestamp int64) (*man } if afterNode != nil { return afterNode, nil - } return nil, nil } -func (h *history) Store(ctx context.Context) (swarm.Address, error) { +func (h *HistoryStruct) Store(ctx context.Context) (swarm.Address, error) { return h.manifest.Store(ctx) } diff --git a/pkg/dynamicaccess/history_test.go b/pkg/dynamicaccess/history_test.go index 5c7f5670cf6..edc86dc7f22 100644 --- a/pkg/dynamicaccess/history_test.go +++ b/pkg/dynamicaccess/history_test.go @@ -1,3 +1,7 @@ +// Copyright 2024 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package dynamicaccess_test import ( @@ -61,27 +65,27 @@ func TestMultiNodeHistoryLookup(t *testing.T) { testActRef1 := swarm.NewAddress([]byte("39a5ea87b141fe44aa609c3327ecd891")) firstTime := time.Date(1994, time.April, 1, 0, 0, 0, 0, time.UTC).Unix() mtdt1 := map[string]string{"firstTime": "1994-04-01"} - h.Add(ctx, testActRef1, &firstTime, &mtdt1) + _ = h.Add(ctx, testActRef1, &firstTime, &mtdt1) testActRef2 := swarm.NewAddress([]byte("39a5ea87b141fe44aa609c3327ecd892")) secondTime := time.Date(2000, time.April, 1, 0, 0, 0, 0, time.UTC).Unix() mtdt2 := map[string]string{"secondTime": "2000-04-01"} - h.Add(ctx, testActRef2, &secondTime, &mtdt2) + _ = h.Add(ctx, testActRef2, &secondTime, &mtdt2) testActRef3 := swarm.NewAddress([]byte("39a5ea87b141fe44aa609c3327ecd893")) thirdTime := time.Date(2015, time.April, 1, 0, 0, 0, 0, time.UTC).Unix() mtdt3 := map[string]string{"thirdTime": "2015-04-01"} - h.Add(ctx, testActRef3, &thirdTime, &mtdt3) + _ = h.Add(ctx, testActRef3, &thirdTime, &mtdt3) testActRef4 := swarm.NewAddress([]byte("39a5ea87b141fe44aa609c3327ecd894")) fourthTime := time.Date(2020, time.April, 1, 0, 0, 0, 0, time.UTC).Unix() mtdt4 := map[string]string{"fourthTime": "2020-04-01"} - h.Add(ctx, testActRef4, &fourthTime, &mtdt4) + _ = h.Add(ctx, testActRef4, &fourthTime, &mtdt4) testActRef5 := swarm.NewAddress([]byte("39a5ea87b141fe44aa609c3327ecd895")) fifthTime := time.Date(2030, time.April, 1, 0, 0, 0, 0, time.UTC).Unix() mtdt5 := map[string]string{"fifthTime": "2030-04-01"} - h.Add(ctx, testActRef5, &fifthTime, &mtdt5) + _ = h.Add(ctx, testActRef5, &fifthTime, &mtdt5) // latest searchedTime := time.Date(1980, time.April, 1, 0, 0, 0, 0, time.UTC).Unix() @@ -126,7 +130,7 @@ func TestHistoryStore(t *testing.T) { testActRef1 := swarm.NewAddress([]byte("39a5ea87b141fe44aa609c3327ecd891")) firstTime := time.Date(1994, time.April, 1, 0, 0, 0, 0, time.UTC).Unix() mtdt1 := map[string]string{"firstTime": "1994-04-01"} - h1.Add(ctx, testActRef1, &firstTime, &mtdt1) + _ = h1.Add(ctx, testActRef1, &firstTime, &mtdt1) href1, err := h1.Store(ctx) assert.NoError(t, err) @@ -134,7 +138,7 @@ func TestHistoryStore(t *testing.T) { h2, err := dynamicaccess.NewHistoryReference(ls, href1) assert.NoError(t, err) - entry1, err := h2.Lookup(ctx, firstTime) + entry1, _ := h2.Lookup(ctx, firstTime) actRef1 := entry1.Reference() assert.True(t, actRef1.Equal(testActRef1)) assert.True(t, reflect.DeepEqual(mtdt1, entry1.Metadata())) diff --git a/pkg/dynamicaccess/mock/accesslogic.go b/pkg/dynamicaccess/mock/accesslogic.go index 8be8e3a07fd..6b48c824eb9 100644 --- a/pkg/dynamicaccess/mock/accesslogic.go +++ b/pkg/dynamicaccess/mock/accesslogic.go @@ -1,3 +1,6 @@ +// Copyright 2024 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. package mock type AccessLogicMock struct { diff --git a/pkg/dynamicaccess/mock/controller.go b/pkg/dynamicaccess/mock/controller.go index 09cacb65145..7f77ca2ca32 100644 --- a/pkg/dynamicaccess/mock/controller.go +++ b/pkg/dynamicaccess/mock/controller.go @@ -126,7 +126,7 @@ func (m *mockDacService) UploadHandler(ctx context.Context, ls file.LoadSaver, r } } else { h, _ = dynamicaccess.NewHistory(m.ls) - h.Add(ctx, kvsRef, &now, nil) + _ = h.Add(ctx, kvsRef, &now, nil) historyRef, _ = h.Store(ctx) m.historyMap[historyRef.String()] = h } @@ -140,7 +140,7 @@ func (m *mockDacService) Close() error { return nil } -func (m *mockDacService) HandleGrantees(ctx context.Context, ls file.LoadSaver, gls file.LoadSaver, encryptedglref swarm.Address, historyref swarm.Address, publisher *ecdsa.PublicKey, addList []*ecdsa.PublicKey, removeList []*ecdsa.PublicKey) (swarm.Address, swarm.Address, swarm.Address, swarm.Address, error) { +func (m *mockDacService) HandleGrantees(_ context.Context, ls file.LoadSaver, gls file.LoadSaver, encryptedglref swarm.Address, historyref swarm.Address, publisher *ecdsa.PublicKey, addList []*ecdsa.PublicKey, removeList []*ecdsa.PublicKey) (swarm.Address, swarm.Address, swarm.Address, swarm.Address, error) { historyRef, _ := swarm.ParseHexAddress("67bdf80a9bbea8eca9c8480e43fdceb485d2d74d5708e45144b8c4adacd13d9c") glRef, _ := swarm.ParseHexAddress("3339613565613837623134316665343461613630396333333237656364383934") eglRef, _ := swarm.ParseHexAddress("fc4e9fe978991257b897d987bc4ff13058b66ef45a53189a0b4fe84bb3346396") diff --git a/pkg/dynamicaccess/mock/grantee.go b/pkg/dynamicaccess/mock/grantee.go index 50689ade08f..6a8f01c87cb 100644 --- a/pkg/dynamicaccess/mock/grantee.go +++ b/pkg/dynamicaccess/mock/grantee.go @@ -1,3 +1,7 @@ +// Copyright 2024 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package mock import ( diff --git a/pkg/dynamicaccess/mock/session.go b/pkg/dynamicaccess/mock/session.go index 9613aacedfa..6e5d43a9576 100644 --- a/pkg/dynamicaccess/mock/session.go +++ b/pkg/dynamicaccess/mock/session.go @@ -1,3 +1,7 @@ +// Copyright 2024 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package mock import ( @@ -17,7 +21,6 @@ func (s *SessionMock) Key(publicKey *ecdsa.PublicKey, nonces [][]byte) ([][]byte return nil, nil } return s.KeyFunc(publicKey, nonces) - } func NewSessionMock(key *ecdsa.PrivateKey) *SessionMock { diff --git a/pkg/dynamicaccess/session.go b/pkg/dynamicaccess/session.go index 0b58c1aa3dd..fb1f44241be 100644 --- a/pkg/dynamicaccess/session.go +++ b/pkg/dynamicaccess/session.go @@ -1,8 +1,13 @@ +// Copyright 2024 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package dynamicaccess import ( "crypto/ecdsa" "errors" + "fmt" "github.com/ethersphere/bee/v2/pkg/crypto" "github.com/ethersphere/bee/v2/pkg/keystore" @@ -14,19 +19,24 @@ type Session interface { Key(publicKey *ecdsa.PublicKey, nonces [][]byte) ([][]byte, error) } -var _ Session = (*session)(nil) +var _ Session = (*SessionStruct)(nil) -type session struct { +type SessionStruct struct { key *ecdsa.PrivateKey } -func (s *session) Key(publicKey *ecdsa.PublicKey, nonces [][]byte) ([][]byte, error) { +var ( + ErrInvalidPublicKey = errors.New("invalid public key") + ErrSecretKeyInfinity = errors.New("shared secret is point at infinity") +) + +func (s *SessionStruct) Key(publicKey *ecdsa.PublicKey, nonces [][]byte) ([][]byte, error) { if publicKey == nil { - return nil, errors.New("invalid public key") + return nil, ErrInvalidPublicKey } x, y := publicKey.Curve.ScalarMult(publicKey.X, publicKey.Y, s.key.D.Bytes()) if x == nil || y == nil { - return nil, errors.New("shared secret is point at infinity") + return nil, ErrSecretKeyInfinity } if len(nonces) == 0 { @@ -37,7 +47,7 @@ func (s *session) Key(publicKey *ecdsa.PublicKey, nonces [][]byte) ([][]byte, er for _, nonce := range nonces { key, err := crypto.LegacyKeccak256(append(x.Bytes(), nonce...)) if err != nil { - return nil, err + return nil, fmt.Errorf("failed to get Keccak256 hash: %w", err) } keys = append(keys, key) } @@ -45,13 +55,13 @@ func (s *session) Key(publicKey *ecdsa.PublicKey, nonces [][]byte) ([][]byte, er return keys, nil } -func NewDefaultSession(key *ecdsa.PrivateKey) Session { - return &session{ +func NewDefaultSession(key *ecdsa.PrivateKey) *SessionStruct { + return &SessionStruct{ key: key, } } // Currently implemented only in mock/session.go -func NewFromKeystore(ks keystore.Service, tag, password string) Session { +func NewFromKeystore(keystore.Service, string, string) Session { return nil } diff --git a/pkg/dynamicaccess/session_test.go b/pkg/dynamicaccess/session_test.go index 493b998a805..701384b93bb 100644 --- a/pkg/dynamicaccess/session_test.go +++ b/pkg/dynamicaccess/session_test.go @@ -1,3 +1,7 @@ +// Copyright 2024 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package dynamicaccess_test import ( @@ -14,7 +18,7 @@ import ( memkeystore "github.com/ethersphere/bee/v2/pkg/keystore/mem" ) -func mockKeyFunc(publicKey *ecdsa.PublicKey, nonces [][]byte) ([][]byte, error) { +func mockKeyFunc(*ecdsa.PublicKey, [][]byte) ([][]byte, error) { return [][]byte{{1}}, nil } diff --git a/pkg/kvs/kvs_test.go b/pkg/kvs/kvs_test.go index 462e092d532..e2da7aa7030 100644 --- a/pkg/kvs/kvs_test.go +++ b/pkg/kvs/kvs_test.go @@ -33,11 +33,11 @@ func createLs() file.LoadSaver { } func keyValuePair(t *testing.T) ([]byte, []byte) { + t.Helper() return swarm.RandAddress(t).Bytes(), swarm.RandAddress(t).Bytes() } func TestKvs(t *testing.T) { - s, err := kvs.New(createLs()) assert.NoError(t, err) @@ -130,7 +130,7 @@ func TestKvs_Save(t *testing.T) { }) t.Run("Save not empty KVS return valid swarm address", func(t *testing.T) { s, _ := kvs.New(createLs()) - s.Put(ctx, key1, val1) + _ = s.Put(ctx, key1, val1) ref, err := s.Save(ctx) assert.NoError(t, err) assert.True(t, ref.IsValidNonEmpty()) diff --git a/pkg/kvs/mock/kvs.go b/pkg/kvs/mock/kvs.go index 0203cc52ce6..f5818972004 100644 --- a/pkg/kvs/mock/kvs.go +++ b/pkg/kvs/mock/kvs.go @@ -1,3 +1,7 @@ +// Copyright 2024 The Swarm Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + package mock import ( @@ -24,7 +28,8 @@ func getInMemorySwarm() *single { defer lock.Unlock() if singleInMemorySwarm == nil { singleInMemorySwarm = &single{ - memoryMock: make(map[string]map[string][]byte)} + memoryMock: make(map[string]map[string][]byte), + } } } return singleInMemorySwarm diff --git a/pkg/manifest/mantaray/node.go b/pkg/manifest/mantaray/node.go index 5a59c010d52..9561c299db5 100644 --- a/pkg/manifest/mantaray/node.go +++ b/pkg/manifest/mantaray/node.go @@ -16,13 +16,8 @@ const ( ) var ( - ZeroObfuscationKey []byte -) - -// nolint:gochecknoinits -func init() { ZeroObfuscationKey = make([]byte, 32) -} +) // Error used when lookup path does not match var (