From 3177d1a30aac8dd46360ae609713d2863df38496 Mon Sep 17 00:00:00 2001 From: aryan Date: Tue, 21 Feb 2023 15:11:06 +0530 Subject: [PATCH 01/26] things, twins, and logger lint fixed Signed-off-by: aryan --- logger/logger.go | 8 ++--- things/api/auth/grpc/endpoint_test.go | 4 ++- things/api/auth/grpc/setup_test.go | 31 ++++++++++++---- things/api/things/http/endpoint_test.go | 48 ++++++++++++++++--------- things/mocks/channels.go | 3 -- things/mocks/things.go | 4 --- things/postgres/channels.go | 22 +++++++++--- things/postgres/channels_test.go | 19 +++++++--- things/postgres/things.go | 5 ++- things/redis/streams.go | 35 ++++++++++-------- things/redis/things_test.go | 3 +- twins/api/http/endpoint_twins_test.go | 2 +- twins/mongodb/states.go | 2 +- twins/mongodb/states_test.go | 12 ++++--- twins/mongodb/twins_test.go | 6 ++-- twins/service.go | 10 +++--- twins/service_test.go | 3 +- 17 files changed, 143 insertions(+), 74 deletions(-) diff --git a/logger/logger.go b/logger/logger.go index c2b08b808d..f8c2a335d1 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -47,25 +47,25 @@ func New(out io.Writer, levelText string) (Logger, error) { func (l logger) Debug(msg string) { if Debug.isAllowed(l.level) { - l.kitLogger.Log("level", Debug.String(), "message", msg) + _ = l.kitLogger.Log("level", Debug.String(), "message", msg) } } func (l logger) Info(msg string) { if Info.isAllowed(l.level) { - l.kitLogger.Log("level", Info.String(), "message", msg) + _ = l.kitLogger.Log("level", Info.String(), "message", msg) } } func (l logger) Warn(msg string) { if Warn.isAllowed(l.level) { - l.kitLogger.Log("level", Warn.String(), "message", msg) + _ = l.kitLogger.Log("level", Warn.String(), "message", msg) } } func (l logger) Error(msg string) { if Error.isAllowed(l.level) { - l.kitLogger.Log("level", Error.String(), "message", msg) + _ = l.kitLogger.Log("level", Error.String(), "message", msg) } } diff --git a/things/api/auth/grpc/endpoint_test.go b/things/api/auth/grpc/endpoint_test.go index d88229f65d..c9b89eaf9a 100644 --- a/things/api/auth/grpc/endpoint_test.go +++ b/things/api/auth/grpc/endpoint_test.go @@ -100,7 +100,9 @@ func TestCanAccessByID(t *testing.T) { chs, err := svc.CreateChannels(context.Background(), token, channel) require.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) ch := chs[0] - svc.Connect(context.Background(), token, []string{ch.ID}, []string{th2.ID}) + + err = svc.Connect(context.Background(), token, []string{ch.ID}, []string{th2.ID}) + assert.Nil(t, err, fmt.Sprintf("got unexpected error while connecting to service: %s", err)) usersAddr := fmt.Sprintf("localhost:%d", port) conn, err := grpc.Dial(usersAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) diff --git a/things/api/auth/grpc/setup_test.go b/things/api/auth/grpc/setup_test.go index b2201ae67b..f9de150a54 100644 --- a/things/api/auth/grpc/setup_test.go +++ b/things/api/auth/grpc/setup_test.go @@ -5,6 +5,7 @@ package grpc_test import ( "fmt" + "log" "net" "os" "testing" @@ -15,6 +16,7 @@ import ( grpcapi "github.com/mainflux/mainflux/things/api/auth/grpc" "github.com/mainflux/mainflux/things/mocks" "github.com/opentracing/opentracing-go/mocktracer" + "github.com/stretchr/testify/assert" "google.golang.org/grpc" ) @@ -28,17 +30,34 @@ const ( var svc things.Service func TestMain(m *testing.M) { - startServer() - code := m.Run() - os.Exit(code) + serverErr := make(chan error) + testRes := make(chan int) + startServer(&testing.T{}, serverErr) + + for { + select { + case testRes <- m.Run(): + code := <-testRes + os.Exit(code) + case err := <-serverErr: + if err != nil { + log.Fatalf("gPRC Server Terminated") + } + } + } } -func startServer() { +func startServer(t *testing.T, serverErr chan error) { svc = newService(map[string]string{token: email}) - listener, _ := net.Listen("tcp", fmt.Sprintf(":%d", port)) + listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) + assert.Nil(t, err, fmt.Sprintf("got unexpected error while creating new listener: %s", err)) + server := grpc.NewServer() mainflux.RegisterThingsServiceServer(server, grpcapi.NewServer(mocktracer.New(), svc)) - go server.Serve(listener) + + go func() { + serverErr <- server.Serve(listener) + }() } func newService(tokens map[string]string) things.Service { diff --git a/things/api/things/http/endpoint_test.go b/things/api/things/http/endpoint_test.go index 07061a3626..1e638dd68e 100644 --- a/things/api/things/http/endpoint_test.go +++ b/things/api/things/http/endpoint_test.go @@ -956,12 +956,14 @@ func TestListThings(t *testing.T) { token: tc.auth, } res, err := req.make() - assert.Nil(t, err, fmt.Sprintf("%s: got unexpected error %s", tc.desc, err)) + assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) var data thingsPageRes - json.NewDecoder(res.Body).Decode(&data) + err = json.NewDecoder(res.Body).Decode(&data) + assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) + assert.Equal(t, tc.statusCode, res.StatusCode, fmt.Sprintf("%s: expected status code %d got %d", tc.desc, tc.statusCode, res.StatusCode)) - assert.ElementsMatch(t, tc.res, data.Things, fmt.Sprintf("%s: got incorrect list of things from response body", tc.desc)) + assert.ElementsMatch(t, tc.res, data.Things, fmt.Sprintf("%s: expected body %v got %v", tc.desc, tc.res, data.Things)) } } @@ -1153,12 +1155,14 @@ func TestSearchThings(t *testing.T) { body: strings.NewReader(tc.req), } res, err := req.make() - assert.Nil(t, err, fmt.Sprintf("%s: got unexpected error %s", tc.desc, err)) + assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) var data thingsPageRes - json.NewDecoder(res.Body).Decode(&data) + err = json.NewDecoder(res.Body).Decode(&data) + assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) + assert.Equal(t, tc.statusCode, res.StatusCode, fmt.Sprintf("%s: expected status code %d got %d", tc.desc, tc.statusCode, res.StatusCode)) - assert.ElementsMatch(t, tc.res, data.Things, fmt.Sprintf("%s: got incorrect list of things from response body", tc.desc)) + assert.ElementsMatch(t, tc.res, data.Things, fmt.Sprintf("%s: expected body %v got %v", tc.desc, tc.res, data.Things)) } } @@ -1337,12 +1341,14 @@ func TestListThingsByChannel(t *testing.T) { token: tc.auth, } res, err := req.make() - assert.Nil(t, err, fmt.Sprintf("%s: got unexpected error %s", tc.desc, err)) + assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) var data thingsPageRes - json.NewDecoder(res.Body).Decode(&data) + err = json.NewDecoder(res.Body).Decode(&data) + assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) + assert.Equal(t, tc.statusCode, res.StatusCode, fmt.Sprintf("%s: expected status code %d got %d", tc.desc, tc.statusCode, res.StatusCode)) - assert.ElementsMatch(t, tc.res, data.Things, fmt.Sprintf("%s: got incorrect list of things from response body", tc.desc)) + assert.ElementsMatch(t, tc.res, data.Things, fmt.Sprintf("%s: expected body %v got %v", tc.desc, tc.res, data.Things)) } } @@ -1725,7 +1731,8 @@ func TestViewChannel(t *testing.T) { ths, err := svc.CreateThings(context.Background(), token, thing) require.Nil(t, err, fmt.Sprintf("got unexpected error: %s\n", err)) th := ths[0] - svc.Connect(context.Background(), token, []string{sch.ID}, []string{th.ID}) + err = svc.Connect(context.Background(), token, []string{sch.ID}, []string{th.ID}) + assert.Nil(t, err, fmt.Sprintf("got unexpected error when connecting to service: %s", err)) data := toJSON(channelRes{ ID: sch.ID, @@ -1815,7 +1822,8 @@ func TestListChannels(t *testing.T) { ths, err := svc.CreateThings(context.Background(), token, thing) assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) th := ths[0] - svc.Connect(context.Background(), token, []string{ch.ID}, []string{th.ID}) + err = svc.Connect(context.Background(), token, []string{ch.ID}, []string{th.ID}) + assert.Nil(t, err, fmt.Sprintf("got unexpected error while connecting to service: %s", err)) channels = append(channels, channelRes{ ID: ch.ID, @@ -2006,9 +2014,11 @@ func TestListChannels(t *testing.T) { assert.Nil(t, err, fmt.Sprintf("%s: got unexpected error %s", tc.desc, err)) var body channelsPageRes - json.NewDecoder(res.Body).Decode(&body) + err = json.NewDecoder(res.Body).Decode(&body) + assert.Nil(t, err, fmt.Sprintf("%s: unexpected error while deconding response body: %s", tc.desc, err)) + assert.Equal(t, tc.statusCode, res.StatusCode, fmt.Sprintf("%s: expected status code %d got %d", tc.desc, tc.statusCode, res.StatusCode)) - assert.ElementsMatch(t, tc.res, body.Channels, fmt.Sprintf("%s: got incorrect list of channels from response body", tc.desc)) + assert.ElementsMatch(t, tc.res, body.Channels, fmt.Sprintf("%s: expected body %v got %v", tc.desc, tc.res, body.Channels)) } } @@ -2186,9 +2196,11 @@ func TestListChannelsByThing(t *testing.T) { assert.Nil(t, err, fmt.Sprintf("%s: got unexpected error %s", tc.desc, err)) var body channelsPageRes - json.NewDecoder(res.Body).Decode(&body) + err = json.NewDecoder(res.Body).Decode(&body) + assert.Nil(t, err, fmt.Sprintf("%s: unexpected error while decoding response body: %s", tc.desc, err)) + assert.Equal(t, tc.statusCode, res.StatusCode, fmt.Sprintf("%s: expected status code %d got %d", tc.desc, tc.statusCode, res.StatusCode)) - assert.ElementsMatch(t, tc.res, body.Channels, fmt.Sprintf("%s: got incorrect list of channels from response body", tc.desc)) + assert.ElementsMatch(t, tc.res, body.Channels, fmt.Sprintf("%s: expected body %v got %v", tc.desc, tc.res, body.Channels)) } } @@ -2741,9 +2753,13 @@ func TestDisconnnect(t *testing.T) { ths, _ := svc.CreateThings(context.Background(), token, thing) th1 := ths[0] + chs, _ := svc.CreateChannels(context.Background(), token, channel) ch1 := chs[0] - svc.Connect(context.Background(), token, []string{ch1.ID}, []string{th1.ID}) + + err := svc.Connect(context.Background(), token, []string{ch1.ID}, []string{th1.ID}) + assert.Nil(t, err, fmt.Sprintf("got unexpected error while connecting to service: %s", err)) + chs, _ = svc.CreateChannels(context.Background(), otherToken, channel) ch2 := chs[0] diff --git a/things/mocks/channels.go b/things/mocks/channels.go index 72c6a2d6f2..4b646ae2c2 100644 --- a/things/mocks/channels.go +++ b/things/mocks/channels.go @@ -80,9 +80,6 @@ func (crm *channelRepositoryMock) RetrieveByID(_ context.Context, owner, id stri } func (crm *channelRepositoryMock) RetrieveAll(_ context.Context, owner string, pm things.PageMetadata) (things.ChannelsPage, error) { - if pm.Limit < 0 { - return things.ChannelsPage{}, nil - } if pm.Limit == 0 { pm.Limit = 10 } diff --git a/things/mocks/things.go b/things/mocks/things.go index d318c1e7b4..42d94932fd 100644 --- a/things/mocks/things.go +++ b/things/mocks/things.go @@ -117,10 +117,6 @@ func (trm *thingRepositoryMock) RetrieveAll(_ context.Context, owner string, pm trm.mu.Lock() defer trm.mu.Unlock() - if pm.Limit < 0 { - return things.Page{}, nil - } - first := uint64(pm.Offset) + 1 last := first + uint64(pm.Limit) diff --git a/things/postgres/channels.go b/things/postgres/channels.go index 15096d504e..fe880fa1c3 100644 --- a/things/postgres/channels.go +++ b/things/postgres/channels.go @@ -52,7 +52,10 @@ func (cr channelRepository) Save(ctx context.Context, channels ...things.Channel _, err = tx.NamedExecContext(ctx, q, dbch) if err != nil { - tx.Rollback() + err = tx.Rollback() + if err != nil { + return []things.Channel{}, errors.Wrap(errors.ErrCreateEntity, err) + } pgErr, ok := err.(*pgconn.PgError) if ok { switch pgErr.Code { @@ -291,8 +294,9 @@ func (cr channelRepository) Remove(ctx context.Context, owner, id string) error Owner: owner, } q := `DELETE FROM channels WHERE id = :id AND owner = :owner` - cr.db.NamedExecContext(ctx, q, dbch) - return nil + + _, err := cr.db.NamedExecContext(ctx, q, dbch) + return err } func (cr channelRepository) Connect(ctx context.Context, owner string, chIDs, thIDs []string) error { @@ -314,7 +318,11 @@ func (cr channelRepository) Connect(ctx context.Context, owner string, chIDs, th _, err := tx.NamedExecContext(ctx, q, dbco) if err != nil { - tx.Rollback() + err = tx.Rollback() + if err != nil { + return errors.Wrap(things.ErrConnect, err) + } + pgErr, ok := err.(*pgconn.PgError) if ok { switch pgErr.Code { @@ -357,7 +365,11 @@ func (cr channelRepository) Disconnect(ctx context.Context, owner string, chIDs, res, err := tx.NamedExecContext(ctx, q, dbco) if err != nil { - tx.Rollback() + err = tx.Rollback() + if err != nil { + return errors.Wrap(things.ErrConnect, err) + } + pgErr, ok := err.(*pgconn.PgError) if ok { switch pgErr.Code { diff --git a/things/postgres/channels_test.go b/things/postgres/channels_test.go index 6ce8cbf01d..1cd271d9c6 100644 --- a/things/postgres/channels_test.go +++ b/things/postgres/channels_test.go @@ -172,7 +172,9 @@ func TestSingleChannelRetrieval(t *testing.T) { } chs, _ := chanRepo.Save(context.Background(), ch) ch.ID = chs[0].ID - chanRepo.Connect(context.Background(), email, []string{ch.ID}, []string{th.ID}) + + err = chanRepo.Connect(context.Background(), email, []string{ch.ID}, []string{th.ID}) + assert.Nil(t, err, fmt.Sprintf("got unexpected error while connecting to service: %s", err)) nonexistentChanID, err := idProvider.ID() assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) @@ -256,7 +258,8 @@ func TestMultiChannelRetrieval(t *testing.T) { ch.Name = name } - chanRepo.Save(context.Background(), ch) + _, err = chanRepo.Save(context.Background(), ch) + assert.Nil(t, err, fmt.Sprintf("got unexpected error while saving channels: %s", err)) } cases := []struct { @@ -702,7 +705,9 @@ func TestDisconnect(t *testing.T) { }) assert.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) chID = chs[0].ID - chanRepo.Connect(context.Background(), email, []string{chID}, []string{thID}) + + err = chanRepo.Connect(context.Background(), email, []string{chID}, []string{thID}) + assert.Nil(t, err, fmt.Sprintf("got unexpected error while connecting to service: %s", err)) nonexistentThingID, err := idProvider.ID() assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) @@ -788,7 +793,9 @@ func TestHasThing(t *testing.T) { }) assert.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) chID = chs[0].ID - chanRepo.Connect(context.Background(), email, []string{chID}, []string{thID}) + + err = chanRepo.Connect(context.Background(), email, []string{chID}, []string{thID}) + assert.Nil(t, err, fmt.Sprintf("got unexpected error while connecting to service: %s", err)) nonexistentChanID, err := idProvider.ID() assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) @@ -866,7 +873,9 @@ func TestHasThingByID(t *testing.T) { }) assert.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) chID = chs[0].ID - chanRepo.Connect(context.Background(), email, []string{chID}, []string{thID}) + + err = chanRepo.Connect(context.Background(), email, []string{chID}, []string{thID}) + assert.Nil(t, err, fmt.Sprintf("got unexpected error while connecting to service: %s", err)) nonexistentChanID, err := idProvider.ID() assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) diff --git a/things/postgres/things.go b/things/postgres/things.go index 0db9f4a606..e5d8f5a376 100644 --- a/things/postgres/things.go +++ b/things/postgres/things.go @@ -48,7 +48,10 @@ func (tr thingRepository) Save(ctx context.Context, ths ...things.Thing) ([]thin } if _, err := tx.NamedExecContext(ctx, q, dbth); err != nil { - tx.Rollback() + err = tx.Rollback() + if err != nil { + return []things.Thing{}, errors.Wrap(errors.ErrCreateEntity, err) + } pgErr, ok := err.(*pgconn.PgError) if ok { switch pgErr.Code { diff --git a/things/redis/streams.go b/things/redis/streams.go index 8132b2fe2b..2617bd2286 100644 --- a/things/redis/streams.go +++ b/things/redis/streams.go @@ -49,7 +49,11 @@ func (es eventStore) CreateThings(ctx context.Context, token string, ths ...thin MaxLenApprox: streamLen, Values: event.Encode(), } - es.client.XAdd(ctx, record).Err() + + err = es.client.XAdd(ctx, record).Err() + if err != nil { + return sths, err + } } return sths, nil @@ -70,9 +74,8 @@ func (es eventStore) UpdateThing(ctx context.Context, token string, thing things MaxLenApprox: streamLen, Values: event.Encode(), } - es.client.XAdd(ctx, record).Err() - return nil + return es.client.XAdd(ctx, record).Err() } // UpdateKey doesn't send event because key shouldn't be sent over stream. @@ -111,9 +114,8 @@ func (es eventStore) RemoveThing(ctx context.Context, token, id string) error { MaxLenApprox: streamLen, Values: event.Encode(), } - es.client.XAdd(ctx, record).Err() - return nil + return es.client.XAdd(ctx, record).Err() } func (es eventStore) CreateChannels(ctx context.Context, token string, channels ...things.Channel) ([]things.Channel, error) { @@ -134,7 +136,10 @@ func (es eventStore) CreateChannels(ctx context.Context, token string, channels MaxLenApprox: streamLen, Values: event.Encode(), } - es.client.XAdd(ctx, record).Err() + err = es.client.XAdd(ctx, record).Err() + if err != nil { + return schs, err + } } return schs, nil @@ -155,9 +160,7 @@ func (es eventStore) UpdateChannel(ctx context.Context, token string, channel th MaxLenApprox: streamLen, Values: event.Encode(), } - es.client.XAdd(ctx, record).Err() - - return nil + return es.client.XAdd(ctx, record).Err() } func (es eventStore) ViewChannel(ctx context.Context, token, id string) (things.Channel, error) { @@ -185,9 +188,7 @@ func (es eventStore) RemoveChannel(ctx context.Context, token, id string) error MaxLenApprox: streamLen, Values: event.Encode(), } - es.client.XAdd(ctx, record).Err() - - return nil + return es.client.XAdd(ctx, record).Err() } func (es eventStore) Connect(ctx context.Context, token string, chIDs, thIDs []string) error { @@ -206,7 +207,10 @@ func (es eventStore) Connect(ctx context.Context, token string, chIDs, thIDs []s MaxLenApprox: streamLen, Values: event.Encode(), } - es.client.XAdd(ctx, record).Err() + err := es.client.XAdd(ctx, record).Err() + if err != nil { + return err + } } } @@ -229,7 +233,10 @@ func (es eventStore) Disconnect(ctx context.Context, token string, chIDs, thIDs MaxLenApprox: streamLen, Values: event.Encode(), } - es.client.XAdd(ctx, record).Err() + err := es.client.XAdd(ctx, record).Err() + if err != nil { + return err + } } } diff --git a/things/redis/things_test.go b/things/redis/things_test.go index 13e7680cf3..d4780e56a9 100644 --- a/things/redis/things_test.go +++ b/things/redis/things_test.go @@ -95,7 +95,8 @@ func TestThingRemove(t *testing.T) { assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) id := "123" id2 := "321" - thingCache.Save(context.Background(), key, id) + err = thingCache.Save(context.Background(), key, id) + assert.Nil(t, err, fmt.Sprintf("got unexpected error while saving thingKey-thingID pair: %s", err)) cases := []struct { desc string diff --git a/twins/api/http/endpoint_twins_test.go b/twins/api/http/endpoint_twins_test.go index 9921b11048..56d7202b97 100644 --- a/twins/api/http/endpoint_twins_test.go +++ b/twins/api/http/endpoint_twins_test.go @@ -392,7 +392,7 @@ func TestViewTwin(t *testing.T) { var resData twinRes err = json.NewDecoder(res.Body).Decode(&resData) - assert.Nil(t, err, fmt.Sprintf("%s: got unexpected error while decoding json: %s", tc.desc, err)) + assert.Nil(t, err, fmt.Sprintf("%s: gotunexpected error while decoding response body: %s\n", tc.desc, err)) assert.Equal(t, tc.res, resData, fmt.Sprintf("%s: expected body %v got %v", tc.desc, tc.res, resData)) } } diff --git a/twins/mongodb/states.go b/twins/mongodb/states.go index b8585eaec2..1004776984 100644 --- a/twins/mongodb/states.go +++ b/twins/mongodb/states.go @@ -14,7 +14,7 @@ import ( const ( statesCollection string = "states" - twinid = "twinid" + twinid string = "twinid" ) type stateRepository struct { diff --git a/twins/mongodb/states_test.go b/twins/mongodb/states_test.go index cfe038cb0c..e0c1cc0408 100644 --- a/twins/mongodb/states_test.go +++ b/twins/mongodb/states_test.go @@ -58,7 +58,8 @@ func TestStatesRetrieveAll(t *testing.T) { require.Nil(t, err, fmt.Sprintf("Creating new MongoDB client expected to succeed: %s.\n", err)) db := client.Database(testDB) - db.Collection("states").DeleteMany(context.Background(), bson.D{}) + _, err = db.Collection("states").DeleteMany(context.Background(), bson.D{}) + require.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) repo := mongodb.NewStateRepository(db) @@ -73,7 +74,8 @@ func TestStatesRetrieveAll(t *testing.T) { Created: time.Now(), } - repo.Save(context.Background(), st) + err = repo.Save(context.Background(), st) + require.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) } cases := map[string]struct { @@ -120,7 +122,8 @@ func TestStatesRetrieveLast(t *testing.T) { require.Nil(t, err, fmt.Sprintf("Creating new MongoDB client expected to succeed: %s.\n", err)) db := client.Database(testDB) - db.Collection("states").DeleteMany(context.Background(), bson.D{}) + _, err = db.Collection("states").DeleteMany(context.Background(), bson.D{}) + require.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) repo := mongodb.NewStateRepository(db) @@ -135,7 +138,8 @@ func TestStatesRetrieveLast(t *testing.T) { Created: time.Now(), } - repo.Save(context.Background(), st) + err = repo.Save(context.Background(), st) + require.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) } cases := map[string]struct { diff --git a/twins/mongodb/twins_test.go b/twins/mongodb/twins_test.go index dba9796668..6854536bb5 100644 --- a/twins/mongodb/twins_test.go +++ b/twins/mongodb/twins_test.go @@ -249,7 +249,8 @@ func TestTwinsRetrieveAll(t *testing.T) { require.Nil(t, err, fmt.Sprintf("Creating new MongoDB client expected to succeed: %s.\n", err)) db := client.Database(testDB) - db.Collection(collection).DeleteMany(context.Background(), bson.D{}) + _, err = db.Collection(collection).DeleteMany(context.Background(), bson.D{}) + require.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) twinRepo := mongodb.NewTwinRepository(db) @@ -269,7 +270,8 @@ func TestTwinsRetrieveAll(t *testing.T) { tw.Name = name } - twinRepo.Save(context.Background(), tw) + _, err = twinRepo.Save(context.Background(), tw) + require.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) } cases := map[string]struct { diff --git a/twins/service.go b/twins/service.go index ff374d5764..127fffad58 100644 --- a/twins/service.go +++ b/twins/service.go @@ -285,17 +285,17 @@ func (ts *twinsService) saveState(msg *messaging.Message, twinID string) error { tw, err := ts.twins.RetrieveByID(ctx, twinID) if err != nil { - return fmt.Errorf("Retrieving twin for %s failed: %s", msg.Publisher, err) + return fmt.Errorf("retrieving twin for %s failed: %s", msg.Publisher, err) } var recs []senml.Record if err := json.Unmarshal(msg.Payload, &recs); err != nil { - return fmt.Errorf("Unmarshal payload for %s failed: %s", msg.Publisher, err) + return fmt.Errorf("unmarshal payload for %s failed: %s", msg.Publisher, err) } st, err := ts.states.RetrieveLast(ctx, tw.ID) if err != nil { - return fmt.Errorf("Retrieve last state for %s failed: %s", msg.Publisher, err) + return fmt.Errorf("retrieve last state for %s failed: %s", msg.Publisher, err) } for _, rec := range recs { @@ -305,11 +305,11 @@ func (ts *twinsService) saveState(msg *messaging.Message, twinID string) error { return nil case update: if err := ts.states.Update(ctx, st); err != nil { - return fmt.Errorf("Update state for %s failed: %s", msg.Publisher, err) + return fmt.Errorf("update state for %s failed: %s", msg.Publisher, err) } case save: if err := ts.states.Save(ctx, st); err != nil { - return fmt.Errorf("Save state for %s failed: %s", msg.Publisher, err) + return fmt.Errorf("save state for %s failed: %s", msg.Publisher, err) } } } diff --git a/twins/service_test.go b/twins/service_test.go index bca24909ff..a6f0e308fe 100644 --- a/twins/service_test.go +++ b/twins/service_test.go @@ -154,7 +154,8 @@ func TestListTwins(t *testing.T) { n := uint64(10) for i := uint64(0); i < n; i++ { - svc.AddTwin(context.Background(), token, twin, def) + _, err := svc.AddTwin(context.Background(), token, twin, def) + require.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) } cases := []struct { From 24d8b6dc62035cad8201dcb125a73c17ef80bcc5 Mon Sep 17 00:00:00 2001 From: aryan Date: Wed, 22 Feb 2023 16:18:34 +0530 Subject: [PATCH 02/26] all services updated, auth jwt not working, ineffectual assignment issue Signed-off-by: aryan --- auth/jwt/tokenizer.go | 24 +- auth/postgres/groups.go | 12 +- bootstrap/api/endpoint_test.go | 8 +- bootstrap/mocks/configs.go | 4 - bootstrap/redis/producer/streams.go | 20 +- bootstrap/redis/producer/streams_test.go | 47 ++- go.mod | 2 +- go.sum | 4 +- lora/adapter_test.go | 11 +- lora/mqtt/sub.go | 5 +- opcua/db/subs.go | 5 +- opcua/gopcua/subscribe.go | 7 +- readers/api/endpoint_test.go | 4 +- readers/cassandra/messages.go | 5 +- readers/mocks/messages.go | 10 +- readers/mongodb/messages.go | 5 +- readers/postgres/messages.go | 5 +- readers/timescale/messages.go | 5 +- things/postgres/things_test.go | 6 +- tools/mqtt-bench/bench.go | 13 +- tools/mqtt-bench/client.go | 1 - tools/mqtt-bench/results.go | 5 +- .../golang-jwt/jwt/v4/MIGRATION_GUIDE.md | 22 -- vendor/github.com/golang-jwt/jwt/v4/claims.go | 273 ---------------- vendor/github.com/golang-jwt/jwt/v4/errors.go | 112 ------- .../golang-jwt/jwt/v4/map_claims.go | 151 --------- .../golang-jwt/jwt/v4/parser_option.go | 29 -- vendor/github.com/golang-jwt/jwt/v4/token.go | 127 -------- .../golang-jwt/jwt/{v4 => v5}/.gitignore | 0 .../golang-jwt/jwt/{v4 => v5}/LICENSE | 0 .../golang-jwt/jwt/v5/MIGRATION_GUIDE.md | 100 ++++++ .../golang-jwt/jwt/{v4 => v5}/README.md | 30 +- .../golang-jwt/jwt/{v4 => v5}/SECURITY.md | 0 .../jwt/{v4 => v5}/VERSION_HISTORY.md | 16 +- vendor/github.com/golang-jwt/jwt/v5/claims.go | 16 + .../golang-jwt/jwt/{v4 => v5}/doc.go | 0 .../golang-jwt/jwt/{v4 => v5}/ecdsa.go | 0 .../golang-jwt/jwt/{v4 => v5}/ecdsa_utils.go | 0 .../golang-jwt/jwt/{v4 => v5}/ed25519.go | 0 .../jwt/{v4 => v5}/ed25519_utils.go | 0 vendor/github.com/golang-jwt/jwt/v5/errors.go | 49 +++ .../golang-jwt/jwt/v5/errors_go1_20.go | 47 +++ .../golang-jwt/jwt/v5/errors_go_other.go | 78 +++++ .../golang-jwt/jwt/{v4 => v5}/hmac.go | 0 .../golang-jwt/jwt/v5/map_claims.go | 109 +++++++ .../golang-jwt/jwt/{v4 => v5}/none.go | 7 +- .../golang-jwt/jwt/{v4 => v5}/parser.go | 96 +++--- .../golang-jwt/jwt/v5/parser_option.go | 101 ++++++ .../golang-jwt/jwt/v5/registered_claims.go | 63 ++++ .../golang-jwt/jwt/{v4 => v5}/rsa.go | 0 .../golang-jwt/jwt/{v4 => v5}/rsa_pss.go | 0 .../golang-jwt/jwt/{v4 => v5}/rsa_utils.go | 0 .../jwt/{v4 => v5}/signing_method.go | 0 .../jwt/{v4 => v5}/staticcheck.conf | 0 vendor/github.com/golang-jwt/jwt/v5/token.go | 145 +++++++++ .../golang-jwt/jwt/{v4 => v5}/types.go | 43 +-- .../github.com/golang-jwt/jwt/v5/validator.go | 301 ++++++++++++++++++ vendor/modules.txt | 6 +- ws/api/endpoints.go | 4 +- 59 files changed, 1243 insertions(+), 890 deletions(-) delete mode 100644 vendor/github.com/golang-jwt/jwt/v4/MIGRATION_GUIDE.md delete mode 100644 vendor/github.com/golang-jwt/jwt/v4/claims.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v4/errors.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v4/map_claims.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v4/parser_option.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v4/token.go rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/.gitignore (100%) rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/LICENSE (100%) create mode 100644 vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/README.md (89%) rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/SECURITY.md (100%) rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/VERSION_HISTORY.md (96%) create mode 100644 vendor/github.com/golang-jwt/jwt/v5/claims.go rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/doc.go (100%) rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/ecdsa.go (100%) rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/ecdsa_utils.go (100%) rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/ed25519.go (100%) rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/ed25519_utils.go (100%) create mode 100644 vendor/github.com/golang-jwt/jwt/v5/errors.go create mode 100644 vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go create mode 100644 vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/hmac.go (100%) create mode 100644 vendor/github.com/golang-jwt/jwt/v5/map_claims.go rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/none.go (85%) rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/parser.go (54%) create mode 100644 vendor/github.com/golang-jwt/jwt/v5/parser_option.go create mode 100644 vendor/github.com/golang-jwt/jwt/v5/registered_claims.go rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/rsa.go (100%) rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/rsa_pss.go (100%) rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/rsa_utils.go (100%) rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/signing_method.go (100%) rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/staticcheck.conf (100%) create mode 100644 vendor/github.com/golang-jwt/jwt/v5/token.go rename vendor/github.com/golang-jwt/jwt/{v4 => v5}/types.go (76%) create mode 100644 vendor/github.com/golang-jwt/jwt/v5/validator.go diff --git a/auth/jwt/tokenizer.go b/auth/jwt/tokenizer.go index 29a3231519..6761b8e6b8 100644 --- a/auth/jwt/tokenizer.go +++ b/auth/jwt/tokenizer.go @@ -6,7 +6,7 @@ package jwt import ( "time" - "github.com/golang-jwt/jwt/v4" + "github.com/golang-jwt/jwt/v5" "github.com/mainflux/mainflux/auth" "github.com/mainflux/mainflux/pkg/errors" ) @@ -14,7 +14,7 @@ import ( const issuerName = "mainflux.auth" type claims struct { - jwt.StandardClaims + jwt.RegisteredClaims IssuerID string `json:"issuer_id,omitempty"` Type *uint32 `json:"type,omitempty"` } @@ -24,7 +24,7 @@ func (c claims) Valid() error { return errors.ErrMalformedEntity } - return c.StandardClaims.Valid() + return c.RegisteredClaims.ExpiresAt.GobDecode([]byte{}) //.Valid() } type tokenizer struct { @@ -38,20 +38,20 @@ func New(secret string) auth.Tokenizer { func (svc tokenizer) Issue(key auth.Key) (string, error) { claims := claims{ - StandardClaims: jwt.StandardClaims{ + RegisteredClaims: jwt.RegisteredClaims{ Issuer: issuerName, Subject: key.Subject, - IssuedAt: key.IssuedAt.UTC().Unix(), + IssuedAt: &jwt.NumericDate{Time: key.IssuedAt.UTC()}, }, IssuerID: key.IssuerID, Type: &key.Type, } if !key.ExpiresAt.IsZero() { - claims.ExpiresAt = key.ExpiresAt.UTC().Unix() + claims.ExpiresAt = &jwt.NumericDate{Time: key.ExpiresAt.UTC()} } if key.ID != "" { - claims.Id = key.ID + claims.ID = key.ID } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) @@ -68,7 +68,7 @@ func (svc tokenizer) Parse(token string) (auth.Key, error) { }) if err != nil { - if e, ok := err.(*jwt.ValidationError); ok && e.Errors == jwt.ValidationErrorExpired { + if errors.Contains(err, jwt.ErrTokenExpired) { // Expired User key needs to be revoked. if c.Type != nil && *c.Type == auth.APIKey { return c.toKey(), auth.ErrAPIKeyExpired @@ -83,13 +83,13 @@ func (svc tokenizer) Parse(token string) (auth.Key, error) { func (c claims) toKey() auth.Key { key := auth.Key{ - ID: c.Id, + ID: c.ID, IssuerID: c.IssuerID, Subject: c.Subject, - IssuedAt: time.Unix(c.IssuedAt, 0).UTC(), + IssuedAt: time.Unix(c.IssuedAt.Unix(), 0).UTC(), } - if c.ExpiresAt != 0 { - key.ExpiresAt = time.Unix(c.ExpiresAt, 0).UTC() + if c.ExpiresAt.Unix() != 0 { + key.ExpiresAt = time.Unix(c.ExpiresAt.Unix(), 0).UTC() } // Default type is 0. diff --git a/auth/postgres/groups.go b/auth/postgres/groups.go index 79ba3d01f6..009e28931b 100644 --- a/auth/postgres/groups.go +++ b/auth/postgres/groups.go @@ -440,7 +440,11 @@ func (gr groupRepository) Assign(ctx context.Context, groupID, groupType string, dbg.UpdatedAt = created if _, err := tx.NamedExecContext(ctx, qIns, dbg); err != nil { - tx.Rollback() + err = tx.Rollback() + if err != nil { + return errors.Wrap(auth.ErrAssignToGroup, err) + } + pgErr, ok := err.(*pgconn.PgError) if ok { switch pgErr.Code { @@ -479,7 +483,11 @@ func (gr groupRepository) Unassign(ctx context.Context, groupID string, ids ...s } if _, err := tx.NamedExecContext(ctx, qDel, dbg); err != nil { - tx.Rollback() + err = tx.Rollback() + if err != nil { + return errors.Wrap(auth.ErrAssignToGroup, err) + } + pgErr, ok := err.(*pgconn.PgError) if ok { switch pgErr.Code { diff --git a/bootstrap/api/endpoint_test.go b/bootstrap/api/endpoint_test.go index 2bc85e5038..162bfcc5c0 100644 --- a/bootstrap/api/endpoint_test.go +++ b/bootstrap/api/endpoint_test.go @@ -967,7 +967,9 @@ func TestList(t *testing.T) { assert.Equal(t, tc.status, res.StatusCode, fmt.Sprintf("%s: expected status code %d got %d", tc.desc, tc.status, res.StatusCode)) var body configPage - json.NewDecoder(res.Body).Decode(&body) + err = json.NewDecoder(res.Body).Decode(&body) + assert.Nil(t, err, fmt.Sprintf("%s: unexpected error while decoding response body: %s", tc.desc, err)) + assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) assert.ElementsMatch(t, tc.res.Configs, body.Configs, fmt.Sprintf("%s: expected response '%s' got '%s'", tc.desc, tc.res.Configs, body.Configs)) assert.Equal(t, tc.res.Total, body.Total, fmt.Sprintf("%s: expected response total '%d' got '%d'", tc.desc, tc.res.Total, body.Total)) @@ -1157,7 +1159,9 @@ func TestBootstrap(t *testing.T) { assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) if tc.secure && tc.status == http.StatusOK { body, err = dec(body) - assert.Nil(t, err, fmt.Sprintf("%sGot unexpected error: %s\n", tc.desc, err)) + if err != nil { + assert.Nil(t, err, fmt.Sprintf("%s: unexpected error while decoding body: %s", tc.desc, err)) + } } data := strings.Trim(string(body), "\n") diff --git a/bootstrap/mocks/configs.go b/bootstrap/mocks/configs.go index 7206745954..4dfd9b682a 100644 --- a/bootstrap/mocks/configs.go +++ b/bootstrap/mocks/configs.go @@ -83,10 +83,6 @@ func (crm *configRepositoryMock) RetrieveAll(token string, filter bootstrap.Filt configs := make([]bootstrap.Config, 0) - if offset < 0 || limit <= 0 { - return bootstrap.ConfigsPage{} - } - first := uint64(offset) + 1 last := first + uint64(limit) var state bootstrap.State = emptyState diff --git a/bootstrap/redis/producer/streams.go b/bootstrap/redis/producer/streams.go index 1cde7af7e1..2b3fa96c98 100644 --- a/bootstrap/redis/producer/streams.go +++ b/bootstrap/redis/producer/streams.go @@ -53,7 +53,7 @@ func (es eventStore) Add(ctx context.Context, token string, cfg bootstrap.Config timestamp: time.Now(), } - es.add(ctx, ev) + err = es.add(ctx, ev) return saved, err } @@ -74,9 +74,7 @@ func (es eventStore) Update(ctx context.Context, token string, cfg bootstrap.Con timestamp: time.Now(), } - es.add(ctx, ev) - - return nil + return es.add(ctx, ev) } func (es eventStore) UpdateCert(ctx context.Context, token, thingKey, clientCert, clientKey, caCert string) error { @@ -94,9 +92,7 @@ func (es eventStore) UpdateConnections(ctx context.Context, token, id string, co timestamp: time.Now(), } - es.add(ctx, ev) - - return nil + return es.add(ctx, ev) } func (es eventStore) List(ctx context.Context, token string, filter bootstrap.Filter, offset, limit uint64) (bootstrap.ConfigsPage, error) { @@ -113,9 +109,7 @@ func (es eventStore) Remove(ctx context.Context, token, id string) error { timestamp: time.Now(), } - es.add(ctx, ev) - - return nil + return es.add(ctx, ev) } func (es eventStore) Bootstrap(ctx context.Context, externalKey, externalID string, secure bool) (bootstrap.Config, error) { @@ -131,7 +125,7 @@ func (es eventStore) Bootstrap(ctx context.Context, externalKey, externalID stri ev.success = false } - es.add(ctx, ev) + err = es.add(ctx, ev) return cfg, err } @@ -147,9 +141,7 @@ func (es eventStore) ChangeState(ctx context.Context, token, id string, state bo timestamp: time.Now(), } - es.add(ctx, ev) - - return nil + return es.add(ctx, ev) } func (es eventStore) RemoveConfigHandler(ctx context.Context, id string) error { diff --git a/bootstrap/redis/producer/streams_test.go b/bootstrap/redis/producer/streams_test.go index 9a61213bdb..70a1e20c5c 100644 --- a/bootstrap/redis/producer/streams_test.go +++ b/bootstrap/redis/producer/streams_test.go @@ -25,6 +25,7 @@ import ( "github.com/mainflux/mainflux/things" httpapi "github.com/mainflux/mainflux/things/api/things/http" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -92,7 +93,9 @@ func newThingsServer(svc things.Service) *httptest.Server { return httptest.NewServer(mux) } func TestAdd(t *testing.T) { - redisClient.FlushAll(context.Background()).Err() + err := redisClient.FlushAll(context.Background()).Err() + assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) + users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) @@ -106,6 +109,7 @@ func TestAdd(t *testing.T) { invalidConfig := config invalidConfig.MFChannels = []bootstrap.Channel{{ID: "empty"}} + invalidConfig.MFChannels = []bootstrap.Channel{{ID: "empty"}} cases := []struct { desc string @@ -179,7 +183,8 @@ func TestView(t *testing.T) { } func TestUpdate(t *testing.T) { - redisClient.FlushAll(context.Background()).Err() + err := redisClient.FlushAll(context.Background()).Err() + assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) @@ -192,8 +197,10 @@ func TestUpdate(t *testing.T) { ch.ID = "2" c.MFChannels = append(c.MFChannels, ch) saved, err := svc.Add(context.Background(), validToken, c) - assert.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) - redisClient.FlushAll(context.Background()).Err() + require.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) + + err = redisClient.FlushAll(context.Background()).Err() + assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) modified := saved modified.Content = "new-config" @@ -254,7 +261,8 @@ func TestUpdate(t *testing.T) { } func TestUpdateConnections(t *testing.T) { - redisClient.FlushAll(context.Background()).Err() + err := redisClient.FlushAll(context.Background()).Err() + assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) @@ -262,8 +270,9 @@ func TestUpdateConnections(t *testing.T) { svc = producer.NewEventStoreMiddleware(svc, redisClient) saved, err := svc.Add(context.Background(), validToken, config) - assert.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) - redisClient.FlushAll(context.Background()).Err() + require.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) + err = redisClient.FlushAll(context.Background()).Err() + assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) cases := []struct { desc string @@ -336,7 +345,8 @@ func TestList(t *testing.T) { } func TestRemove(t *testing.T) { - redisClient.FlushAll(context.Background()).Err() + err := redisClient.FlushAll(context.Background()).Err() + assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) @@ -346,8 +356,9 @@ func TestRemove(t *testing.T) { c := config saved, err := svc.Add(context.Background(), validToken, c) - assert.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) - redisClient.FlushAll(context.Background()).Err() + require.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) + err = redisClient.FlushAll(context.Background()).Err() + assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) cases := []struct { desc string @@ -399,7 +410,8 @@ func TestRemove(t *testing.T) { } func TestBootstrap(t *testing.T) { - redisClient.FlushAll(context.Background()).Err() + err := redisClient.FlushAll(context.Background()).Err() + assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) @@ -409,8 +421,9 @@ func TestBootstrap(t *testing.T) { c := config saved, err := svc.Add(context.Background(), validToken, c) - assert.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) - redisClient.FlushAll(context.Background()).Err() + require.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) + err = redisClient.FlushAll(context.Background()).Err() + assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) cases := []struct { desc string @@ -468,7 +481,8 @@ func TestBootstrap(t *testing.T) { } func TestChangeState(t *testing.T) { - redisClient.FlushAll(context.Background()).Err() + err := redisClient.FlushAll(context.Background()).Err() + assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) users := mocks.NewAuthClient(map[string]string{validToken: email}) server := newThingsServer(newThingsService(users)) @@ -478,8 +492,9 @@ func TestChangeState(t *testing.T) { c := config saved, err := svc.Add(context.Background(), validToken, c) - assert.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) - redisClient.FlushAll(context.Background()).Err() + require.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) + err = redisClient.FlushAll(context.Background()).Err() + assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) cases := []struct { desc string diff --git a/go.mod b/go.mod index 17a5a96afb..d077c760e9 100644 --- a/go.mod +++ b/go.mod @@ -15,7 +15,7 @@ require ( github.com/go-zoo/bone v1.3.0 github.com/gocql/gocql v1.2.1 github.com/gofrs/uuid v4.3.0+incompatible - github.com/golang-jwt/jwt/v4 v4.4.2 + github.com/golang-jwt/jwt/v5 v5.0.0-rc.1 github.com/golang/protobuf v1.5.2 github.com/gopcua/opcua v0.1.6 github.com/gorilla/websocket v1.5.0 diff --git a/go.sum b/go.sum index d3256d145f..d29f90a555 100644 --- a/go.sum +++ b/go.sum @@ -217,8 +217,8 @@ github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zV github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= -github.com/golang-jwt/jwt/v4 v4.4.2 h1:rcc4lwaZgFMCZ5jxF9ABolDcIHdBytAFgqFPbSJQAYs= -github.com/golang-jwt/jwt/v4 v4.4.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/golang-jwt/jwt/v5 v5.0.0-rc.1 h1:tDQ1LjKga657layZ4JLsRdxgvupebc0xuPwRNuTfUgs= +github.com/golang-jwt/jwt/v5 v5.0.0-rc.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= diff --git a/lora/adapter_test.go b/lora/adapter_test.go index 088cd22c33..3a44a03fc2 100644 --- a/lora/adapter_test.go +++ b/lora/adapter_test.go @@ -13,6 +13,7 @@ import ( "github.com/mainflux/mainflux/lora/mocks" "github.com/mainflux/mainflux/pkg/errors" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) const ( @@ -40,19 +41,19 @@ func TestPublish(t *testing.T) { svc := newService() err := svc.CreateChannel(context.Background(), chanID, appID) - assert.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) + require.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) err = svc.CreateThing(context.Background(), thingID, devEUI) - assert.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) + require.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) err = svc.ConnectThing(context.Background(), chanID, thingID) - assert.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) + require.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) err = svc.CreateChannel(context.Background(), chanID2, appID2) - assert.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) + require.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) err = svc.CreateThing(context.Background(), thingID2, devEUI2) - assert.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) + require.Nil(t, err, fmt.Sprintf("unexpected error: %s\n", err)) msgBase64 := base64.StdEncoding.EncodeToString([]byte(msg)) diff --git a/lora/mqtt/sub.go b/lora/mqtt/sub.go index c12eb30852..58b7d7b679 100644 --- a/lora/mqtt/sub.go +++ b/lora/mqtt/sub.go @@ -54,5 +54,8 @@ func (b broker) handleMsg(c mqtt.Client, msg mqtt.Message) { return } - b.svc.Publish(context.Background(), &m) + err := b.svc.Publish(context.Background(), &m) + if err != nil { + b.logger.Error(fmt.Sprintf("got error while publishing messages: %s", err)) + } } diff --git a/opcua/db/subs.go b/opcua/db/subs.go index 99ca7a270f..c92f534fe5 100644 --- a/opcua/db/subs.go +++ b/opcua/db/subs.go @@ -35,8 +35,11 @@ func Save(serverURI, nodeID string) error { return errors.Wrap(errWriteFile, err) } csvWriter := csv.NewWriter(file) - csvWriter.Write([]string{serverURI, nodeID}) + err = csvWriter.Write([]string{serverURI, nodeID}) csvWriter.Flush() + if err != nil { + return errors.Wrap(errWriteFile, err) + } return nil } diff --git a/opcua/gopcua/subscribe.go b/opcua/gopcua/subscribe.go index 0e7b60008e..afc980838f 100644 --- a/opcua/gopcua/subscribe.go +++ b/opcua/gopcua/subscribe.go @@ -111,7 +111,12 @@ func (c client) Subscribe(ctx context.Context, cfg opcua.Config) error { if err != nil { return errors.Wrap(errFailedSub, err) } - defer sub.Cancel() + defer func() { + err = sub.Cancel() + if err != nil { + c.logger.Error(fmt.Sprintf("subscription could not be cancelled: %s", err)) + } + }() if err := c.runHandler(ctx, sub, cfg.ServerURI, cfg.NodeID); err != nil { c.logger.Warn(fmt.Sprintf("Unsubscribed from OPC-UA node %s.%s: %s", cfg.ServerURI, cfg.NodeID, err)) diff --git a/readers/api/endpoint_test.go b/readers/api/endpoint_test.go index 84cac0f2f6..7b4faa305e 100644 --- a/readers/api/endpoint_test.go +++ b/readers/api/endpoint_test.go @@ -733,7 +733,9 @@ func TestReadAll(t *testing.T) { assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) var page pageRes - json.NewDecoder(res.Body).Decode(&page) + err = json.NewDecoder(res.Body).Decode(&page) + assert.Nil(t, err, fmt.Sprintf("%s: unexpected error while decoding response body: %s", tc.desc, err)) + assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) assert.Equal(t, tc.status, res.StatusCode, fmt.Sprintf("%s: expected %d got %d", tc.desc, tc.status, res.StatusCode)) assert.Equal(t, tc.res.Total, page.Total, fmt.Sprintf("%s: expected %d got %d", tc.desc, tc.res.Total, page.Total)) diff --git a/readers/cassandra/messages.go b/readers/cassandra/messages.go index 3226985542..33f06d3dad 100644 --- a/readers/cassandra/messages.go +++ b/readers/cassandra/messages.go @@ -128,7 +128,10 @@ func buildQuery(chanID string, rpm readers.PageMetadata) (string, []interface{}) if err != nil { return condCQL, vals } - json.Unmarshal(meta, &query) + err = json.Unmarshal(meta, &query) + if err != nil { + return condCQL, vals + } for name, val := range query { switch name { diff --git a/readers/mocks/messages.go b/readers/mocks/messages.go index 0a55c8925f..a1c5f68865 100644 --- a/readers/mocks/messages.go +++ b/readers/mocks/messages.go @@ -39,8 +39,14 @@ func (repo *messageRepositoryMock) ReadAll(chanID string, rpm readers.PageMetada } var query map[string]interface{} - meta, _ := json.Marshal(rpm) - json.Unmarshal(meta, &query) + meta, err := json.Marshal(rpm) + if err != nil { + return readers.MessagesPage{}, err + } + err = json.Unmarshal(meta, &query) + if err != nil { + return readers.MessagesPage{}, err + } var msgs []readers.Message for _, m := range repo.messages[chanID] { diff --git a/readers/mongodb/messages.go b/readers/mongodb/messages.go index 2b483847eb..7e1257736c 100644 --- a/readers/mongodb/messages.go +++ b/readers/mongodb/messages.go @@ -101,7 +101,10 @@ func fmtCondition(chanID string, rpm readers.PageMetadata) bson.D { if err != nil { return filter } - json.Unmarshal(meta, &query) + err = json.Unmarshal(meta, &query) + if err != nil { + return filter + } for name, value := range query { switch name { diff --git a/readers/postgres/messages.go b/readers/postgres/messages.go index 486075cc44..3b72139f50 100644 --- a/readers/postgres/messages.go +++ b/readers/postgres/messages.go @@ -123,7 +123,10 @@ func fmtCondition(chanID string, rpm readers.PageMetadata) string { if err != nil { return condition } - json.Unmarshal(meta, &query) + err = json.Unmarshal(meta, &query) + if err != nil { + return condition + } for name := range query { switch name { diff --git a/readers/timescale/messages.go b/readers/timescale/messages.go index cd54218f60..ad44118d06 100644 --- a/readers/timescale/messages.go +++ b/readers/timescale/messages.go @@ -121,7 +121,10 @@ func fmtCondition(chanID string, rpm readers.PageMetadata) string { if err != nil { return condition } - json.Unmarshal(meta, &query) + err = json.Unmarshal(meta, &query) + if err != nil { + return condition + } for name := range query { switch name { diff --git a/things/postgres/things_test.go b/things/postgres/things_test.go index 1a0405695c..ff5687a111 100644 --- a/things/postgres/things_test.go +++ b/things/postgres/things_test.go @@ -395,10 +395,12 @@ func TestMultiThingRetrieval(t *testing.T) { subMetaStr := `{"field2":{"subfield12":{"subfield121":"value3"}}}` metadata := things.Metadata{} - json.Unmarshal([]byte(metaStr), &metadata) + err = json.Unmarshal([]byte(metaStr), &metadata) + assert.Nil(t, err, fmt.Sprintf("got expected error while unmarshalling %s\n", err)) subMeta := things.Metadata{} - json.Unmarshal([]byte(subMetaStr), &subMeta) + err = json.Unmarshal([]byte(subMetaStr), &subMeta) + assert.Nil(t, err, fmt.Sprintf("got expected error while unmarshalling %s\n", err)) wrongMeta := things.Metadata{ "field": "value1", diff --git a/tools/mqtt-bench/bench.go b/tools/mqtt-bench/bench.go index 62d81751ee..b034852019 100644 --- a/tools/mqtt-bench/bench.go +++ b/tools/mqtt-bench/bench.go @@ -26,7 +26,13 @@ func Benchmark(cfg Config) { var caByte []byte if cfg.MQTT.TLS.MTLS { caFile, err := os.Open(cfg.MQTT.TLS.CA) - defer caFile.Close() + + defer func() { + err = caFile.Close() + if err != nil { + fmt.Println(err) + } + }() if err != nil { fmt.Println(err) } @@ -110,7 +116,10 @@ func getBytePayload(size int, m message) (handler, error) { sz := size - n for { b = make([]byte, sz) - rand.Read(b) + _, err = rand.Read(b) + if err != nil { + return nil, err + } m.Payload = b content, err := json.Marshal(&m) if err != nil { diff --git a/tools/mqtt-bench/client.go b/tools/mqtt-bench/client.go index 9a0e065383..d93fc766d1 100644 --- a/tools/mqtt-bench/client.go +++ b/tools/mqtt-bench/client.go @@ -147,7 +147,6 @@ func (c *Client) connect() error { cfg.Certificates = []tls.Certificate{c.ClientCert} } - cfg.BuildNameToCertificate() opts.SetTLSConfig(cfg) opts.SetProtocolVersion(4) } diff --git a/tools/mqtt-bench/results.go b/tools/mqtt-bench/results.go index f2e545d7b8..20b80df07e 100644 --- a/tools/mqtt-bench/results.go +++ b/tools/mqtt-bench/results.go @@ -157,7 +157,10 @@ func printResults(results []*runResults, totals *totalResults, format string, qu log.Printf("Failed to prepare results for printing - %s\n", err.Error()) } var out bytes.Buffer - json.Indent(&out, data, "", "\t") + err = json.Indent(&out, data, "", "\t") + if err != nil { + return + } fmt.Println(out.String()) default: diff --git a/vendor/github.com/golang-jwt/jwt/v4/MIGRATION_GUIDE.md b/vendor/github.com/golang-jwt/jwt/v4/MIGRATION_GUIDE.md deleted file mode 100644 index 32966f5981..0000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/MIGRATION_GUIDE.md +++ /dev/null @@ -1,22 +0,0 @@ -## Migration Guide (v4.0.0) - -Starting from [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0), the import path will be: - - "github.com/golang-jwt/jwt/v4" - -The `/v4` version will be backwards compatible with existing `v3.x.y` tags in this repo, as well as -`github.com/dgrijalva/jwt-go`. For most users this should be a drop-in replacement, if you're having -troubles migrating, please open an issue. - -You can replace all occurrences of `github.com/dgrijalva/jwt-go` or `github.com/golang-jwt/jwt` with `github.com/golang-jwt/jwt/v4`, either manually or by using tools such as `sed` or `gofmt`. - -And then you'd typically run: - -``` -go get github.com/golang-jwt/jwt/v4 -go mod tidy -``` - -## Older releases (before v3.2.0) - -The original migration guide for older releases can be found at https://github.com/dgrijalva/jwt-go/blob/master/MIGRATION_GUIDE.md. diff --git a/vendor/github.com/golang-jwt/jwt/v4/claims.go b/vendor/github.com/golang-jwt/jwt/v4/claims.go deleted file mode 100644 index 9d95cad2bf..0000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/claims.go +++ /dev/null @@ -1,273 +0,0 @@ -package jwt - -import ( - "crypto/subtle" - "fmt" - "time" -) - -// Claims must just have a Valid method that determines -// if the token is invalid for any supported reason -type Claims interface { - Valid() error -} - -// RegisteredClaims are a structured version of the JWT Claims Set, -// restricted to Registered Claim Names, as referenced at -// https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 -// -// This type can be used on its own, but then additional private and -// public claims embedded in the JWT will not be parsed. The typical usecase -// therefore is to embedded this in a user-defined claim type. -// -// See examples for how to use this with your own claim types. -type RegisteredClaims struct { - // the `iss` (Issuer) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1 - Issuer string `json:"iss,omitempty"` - - // the `sub` (Subject) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2 - Subject string `json:"sub,omitempty"` - - // the `aud` (Audience) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3 - Audience ClaimStrings `json:"aud,omitempty"` - - // the `exp` (Expiration Time) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4 - ExpiresAt *NumericDate `json:"exp,omitempty"` - - // the `nbf` (Not Before) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5 - NotBefore *NumericDate `json:"nbf,omitempty"` - - // the `iat` (Issued At) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6 - IssuedAt *NumericDate `json:"iat,omitempty"` - - // the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7 - ID string `json:"jti,omitempty"` -} - -// Valid validates time based claims "exp, iat, nbf". -// There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (c RegisteredClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc() - - // The claims below are optional, by default, so if they are set to the - // default value in Go, let's not fail the verification for them. - if !c.VerifyExpiresAt(now, false) { - delta := now.Sub(c.ExpiresAt.Time) - vErr.Inner = fmt.Errorf("%s by %s", ErrTokenExpired, delta) - vErr.Errors |= ValidationErrorExpired - } - - if !c.VerifyIssuedAt(now, false) { - vErr.Inner = ErrTokenUsedBeforeIssued - vErr.Errors |= ValidationErrorIssuedAt - } - - if !c.VerifyNotBefore(now, false) { - vErr.Inner = ErrTokenNotValidYet - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} - -// VerifyAudience compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *RegisteredClaims) VerifyAudience(cmp string, req bool) bool { - return verifyAud(c.Audience, cmp, req) -} - -// VerifyExpiresAt compares the exp claim against cmp (cmp < exp). -// If req is false, it will return true, if exp is unset. -func (c *RegisteredClaims) VerifyExpiresAt(cmp time.Time, req bool) bool { - if c.ExpiresAt == nil { - return verifyExp(nil, cmp, req) - } - - return verifyExp(&c.ExpiresAt.Time, cmp, req) -} - -// VerifyIssuedAt compares the iat claim against cmp (cmp >= iat). -// If req is false, it will return true, if iat is unset. -func (c *RegisteredClaims) VerifyIssuedAt(cmp time.Time, req bool) bool { - if c.IssuedAt == nil { - return verifyIat(nil, cmp, req) - } - - return verifyIat(&c.IssuedAt.Time, cmp, req) -} - -// VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). -// If req is false, it will return true, if nbf is unset. -func (c *RegisteredClaims) VerifyNotBefore(cmp time.Time, req bool) bool { - if c.NotBefore == nil { - return verifyNbf(nil, cmp, req) - } - - return verifyNbf(&c.NotBefore.Time, cmp, req) -} - -// VerifyIssuer compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *RegisteredClaims) VerifyIssuer(cmp string, req bool) bool { - return verifyIss(c.Issuer, cmp, req) -} - -// StandardClaims are a structured version of the JWT Claims Set, as referenced at -// https://datatracker.ietf.org/doc/html/rfc7519#section-4. They do not follow the -// specification exactly, since they were based on an earlier draft of the -// specification and not updated. The main difference is that they only -// support integer-based date fields and singular audiences. This might lead to -// incompatibilities with other JWT implementations. The use of this is discouraged, instead -// the newer RegisteredClaims struct should be used. -// -// Deprecated: Use RegisteredClaims instead for a forward-compatible way to access registered claims in a struct. -type StandardClaims struct { - Audience string `json:"aud,omitempty"` - ExpiresAt int64 `json:"exp,omitempty"` - Id string `json:"jti,omitempty"` - IssuedAt int64 `json:"iat,omitempty"` - Issuer string `json:"iss,omitempty"` - NotBefore int64 `json:"nbf,omitempty"` - Subject string `json:"sub,omitempty"` -} - -// Valid validates time based claims "exp, iat, nbf". There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (c StandardClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc().Unix() - - // The claims below are optional, by default, so if they are set to the - // default value in Go, let's not fail the verification for them. - if !c.VerifyExpiresAt(now, false) { - delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) - vErr.Inner = fmt.Errorf("%s by %s", ErrTokenExpired, delta) - vErr.Errors |= ValidationErrorExpired - } - - if !c.VerifyIssuedAt(now, false) { - vErr.Inner = ErrTokenUsedBeforeIssued - vErr.Errors |= ValidationErrorIssuedAt - } - - if !c.VerifyNotBefore(now, false) { - vErr.Inner = ErrTokenNotValidYet - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} - -// VerifyAudience compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { - return verifyAud([]string{c.Audience}, cmp, req) -} - -// VerifyExpiresAt compares the exp claim against cmp (cmp < exp). -// If req is false, it will return true, if exp is unset. -func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { - if c.ExpiresAt == 0 { - return verifyExp(nil, time.Unix(cmp, 0), req) - } - - t := time.Unix(c.ExpiresAt, 0) - return verifyExp(&t, time.Unix(cmp, 0), req) -} - -// VerifyIssuedAt compares the iat claim against cmp (cmp >= iat). -// If req is false, it will return true, if iat is unset. -func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { - if c.IssuedAt == 0 { - return verifyIat(nil, time.Unix(cmp, 0), req) - } - - t := time.Unix(c.IssuedAt, 0) - return verifyIat(&t, time.Unix(cmp, 0), req) -} - -// VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). -// If req is false, it will return true, if nbf is unset. -func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { - if c.NotBefore == 0 { - return verifyNbf(nil, time.Unix(cmp, 0), req) - } - - t := time.Unix(c.NotBefore, 0) - return verifyNbf(&t, time.Unix(cmp, 0), req) -} - -// VerifyIssuer compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { - return verifyIss(c.Issuer, cmp, req) -} - -// ----- helpers - -func verifyAud(aud []string, cmp string, required bool) bool { - if len(aud) == 0 { - return !required - } - // use a var here to keep constant time compare when looping over a number of claims - result := false - - var stringClaims string - for _, a := range aud { - if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 { - result = true - } - stringClaims = stringClaims + a - } - - // case where "" is sent in one or many aud claims - if len(stringClaims) == 0 { - return !required - } - - return result -} - -func verifyExp(exp *time.Time, now time.Time, required bool) bool { - if exp == nil { - return !required - } - return now.Before(*exp) -} - -func verifyIat(iat *time.Time, now time.Time, required bool) bool { - if iat == nil { - return !required - } - return now.After(*iat) || now.Equal(*iat) -} - -func verifyNbf(nbf *time.Time, now time.Time, required bool) bool { - if nbf == nil { - return !required - } - return now.After(*nbf) || now.Equal(*nbf) -} - -func verifyIss(iss string, cmp string, required bool) bool { - if iss == "" { - return !required - } - if subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 { - return true - } else { - return false - } -} diff --git a/vendor/github.com/golang-jwt/jwt/v4/errors.go b/vendor/github.com/golang-jwt/jwt/v4/errors.go deleted file mode 100644 index 10ac8835cc..0000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/errors.go +++ /dev/null @@ -1,112 +0,0 @@ -package jwt - -import ( - "errors" -) - -// Error constants -var ( - ErrInvalidKey = errors.New("key is invalid") - ErrInvalidKeyType = errors.New("key is of invalid type") - ErrHashUnavailable = errors.New("the requested hash function is unavailable") - - ErrTokenMalformed = errors.New("token is malformed") - ErrTokenUnverifiable = errors.New("token is unverifiable") - ErrTokenSignatureInvalid = errors.New("token signature is invalid") - - ErrTokenInvalidAudience = errors.New("token has invalid audience") - ErrTokenExpired = errors.New("token is expired") - ErrTokenUsedBeforeIssued = errors.New("token used before issued") - ErrTokenInvalidIssuer = errors.New("token has invalid issuer") - ErrTokenNotValidYet = errors.New("token is not valid yet") - ErrTokenInvalidId = errors.New("token has invalid id") - ErrTokenInvalidClaims = errors.New("token has invalid claims") -) - -// The errors that might occur when parsing and validating a token -const ( - ValidationErrorMalformed uint32 = 1 << iota // Token is malformed - ValidationErrorUnverifiable // Token could not be verified because of signing problems - ValidationErrorSignatureInvalid // Signature validation failed - - // Standard Claim validation errors - ValidationErrorAudience // AUD validation failed - ValidationErrorExpired // EXP validation failed - ValidationErrorIssuedAt // IAT validation failed - ValidationErrorIssuer // ISS validation failed - ValidationErrorNotValidYet // NBF validation failed - ValidationErrorId // JTI validation failed - ValidationErrorClaimsInvalid // Generic claims validation error -) - -// NewValidationError is a helper for constructing a ValidationError with a string error message -func NewValidationError(errorText string, errorFlags uint32) *ValidationError { - return &ValidationError{ - text: errorText, - Errors: errorFlags, - } -} - -// ValidationError represents an error from Parse if token is not valid -type ValidationError struct { - Inner error // stores the error returned by external dependencies, i.e.: KeyFunc - Errors uint32 // bitfield. see ValidationError... constants - text string // errors that do not have a valid error just have text -} - -// Error is the implementation of the err interface. -func (e ValidationError) Error() string { - if e.Inner != nil { - return e.Inner.Error() - } else if e.text != "" { - return e.text - } else { - return "token is invalid" - } -} - -// Unwrap gives errors.Is and errors.As access to the inner error. -func (e *ValidationError) Unwrap() error { - return e.Inner -} - -// No errors -func (e *ValidationError) valid() bool { - return e.Errors == 0 -} - -// Is checks if this ValidationError is of the supplied error. We are first checking for the exact error message -// by comparing the inner error message. If that fails, we compare using the error flags. This way we can use -// custom error messages (mainly for backwards compatability) and still leverage errors.Is using the global error variables. -func (e *ValidationError) Is(err error) bool { - // Check, if our inner error is a direct match - if errors.Is(errors.Unwrap(e), err) { - return true - } - - // Otherwise, we need to match using our error flags - switch err { - case ErrTokenMalformed: - return e.Errors&ValidationErrorMalformed != 0 - case ErrTokenUnverifiable: - return e.Errors&ValidationErrorUnverifiable != 0 - case ErrTokenSignatureInvalid: - return e.Errors&ValidationErrorSignatureInvalid != 0 - case ErrTokenInvalidAudience: - return e.Errors&ValidationErrorAudience != 0 - case ErrTokenExpired: - return e.Errors&ValidationErrorExpired != 0 - case ErrTokenUsedBeforeIssued: - return e.Errors&ValidationErrorIssuedAt != 0 - case ErrTokenInvalidIssuer: - return e.Errors&ValidationErrorIssuer != 0 - case ErrTokenNotValidYet: - return e.Errors&ValidationErrorNotValidYet != 0 - case ErrTokenInvalidId: - return e.Errors&ValidationErrorId != 0 - case ErrTokenInvalidClaims: - return e.Errors&ValidationErrorClaimsInvalid != 0 - } - - return false -} diff --git a/vendor/github.com/golang-jwt/jwt/v4/map_claims.go b/vendor/github.com/golang-jwt/jwt/v4/map_claims.go deleted file mode 100644 index 2700d64a0d..0000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/map_claims.go +++ /dev/null @@ -1,151 +0,0 @@ -package jwt - -import ( - "encoding/json" - "errors" - "time" - // "fmt" -) - -// MapClaims is a claims type that uses the map[string]interface{} for JSON decoding. -// This is the default claims type if you don't supply one -type MapClaims map[string]interface{} - -// VerifyAudience Compares the aud claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyAudience(cmp string, req bool) bool { - var aud []string - switch v := m["aud"].(type) { - case string: - aud = append(aud, v) - case []string: - aud = v - case []interface{}: - for _, a := range v { - vs, ok := a.(string) - if !ok { - return false - } - aud = append(aud, vs) - } - } - return verifyAud(aud, cmp, req) -} - -// VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). -// If req is false, it will return true, if exp is unset. -func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { - cmpTime := time.Unix(cmp, 0) - - v, ok := m["exp"] - if !ok { - return !req - } - - switch exp := v.(type) { - case float64: - if exp == 0 { - return verifyExp(nil, cmpTime, req) - } - - return verifyExp(&newNumericDateFromSeconds(exp).Time, cmpTime, req) - case json.Number: - v, _ := exp.Float64() - - return verifyExp(&newNumericDateFromSeconds(v).Time, cmpTime, req) - } - - return false -} - -// VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). -// If req is false, it will return true, if iat is unset. -func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { - cmpTime := time.Unix(cmp, 0) - - v, ok := m["iat"] - if !ok { - return !req - } - - switch iat := v.(type) { - case float64: - if iat == 0 { - return verifyIat(nil, cmpTime, req) - } - - return verifyIat(&newNumericDateFromSeconds(iat).Time, cmpTime, req) - case json.Number: - v, _ := iat.Float64() - - return verifyIat(&newNumericDateFromSeconds(v).Time, cmpTime, req) - } - - return false -} - -// VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). -// If req is false, it will return true, if nbf is unset. -func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { - cmpTime := time.Unix(cmp, 0) - - v, ok := m["nbf"] - if !ok { - return !req - } - - switch nbf := v.(type) { - case float64: - if nbf == 0 { - return verifyNbf(nil, cmpTime, req) - } - - return verifyNbf(&newNumericDateFromSeconds(nbf).Time, cmpTime, req) - case json.Number: - v, _ := nbf.Float64() - - return verifyNbf(&newNumericDateFromSeconds(v).Time, cmpTime, req) - } - - return false -} - -// VerifyIssuer compares the iss claim against cmp. -// If required is false, this method will return true if the value matches or is unset -func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { - iss, _ := m["iss"].(string) - return verifyIss(iss, cmp, req) -} - -// Valid validates time based claims "exp, iat, nbf". -// There is no accounting for clock skew. -// As well, if any of the above claims are not in the token, it will still -// be considered a valid claim. -func (m MapClaims) Valid() error { - vErr := new(ValidationError) - now := TimeFunc().Unix() - - if !m.VerifyExpiresAt(now, false) { - // TODO(oxisto): this should be replaced with ErrTokenExpired - vErr.Inner = errors.New("Token is expired") - vErr.Errors |= ValidationErrorExpired - } - - if !m.VerifyIssuedAt(now, false) { - // TODO(oxisto): this should be replaced with ErrTokenUsedBeforeIssued - vErr.Inner = errors.New("Token used before issued") - vErr.Errors |= ValidationErrorIssuedAt - } - - if !m.VerifyNotBefore(now, false) { - // TODO(oxisto): this should be replaced with ErrTokenNotValidYet - vErr.Inner = errors.New("Token is not valid yet") - vErr.Errors |= ValidationErrorNotValidYet - } - - if vErr.valid() { - return nil - } - - return vErr -} diff --git a/vendor/github.com/golang-jwt/jwt/v4/parser_option.go b/vendor/github.com/golang-jwt/jwt/v4/parser_option.go deleted file mode 100644 index 6ea6f9527d..0000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/parser_option.go +++ /dev/null @@ -1,29 +0,0 @@ -package jwt - -// ParserOption is used to implement functional-style options that modify the behavior of the parser. To add -// new options, just create a function (ideally beginning with With or Without) that returns an anonymous function that -// takes a *Parser type as input and manipulates its configuration accordingly. -type ParserOption func(*Parser) - -// WithValidMethods is an option to supply algorithm methods that the parser will check. Only those methods will be considered valid. -// It is heavily encouraged to use this option in order to prevent attacks such as https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/. -func WithValidMethods(methods []string) ParserOption { - return func(p *Parser) { - p.ValidMethods = methods - } -} - -// WithJSONNumber is an option to configure the underlying JSON parser with UseNumber -func WithJSONNumber() ParserOption { - return func(p *Parser) { - p.UseJSONNumber = true - } -} - -// WithoutClaimsValidation is an option to disable claims validation. This option should only be used if you exactly know -// what you are doing. -func WithoutClaimsValidation() ParserOption { - return func(p *Parser) { - p.SkipClaimsValidation = true - } -} diff --git a/vendor/github.com/golang-jwt/jwt/v4/token.go b/vendor/github.com/golang-jwt/jwt/v4/token.go deleted file mode 100644 index 3cb0f3f0e4..0000000000 --- a/vendor/github.com/golang-jwt/jwt/v4/token.go +++ /dev/null @@ -1,127 +0,0 @@ -package jwt - -import ( - "encoding/base64" - "encoding/json" - "strings" - "time" -) - -// DecodePaddingAllowed will switch the codec used for decoding JWTs respectively. Note that the JWS RFC7515 -// states that the tokens will utilize a Base64url encoding with no padding. Unfortunately, some implementations -// of JWT are producing non-standard tokens, and thus require support for decoding. Note that this is a global -// variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe. -// To use the non-recommended decoding, set this boolean to `true` prior to using this package. -var DecodePaddingAllowed bool - -// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). -// You can override it to use another time value. This is useful for testing or if your -// server uses a different time zone than your tokens. -var TimeFunc = time.Now - -// Keyfunc will be used by the Parse methods as a callback function to supply -// the key for verification. The function receives the parsed, -// but unverified Token. This allows you to use properties in the -// Header of the token (such as `kid`) to identify which key to use. -type Keyfunc func(*Token) (interface{}, error) - -// Token represents a JWT Token. Different fields will be used depending on whether you're -// creating or parsing/verifying a token. -type Token struct { - Raw string // The raw token. Populated when you Parse a token - Method SigningMethod // The signing method used or to be used - Header map[string]interface{} // The first segment of the token - Claims Claims // The second segment of the token - Signature string // The third segment of the token. Populated when you Parse a token - Valid bool // Is the token valid? Populated when you Parse/Verify a token -} - -// New creates a new Token with the specified signing method and an empty map of claims. -func New(method SigningMethod) *Token { - return NewWithClaims(method, MapClaims{}) -} - -// NewWithClaims creates a new Token with the specified signing method and claims. -func NewWithClaims(method SigningMethod, claims Claims) *Token { - return &Token{ - Header: map[string]interface{}{ - "typ": "JWT", - "alg": method.Alg(), - }, - Claims: claims, - Method: method, - } -} - -// SignedString creates and returns a complete, signed JWT. -// The token is signed using the SigningMethod specified in the token. -func (t *Token) SignedString(key interface{}) (string, error) { - var sig, sstr string - var err error - if sstr, err = t.SigningString(); err != nil { - return "", err - } - if sig, err = t.Method.Sign(sstr, key); err != nil { - return "", err - } - return strings.Join([]string{sstr, sig}, "."), nil -} - -// SigningString generates the signing string. This is the -// most expensive part of the whole deal. Unless you -// need this for something special, just go straight for -// the SignedString. -func (t *Token) SigningString() (string, error) { - var err error - var jsonValue []byte - - if jsonValue, err = json.Marshal(t.Header); err != nil { - return "", err - } - header := EncodeSegment(jsonValue) - - if jsonValue, err = json.Marshal(t.Claims); err != nil { - return "", err - } - claim := EncodeSegment(jsonValue) - - return strings.Join([]string{header, claim}, "."), nil -} - -// Parse parses, validates, verifies the signature and returns the parsed token. -// keyFunc will receive the parsed token and should return the cryptographic key -// for verifying the signature. -// The caller is strongly encouraged to set the WithValidMethods option to -// validate the 'alg' claim in the token matches the expected algorithm. -// For more details about the importance of validating the 'alg' claim, -// see https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/ -func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { - return NewParser(options...).Parse(tokenString, keyFunc) -} - -func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { - return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc) -} - -// EncodeSegment encodes a JWT specific base64url encoding with padding stripped -// -// Deprecated: In a future release, we will demote this function to a non-exported function, since it -// should only be used internally -func EncodeSegment(seg []byte) string { - return base64.RawURLEncoding.EncodeToString(seg) -} - -// DecodeSegment decodes a JWT specific base64url encoding with padding stripped -// -// Deprecated: In a future release, we will demote this function to a non-exported function, since it -// should only be used internally -func DecodeSegment(seg string) ([]byte, error) { - if DecodePaddingAllowed { - if l := len(seg) % 4; l > 0 { - seg += strings.Repeat("=", 4-l) - } - return base64.URLEncoding.DecodeString(seg) - } - - return base64.RawURLEncoding.DecodeString(seg) -} diff --git a/vendor/github.com/golang-jwt/jwt/v4/.gitignore b/vendor/github.com/golang-jwt/jwt/v5/.gitignore similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/.gitignore rename to vendor/github.com/golang-jwt/jwt/v5/.gitignore diff --git a/vendor/github.com/golang-jwt/jwt/v4/LICENSE b/vendor/github.com/golang-jwt/jwt/v5/LICENSE similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/LICENSE rename to vendor/github.com/golang-jwt/jwt/v5/LICENSE diff --git a/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md b/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md new file mode 100644 index 0000000000..1ee690f932 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md @@ -0,0 +1,100 @@ +# Migration Guide (v5.0.0) + +Version `v5` contains a major rework of core functionalities in the `jwt-go` library. This includes support for several +validation options as well as a re-design of the `Claims` interface. Lastly, we reworked how errors work under the hood, +which should provide a better overall developer experience. + +Starting from [v5.0.0](https://github.com/golang-jwt/jwt/releases/tag/v5.0.0), the import path will be: + + "github.com/golang-jwt/jwt/v5" + +For most users, changing the import path *should* suffice. However, since we intentionally changed and cleaned some of +the public API, existing programs might need to be adopted. The following paragraphs go through the individual changes +and make suggestions how to change existing programs. + +## Parsing and Validation Options + +Under the hood, a new `validator` struct takes care of validating the claims. A long awaited feature has been the option +to fine-tune the validation of tokens. This is now possible with several `ParserOption` functions that can be appended +to most `Parse` functions, such as `ParseWithClaims`. The most important options and changes are: + * `WithLeeway`, which can be used to specific leeway that is taken into account when validating time-based claims, such as `exp` or `nbf`. + * The new default behavior now disables checking the `iat` claim by default. Usage of this claim is OPTIONAL according to the JWT RFC. The claim itself is also purely informational according to the RFC, so a strict validation failure is not recommended. If you want to check for sensible values in these claims, please use the `WithIssuedAt` parser option. + * New options have also been added to check for expected `aud`, `sub` and `iss`, namely `WithAudience`, `WithSubject` and `WithIssuer`. + +## Changes to the `Claims` interface + +### Complete Restructuring + +Previously, the claims interface was satisfied with an implementation of a `Valid() error` function. This had several issues: + * The different claim types (struct claims, map claims, etc.) then contained similar (but not 100 % identical) code of how this validation was done. This lead to a lot of (almost) duplicate code and was hard to maintain + * It was not really semantically close to what a "claim" (or a set of claims) really is; which is a list of defined key/value pairs with a certain semantic meaning. + +Since all the validation functionality is now extracted into the validator, all `VerifyXXX` and `Valid` functions have been removed from the `Claims` interface. Instead, the interface now represents a list of getters to retrieve values with a specific meaning. This allows us to completely decouple the validation logic with the underlying storage representation of the claim, which could be a struct, a map or even something stored in a database. + +```go +type Claims interface { + GetExpirationTime() (*NumericDate, error) + GetIssuedAt() (*NumericDate, error) + GetNotBefore() (*NumericDate, error) + GetIssuer() (string, error) + GetSubject() (string, error) + GetAudience() (ClaimStrings, error) +} +``` + +### Supported Claim Types and Removal of `StandardClaims` + +The two standard claim types supported by this library, `MapClaims` and `RegisteredClaims` both implement the necessary functions of this interface. The old `StandardClaims` struct, which has already been deprecated in `v4` is now removed. + +Users using custom claims, in most cases, will not experience any changes in the behavior as long as they embedded +`RegisteredClaims`. If they created a new claim type from scratch, they now need to implemented the proper getter +functions. + +### Migrating Application Specific Logic of the old `Valid` + +Previously, users could override the `Valid` method in a custom claim, for example to extend the validation with application-specific claims. However, this was always very dangerous, since once could easily disable the standard validation and signature checking. + +In order to avoid that, while still supporting the use-case, a new `ClaimsValidator` interface has been introduced. This interface consists of the `Validate() error` function. If the validator sees, that a `Claims` struct implements this interface, the errors returned to the `Validate` function will be *appended* to the regular standard validation. It is not possible to disable the standard validation anymore (even only by accident). + +Usage examples can be found in [example_test.go](./example_test.go), to build claims structs like the following. + +```go +// MyCustomClaims includes all registered claims, plus Foo. +type MyCustomClaims struct { + Foo string `json:"foo"` + jwt.RegisteredClaims +} + +// Validate can be used to execute additional application-specific claims +// validation. +func (m MyCustomClaims) Validate() error { + if m.Foo != "bar" { + return errors.New("must be foobar") + } + + return nil +} +``` + +# Migration Guide (v4.0.0) + +Starting from [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0), the import path will be: + + "github.com/golang-jwt/jwt/v4" + +The `/v4` version will be backwards compatible with existing `v3.x.y` tags in this repo, as well as +`github.com/dgrijalva/jwt-go`. For most users this should be a drop-in replacement, if you're having +troubles migrating, please open an issue. + +You can replace all occurrences of `github.com/dgrijalva/jwt-go` or `github.com/golang-jwt/jwt` with `github.com/golang-jwt/jwt/v5`, either manually or by using tools such as `sed` or `gofmt`. + +And then you'd typically run: + +``` +go get github.com/golang-jwt/jwt/v4 +go mod tidy +``` + +# Older releases (before v3.2.0) + +The original migration guide for older releases can be found at https://github.com/dgrijalva/jwt-go/blob/master/MIGRATION_GUIDE.md. diff --git a/vendor/github.com/golang-jwt/jwt/v4/README.md b/vendor/github.com/golang-jwt/jwt/v5/README.md similarity index 89% rename from vendor/github.com/golang-jwt/jwt/v4/README.md rename to vendor/github.com/golang-jwt/jwt/v5/README.md index f5d551ca8f..87259e8403 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/README.md +++ b/vendor/github.com/golang-jwt/jwt/v5/README.md @@ -1,12 +1,12 @@ # jwt-go [![build](https://github.com/golang-jwt/jwt/actions/workflows/build.yml/badge.svg)](https://github.com/golang-jwt/jwt/actions/workflows/build.yml) -[![Go Reference](https://pkg.go.dev/badge/github.com/golang-jwt/jwt/v4.svg)](https://pkg.go.dev/github.com/golang-jwt/jwt/v4) +[![Go Reference](https://pkg.go.dev/badge/github.com/golang-jwt/jwt/v5.svg)](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](https://datatracker.ietf.org/doc/html/rfc7519). Starting with [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0) this project adds Go module support, but maintains backwards compatibility with older `v3.x.y` tags and upstream `github.com/dgrijalva/jwt-go`. -See the [`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) for more information. +See the [`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) for more information. Version v5.0.0 introduces major improvements to the validation of tokens, but is not entirely backwards compatible. > After the original author of the library suggested migrating the maintenance of `jwt-go`, a dedicated team of open source maintainers decided to clone the existing library into this repository. See [dgrijalva/jwt-go#462](https://github.com/dgrijalva/jwt-go/issues/462) for a detailed discussion on this topic. @@ -41,22 +41,22 @@ This library supports the parsing and verification as well as the generation and 1. To install the jwt package, you first need to have [Go](https://go.dev/doc/install) installed, then you can use the command below to add `jwt-go` as a dependency in your Go program. ```sh -go get -u github.com/golang-jwt/jwt/v4 +go get -u github.com/golang-jwt/jwt/v5 ``` 2. Import it in your code: ```go -import "github.com/golang-jwt/jwt/v4" +import "github.com/golang-jwt/jwt/v5" ``` ## Examples -See [the project documentation](https://pkg.go.dev/github.com/golang-jwt/jwt/v4) for examples of usage: +See [the project documentation](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) for examples of usage: -* [Simple example of parsing and validating a token](https://pkg.go.dev/github.com/golang-jwt/jwt#example-Parse-Hmac) -* [Simple example of building and signing a token](https://pkg.go.dev/github.com/golang-jwt/jwt#example-New-Hmac) -* [Directory of Examples](https://pkg.go.dev/github.com/golang-jwt/jwt#pkg-examples) +* [Simple example of parsing and validating a token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-Parse-Hmac) +* [Simple example of building and signing a token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-New-Hmac) +* [Directory of Examples](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#pkg-examples) ## Extensions @@ -68,7 +68,7 @@ A common use case would be integrating with different 3rd party signature provid | --------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ | | GCP | Integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS) | https://github.com/someone1/gcp-jwt-go | | AWS | Integrates with AWS Key Management Service, KMS | https://github.com/matelang/jwt-go-aws-kms | -| JWKS | Provides support for JWKS ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)) as a `jwt.Keyfunc` | https://github.com/MicahParks/keyfunc | +| JWKS | Provides support for JWKS ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)) as a `jwt.Keyfunc` | https://github.com/MicahParks/keyfunc | *Disclaimer*: Unless otherwise specified, these integrations are maintained by third parties and should not be considered as a primary offer by any of the mentioned cloud providers @@ -96,7 +96,7 @@ A token is simply a JSON object that is signed by its author. this tells you exa * The author of the token was in the possession of the signing secret * The data has not been modified since it was signed -It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, `JWE`, that provides this functionality. JWE is currently outside the scope of this library. +It's important to know that JWT does not provide encryption, which means anyone who has access to the token can read its contents. If you need to protect (encrypt) the data, there is a companion spec, `JWE`, that provides this functionality. The companion project https://github.com/golang-jwt/jwe aims at a (very) experimental implementation of the JWE standard. ### Choosing a Signing Method @@ -110,10 +110,10 @@ Asymmetric signing methods, such as RSA, use different keys for signing and veri Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones: -* The [HMAC signing method](https://pkg.go.dev/github.com/golang-jwt/jwt#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation -* The [RSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation -* The [ECDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation -* The [EdDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt#SigningMethodEd25519) (`Ed25519`) expect `ed25519.PrivateKey` for signing and `ed25519.PublicKey` for validation +* The [HMAC signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation +* The [RSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation +* The [ECDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation +* The [EdDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#SigningMethodEd25519) (`Ed25519`) expect `ed25519.PrivateKey` for signing and `ed25519.PublicKey` for validation ### JWT and OAuth @@ -131,7 +131,7 @@ This library uses descriptive error messages whenever possible. If you are not g ## More -Documentation can be found [on pkg.go.dev](https://pkg.go.dev/github.com/golang-jwt/jwt). +Documentation can be found [on pkg.go.dev](https://pkg.go.dev/github.com/golang-jwt/jwt/v5). The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in the documentation. diff --git a/vendor/github.com/golang-jwt/jwt/v4/SECURITY.md b/vendor/github.com/golang-jwt/jwt/v5/SECURITY.md similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/SECURITY.md rename to vendor/github.com/golang-jwt/jwt/v5/SECURITY.md diff --git a/vendor/github.com/golang-jwt/jwt/v4/VERSION_HISTORY.md b/vendor/github.com/golang-jwt/jwt/v5/VERSION_HISTORY.md similarity index 96% rename from vendor/github.com/golang-jwt/jwt/v4/VERSION_HISTORY.md rename to vendor/github.com/golang-jwt/jwt/v5/VERSION_HISTORY.md index afbfc4e408..b5039e49c1 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/VERSION_HISTORY.md +++ b/vendor/github.com/golang-jwt/jwt/v5/VERSION_HISTORY.md @@ -1,17 +1,19 @@ -## `jwt-go` Version History +# `jwt-go` Version History -#### 4.0.0 +The following version history is kept for historic purposes. To retrieve the current changes of each version, please refer to the change-log of the specific release versions on https://github.com/golang-jwt/jwt/releases. + +## 4.0.0 * Introduces support for Go modules. The `v4` version will be backwards compatible with `v3.x.y`. -#### 3.2.2 +## 3.2.2 * Starting from this release, we are adopting the policy to support the most 2 recent versions of Go currently available. By the time of this release, this is Go 1.15 and 1.16 ([#28](https://github.com/golang-jwt/jwt/pull/28)). * Fixed a potential issue that could occur when the verification of `exp`, `iat` or `nbf` was not required and contained invalid contents, i.e. non-numeric/date. Thanks for @thaJeztah for making us aware of that and @giorgos-f3 for originally reporting it to the formtech fork ([#40](https://github.com/golang-jwt/jwt/pull/40)). * Added support for EdDSA / ED25519 ([#36](https://github.com/golang-jwt/jwt/pull/36)). * Optimized allocations ([#33](https://github.com/golang-jwt/jwt/pull/33)). -#### 3.2.1 +## 3.2.1 * **Import Path Change**: See MIGRATION_GUIDE.md for tips on updating your code * Changed the import path from `github.com/dgrijalva/jwt-go` to `github.com/golang-jwt/jwt` @@ -117,17 +119,17 @@ It is likely the only integration change required here will be to change `func(t * Refactored the RSA implementation to be easier to read * Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM` -#### 1.0.2 +## 1.0.2 * Fixed bug in parsing public keys from certificates * Added more tests around the parsing of keys for RS256 * Code refactoring in RS256 implementation. No functional changes -#### 1.0.1 +## 1.0.1 * Fixed panic if RS256 signing method was passed an invalid key -#### 1.0.0 +## 1.0.0 * First versioned release * API stabilized diff --git a/vendor/github.com/golang-jwt/jwt/v5/claims.go b/vendor/github.com/golang-jwt/jwt/v5/claims.go new file mode 100644 index 0000000000..d50ff3dad8 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/claims.go @@ -0,0 +1,16 @@ +package jwt + +// Claims represent any form of a JWT Claims Set according to +// https://datatracker.ietf.org/doc/html/rfc7519#section-4. In order to have a +// common basis for validation, it is required that an implementation is able to +// supply at least the claim names provided in +// https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 namely `exp`, +// `iat`, `nbf`, `iss`, `sub` and `aud`. +type Claims interface { + GetExpirationTime() (*NumericDate, error) + GetIssuedAt() (*NumericDate, error) + GetNotBefore() (*NumericDate, error) + GetIssuer() (string, error) + GetSubject() (string, error) + GetAudience() (ClaimStrings, error) +} diff --git a/vendor/github.com/golang-jwt/jwt/v4/doc.go b/vendor/github.com/golang-jwt/jwt/v5/doc.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/doc.go rename to vendor/github.com/golang-jwt/jwt/v5/doc.go diff --git a/vendor/github.com/golang-jwt/jwt/v4/ecdsa.go b/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/ecdsa.go rename to vendor/github.com/golang-jwt/jwt/v5/ecdsa.go diff --git a/vendor/github.com/golang-jwt/jwt/v4/ecdsa_utils.go b/vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/ecdsa_utils.go rename to vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go diff --git a/vendor/github.com/golang-jwt/jwt/v4/ed25519.go b/vendor/github.com/golang-jwt/jwt/v5/ed25519.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/ed25519.go rename to vendor/github.com/golang-jwt/jwt/v5/ed25519.go diff --git a/vendor/github.com/golang-jwt/jwt/v4/ed25519_utils.go b/vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/ed25519_utils.go rename to vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go diff --git a/vendor/github.com/golang-jwt/jwt/v5/errors.go b/vendor/github.com/golang-jwt/jwt/v5/errors.go new file mode 100644 index 0000000000..23bb616ddd --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/errors.go @@ -0,0 +1,49 @@ +package jwt + +import ( + "errors" + "strings" +) + +var ( + ErrInvalidKey = errors.New("key is invalid") + ErrInvalidKeyType = errors.New("key is of invalid type") + ErrHashUnavailable = errors.New("the requested hash function is unavailable") + ErrTokenMalformed = errors.New("token is malformed") + ErrTokenUnverifiable = errors.New("token is unverifiable") + ErrTokenSignatureInvalid = errors.New("token signature is invalid") + ErrTokenRequiredClaimMissing = errors.New("token is missing required claim") + ErrTokenInvalidAudience = errors.New("token has invalid audience") + ErrTokenExpired = errors.New("token is expired") + ErrTokenUsedBeforeIssued = errors.New("token used before issued") + ErrTokenInvalidIssuer = errors.New("token has invalid issuer") + ErrTokenInvalidSubject = errors.New("token has invalid subject") + ErrTokenNotValidYet = errors.New("token is not valid yet") + ErrTokenInvalidId = errors.New("token has invalid id") + ErrTokenInvalidClaims = errors.New("token has invalid claims") + ErrInvalidType = errors.New("invalid type for claim") +) + +// joinedError is an error type that works similar to what [errors.Join] +// produces, with the exception that it has a nice error string; mainly its +// error messages are concatenated using a comma, rather than a newline. +type joinedError struct { + errs []error +} + +func (je joinedError) Error() string { + msg := []string{} + for _, err := range je.errs { + msg = append(msg, err.Error()) + } + + return strings.Join(msg, ", ") +} + +// joinErrors joins together multiple errors. Useful for scenarios where +// multiple errors next to each other occur, e.g., in claims validation. +func joinErrors(errs ...error) error { + return &joinedError{ + errs: errs, + } +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go b/vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go new file mode 100644 index 0000000000..a893d355e1 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go @@ -0,0 +1,47 @@ +//go:build go1.20 +// +build go1.20 + +package jwt + +import ( + "fmt" +) + +// Unwrap implements the multiple error unwrapping for this error type, which is +// possible in Go 1.20. +func (je joinedError) Unwrap() []error { + return je.errs +} + +// newError creates a new error message with a detailed error message. The +// message will be prefixed with the contents of the supplied error type. +// Additionally, more errors, that provide more context can be supplied which +// will be appended to the message. This makes use of Go 1.20's possibility to +// include more than one %w formatting directive in [fmt.Errorf]. +// +// For example, +// +// newError("no keyfunc was provided", ErrTokenUnverifiable) +// +// will produce the error string +// +// "token is unverifiable: no keyfunc was provided" +func newError(message string, err error, more ...error) error { + var format string + var args []any + if message != "" { + format = "%w: %s" + args = []any{err, message} + } else { + format = "%w" + args = []any{err} + } + + for _, e := range more { + format += ": %w" + args = append(args, e) + } + + err = fmt.Errorf(format, args...) + return err +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go b/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go new file mode 100644 index 0000000000..3afb04e648 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go @@ -0,0 +1,78 @@ +//go:build !go1.20 +// +build !go1.20 + +package jwt + +import ( + "errors" + "fmt" +) + +// Is implements checking for multiple errors using [errors.Is], since multiple +// error unwrapping is not possible in versions less than Go 1.20. +func (je joinedError) Is(err error) bool { + for _, e := range je.errs { + if errors.Is(e, err) { + return true + } + } + + return false +} + +// wrappedErrors is a workaround for wrapping multiple errors in environments +// where Go 1.20 is not available. It basically uses the already implemented +// functionatlity of joinedError to handle multiple errors with supplies a +// custom error message that is identical to the one we produce in Go 1.20 using +// multiple %w directives. +type wrappedErrors struct { + msg string + joinedError +} + +// Error returns the stored error string +func (we wrappedErrors) Error() string { + return we.msg +} + +// newError creates a new error message with a detailed error message. The +// message will be prefixed with the contents of the supplied error type. +// Additionally, more errors, that provide more context can be supplied which +// will be appended to the message. Since we cannot use of Go 1.20's possibility +// to include more than one %w formatting directive in [fmt.Errorf], we have to +// emulate that. +// +// For example, +// +// newError("no keyfunc was provided", ErrTokenUnverifiable) +// +// will produce the error string +// +// "token is unverifiable: no keyfunc was provided" +func newError(message string, err error, more ...error) error { + // We cannot wrap multiple errors here with %w, so we have to be a little + // bit creative. Basically, we are using %s instead of %w to produce the + // same error message and then throw the result into a custom error struct. + var format string + var args []any + if message != "" { + format = "%s: %s" + args = []any{err, message} + } else { + format = "%s" + args = []any{err} + } + errs := []error{err} + + for _, e := range more { + format += ": %s" + args = append(args, e) + errs = append(errs, e) + } + + err = &wrappedErrors{ + msg: fmt.Sprintf(format, args...), + joinedError: joinedError{errs: errs}, + } + return err +} diff --git a/vendor/github.com/golang-jwt/jwt/v4/hmac.go b/vendor/github.com/golang-jwt/jwt/v5/hmac.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/hmac.go rename to vendor/github.com/golang-jwt/jwt/v5/hmac.go diff --git a/vendor/github.com/golang-jwt/jwt/v5/map_claims.go b/vendor/github.com/golang-jwt/jwt/v5/map_claims.go new file mode 100644 index 0000000000..b2b51a1f80 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/map_claims.go @@ -0,0 +1,109 @@ +package jwt + +import ( + "encoding/json" + "fmt" +) + +// MapClaims is a claims type that uses the map[string]interface{} for JSON +// decoding. This is the default claims type if you don't supply one +type MapClaims map[string]interface{} + +// GetExpirationTime implements the Claims interface. +func (m MapClaims) GetExpirationTime() (*NumericDate, error) { + return m.parseNumericDate("exp") +} + +// GetNotBefore implements the Claims interface. +func (m MapClaims) GetNotBefore() (*NumericDate, error) { + return m.parseNumericDate("nbf") +} + +// GetIssuedAt implements the Claims interface. +func (m MapClaims) GetIssuedAt() (*NumericDate, error) { + return m.parseNumericDate("iat") +} + +// GetAudience implements the Claims interface. +func (m MapClaims) GetAudience() (ClaimStrings, error) { + return m.parseClaimsString("aud") +} + +// GetIssuer implements the Claims interface. +func (m MapClaims) GetIssuer() (string, error) { + return m.parseString("iss") +} + +// GetSubject implements the Claims interface. +func (m MapClaims) GetSubject() (string, error) { + return m.parseString("sub") +} + +// parseNumericDate tries to parse a key in the map claims type as a number +// date. This will succeed, if the underlying type is either a [float64] or a +// [json.Number]. Otherwise, nil will be returned. +func (m MapClaims) parseNumericDate(key string) (*NumericDate, error) { + v, ok := m[key] + if !ok { + return nil, nil + } + + switch exp := v.(type) { + case float64: + if exp == 0 { + return nil, nil + } + + return newNumericDateFromSeconds(exp), nil + case json.Number: + v, _ := exp.Float64() + + return newNumericDateFromSeconds(v), nil + } + + return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) +} + +// parseClaimsString tries to parse a key in the map claims type as a +// [ClaimsStrings] type, which can either be a string or an array of string. +func (m MapClaims) parseClaimsString(key string) (ClaimStrings, error) { + var cs []string + switch v := m[key].(type) { + case string: + cs = append(cs, v) + case []string: + cs = v + case []interface{}: + for _, a := range v { + vs, ok := a.(string) + if !ok { + return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) + } + cs = append(cs, vs) + } + } + + return cs, nil +} + +// parseString tries to parse a key in the map claims type as a [string] type. +// If the key does not exist, an empty string is returned. If the key has the +// wrong type, an error is returned. +func (m MapClaims) parseString(key string) (string, error) { + var ( + ok bool + raw interface{} + iss string + ) + raw, ok = m[key] + if !ok { + return "", nil + } + + iss, ok = raw.(string) + if !ok { + return "", newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) + } + + return iss, nil +} diff --git a/vendor/github.com/golang-jwt/jwt/v4/none.go b/vendor/github.com/golang-jwt/jwt/v5/none.go similarity index 85% rename from vendor/github.com/golang-jwt/jwt/v4/none.go rename to vendor/github.com/golang-jwt/jwt/v5/none.go index f19835d207..a16495acbe 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/none.go +++ b/vendor/github.com/golang-jwt/jwt/v5/none.go @@ -13,7 +13,7 @@ type unsafeNoneMagicConstant string func init() { SigningMethodNone = &signingMethodNone{} - NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid) + NoneSignatureTypeDisallowedError = newError("'none' signature type is not allowed", ErrTokenUnverifiable) RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { return SigningMethodNone @@ -33,10 +33,7 @@ func (m *signingMethodNone) Verify(signingString, signature string, key interfac } // If signing method is none, signature must be an empty string if signature != "" { - return NewValidationError( - "'none' signing method with non-empty signature", - ValidationErrorSignatureInvalid, - ) + return newError("'none' signing method with non-empty signature", ErrTokenUnverifiable) } // Accept 'none' signing method. diff --git a/vendor/github.com/golang-jwt/jwt/v4/parser.go b/vendor/github.com/golang-jwt/jwt/v5/parser.go similarity index 54% rename from vendor/github.com/golang-jwt/jwt/v4/parser.go rename to vendor/github.com/golang-jwt/jwt/v5/parser.go index 2f61a69d7f..46b67931d6 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/parser.go +++ b/vendor/github.com/golang-jwt/jwt/v5/parser.go @@ -9,26 +9,24 @@ import ( type Parser struct { // If populated, only these methods will be considered valid. - // - // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead. - ValidMethods []string + validMethods []string // Use JSON Number format in JSON decoder. - // - // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead. - UseJSONNumber bool + useJSONNumber bool // Skip claims validation during token parsing. - // - // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead. - SkipClaimsValidation bool + skipClaimsValidation bool + + validator *validator } // NewParser creates a new Parser with the specified options func NewParser(options ...ParserOption) *Parser { - p := &Parser{} + p := &Parser{ + validator: &validator{}, + } - // loop through our parsing options and apply them + // Loop through our parsing options and apply them for _, option := range options { option(p) } @@ -42,6 +40,13 @@ func (p *Parser) Parse(tokenString string, keyFunc Keyfunc) (*Token, error) { return p.ParseWithClaims(tokenString, MapClaims{}, keyFunc) } +// ParseWithClaims parses, validates, and verifies like Parse, but supplies a default object implementing the Claims +// interface. This provides default values which can be overridden and allows a caller to use their own type, rather +// than the default MapClaims implementation of Claims. +// +// Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims), +// make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the +// proper memory for it before passing in the overall claims, otherwise you might run into a panic. func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc) (*Token, error) { token, parts, err := p.ParseUnverified(tokenString, claims) if err != nil { @@ -49,10 +54,10 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf } // Verify signing method is in the required set - if p.ValidMethods != nil { + if p.validMethods != nil { var signingMethodValid = false var alg = token.Method.Alg() - for _, m := range p.ValidMethods { + for _, m := range p.validMethods { if m == alg { signingMethodValid = true break @@ -60,7 +65,7 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf } if !signingMethodValid { // signing method is not in the listed set - return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) + return token, newError(fmt.Sprintf("signing method %v is invalid", alg), ErrTokenSignatureInvalid) } } @@ -68,45 +73,34 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf var key interface{} if keyFunc == nil { // keyFunc was not provided. short circuiting validation - return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) + return token, newError("no keyfunc was provided", ErrTokenUnverifiable) } if key, err = keyFunc(token); err != nil { - // keyFunc returned an error - if ve, ok := err.(*ValidationError); ok { - return token, ve - } - return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} + return token, newError("error while executing keyfunc", ErrTokenUnverifiable, err) } - vErr := &ValidationError{} + // Perform signature validation + token.Signature = parts[2] + if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { + return token, newError("", ErrTokenSignatureInvalid, err) + } // Validate Claims - if !p.SkipClaimsValidation { - if err := token.Claims.Valid(); err != nil { - - // If the Claims Valid returned an error, check if it is a validation error, - // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set - if e, ok := err.(*ValidationError); !ok { - vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} - } else { - vErr = e - } + if !p.skipClaimsValidation { + // Make sure we have at least a default validator + if p.validator == nil { + p.validator = newValidator() } - } - // Perform validation - token.Signature = parts[2] - if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { - vErr.Inner = err - vErr.Errors |= ValidationErrorSignatureInvalid + if err := p.validator.Validate(claims); err != nil { + return token, newError("", ErrTokenInvalidClaims, err) + } } - if vErr.valid() { - token.Valid = true - return token, nil - } + // No errors so far, token is valid. + token.Valid = true - return token, vErr + return token, nil } // ParseUnverified parses the token but doesn't validate the signature. @@ -118,7 +112,7 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { parts = strings.Split(tokenString, ".") if len(parts) != 3 { - return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) + return nil, parts, newError("token contains an invalid number of segments", ErrTokenMalformed) } token = &Token{Raw: tokenString} @@ -127,12 +121,12 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke var headerBytes []byte if headerBytes, err = DecodeSegment(parts[0]); err != nil { if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { - return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) + return token, parts, newError("tokenstring should not contain 'bearer '", ErrTokenMalformed) } - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + return token, parts, newError("could not base64 decode header", ErrTokenMalformed, err) } if err = json.Unmarshal(headerBytes, &token.Header); err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + return token, parts, newError("could not JSON decode header", ErrTokenMalformed, err) } // parse Claims @@ -140,10 +134,10 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke token.Claims = claims if claimBytes, err = DecodeSegment(parts[1]); err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + return token, parts, newError("could not base64 decode claim", ErrTokenMalformed, err) } dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) - if p.UseJSONNumber { + if p.useJSONNumber { dec.UseNumber() } // JSON Decode. Special case for map type to avoid weird pointer behavior @@ -154,16 +148,16 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke } // Handle decode error if err != nil { - return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} + return token, parts, newError("could not JSON decode claim", ErrTokenMalformed, err) } // Lookup signature method if method, ok := token.Header["alg"].(string); ok { if token.Method = GetSigningMethod(method); token.Method == nil { - return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) + return token, parts, newError("signing method (alg) is unavailable", ErrTokenUnverifiable) } } else { - return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) + return token, parts, newError("signing method (alg) is unspecified", ErrTokenUnverifiable) } return token, parts, nil diff --git a/vendor/github.com/golang-jwt/jwt/v5/parser_option.go b/vendor/github.com/golang-jwt/jwt/v5/parser_option.go new file mode 100644 index 0000000000..8d5917e909 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/parser_option.go @@ -0,0 +1,101 @@ +package jwt + +import "time" + +// ParserOption is used to implement functional-style options that modify the +// behavior of the parser. To add new options, just create a function (ideally +// beginning with With or Without) that returns an anonymous function that takes +// a *Parser type as input and manipulates its configuration accordingly. +type ParserOption func(*Parser) + +// WithValidMethods is an option to supply algorithm methods that the parser +// will check. Only those methods will be considered valid. It is heavily +// encouraged to use this option in order to prevent attacks such as +// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/. +func WithValidMethods(methods []string) ParserOption { + return func(p *Parser) { + p.validMethods = methods + } +} + +// WithJSONNumber is an option to configure the underlying JSON parser with +// UseNumber. +func WithJSONNumber() ParserOption { + return func(p *Parser) { + p.useJSONNumber = true + } +} + +// WithoutClaimsValidation is an option to disable claims validation. This +// option should only be used if you exactly know what you are doing. +func WithoutClaimsValidation() ParserOption { + return func(p *Parser) { + p.skipClaimsValidation = true + } +} + +// WithLeeway returns the ParserOption for specifying the leeway window. +func WithLeeway(leeway time.Duration) ParserOption { + return func(p *Parser) { + p.validator.leeway = leeway + } +} + +// WithTimeFunc returns the ParserOption for specifying the time func. The +// primary use-case for this is testing. If you are looking for a way to account +// for clock-skew, WithLeeway should be used instead. +func WithTimeFunc(f func() time.Time) ParserOption { + return func(p *Parser) { + p.validator.timeFunc = f + } +} + +// WithIssuedAt returns the ParserOption to enable verification +// of issued-at. +func WithIssuedAt() ParserOption { + return func(p *Parser) { + p.validator.verifyIat = true + } +} + +// WithAudience configures the validator to require the specified audience in +// the `aud` claim. Validation will fail if the audience is not listed in the +// token or the `aud` claim is missing. +// +// NOTE: While the `aud` claim is OPTIONAL in a JWT, the handling of it is +// application-specific. Since this validation API is helping developers in +// writing secure application, we decided to REQUIRE the existence of the claim, +// if an audience is expected. +func WithAudience(aud string) ParserOption { + return func(p *Parser) { + p.validator.expectedAud = aud + } +} + +// WithIssuer configures the validator to require the specified issuer in the +// `iss` claim. Validation will fail if a different issuer is specified in the +// token or the `iss` claim is missing. +// +// NOTE: While the `iss` claim is OPTIONAL in a JWT, the handling of it is +// application-specific. Since this validation API is helping developers in +// writing secure application, we decided to REQUIRE the existence of the claim, +// if an issuer is expected. +func WithIssuer(iss string) ParserOption { + return func(p *Parser) { + p.validator.expectedIss = iss + } +} + +// WithSubject configures the validator to require the specified subject in the +// `sub` claim. Validation will fail if a different subject is specified in the +// token or the `sub` claim is missing. +// +// NOTE: While the `sub` claim is OPTIONAL in a JWT, the handling of it is +// application-specific. Since this validation API is helping developers in +// writing secure application, we decided to REQUIRE the existence of the claim, +// if a subject is expected. +func WithSubject(sub string) ParserOption { + return func(p *Parser) { + p.validator.expectedSub = sub + } +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/registered_claims.go b/vendor/github.com/golang-jwt/jwt/v5/registered_claims.go new file mode 100644 index 0000000000..77951a531d --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/registered_claims.go @@ -0,0 +1,63 @@ +package jwt + +// RegisteredClaims are a structured version of the JWT Claims Set, +// restricted to Registered Claim Names, as referenced at +// https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 +// +// This type can be used on its own, but then additional private and +// public claims embedded in the JWT will not be parsed. The typical use-case +// therefore is to embedded this in a user-defined claim type. +// +// See examples for how to use this with your own claim types. +type RegisteredClaims struct { + // the `iss` (Issuer) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1 + Issuer string `json:"iss,omitempty"` + + // the `sub` (Subject) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2 + Subject string `json:"sub,omitempty"` + + // the `aud` (Audience) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3 + Audience ClaimStrings `json:"aud,omitempty"` + + // the `exp` (Expiration Time) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4 + ExpiresAt *NumericDate `json:"exp,omitempty"` + + // the `nbf` (Not Before) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5 + NotBefore *NumericDate `json:"nbf,omitempty"` + + // the `iat` (Issued At) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6 + IssuedAt *NumericDate `json:"iat,omitempty"` + + // the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7 + ID string `json:"jti,omitempty"` +} + +// GetExpirationTime implements the Claims interface. +func (c RegisteredClaims) GetExpirationTime() (*NumericDate, error) { + return c.ExpiresAt, nil +} + +// GetNotBefore implements the Claims interface. +func (c RegisteredClaims) GetNotBefore() (*NumericDate, error) { + return c.NotBefore, nil +} + +// GetIssuedAt implements the Claims interface. +func (c RegisteredClaims) GetIssuedAt() (*NumericDate, error) { + return c.IssuedAt, nil +} + +// GetAudience implements the Claims interface. +func (c RegisteredClaims) GetAudience() (ClaimStrings, error) { + return c.Audience, nil +} + +// GetIssuer implements the Claims interface. +func (c RegisteredClaims) GetIssuer() (string, error) { + return c.Issuer, nil +} + +// GetSubject implements the Claims interface. +func (c RegisteredClaims) GetSubject() (string, error) { + return c.Subject, nil +} diff --git a/vendor/github.com/golang-jwt/jwt/v4/rsa.go b/vendor/github.com/golang-jwt/jwt/v5/rsa.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/rsa.go rename to vendor/github.com/golang-jwt/jwt/v5/rsa.go diff --git a/vendor/github.com/golang-jwt/jwt/v4/rsa_pss.go b/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/rsa_pss.go rename to vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go diff --git a/vendor/github.com/golang-jwt/jwt/v4/rsa_utils.go b/vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/rsa_utils.go rename to vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go diff --git a/vendor/github.com/golang-jwt/jwt/v4/signing_method.go b/vendor/github.com/golang-jwt/jwt/v5/signing_method.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/signing_method.go rename to vendor/github.com/golang-jwt/jwt/v5/signing_method.go diff --git a/vendor/github.com/golang-jwt/jwt/v4/staticcheck.conf b/vendor/github.com/golang-jwt/jwt/v5/staticcheck.conf similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v4/staticcheck.conf rename to vendor/github.com/golang-jwt/jwt/v5/staticcheck.conf diff --git a/vendor/github.com/golang-jwt/jwt/v5/token.go b/vendor/github.com/golang-jwt/jwt/v5/token.go new file mode 100644 index 0000000000..b3459427e8 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/token.go @@ -0,0 +1,145 @@ +package jwt + +import ( + "encoding/base64" + "encoding/json" + "strings" +) + +// DecodePaddingAllowed will switch the codec used for decoding JWTs +// respectively. Note that the JWS RFC7515 states that the tokens will utilize a +// Base64url encoding with no padding. Unfortunately, some implementations of +// JWT are producing non-standard tokens, and thus require support for decoding. +// Note that this is a global variable, and updating it will change the behavior +// on a package level, and is also NOT go-routine safe. To use the +// non-recommended decoding, set this boolean to `true` prior to using this +// package. +var DecodePaddingAllowed bool + +// DecodeStrict will switch the codec used for decoding JWTs into strict mode. +// In this mode, the decoder requires that trailing padding bits are zero, as +// described in RFC 4648 section 3.5. Note that this is a global variable, and +// updating it will change the behavior on a package level, and is also NOT +// go-routine safe. To use strict decoding, set this boolean to `true` prior to +// using this package. +var DecodeStrict bool + +// Keyfunc will be used by the Parse methods as a callback function to supply +// the key for verification. The function receives the parsed, but unverified +// Token. This allows you to use properties in the Header of the token (such as +// `kid`) to identify which key to use. +type Keyfunc func(*Token) (interface{}, error) + +// Token represents a JWT Token. Different fields will be used depending on +// whether you're creating or parsing/verifying a token. +type Token struct { + Raw string // Raw contains the raw token. Populated when you [Parse] a token + Method SigningMethod // Method is the signing method used or to be used + Header map[string]interface{} // Header is the first segment of the token + Claims Claims // Claims is the second segment of the token + Signature string // Signature is the third segment of the token. Populated when you Parse a token + Valid bool // Valid specifies if the token is valid. Populated when you Parse/Verify a token +} + +// New creates a new [Token] with the specified signing method and an empty map of +// claims. +func New(method SigningMethod) *Token { + return NewWithClaims(method, MapClaims{}) +} + +// NewWithClaims creates a new [Token] with the specified signing method and +// claims. +func NewWithClaims(method SigningMethod, claims Claims) *Token { + return &Token{ + Header: map[string]interface{}{ + "typ": "JWT", + "alg": method.Alg(), + }, + Claims: claims, + Method: method, + } +} + +// SignedString creates and returns a complete, signed JWT. The token is signed +// using the SigningMethod specified in the token. +func (t *Token) SignedString(key interface{}) (string, error) { + var sig, sstr string + var err error + if sstr, err = t.SigningString(); err != nil { + return "", err + } + if sig, err = t.Method.Sign(sstr, key); err != nil { + return "", err + } + return strings.Join([]string{sstr, sig}, "."), nil +} + +// SigningString generates the signing string. This is the most expensive part +// of the whole deal. Unless you need this for something special, just go +// straight for the SignedString. +func (t *Token) SigningString() (string, error) { + var err error + var jsonValue []byte + + if jsonValue, err = json.Marshal(t.Header); err != nil { + return "", err + } + header := EncodeSegment(jsonValue) + + if jsonValue, err = json.Marshal(t.Claims); err != nil { + return "", err + } + claim := EncodeSegment(jsonValue) + + return strings.Join([]string{header, claim}, "."), nil +} + +// Parse parses, validates, verifies the signature and returns the parsed token. +// keyFunc will receive the parsed token and should return the cryptographic key +// for verifying the signature. The caller is strongly encouraged to set the +// WithValidMethods option to validate the 'alg' claim in the token matches the +// expected algorithm. For more details about the importance of validating the +// 'alg' claim, see +// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/ +func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { + return NewParser(options...).Parse(tokenString, keyFunc) +} + +// ParseWithClaims is a shortcut for NewParser().ParseWithClaims(). +// +// Note: If you provide a custom claim implementation that embeds one of the +// standard claims (such as RegisteredClaims), make sure that a) you either +// embed a non-pointer version of the claims or b) if you are using a pointer, +// allocate the proper memory for it before passing in the overall claims, +// otherwise you might run into a panic. +func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { + return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc) +} + +// EncodeSegment encodes a JWT specific base64url encoding with padding stripped +// +// Deprecated: In a future release, we will demote this function to a +// non-exported function, since it should only be used internally +func EncodeSegment(seg []byte) string { + return base64.RawURLEncoding.EncodeToString(seg) +} + +// DecodeSegment decodes a JWT specific base64url encoding with padding stripped +// +// Deprecated: In a future release, we will demote this function to a +// non-exported function, since it should only be used internally +func DecodeSegment(seg string) ([]byte, error) { + encoding := base64.RawURLEncoding + + if DecodePaddingAllowed { + if l := len(seg) % 4; l > 0 { + seg += strings.Repeat("=", 4-l) + } + encoding = base64.URLEncoding + } + + if DecodeStrict { + encoding = encoding.Strict() + } + return encoding.DecodeString(seg) +} diff --git a/vendor/github.com/golang-jwt/jwt/v4/types.go b/vendor/github.com/golang-jwt/jwt/v5/types.go similarity index 76% rename from vendor/github.com/golang-jwt/jwt/v4/types.go rename to vendor/github.com/golang-jwt/jwt/v5/types.go index ac8e140eb1..b82b38867d 100644 --- a/vendor/github.com/golang-jwt/jwt/v4/types.go +++ b/vendor/github.com/golang-jwt/jwt/v5/types.go @@ -9,22 +9,23 @@ import ( "time" ) -// TimePrecision sets the precision of times and dates within this library. -// This has an influence on the precision of times when comparing expiry or -// other related time fields. Furthermore, it is also the precision of times -// when serializing. +// TimePrecision sets the precision of times and dates within this library. This +// has an influence on the precision of times when comparing expiry or other +// related time fields. Furthermore, it is also the precision of times when +// serializing. // // For backwards compatibility the default precision is set to seconds, so that // no fractional timestamps are generated. var TimePrecision = time.Second -// MarshalSingleStringAsArray modifies the behaviour of the ClaimStrings type, especially -// its MarshalJSON function. +// MarshalSingleStringAsArray modifies the behavior of the ClaimStrings type, +// especially its MarshalJSON function. // // If it is set to true (the default), it will always serialize the type as an -// array of strings, even if it just contains one element, defaulting to the behaviour -// of the underlying []string. If it is set to false, it will serialize to a single -// string, if it contains one element. Otherwise, it will serialize to an array of strings. +// array of strings, even if it just contains one element, defaulting to the +// behavior of the underlying []string. If it is set to false, it will serialize +// to a single string, if it contains one element. Otherwise, it will serialize +// to an array of strings. var MarshalSingleStringAsArray = true // NumericDate represents a JSON numeric date value, as referenced at @@ -58,9 +59,10 @@ func (date NumericDate) MarshalJSON() (b []byte, err error) { // For very large timestamps, UnixNano would overflow an int64, but this // function requires nanosecond level precision, so we have to use the // following technique to get round the issue: + // // 1. Take the normal unix timestamp to form the whole number part of the // output, - // 2. Take the result of the Nanosecond function, which retuns the offset + // 2. Take the result of the Nanosecond function, which returns the offset // within the second of the particular unix time instance, to form the // decimal part of the output // 3. Concatenate them to produce the final result @@ -72,9 +74,10 @@ func (date NumericDate) MarshalJSON() (b []byte, err error) { return output, nil } -// UnmarshalJSON is an implementation of the json.RawMessage interface and deserializses a -// NumericDate from a JSON representation, i.e. a json.Number. This number represents an UNIX epoch -// with either integer or non-integer seconds. +// UnmarshalJSON is an implementation of the json.RawMessage interface and +// deserializes a [NumericDate] from a JSON representation, i.e. a +// [json.Number]. This number represents an UNIX epoch with either integer or +// non-integer seconds. func (date *NumericDate) UnmarshalJSON(b []byte) (err error) { var ( number json.Number @@ -95,8 +98,9 @@ func (date *NumericDate) UnmarshalJSON(b []byte) (err error) { return nil } -// ClaimStrings is basically just a slice of strings, but it can be either serialized from a string array or just a string. -// This type is necessary, since the "aud" claim can either be a single string or an array. +// ClaimStrings is basically just a slice of strings, but it can be either +// serialized from a string array or just a string. This type is necessary, +// since the "aud" claim can either be a single string or an array. type ClaimStrings []string func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) { @@ -133,10 +137,11 @@ func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) { } func (s ClaimStrings) MarshalJSON() (b []byte, err error) { - // This handles a special case in the JWT RFC. If the string array, e.g. used by the "aud" field, - // only contains one element, it MAY be serialized as a single string. This may or may not be - // desired based on the ecosystem of other JWT library used, so we make it configurable by the - // variable MarshalSingleStringAsArray. + // This handles a special case in the JWT RFC. If the string array, e.g. + // used by the "aud" field, only contains one element, it MAY be serialized + // as a single string. This may or may not be desired based on the ecosystem + // of other JWT library used, so we make it configurable by the variable + // MarshalSingleStringAsArray. if len(s) == 1 && !MarshalSingleStringAsArray { return json.Marshal(s[0]) } diff --git a/vendor/github.com/golang-jwt/jwt/v5/validator.go b/vendor/github.com/golang-jwt/jwt/v5/validator.go new file mode 100644 index 0000000000..3850438939 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v5/validator.go @@ -0,0 +1,301 @@ +package jwt + +import ( + "crypto/subtle" + "fmt" + "time" +) + +// ClaimsValidator is an interface that can be implemented by custom claims who +// wish to execute any additional claims validation based on +// application-specific logic. The Validate function is then executed in +// addition to the regular claims validation and any error returned is appended +// to the final validation result. +// +// type MyCustomClaims struct { +// Foo string `json:"foo"` +// jwt.RegisteredClaims +// } +// +// func (m MyCustomClaims) Validate() error { +// if m.Foo != "bar" { +// return errors.New("must be foobar") +// } +// return nil +// } +type ClaimsValidator interface { + Claims + Validate() error +} + +// validator is the core of the new Validation API. It is automatically used by +// a [Parser] during parsing and can be modified with various parser options. +// +// Note: This struct is intentionally not exported (yet) as we want to +// internally finalize its API. In the future, we might make it publicly +// available. +type validator struct { + // leeway is an optional leeway that can be provided to account for clock skew. + leeway time.Duration + + // timeFunc is used to supply the current time that is needed for + // validation. If unspecified, this defaults to time.Now. + timeFunc func() time.Time + + // verifyIat specifies whether the iat (Issued At) claim will be verified. + // According to https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 this + // only specifies the age of the token, but no validation check is + // necessary. However, if wanted, it can be checked if the iat is + // unrealistic, i.e., in the future. + verifyIat bool + + // expectedAud contains the audience this token expects. Supplying an empty + // string will disable aud checking. + expectedAud string + + // expectedIss contains the issuer this token expects. Supplying an empty + // string will disable iss checking. + expectedIss string + + // expectedSub contains the subject this token expects. Supplying an empty + // string will disable sub checking. + expectedSub string +} + +// newValidator can be used to create a stand-alone validator with the supplied +// options. This validator can then be used to validate already parsed claims. +func newValidator(opts ...ParserOption) *validator { + p := NewParser(opts...) + return p.validator +} + +// Validate validates the given claims. It will also perform any custom +// validation if claims implements the [ClaimsValidator] interface. +func (v *validator) Validate(claims Claims) error { + var ( + now time.Time + errs []error = make([]error, 0, 6) + err error + ) + + // Check, if we have a time func + if v.timeFunc != nil { + now = v.timeFunc() + } else { + now = time.Now() + } + + // We always need to check the expiration time, but usage of the claim + // itself is OPTIONAL. + if err = v.verifyExpiresAt(claims, now, false); err != nil { + errs = append(errs, err) + } + + // We always need to check not-before, but usage of the claim itself is + // OPTIONAL. + if err = v.verifyNotBefore(claims, now, false); err != nil { + errs = append(errs, err) + } + + // Check issued-at if the option is enabled + if v.verifyIat { + if err = v.verifyIssuedAt(claims, now, false); err != nil { + errs = append(errs, err) + } + } + + // If we have an expected audience, we also require the audience claim + if v.expectedAud != "" { + if err = v.verifyAudience(claims, v.expectedAud, true); err != nil { + errs = append(errs, err) + } + } + + // If we have an expected issuer, we also require the issuer claim + if v.expectedIss != "" { + if err = v.verifyIssuer(claims, v.expectedIss, true); err != nil { + errs = append(errs, err) + } + } + + // If we have an expected subject, we also require the subject claim + if v.expectedSub != "" { + if err = v.verifySubject(claims, v.expectedSub, true); err != nil { + errs = append(errs, err) + } + } + + // Finally, we want to give the claim itself some possibility to do some + // additional custom validation based on a custom Validate function. + cvt, ok := claims.(ClaimsValidator) + if ok { + if err := cvt.Validate(); err != nil { + errs = append(errs, err) + } + } + + if len(errs) == 0 { + return nil + } + + return joinErrors(errs...) +} + +// verifyExpiresAt compares the exp claim in claims against cmp. This function +// will succeed if cmp < exp. Additional leeway is taken into account. +// +// If exp is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *validator) verifyExpiresAt(claims Claims, cmp time.Time, required bool) error { + exp, err := claims.GetExpirationTime() + if err != nil { + return err + } + + if exp == nil { + return errorIfRequired(required, "exp") + } + + return errorIfFalse(cmp.Before((exp.Time).Add(+v.leeway)), ErrTokenExpired) +} + +// verifyIssuedAt compares the iat claim in claims against cmp. This function +// will succeed if cmp >= iat. Additional leeway is taken into account. +// +// If iat is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *validator) verifyIssuedAt(claims Claims, cmp time.Time, required bool) error { + iat, err := claims.GetIssuedAt() + if err != nil { + return err + } + + if iat == nil { + return errorIfRequired(required, "iat") + } + + return errorIfFalse(!cmp.Before(iat.Add(-v.leeway)), ErrTokenUsedBeforeIssued) +} + +// verifyNotBefore compares the nbf claim in claims against cmp. This function +// will return true if cmp >= nbf. Additional leeway is taken into account. +// +// If nbf is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *validator) verifyNotBefore(claims Claims, cmp time.Time, required bool) error { + nbf, err := claims.GetNotBefore() + if err != nil { + return err + } + + if nbf == nil { + return errorIfRequired(required, "nbf") + } + + return errorIfFalse(!cmp.Before(nbf.Add(-v.leeway)), ErrTokenNotValidYet) +} + +// verifyAudience compares the aud claim against cmp. +// +// If aud is not set or an empty list, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *validator) verifyAudience(claims Claims, cmp string, required bool) error { + aud, err := claims.GetAudience() + if err != nil { + return err + } + + if len(aud) == 0 { + return errorIfRequired(required, "aud") + } + + // use a var here to keep constant time compare when looping over a number of claims + result := false + + var stringClaims string + for _, a := range aud { + if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 { + result = true + } + stringClaims = stringClaims + a + } + + // case where "" is sent in one or many aud claims + if stringClaims == "" { + return errorIfRequired(required, "aud") + } + + return errorIfFalse(result, ErrTokenInvalidAudience) +} + +// verifyIssuer compares the iss claim in claims against cmp. +// +// If iss is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *validator) verifyIssuer(claims Claims, cmp string, required bool) error { + iss, err := claims.GetIssuer() + if err != nil { + return err + } + + if iss == "" { + return errorIfRequired(required, "iss") + } + + return errorIfFalse(iss == cmp, ErrTokenInvalidIssuer) +} + +// verifySubject compares the sub claim against cmp. +// +// If sub is not set, it will succeed if the claim is not required, +// otherwise ErrTokenRequiredClaimMissing will be returned. +// +// Additionally, if any error occurs while retrieving the claim, e.g., when its +// the wrong type, an ErrTokenUnverifiable error will be returned. +func (v *validator) verifySubject(claims Claims, cmp string, required bool) error { + sub, err := claims.GetSubject() + if err != nil { + return err + } + + if sub == "" { + return errorIfRequired(required, "sub") + } + + return errorIfFalse(sub == cmp, ErrTokenInvalidSubject) +} + +// errorIfFalse returns the error specified in err, if the value is true. +// Otherwise, nil is returned. +func errorIfFalse(value bool, err error) error { + if value { + return nil + } else { + return err + } +} + +// errorIfRequired returns an ErrTokenRequiredClaimMissing error if required is +// true. Otherwise, nil is returned. +func errorIfRequired(required bool, claim string) error { + if required { + return newError(fmt.Sprintf("%s claim is required", claim), ErrTokenRequiredClaimMissing) + } else { + return nil + } +} diff --git a/vendor/modules.txt b/vendor/modules.txt index b83f14a3ff..4afb51a110 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -142,9 +142,9 @@ github.com/gofrs/uuid # github.com/gogo/protobuf v1.3.2 ## explicit; go 1.15 github.com/gogo/protobuf/proto -# github.com/golang-jwt/jwt/v4 v4.4.2 -## explicit; go 1.16 -github.com/golang-jwt/jwt/v4 +# github.com/golang-jwt/jwt/v5 v5.0.0-rc.1 +## explicit; go 1.18 +github.com/golang-jwt/jwt/v5 # github.com/golang/protobuf v1.5.2 ## explicit; go 1.9 github.com/golang/protobuf/jsonpb diff --git a/ws/api/endpoints.go b/ws/api/endpoints.go index b2a3c08319..9d7e71f132 100644 --- a/ws/api/endpoints.go +++ b/ws/api/endpoints.go @@ -145,7 +145,7 @@ func process(svc ws.Service, req connReq, msgs <-chan []byte) { Payload: msg, Created: time.Now().UnixNano(), } - svc.Publish(context.Background(), req.thingKey, &m) + _ = svc.Publish(context.Background(), req.thingKey, &m) } if err := svc.Unsubscribe(context.Background(), req.thingKey, req.chanID, req.subtopic); err != nil { req.conn.Close() @@ -153,7 +153,7 @@ func process(svc ws.Service, req connReq, msgs <-chan []byte) { } func encodeError(w http.ResponseWriter, err error) { - statusCode := http.StatusUnauthorized + var statusCode int switch err { case ws.ErrEmptyID, ws.ErrEmptyTopic: From 3e103615be3dbf8a02ad966752f6f278e188c3d7 Mon Sep 17 00:00:00 2001 From: aryan Date: Wed, 22 Feb 2023 19:01:11 +0530 Subject: [PATCH 03/26] handle error from grpc server in endpointtest Signed-off-by: aryan --- auth/api/grpc/endpoint_test.go | 27 ++-------------- auth/api/grpc/setup_test.go | 59 +++++++++++++++++++++++++++++++--- 2 files changed, 57 insertions(+), 29 deletions(-) diff --git a/auth/api/grpc/endpoint_test.go b/auth/api/grpc/endpoint_test.go index 084e53f8c7..9638b733b7 100644 --- a/auth/api/grpc/endpoint_test.go +++ b/auth/api/grpc/endpoint_test.go @@ -6,15 +6,12 @@ package grpc_test import ( "context" "fmt" - "net" "testing" "time" "github.com/mainflux/mainflux" "github.com/mainflux/mainflux/auth" grpcapi "github.com/mainflux/mainflux/auth/api/grpc" - "github.com/mainflux/mainflux/auth/jwt" - "github.com/mainflux/mainflux/auth/mocks" "github.com/mainflux/mainflux/pkg/uuid" "github.com/opentracing/opentracing-go/mocktracer" "github.com/stretchr/testify/assert" @@ -44,27 +41,6 @@ const ( var svc auth.Service -func newService() auth.Service { - repo := mocks.NewKeyRepository() - groupRepo := mocks.NewGroupRepository() - idProvider := uuid.NewMock() - - mockAuthzDB := map[string][]mocks.MockSubjectSet{} - mockAuthzDB[id] = append(mockAuthzDB[id], mocks.MockSubjectSet{Object: authoritiesObj, Relation: memberRelation}) - ketoMock := mocks.NewKetoMock(mockAuthzDB) - - t := jwt.New(secret) - - return auth.New(repo, groupRepo, idProvider, t, ketoMock, loginDuration) -} - -func startGRPCServer(svc auth.Service, port int) { - listener, _ := net.Listen("tcp", fmt.Sprintf(":%d", port)) - server := grpc.NewServer() - mainflux.RegisterAuthServiceServer(server, grpcapi.NewServer(mocktracer.New(), svc)) - go server.Serve(listener) -} - func TestIssue(t *testing.T) { authAddr := fmt.Sprintf("localhost:%d", port) conn, _ := grpc.Dial(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) @@ -452,7 +428,8 @@ func TestMembers(t *testing.T) { } authAddr := fmt.Sprintf("localhost:%d", port) - conn, _ := grpc.Dial(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, err := grpc.Dial(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + assert.Nil(t, err, fmt.Sprintf("got unexpected error while creating client connection: %s", err)) client := grpcapi.NewClient(mocktracer.New(), conn, time.Second) for _, tc := range cases { diff --git a/auth/api/grpc/setup_test.go b/auth/api/grpc/setup_test.go index 0af08379c4..e8cb56f063 100644 --- a/auth/api/grpc/setup_test.go +++ b/auth/api/grpc/setup_test.go @@ -4,15 +4,66 @@ package grpc_test import ( + "fmt" + "log" + "net" "os" "testing" + + "github.com/mainflux/mainflux" + "github.com/mainflux/mainflux/auth" + grpcapi "github.com/mainflux/mainflux/auth/api/grpc" + "github.com/mainflux/mainflux/auth/jwt" + "github.com/mainflux/mainflux/auth/mocks" + "github.com/mainflux/mainflux/pkg/uuid" + "github.com/opentracing/opentracing-go/mocktracer" + "github.com/stretchr/testify/assert" + "google.golang.org/grpc" ) func TestMain(m *testing.M) { - svc = newService() - startGRPCServer(svc, port) + t := &testing.T{} + serverErr := make(chan error) + testRes := make(chan int) + + svc = newService(t) + startGRPCServer(t, serverErr, svc, port) + + for { + select { + case testRes <- m.Run(): + code := <-testRes + os.Exit(code) + case err := <-serverErr: + if err != nil { + log.Fatalf("gPRC Server Terminated") + } + } + } +} + +func startGRPCServer(t *testing.T, serverErr chan error, svc auth.Service, port int) { + listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) + assert.Nil(t, err, fmt.Sprintf("got unexpected error while creating new listerner: %s", err)) + + server := grpc.NewServer() + mainflux.RegisterAuthServiceServer(server, grpcapi.NewServer(mocktracer.New(), svc)) + + go func() { + serverErr <- server.Serve(listener) + }() +} + +func newService(t *testing.T) auth.Service { + repo := mocks.NewKeyRepository() + groupRepo := mocks.NewGroupRepository() + idProvider := uuid.NewMock() + + mockAuthzDB := map[string][]mocks.MockSubjectSet{} + mockAuthzDB[id] = append(mockAuthzDB[id], mocks.MockSubjectSet{Object: authoritiesObj, Relation: memberRelation}) + ketoMock := mocks.NewKetoMock(mockAuthzDB) - code := m.Run() + tokenizer := jwt.New(secret) - os.Exit(code) + return auth.New(repo, groupRepo, idProvider, tokenizer, ketoMock, loginDuration) } From 6fa690a1f6d6e67ce10ccc265511903050a6c8eb Mon Sep 17 00:00:00 2001 From: aryan Date: Thu, 2 Mar 2023 02:57:51 +0530 Subject: [PATCH 04/26] temp commit, auth/jwt needs to be resolved Signed-off-by: aryan --- auth/postgres/groups.go | 3 +- auth/service.go | 3 ++ bootstrap/redis/producer/streams.go | 11 ++++++ bootstrap/redis/producer/streams_test.go | 24 +++++++++--- bootstrap/service.go | 26 +++++++++++-- things/postgres/channels.go | 49 ++++++++++++++++++++++-- things/postgres/channels_test.go | 11 +++++- things/postgres/things.go | 3 +- 8 files changed, 111 insertions(+), 19 deletions(-) diff --git a/auth/postgres/groups.go b/auth/postgres/groups.go index 009e28931b..079a8bdf23 100644 --- a/auth/postgres/groups.go +++ b/auth/postgres/groups.go @@ -440,8 +440,7 @@ func (gr groupRepository) Assign(ctx context.Context, groupID, groupType string, dbg.UpdatedAt = created if _, err := tx.NamedExecContext(ctx, qIns, dbg); err != nil { - err = tx.Rollback() - if err != nil { + if err := tx.Rollback(); err != nil { return errors.Wrap(auth.ErrAssignToGroup, err) } diff --git a/auth/service.go b/auth/service.go index 546ad4a786..ad95f0992e 100644 --- a/auth/service.go +++ b/auth/service.go @@ -139,6 +139,9 @@ func (svc service) RetrieveKey(ctx context.Context, token, id string) (Key, erro func (svc service) Identify(ctx context.Context, token string) (Identity, error) { key, err := svc.tokenizer.Parse(token) + fmt.Println() + fmt.Println(err) + fmt.Println() if err == ErrAPIKeyExpired { err = svc.keys.Remove(ctx, key.IssuerID, key.ID) return Identity{}, errors.Wrap(ErrAPIKeyExpired, err) diff --git a/bootstrap/redis/producer/streams.go b/bootstrap/redis/producer/streams.go index 2b3fa96c98..0c00be984b 100644 --- a/bootstrap/redis/producer/streams.go +++ b/bootstrap/redis/producer/streams.go @@ -5,6 +5,7 @@ package producer import ( "context" + "fmt" "time" "github.com/go-redis/redis/v8" @@ -113,6 +114,9 @@ func (es eventStore) Remove(ctx context.Context, token, id string) error { } func (es eventStore) Bootstrap(ctx context.Context, externalKey, externalID string, secure bool) (bootstrap.Config, error) { + fmt.Println() + fmt.Println("Eventstore bootstrap called:") + fmt.Println() cfg, err := es.svc.Bootstrap(ctx, externalKey, externalID, secure) ev := bootstrapEvent{ @@ -123,9 +127,16 @@ func (es eventStore) Bootstrap(ctx context.Context, externalKey, externalID stri if err != nil { ev.success = false + fmt.Println() + fmt.Println("returning err 1: ", err) + fmt.Println() + return cfg, err } err = es.add(ctx, ev) + fmt.Println() + fmt.Println("returning err 2: ", err) + fmt.Println() return cfg, err } diff --git a/bootstrap/redis/producer/streams_test.go b/bootstrap/redis/producer/streams_test.go index 70a1e20c5c..a58769c43d 100644 --- a/bootstrap/redis/producer/streams_test.go +++ b/bootstrap/redis/producer/streams_test.go @@ -421,6 +421,9 @@ func TestBootstrap(t *testing.T) { c := config saved, err := svc.Add(context.Background(), validToken, c) + fmt.Println() + fmt.Println("Saved : ", saved) + fmt.Println() require.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) err = redisClient.FlushAll(context.Background()).Err() assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) @@ -450,7 +453,7 @@ func TestBootstrap(t *testing.T) { externalKey: "external", err: bootstrap.ErrExternalKey, event: map[string]interface{}{ - "external_id": saved.ExternalID, + "external_id": "external", "success": "0", "timestamp": time.Now().Unix(), "operation": thingBootstrap, @@ -460,8 +463,10 @@ func TestBootstrap(t *testing.T) { lastID := "0" for _, tc := range cases { - _, err := svc.Bootstrap(context.Background(), tc.externalKey, tc.externalID, false) - assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) + fmt.Printf("\n\n\n%s\n\n\n", tc.desc) + _, errr := svc.Bootstrap(context.Background(), tc.externalKey, tc.externalID, false) + fmt.Println("returned error : ", errr) + assert.True(t, errors.Contains(errr, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, errr)) streams := redisClient.XRead(context.Background(), &redis.XReadArgs{ Streams: []string{streamID, lastID}, @@ -475,7 +480,13 @@ func TestBootstrap(t *testing.T) { event = msg.Values lastID = msg.ID } - + fmt.Println() + fmt.Println("tc.event : ") + fmt.Println(tc.event) + fmt.Println() + fmt.Println("event from XRead: ") + fmt.Println(event) + fmt.Println() test(t, tc.event, event, tc.desc) } } @@ -552,14 +563,15 @@ func TestChangeState(t *testing.T) { func test(t *testing.T, expected, actual map[string]interface{}, description string) { if expected != nil && actual != nil { ts1 := expected["timestamp"].(int64) + ts2, err := strconv.ParseInt(actual["timestamp"].(string), 10, 64) - assert.Nil(t, err, fmt.Sprintf("%s: expected to get a valid timestamp, got %s", description, err)) + require.Nil(t, err, fmt.Sprintf("%s: expected to get a valid timestamp, got %s", description, err)) val := ts1 == ts2 || ts2 <= ts1+defaultTimout assert.True(t, val, fmt.Sprintf("%s: timestamp is not in valid range", description)) delete(expected, "timestamp") delete(actual, "timestamp") - assert.Equal(t, expected, actual, fmt.Sprintf("%s: expected %v got %v\n", description, expected, actual)) + assert.Equal(t, expected, actual, fmt.Sprintf("%s: got incorrect event\n", description)) } } diff --git a/bootstrap/service.go b/bootstrap/service.go index fc5675b4a6..28c8f3d656 100644 --- a/bootstrap/service.go +++ b/bootstrap/service.go @@ -8,6 +8,7 @@ import ( "crypto/aes" "crypto/cipher" "encoding/hex" + "fmt" "time" "github.com/mainflux/mainflux" @@ -272,19 +273,38 @@ func (bs bootstrapService) Remove(ctx context.Context, token, id string) error { func (bs bootstrapService) Bootstrap(ctx context.Context, externalKey, externalID string, secure bool) (Config, error) { cfg, err := bs.configs.RetrieveByExternalID(externalID) + fmt.Println() + fmt.Println("RetreivebyexternalId : : err 1", err) + fmt.Println() + fmt.Println("Received config : ", cfg.ExternalID) + fmt.Println("Received config : ", cfg.ExternalKey) + fmt.Println("Received config : ", cfg.Name) + fmt.Println("Received config : ", cfg.MFThing) + fmt.Println() if err != nil { - return cfg, errors.Wrap(ErrBootstrap, err) + fmt.Println("returning err 2: : ", err) + err = errors.Wrap(ErrBootstrap, err) + fmt.Println(err) + return cfg, err } - if secure { dec, err := bs.dec(externalKey) if err != nil { + fmt.Println() + fmt.Println("returnring err 3 : ", err) + fmt.Println() return Config{}, errors.Wrap(ErrExternalKeySecure, err) } externalKey = dec } - + fmt.Println() + fmt.Println("key value : ", cfg.ExternalKey, " ", externalKey) + fmt.Println() if cfg.ExternalKey != externalKey { + fmt.Println() + fmt.Println("returning error 4 : ", err) + fmt.Println() + return Config{}, ErrExternalKey } diff --git a/things/postgres/channels.go b/things/postgres/channels.go index fe880fa1c3..652c3c0407 100644 --- a/things/postgres/channels.go +++ b/things/postgres/channels.go @@ -40,6 +40,9 @@ func NewChannelRepository(db Database) things.ChannelRepository { func (cr channelRepository) Save(ctx context.Context, channels ...things.Channel) ([]things.Channel, error) { tx, err := cr.db.BeginTxx(ctx, nil) + fmt.Println() + fmt.Println("1 : ", err) + fmt.Println() if err != nil { return nil, errors.Wrap(errors.ErrCreateEntity, err) } @@ -51,27 +54,51 @@ func (cr channelRepository) Save(ctx context.Context, channels ...things.Channel dbch := toDBChannel(channel) _, err = tx.NamedExecContext(ctx, q, dbch) + fmt.Println() + fmt.Println("namedexeccontext error : ", err) + fmt.Println() if err != nil { - err = tx.Rollback() - if err != nil { + if err := tx.Rollback(); err != nil { return []things.Channel{}, errors.Wrap(errors.ErrCreateEntity, err) } + // rollBackerr := tx.Rollback() + // fmt.Println() + // fmt.Println("2 : ", rollBackerr) + // fmt.Println() + // if rollBackerr != nil { + // return []things.Channel{}, errors.Wrap(errors.ErrCreateEntity, err) + // } pgErr, ok := err.(*pgconn.PgError) if ok { switch pgErr.Code { case pgerrcode.InvalidTextRepresentation: + fmt.Println() + fmt.Println("returning switch case 1") + fmt.Println() return []things.Channel{}, errors.Wrap(errors.ErrMalformedEntity, err) case pgerrcode.UniqueViolation: + fmt.Println() + fmt.Println("returning switch case 2") + fmt.Println() return []things.Channel{}, errors.Wrap(errors.ErrConflict, err) case pgerrcode.StringDataRightTruncationDataException: + fmt.Println() + fmt.Println("returning switch case 3") + fmt.Println() return []things.Channel{}, errors.Wrap(errors.ErrMalformedEntity, err) } } + fmt.Println() + fmt.Println("returning after switch case, not ok") + fmt.Println() return []things.Channel{}, errors.Wrap(errors.ErrCreateEntity, err) } } if err = tx.Commit(); err != nil { + fmt.Println() + fmt.Println("4 : ", err) + fmt.Println() return []things.Channel{}, errors.Wrap(errors.ErrCreateEntity, err) } @@ -130,12 +157,18 @@ func (cr channelRepository) RetrieveByID(ctx context.Context, owner, id string) } func (cr channelRepository) RetrieveAll(ctx context.Context, owner string, pm things.PageMetadata) (things.ChannelsPage, error) { + fmt.Println() + fmt.Println("Is tjjhfkfk") + fmt.Println() nq, name := getNameQuery(pm.Name) oq := getOrderQuery(pm.Order) dq := getDirQuery(pm.Dir) ownerQuery := getOwnerQuery(pm.FetchSharedThings) meta, mq, err := getMetadataQuery(pm.Metadata) if err != nil { + fmt.Println() + fmt.Println("1 : ", err) + fmt.Println() return things.ChannelsPage{}, errors.Wrap(errors.ErrViewEntity, err) } @@ -167,6 +200,9 @@ func (cr channelRepository) RetrieveAll(ctx context.Context, owner string, pm th } rows, err := cr.db.NamedQueryContext(ctx, q, params) if err != nil { + fmt.Println() + fmt.Println("2 : ", err) + fmt.Println() return things.ChannelsPage{}, errors.Wrap(errors.ErrViewEntity, err) } defer rows.Close() @@ -175,6 +211,9 @@ func (cr channelRepository) RetrieveAll(ctx context.Context, owner string, pm th for rows.Next() { dbch := dbChannel{Owner: owner} if err := rows.StructScan(&dbch); err != nil { + fmt.Println() + fmt.Println("3 : ", err) + fmt.Println() return things.ChannelsPage{}, errors.Wrap(errors.ErrViewEntity, err) } ch := toChannel(dbch) @@ -186,6 +225,9 @@ func (cr channelRepository) RetrieveAll(ctx context.Context, owner string, pm th total, err := total(ctx, cr.db, cq, params) if err != nil { + fmt.Println() + fmt.Println("4 : ", err) + fmt.Println() return things.ChannelsPage{}, errors.Wrap(errors.ErrViewEntity, err) } @@ -318,8 +360,7 @@ func (cr channelRepository) Connect(ctx context.Context, owner string, chIDs, th _, err := tx.NamedExecContext(ctx, q, dbco) if err != nil { - err = tx.Rollback() - if err != nil { + if err := tx.Rollback(); err != nil { return errors.Wrap(things.ErrConnect, err) } diff --git a/things/postgres/channels_test.go b/things/postgres/channels_test.go index 1cd271d9c6..040ffd42b0 100644 --- a/things/postgres/channels_test.go +++ b/things/postgres/channels_test.go @@ -78,8 +78,11 @@ func TestChannelsSave(t *testing.T) { } for _, tc := range cases { - resp, err := channelRepo.Save(context.Background(), tc.channels...) - assert.Equal(t, tc.response, resp, fmt.Sprintf("%s: got incorrect list of channels from Save()", tc.desc)) + fmt.Printf("\n\n###\n%s\n###\n\n", tc.desc) + _, err := channelRepo.Save(context.Background(), tc.channels...) + fmt.Println() + fmt.Println("returned error : ", err) + fmt.Println() assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) } } @@ -672,7 +675,11 @@ func TestConnect(t *testing.T) { } for _, tc := range cases { + fmt.Printf("\n\n###\n%s\n###\n\n", tc.desc) err := chanRepo.Connect(context.Background(), tc.owner, []string{tc.chID}, []string{tc.thID}) + fmt.Println() + fmt.Println("returned error : ", err) + fmt.Println() assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) } } diff --git a/things/postgres/things.go b/things/postgres/things.go index e5d8f5a376..854c997f61 100644 --- a/things/postgres/things.go +++ b/things/postgres/things.go @@ -48,8 +48,7 @@ func (tr thingRepository) Save(ctx context.Context, ths ...things.Thing) ([]thin } if _, err := tx.NamedExecContext(ctx, q, dbth); err != nil { - err = tx.Rollback() - if err != nil { + if err := tx.Rollback(); err != nil { return []things.Thing{}, errors.Wrap(errors.ErrCreateEntity, err) } pgErr, ok := err.(*pgconn.PgError) From 34a21cad126a3e60e1b2ccd009a5a441f2d22b7a Mon Sep 17 00:00:00 2001 From: aryan Date: Fri, 3 Mar 2023 18:48:18 +0530 Subject: [PATCH 05/26] revert back to jwt v4 temporarily Signed-off-by: aryan --- auth/jwt/tokenizer.go | 24 +- go.mod | 1 + go.sum | 2 + .../golang-jwt/jwt/{v5 => v4}/.gitignore | 0 .../golang-jwt/jwt/{v5 => v4}/LICENSE | 0 .../golang-jwt/jwt/v4/MIGRATION_GUIDE.md | 22 ++ .../golang-jwt/jwt/{v5 => v4}/README.md | 28 +- .../golang-jwt/jwt/{v5 => v4}/SECURITY.md | 0 .../jwt/{v5 => v4}/VERSION_HISTORY.md | 16 +- vendor/github.com/golang-jwt/jwt/v4/claims.go | 269 ++++++++++++++++ .../golang-jwt/jwt/{v5 => v4}/doc.go | 0 .../golang-jwt/jwt/{v5 => v4}/ecdsa.go | 0 .../golang-jwt/jwt/{v5 => v4}/ecdsa_utils.go | 0 .../golang-jwt/jwt/{v5 => v4}/ed25519.go | 0 .../jwt/{v5 => v4}/ed25519_utils.go | 0 vendor/github.com/golang-jwt/jwt/v4/errors.go | 112 +++++++ .../golang-jwt/jwt/{v5 => v4}/hmac.go | 0 .../golang-jwt/jwt/v4/map_claims.go | 151 +++++++++ .../golang-jwt/jwt/{v5 => v4}/none.go | 7 +- .../golang-jwt/jwt/{v5 => v4}/parser.go | 89 +++--- .../golang-jwt/jwt/v4/parser_option.go | 29 ++ .../golang-jwt/jwt/{v5 => v4}/rsa.go | 0 .../golang-jwt/jwt/{v5 => v4}/rsa_pss.go | 0 .../golang-jwt/jwt/{v5 => v4}/rsa_utils.go | 0 .../jwt/{v5 => v4}/signing_method.go | 0 .../jwt/{v5 => v4}/staticcheck.conf | 0 vendor/github.com/golang-jwt/jwt/v4/token.go | 143 +++++++++ .../golang-jwt/jwt/{v5 => v4}/types.go | 43 ++- .../golang-jwt/jwt/v5/MIGRATION_GUIDE.md | 100 ------ vendor/github.com/golang-jwt/jwt/v5/claims.go | 16 - vendor/github.com/golang-jwt/jwt/v5/errors.go | 49 --- .../golang-jwt/jwt/v5/errors_go1_20.go | 47 --- .../golang-jwt/jwt/v5/errors_go_other.go | 78 ----- .../golang-jwt/jwt/v5/map_claims.go | 109 ------- .../golang-jwt/jwt/v5/parser_option.go | 101 ------ .../golang-jwt/jwt/v5/registered_claims.go | 63 ---- vendor/github.com/golang-jwt/jwt/v5/token.go | 145 --------- .../github.com/golang-jwt/jwt/v5/validator.go | 301 ------------------ vendor/modules.txt | 4 +- 39 files changed, 840 insertions(+), 1109 deletions(-) rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/.gitignore (100%) rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/LICENSE (100%) create mode 100644 vendor/github.com/golang-jwt/jwt/v4/MIGRATION_GUIDE.md rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/README.md (93%) rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/SECURITY.md (100%) rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/VERSION_HISTORY.md (96%) create mode 100644 vendor/github.com/golang-jwt/jwt/v4/claims.go rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/doc.go (100%) rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/ecdsa.go (100%) rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/ecdsa_utils.go (100%) rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/ed25519.go (100%) rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/ed25519_utils.go (100%) create mode 100644 vendor/github.com/golang-jwt/jwt/v4/errors.go rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/hmac.go (100%) create mode 100644 vendor/github.com/golang-jwt/jwt/v4/map_claims.go rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/none.go (85%) rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/parser.go (59%) create mode 100644 vendor/github.com/golang-jwt/jwt/v4/parser_option.go rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/rsa.go (100%) rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/rsa_pss.go (100%) rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/rsa_utils.go (100%) rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/signing_method.go (100%) rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/staticcheck.conf (100%) create mode 100644 vendor/github.com/golang-jwt/jwt/v4/token.go rename vendor/github.com/golang-jwt/jwt/{v5 => v4}/types.go (76%) delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/claims.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/errors.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/map_claims.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/parser_option.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/registered_claims.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/token.go delete mode 100644 vendor/github.com/golang-jwt/jwt/v5/validator.go diff --git a/auth/jwt/tokenizer.go b/auth/jwt/tokenizer.go index 6761b8e6b8..29a3231519 100644 --- a/auth/jwt/tokenizer.go +++ b/auth/jwt/tokenizer.go @@ -6,7 +6,7 @@ package jwt import ( "time" - "github.com/golang-jwt/jwt/v5" + "github.com/golang-jwt/jwt/v4" "github.com/mainflux/mainflux/auth" "github.com/mainflux/mainflux/pkg/errors" ) @@ -14,7 +14,7 @@ import ( const issuerName = "mainflux.auth" type claims struct { - jwt.RegisteredClaims + jwt.StandardClaims IssuerID string `json:"issuer_id,omitempty"` Type *uint32 `json:"type,omitempty"` } @@ -24,7 +24,7 @@ func (c claims) Valid() error { return errors.ErrMalformedEntity } - return c.RegisteredClaims.ExpiresAt.GobDecode([]byte{}) //.Valid() + return c.StandardClaims.Valid() } type tokenizer struct { @@ -38,20 +38,20 @@ func New(secret string) auth.Tokenizer { func (svc tokenizer) Issue(key auth.Key) (string, error) { claims := claims{ - RegisteredClaims: jwt.RegisteredClaims{ + StandardClaims: jwt.StandardClaims{ Issuer: issuerName, Subject: key.Subject, - IssuedAt: &jwt.NumericDate{Time: key.IssuedAt.UTC()}, + IssuedAt: key.IssuedAt.UTC().Unix(), }, IssuerID: key.IssuerID, Type: &key.Type, } if !key.ExpiresAt.IsZero() { - claims.ExpiresAt = &jwt.NumericDate{Time: key.ExpiresAt.UTC()} + claims.ExpiresAt = key.ExpiresAt.UTC().Unix() } if key.ID != "" { - claims.ID = key.ID + claims.Id = key.ID } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) @@ -68,7 +68,7 @@ func (svc tokenizer) Parse(token string) (auth.Key, error) { }) if err != nil { - if errors.Contains(err, jwt.ErrTokenExpired) { + if e, ok := err.(*jwt.ValidationError); ok && e.Errors == jwt.ValidationErrorExpired { // Expired User key needs to be revoked. if c.Type != nil && *c.Type == auth.APIKey { return c.toKey(), auth.ErrAPIKeyExpired @@ -83,13 +83,13 @@ func (svc tokenizer) Parse(token string) (auth.Key, error) { func (c claims) toKey() auth.Key { key := auth.Key{ - ID: c.ID, + ID: c.Id, IssuerID: c.IssuerID, Subject: c.Subject, - IssuedAt: time.Unix(c.IssuedAt.Unix(), 0).UTC(), + IssuedAt: time.Unix(c.IssuedAt, 0).UTC(), } - if c.ExpiresAt.Unix() != 0 { - key.ExpiresAt = time.Unix(c.ExpiresAt.Unix(), 0).UTC() + if c.ExpiresAt != 0 { + key.ExpiresAt = time.Unix(c.ExpiresAt, 0).UTC() } // Default type is 0. diff --git a/go.mod b/go.mod index d077c760e9..aec15644b0 100644 --- a/go.mod +++ b/go.mod @@ -76,6 +76,7 @@ require ( github.com/go-gorp/gorp/v3 v3.1.0 // indirect github.com/go-logfmt/logfmt v0.5.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect + github.com/golang-jwt/jwt/v4 v4.5.0 // indirect github.com/golang/snappy v0.0.4 // indirect github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed // indirect diff --git a/go.sum b/go.sum index d29f90a555..100474c2dc 100644 --- a/go.sum +++ b/go.sum @@ -217,6 +217,8 @@ github.com/gogo/protobuf v1.2.1/go.mod h1:hp+jE20tsWTFYpLwKvXlhS1hjn+gTNwPg2I6zV github.com/gogo/protobuf v1.3.1/go.mod h1:SlYgWuQ5SjCEi6WLHjHCa1yvBfUnHcTbrrZtXPKa29o= github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= +github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= github.com/golang-jwt/jwt/v5 v5.0.0-rc.1 h1:tDQ1LjKga657layZ4JLsRdxgvupebc0xuPwRNuTfUgs= github.com/golang-jwt/jwt/v5 v5.0.0-rc.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= diff --git a/vendor/github.com/golang-jwt/jwt/v5/.gitignore b/vendor/github.com/golang-jwt/jwt/v4/.gitignore similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v5/.gitignore rename to vendor/github.com/golang-jwt/jwt/v4/.gitignore diff --git a/vendor/github.com/golang-jwt/jwt/v5/LICENSE b/vendor/github.com/golang-jwt/jwt/v4/LICENSE similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v5/LICENSE rename to vendor/github.com/golang-jwt/jwt/v4/LICENSE diff --git a/vendor/github.com/golang-jwt/jwt/v4/MIGRATION_GUIDE.md b/vendor/github.com/golang-jwt/jwt/v4/MIGRATION_GUIDE.md new file mode 100644 index 0000000000..32966f5981 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v4/MIGRATION_GUIDE.md @@ -0,0 +1,22 @@ +## Migration Guide (v4.0.0) + +Starting from [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0), the import path will be: + + "github.com/golang-jwt/jwt/v4" + +The `/v4` version will be backwards compatible with existing `v3.x.y` tags in this repo, as well as +`github.com/dgrijalva/jwt-go`. For most users this should be a drop-in replacement, if you're having +troubles migrating, please open an issue. + +You can replace all occurrences of `github.com/dgrijalva/jwt-go` or `github.com/golang-jwt/jwt` with `github.com/golang-jwt/jwt/v4`, either manually or by using tools such as `sed` or `gofmt`. + +And then you'd typically run: + +``` +go get github.com/golang-jwt/jwt/v4 +go mod tidy +``` + +## Older releases (before v3.2.0) + +The original migration guide for older releases can be found at https://github.com/dgrijalva/jwt-go/blob/master/MIGRATION_GUIDE.md. diff --git a/vendor/github.com/golang-jwt/jwt/v5/README.md b/vendor/github.com/golang-jwt/jwt/v4/README.md similarity index 93% rename from vendor/github.com/golang-jwt/jwt/v5/README.md rename to vendor/github.com/golang-jwt/jwt/v4/README.md index 87259e8403..30f2f2a6f7 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/README.md +++ b/vendor/github.com/golang-jwt/jwt/v4/README.md @@ -1,12 +1,12 @@ # jwt-go [![build](https://github.com/golang-jwt/jwt/actions/workflows/build.yml/badge.svg)](https://github.com/golang-jwt/jwt/actions/workflows/build.yml) -[![Go Reference](https://pkg.go.dev/badge/github.com/golang-jwt/jwt/v5.svg)](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) +[![Go Reference](https://pkg.go.dev/badge/github.com/golang-jwt/jwt/v4.svg)](https://pkg.go.dev/github.com/golang-jwt/jwt/v4) A [go](http://www.golang.org) (or 'golang' for search engine friendliness) implementation of [JSON Web Tokens](https://datatracker.ietf.org/doc/html/rfc7519). Starting with [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0) this project adds Go module support, but maintains backwards compatibility with older `v3.x.y` tags and upstream `github.com/dgrijalva/jwt-go`. -See the [`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) for more information. Version v5.0.0 introduces major improvements to the validation of tokens, but is not entirely backwards compatible. +See the [`MIGRATION_GUIDE.md`](./MIGRATION_GUIDE.md) for more information. > After the original author of the library suggested migrating the maintenance of `jwt-go`, a dedicated team of open source maintainers decided to clone the existing library into this repository. See [dgrijalva/jwt-go#462](https://github.com/dgrijalva/jwt-go/issues/462) for a detailed discussion on this topic. @@ -41,22 +41,22 @@ This library supports the parsing and verification as well as the generation and 1. To install the jwt package, you first need to have [Go](https://go.dev/doc/install) installed, then you can use the command below to add `jwt-go` as a dependency in your Go program. ```sh -go get -u github.com/golang-jwt/jwt/v5 +go get -u github.com/golang-jwt/jwt/v4 ``` 2. Import it in your code: ```go -import "github.com/golang-jwt/jwt/v5" +import "github.com/golang-jwt/jwt/v4" ``` ## Examples -See [the project documentation](https://pkg.go.dev/github.com/golang-jwt/jwt/v5) for examples of usage: +See [the project documentation](https://pkg.go.dev/github.com/golang-jwt/jwt/v4) for examples of usage: -* [Simple example of parsing and validating a token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-Parse-Hmac) -* [Simple example of building and signing a token](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#example-New-Hmac) -* [Directory of Examples](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#pkg-examples) +* [Simple example of parsing and validating a token](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#example-Parse-Hmac) +* [Simple example of building and signing a token](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#example-New-Hmac) +* [Directory of Examples](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#pkg-examples) ## Extensions @@ -68,7 +68,7 @@ A common use case would be integrating with different 3rd party signature provid | --------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------ | | GCP | Integrates with multiple Google Cloud Platform signing tools (AppEngine, IAM API, Cloud KMS) | https://github.com/someone1/gcp-jwt-go | | AWS | Integrates with AWS Key Management Service, KMS | https://github.com/matelang/jwt-go-aws-kms | -| JWKS | Provides support for JWKS ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)) as a `jwt.Keyfunc` | https://github.com/MicahParks/keyfunc | +| JWKS | Provides support for JWKS ([RFC 7517](https://datatracker.ietf.org/doc/html/rfc7517)) as a `jwt.Keyfunc` | https://github.com/MicahParks/keyfunc | *Disclaimer*: Unless otherwise specified, these integrations are maintained by third parties and should not be considered as a primary offer by any of the mentioned cloud providers @@ -110,10 +110,10 @@ Asymmetric signing methods, such as RSA, use different keys for signing and veri Each signing method expects a different object type for its signing keys. See the package documentation for details. Here are the most common ones: -* The [HMAC signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation -* The [RSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation -* The [ECDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation -* The [EdDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v5#SigningMethodEd25519) (`Ed25519`) expect `ed25519.PrivateKey` for signing and `ed25519.PublicKey` for validation +* The [HMAC signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#SigningMethodHMAC) (`HS256`,`HS384`,`HS512`) expect `[]byte` values for signing and validation +* The [RSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#SigningMethodRSA) (`RS256`,`RS384`,`RS512`) expect `*rsa.PrivateKey` for signing and `*rsa.PublicKey` for validation +* The [ECDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#SigningMethodECDSA) (`ES256`,`ES384`,`ES512`) expect `*ecdsa.PrivateKey` for signing and `*ecdsa.PublicKey` for validation +* The [EdDSA signing method](https://pkg.go.dev/github.com/golang-jwt/jwt/v4#SigningMethodEd25519) (`Ed25519`) expect `ed25519.PrivateKey` for signing and `ed25519.PublicKey` for validation ### JWT and OAuth @@ -131,7 +131,7 @@ This library uses descriptive error messages whenever possible. If you are not g ## More -Documentation can be found [on pkg.go.dev](https://pkg.go.dev/github.com/golang-jwt/jwt/v5). +Documentation can be found [on pkg.go.dev](https://pkg.go.dev/github.com/golang-jwt/jwt/v4). The command line utility included in this project (cmd/jwt) provides a straightforward example of token creation and parsing as well as a useful tool for debugging your own integration. You'll also find several implementation examples in the documentation. diff --git a/vendor/github.com/golang-jwt/jwt/v5/SECURITY.md b/vendor/github.com/golang-jwt/jwt/v4/SECURITY.md similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v5/SECURITY.md rename to vendor/github.com/golang-jwt/jwt/v4/SECURITY.md diff --git a/vendor/github.com/golang-jwt/jwt/v5/VERSION_HISTORY.md b/vendor/github.com/golang-jwt/jwt/v4/VERSION_HISTORY.md similarity index 96% rename from vendor/github.com/golang-jwt/jwt/v5/VERSION_HISTORY.md rename to vendor/github.com/golang-jwt/jwt/v4/VERSION_HISTORY.md index b5039e49c1..afbfc4e408 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/VERSION_HISTORY.md +++ b/vendor/github.com/golang-jwt/jwt/v4/VERSION_HISTORY.md @@ -1,19 +1,17 @@ -# `jwt-go` Version History +## `jwt-go` Version History -The following version history is kept for historic purposes. To retrieve the current changes of each version, please refer to the change-log of the specific release versions on https://github.com/golang-jwt/jwt/releases. - -## 4.0.0 +#### 4.0.0 * Introduces support for Go modules. The `v4` version will be backwards compatible with `v3.x.y`. -## 3.2.2 +#### 3.2.2 * Starting from this release, we are adopting the policy to support the most 2 recent versions of Go currently available. By the time of this release, this is Go 1.15 and 1.16 ([#28](https://github.com/golang-jwt/jwt/pull/28)). * Fixed a potential issue that could occur when the verification of `exp`, `iat` or `nbf` was not required and contained invalid contents, i.e. non-numeric/date. Thanks for @thaJeztah for making us aware of that and @giorgos-f3 for originally reporting it to the formtech fork ([#40](https://github.com/golang-jwt/jwt/pull/40)). * Added support for EdDSA / ED25519 ([#36](https://github.com/golang-jwt/jwt/pull/36)). * Optimized allocations ([#33](https://github.com/golang-jwt/jwt/pull/33)). -## 3.2.1 +#### 3.2.1 * **Import Path Change**: See MIGRATION_GUIDE.md for tips on updating your code * Changed the import path from `github.com/dgrijalva/jwt-go` to `github.com/golang-jwt/jwt` @@ -119,17 +117,17 @@ It is likely the only integration change required here will be to change `func(t * Refactored the RSA implementation to be easier to read * Exposed helper methods `ParseRSAPrivateKeyFromPEM` and `ParseRSAPublicKeyFromPEM` -## 1.0.2 +#### 1.0.2 * Fixed bug in parsing public keys from certificates * Added more tests around the parsing of keys for RS256 * Code refactoring in RS256 implementation. No functional changes -## 1.0.1 +#### 1.0.1 * Fixed panic if RS256 signing method was passed an invalid key -## 1.0.0 +#### 1.0.0 * First versioned release * API stabilized diff --git a/vendor/github.com/golang-jwt/jwt/v4/claims.go b/vendor/github.com/golang-jwt/jwt/v4/claims.go new file mode 100644 index 0000000000..364cec8773 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v4/claims.go @@ -0,0 +1,269 @@ +package jwt + +import ( + "crypto/subtle" + "fmt" + "time" +) + +// Claims must just have a Valid method that determines +// if the token is invalid for any supported reason +type Claims interface { + Valid() error +} + +// RegisteredClaims are a structured version of the JWT Claims Set, +// restricted to Registered Claim Names, as referenced at +// https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 +// +// This type can be used on its own, but then additional private and +// public claims embedded in the JWT will not be parsed. The typical usecase +// therefore is to embedded this in a user-defined claim type. +// +// See examples for how to use this with your own claim types. +type RegisteredClaims struct { + // the `iss` (Issuer) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1 + Issuer string `json:"iss,omitempty"` + + // the `sub` (Subject) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2 + Subject string `json:"sub,omitempty"` + + // the `aud` (Audience) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3 + Audience ClaimStrings `json:"aud,omitempty"` + + // the `exp` (Expiration Time) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4 + ExpiresAt *NumericDate `json:"exp,omitempty"` + + // the `nbf` (Not Before) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5 + NotBefore *NumericDate `json:"nbf,omitempty"` + + // the `iat` (Issued At) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6 + IssuedAt *NumericDate `json:"iat,omitempty"` + + // the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7 + ID string `json:"jti,omitempty"` +} + +// Valid validates time based claims "exp, iat, nbf". +// There is no accounting for clock skew. +// As well, if any of the above claims are not in the token, it will still +// be considered a valid claim. +func (c RegisteredClaims) Valid() error { + vErr := new(ValidationError) + now := TimeFunc() + + // The claims below are optional, by default, so if they are set to the + // default value in Go, let's not fail the verification for them. + if !c.VerifyExpiresAt(now, false) { + delta := now.Sub(c.ExpiresAt.Time) + vErr.Inner = fmt.Errorf("%s by %s", ErrTokenExpired, delta) + vErr.Errors |= ValidationErrorExpired + } + + if !c.VerifyIssuedAt(now, false) { + vErr.Inner = ErrTokenUsedBeforeIssued + vErr.Errors |= ValidationErrorIssuedAt + } + + if !c.VerifyNotBefore(now, false) { + vErr.Inner = ErrTokenNotValidYet + vErr.Errors |= ValidationErrorNotValidYet + } + + if vErr.valid() { + return nil + } + + return vErr +} + +// VerifyAudience compares the aud claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *RegisteredClaims) VerifyAudience(cmp string, req bool) bool { + return verifyAud(c.Audience, cmp, req) +} + +// VerifyExpiresAt compares the exp claim against cmp (cmp < exp). +// If req is false, it will return true, if exp is unset. +func (c *RegisteredClaims) VerifyExpiresAt(cmp time.Time, req bool) bool { + if c.ExpiresAt == nil { + return verifyExp(nil, cmp, req) + } + + return verifyExp(&c.ExpiresAt.Time, cmp, req) +} + +// VerifyIssuedAt compares the iat claim against cmp (cmp >= iat). +// If req is false, it will return true, if iat is unset. +func (c *RegisteredClaims) VerifyIssuedAt(cmp time.Time, req bool) bool { + if c.IssuedAt == nil { + return verifyIat(nil, cmp, req) + } + + return verifyIat(&c.IssuedAt.Time, cmp, req) +} + +// VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). +// If req is false, it will return true, if nbf is unset. +func (c *RegisteredClaims) VerifyNotBefore(cmp time.Time, req bool) bool { + if c.NotBefore == nil { + return verifyNbf(nil, cmp, req) + } + + return verifyNbf(&c.NotBefore.Time, cmp, req) +} + +// VerifyIssuer compares the iss claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *RegisteredClaims) VerifyIssuer(cmp string, req bool) bool { + return verifyIss(c.Issuer, cmp, req) +} + +// StandardClaims are a structured version of the JWT Claims Set, as referenced at +// https://datatracker.ietf.org/doc/html/rfc7519#section-4. They do not follow the +// specification exactly, since they were based on an earlier draft of the +// specification and not updated. The main difference is that they only +// support integer-based date fields and singular audiences. This might lead to +// incompatibilities with other JWT implementations. The use of this is discouraged, instead +// the newer RegisteredClaims struct should be used. +// +// Deprecated: Use RegisteredClaims instead for a forward-compatible way to access registered claims in a struct. +type StandardClaims struct { + Audience string `json:"aud,omitempty"` + ExpiresAt int64 `json:"exp,omitempty"` + Id string `json:"jti,omitempty"` + IssuedAt int64 `json:"iat,omitempty"` + Issuer string `json:"iss,omitempty"` + NotBefore int64 `json:"nbf,omitempty"` + Subject string `json:"sub,omitempty"` +} + +// Valid validates time based claims "exp, iat, nbf". There is no accounting for clock skew. +// As well, if any of the above claims are not in the token, it will still +// be considered a valid claim. +func (c StandardClaims) Valid() error { + vErr := new(ValidationError) + now := TimeFunc().Unix() + + // The claims below are optional, by default, so if they are set to the + // default value in Go, let's not fail the verification for them. + if !c.VerifyExpiresAt(now, false) { + delta := time.Unix(now, 0).Sub(time.Unix(c.ExpiresAt, 0)) + vErr.Inner = fmt.Errorf("%s by %s", ErrTokenExpired, delta) + vErr.Errors |= ValidationErrorExpired + } + + if !c.VerifyIssuedAt(now, false) { + vErr.Inner = ErrTokenUsedBeforeIssued + vErr.Errors |= ValidationErrorIssuedAt + } + + if !c.VerifyNotBefore(now, false) { + vErr.Inner = ErrTokenNotValidYet + vErr.Errors |= ValidationErrorNotValidYet + } + + if vErr.valid() { + return nil + } + + return vErr +} + +// VerifyAudience compares the aud claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyAudience(cmp string, req bool) bool { + return verifyAud([]string{c.Audience}, cmp, req) +} + +// VerifyExpiresAt compares the exp claim against cmp (cmp < exp). +// If req is false, it will return true, if exp is unset. +func (c *StandardClaims) VerifyExpiresAt(cmp int64, req bool) bool { + if c.ExpiresAt == 0 { + return verifyExp(nil, time.Unix(cmp, 0), req) + } + + t := time.Unix(c.ExpiresAt, 0) + return verifyExp(&t, time.Unix(cmp, 0), req) +} + +// VerifyIssuedAt compares the iat claim against cmp (cmp >= iat). +// If req is false, it will return true, if iat is unset. +func (c *StandardClaims) VerifyIssuedAt(cmp int64, req bool) bool { + if c.IssuedAt == 0 { + return verifyIat(nil, time.Unix(cmp, 0), req) + } + + t := time.Unix(c.IssuedAt, 0) + return verifyIat(&t, time.Unix(cmp, 0), req) +} + +// VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). +// If req is false, it will return true, if nbf is unset. +func (c *StandardClaims) VerifyNotBefore(cmp int64, req bool) bool { + if c.NotBefore == 0 { + return verifyNbf(nil, time.Unix(cmp, 0), req) + } + + t := time.Unix(c.NotBefore, 0) + return verifyNbf(&t, time.Unix(cmp, 0), req) +} + +// VerifyIssuer compares the iss claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (c *StandardClaims) VerifyIssuer(cmp string, req bool) bool { + return verifyIss(c.Issuer, cmp, req) +} + +// ----- helpers + +func verifyAud(aud []string, cmp string, required bool) bool { + if len(aud) == 0 { + return !required + } + // use a var here to keep constant time compare when looping over a number of claims + result := false + + var stringClaims string + for _, a := range aud { + if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 { + result = true + } + stringClaims = stringClaims + a + } + + // case where "" is sent in one or many aud claims + if len(stringClaims) == 0 { + return !required + } + + return result +} + +func verifyExp(exp *time.Time, now time.Time, required bool) bool { + if exp == nil { + return !required + } + return now.Before(*exp) +} + +func verifyIat(iat *time.Time, now time.Time, required bool) bool { + if iat == nil { + return !required + } + return now.After(*iat) || now.Equal(*iat) +} + +func verifyNbf(nbf *time.Time, now time.Time, required bool) bool { + if nbf == nil { + return !required + } + return now.After(*nbf) || now.Equal(*nbf) +} + +func verifyIss(iss string, cmp string, required bool) bool { + if iss == "" { + return !required + } + return subtle.ConstantTimeCompare([]byte(iss), []byte(cmp)) != 0 +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/doc.go b/vendor/github.com/golang-jwt/jwt/v4/doc.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v5/doc.go rename to vendor/github.com/golang-jwt/jwt/v4/doc.go diff --git a/vendor/github.com/golang-jwt/jwt/v5/ecdsa.go b/vendor/github.com/golang-jwt/jwt/v4/ecdsa.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v5/ecdsa.go rename to vendor/github.com/golang-jwt/jwt/v4/ecdsa.go diff --git a/vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go b/vendor/github.com/golang-jwt/jwt/v4/ecdsa_utils.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v5/ecdsa_utils.go rename to vendor/github.com/golang-jwt/jwt/v4/ecdsa_utils.go diff --git a/vendor/github.com/golang-jwt/jwt/v5/ed25519.go b/vendor/github.com/golang-jwt/jwt/v4/ed25519.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v5/ed25519.go rename to vendor/github.com/golang-jwt/jwt/v4/ed25519.go diff --git a/vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go b/vendor/github.com/golang-jwt/jwt/v4/ed25519_utils.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v5/ed25519_utils.go rename to vendor/github.com/golang-jwt/jwt/v4/ed25519_utils.go diff --git a/vendor/github.com/golang-jwt/jwt/v4/errors.go b/vendor/github.com/golang-jwt/jwt/v4/errors.go new file mode 100644 index 0000000000..10ac8835cc --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v4/errors.go @@ -0,0 +1,112 @@ +package jwt + +import ( + "errors" +) + +// Error constants +var ( + ErrInvalidKey = errors.New("key is invalid") + ErrInvalidKeyType = errors.New("key is of invalid type") + ErrHashUnavailable = errors.New("the requested hash function is unavailable") + + ErrTokenMalformed = errors.New("token is malformed") + ErrTokenUnverifiable = errors.New("token is unverifiable") + ErrTokenSignatureInvalid = errors.New("token signature is invalid") + + ErrTokenInvalidAudience = errors.New("token has invalid audience") + ErrTokenExpired = errors.New("token is expired") + ErrTokenUsedBeforeIssued = errors.New("token used before issued") + ErrTokenInvalidIssuer = errors.New("token has invalid issuer") + ErrTokenNotValidYet = errors.New("token is not valid yet") + ErrTokenInvalidId = errors.New("token has invalid id") + ErrTokenInvalidClaims = errors.New("token has invalid claims") +) + +// The errors that might occur when parsing and validating a token +const ( + ValidationErrorMalformed uint32 = 1 << iota // Token is malformed + ValidationErrorUnverifiable // Token could not be verified because of signing problems + ValidationErrorSignatureInvalid // Signature validation failed + + // Standard Claim validation errors + ValidationErrorAudience // AUD validation failed + ValidationErrorExpired // EXP validation failed + ValidationErrorIssuedAt // IAT validation failed + ValidationErrorIssuer // ISS validation failed + ValidationErrorNotValidYet // NBF validation failed + ValidationErrorId // JTI validation failed + ValidationErrorClaimsInvalid // Generic claims validation error +) + +// NewValidationError is a helper for constructing a ValidationError with a string error message +func NewValidationError(errorText string, errorFlags uint32) *ValidationError { + return &ValidationError{ + text: errorText, + Errors: errorFlags, + } +} + +// ValidationError represents an error from Parse if token is not valid +type ValidationError struct { + Inner error // stores the error returned by external dependencies, i.e.: KeyFunc + Errors uint32 // bitfield. see ValidationError... constants + text string // errors that do not have a valid error just have text +} + +// Error is the implementation of the err interface. +func (e ValidationError) Error() string { + if e.Inner != nil { + return e.Inner.Error() + } else if e.text != "" { + return e.text + } else { + return "token is invalid" + } +} + +// Unwrap gives errors.Is and errors.As access to the inner error. +func (e *ValidationError) Unwrap() error { + return e.Inner +} + +// No errors +func (e *ValidationError) valid() bool { + return e.Errors == 0 +} + +// Is checks if this ValidationError is of the supplied error. We are first checking for the exact error message +// by comparing the inner error message. If that fails, we compare using the error flags. This way we can use +// custom error messages (mainly for backwards compatability) and still leverage errors.Is using the global error variables. +func (e *ValidationError) Is(err error) bool { + // Check, if our inner error is a direct match + if errors.Is(errors.Unwrap(e), err) { + return true + } + + // Otherwise, we need to match using our error flags + switch err { + case ErrTokenMalformed: + return e.Errors&ValidationErrorMalformed != 0 + case ErrTokenUnverifiable: + return e.Errors&ValidationErrorUnverifiable != 0 + case ErrTokenSignatureInvalid: + return e.Errors&ValidationErrorSignatureInvalid != 0 + case ErrTokenInvalidAudience: + return e.Errors&ValidationErrorAudience != 0 + case ErrTokenExpired: + return e.Errors&ValidationErrorExpired != 0 + case ErrTokenUsedBeforeIssued: + return e.Errors&ValidationErrorIssuedAt != 0 + case ErrTokenInvalidIssuer: + return e.Errors&ValidationErrorIssuer != 0 + case ErrTokenNotValidYet: + return e.Errors&ValidationErrorNotValidYet != 0 + case ErrTokenInvalidId: + return e.Errors&ValidationErrorId != 0 + case ErrTokenInvalidClaims: + return e.Errors&ValidationErrorClaimsInvalid != 0 + } + + return false +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/hmac.go b/vendor/github.com/golang-jwt/jwt/v4/hmac.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v5/hmac.go rename to vendor/github.com/golang-jwt/jwt/v4/hmac.go diff --git a/vendor/github.com/golang-jwt/jwt/v4/map_claims.go b/vendor/github.com/golang-jwt/jwt/v4/map_claims.go new file mode 100644 index 0000000000..2700d64a0d --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v4/map_claims.go @@ -0,0 +1,151 @@ +package jwt + +import ( + "encoding/json" + "errors" + "time" + // "fmt" +) + +// MapClaims is a claims type that uses the map[string]interface{} for JSON decoding. +// This is the default claims type if you don't supply one +type MapClaims map[string]interface{} + +// VerifyAudience Compares the aud claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyAudience(cmp string, req bool) bool { + var aud []string + switch v := m["aud"].(type) { + case string: + aud = append(aud, v) + case []string: + aud = v + case []interface{}: + for _, a := range v { + vs, ok := a.(string) + if !ok { + return false + } + aud = append(aud, vs) + } + } + return verifyAud(aud, cmp, req) +} + +// VerifyExpiresAt compares the exp claim against cmp (cmp <= exp). +// If req is false, it will return true, if exp is unset. +func (m MapClaims) VerifyExpiresAt(cmp int64, req bool) bool { + cmpTime := time.Unix(cmp, 0) + + v, ok := m["exp"] + if !ok { + return !req + } + + switch exp := v.(type) { + case float64: + if exp == 0 { + return verifyExp(nil, cmpTime, req) + } + + return verifyExp(&newNumericDateFromSeconds(exp).Time, cmpTime, req) + case json.Number: + v, _ := exp.Float64() + + return verifyExp(&newNumericDateFromSeconds(v).Time, cmpTime, req) + } + + return false +} + +// VerifyIssuedAt compares the exp claim against cmp (cmp >= iat). +// If req is false, it will return true, if iat is unset. +func (m MapClaims) VerifyIssuedAt(cmp int64, req bool) bool { + cmpTime := time.Unix(cmp, 0) + + v, ok := m["iat"] + if !ok { + return !req + } + + switch iat := v.(type) { + case float64: + if iat == 0 { + return verifyIat(nil, cmpTime, req) + } + + return verifyIat(&newNumericDateFromSeconds(iat).Time, cmpTime, req) + case json.Number: + v, _ := iat.Float64() + + return verifyIat(&newNumericDateFromSeconds(v).Time, cmpTime, req) + } + + return false +} + +// VerifyNotBefore compares the nbf claim against cmp (cmp >= nbf). +// If req is false, it will return true, if nbf is unset. +func (m MapClaims) VerifyNotBefore(cmp int64, req bool) bool { + cmpTime := time.Unix(cmp, 0) + + v, ok := m["nbf"] + if !ok { + return !req + } + + switch nbf := v.(type) { + case float64: + if nbf == 0 { + return verifyNbf(nil, cmpTime, req) + } + + return verifyNbf(&newNumericDateFromSeconds(nbf).Time, cmpTime, req) + case json.Number: + v, _ := nbf.Float64() + + return verifyNbf(&newNumericDateFromSeconds(v).Time, cmpTime, req) + } + + return false +} + +// VerifyIssuer compares the iss claim against cmp. +// If required is false, this method will return true if the value matches or is unset +func (m MapClaims) VerifyIssuer(cmp string, req bool) bool { + iss, _ := m["iss"].(string) + return verifyIss(iss, cmp, req) +} + +// Valid validates time based claims "exp, iat, nbf". +// There is no accounting for clock skew. +// As well, if any of the above claims are not in the token, it will still +// be considered a valid claim. +func (m MapClaims) Valid() error { + vErr := new(ValidationError) + now := TimeFunc().Unix() + + if !m.VerifyExpiresAt(now, false) { + // TODO(oxisto): this should be replaced with ErrTokenExpired + vErr.Inner = errors.New("Token is expired") + vErr.Errors |= ValidationErrorExpired + } + + if !m.VerifyIssuedAt(now, false) { + // TODO(oxisto): this should be replaced with ErrTokenUsedBeforeIssued + vErr.Inner = errors.New("Token used before issued") + vErr.Errors |= ValidationErrorIssuedAt + } + + if !m.VerifyNotBefore(now, false) { + // TODO(oxisto): this should be replaced with ErrTokenNotValidYet + vErr.Inner = errors.New("Token is not valid yet") + vErr.Errors |= ValidationErrorNotValidYet + } + + if vErr.valid() { + return nil + } + + return vErr +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/none.go b/vendor/github.com/golang-jwt/jwt/v4/none.go similarity index 85% rename from vendor/github.com/golang-jwt/jwt/v5/none.go rename to vendor/github.com/golang-jwt/jwt/v4/none.go index a16495acbe..f19835d207 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/none.go +++ b/vendor/github.com/golang-jwt/jwt/v4/none.go @@ -13,7 +13,7 @@ type unsafeNoneMagicConstant string func init() { SigningMethodNone = &signingMethodNone{} - NoneSignatureTypeDisallowedError = newError("'none' signature type is not allowed", ErrTokenUnverifiable) + NoneSignatureTypeDisallowedError = NewValidationError("'none' signature type is not allowed", ValidationErrorSignatureInvalid) RegisterSigningMethod(SigningMethodNone.Alg(), func() SigningMethod { return SigningMethodNone @@ -33,7 +33,10 @@ func (m *signingMethodNone) Verify(signingString, signature string, key interfac } // If signing method is none, signature must be an empty string if signature != "" { - return newError("'none' signing method with non-empty signature", ErrTokenUnverifiable) + return NewValidationError( + "'none' signing method with non-empty signature", + ValidationErrorSignatureInvalid, + ) } // Accept 'none' signing method. diff --git a/vendor/github.com/golang-jwt/jwt/v5/parser.go b/vendor/github.com/golang-jwt/jwt/v4/parser.go similarity index 59% rename from vendor/github.com/golang-jwt/jwt/v5/parser.go rename to vendor/github.com/golang-jwt/jwt/v4/parser.go index 46b67931d6..c0a6f69279 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/parser.go +++ b/vendor/github.com/golang-jwt/jwt/v4/parser.go @@ -9,24 +9,26 @@ import ( type Parser struct { // If populated, only these methods will be considered valid. - validMethods []string + // + // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead. + ValidMethods []string // Use JSON Number format in JSON decoder. - useJSONNumber bool + // + // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead. + UseJSONNumber bool // Skip claims validation during token parsing. - skipClaimsValidation bool - - validator *validator + // + // Deprecated: In future releases, this field will not be exported anymore and should be set with an option to NewParser instead. + SkipClaimsValidation bool } // NewParser creates a new Parser with the specified options func NewParser(options ...ParserOption) *Parser { - p := &Parser{ - validator: &validator{}, - } + p := &Parser{} - // Loop through our parsing options and apply them + // loop through our parsing options and apply them for _, option := range options { option(p) } @@ -54,10 +56,10 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf } // Verify signing method is in the required set - if p.validMethods != nil { + if p.ValidMethods != nil { var signingMethodValid = false var alg = token.Method.Alg() - for _, m := range p.validMethods { + for _, m := range p.ValidMethods { if m == alg { signingMethodValid = true break @@ -65,7 +67,7 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf } if !signingMethodValid { // signing method is not in the listed set - return token, newError(fmt.Sprintf("signing method %v is invalid", alg), ErrTokenSignatureInvalid) + return token, NewValidationError(fmt.Sprintf("signing method %v is invalid", alg), ValidationErrorSignatureInvalid) } } @@ -73,34 +75,45 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf var key interface{} if keyFunc == nil { // keyFunc was not provided. short circuiting validation - return token, newError("no keyfunc was provided", ErrTokenUnverifiable) + return token, NewValidationError("no Keyfunc was provided.", ValidationErrorUnverifiable) } if key, err = keyFunc(token); err != nil { - return token, newError("error while executing keyfunc", ErrTokenUnverifiable, err) + // keyFunc returned an error + if ve, ok := err.(*ValidationError); ok { + return token, ve + } + return token, &ValidationError{Inner: err, Errors: ValidationErrorUnverifiable} } - // Perform signature validation - token.Signature = parts[2] - if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { - return token, newError("", ErrTokenSignatureInvalid, err) - } + vErr := &ValidationError{} // Validate Claims - if !p.skipClaimsValidation { - // Make sure we have at least a default validator - if p.validator == nil { - p.validator = newValidator() + if !p.SkipClaimsValidation { + if err := token.Claims.Valid(); err != nil { + + // If the Claims Valid returned an error, check if it is a validation error, + // If it was another error type, create a ValidationError with a generic ClaimsInvalid flag set + if e, ok := err.(*ValidationError); !ok { + vErr = &ValidationError{Inner: err, Errors: ValidationErrorClaimsInvalid} + } else { + vErr = e + } } + } - if err := p.validator.Validate(claims); err != nil { - return token, newError("", ErrTokenInvalidClaims, err) - } + // Perform validation + token.Signature = parts[2] + if err = token.Method.Verify(strings.Join(parts[0:2], "."), token.Signature, key); err != nil { + vErr.Inner = err + vErr.Errors |= ValidationErrorSignatureInvalid } - // No errors so far, token is valid. - token.Valid = true + if vErr.valid() { + token.Valid = true + return token, nil + } - return token, nil + return token, vErr } // ParseUnverified parses the token but doesn't validate the signature. @@ -112,7 +125,7 @@ func (p *Parser) ParseWithClaims(tokenString string, claims Claims, keyFunc Keyf func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Token, parts []string, err error) { parts = strings.Split(tokenString, ".") if len(parts) != 3 { - return nil, parts, newError("token contains an invalid number of segments", ErrTokenMalformed) + return nil, parts, NewValidationError("token contains an invalid number of segments", ValidationErrorMalformed) } token = &Token{Raw: tokenString} @@ -121,12 +134,12 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke var headerBytes []byte if headerBytes, err = DecodeSegment(parts[0]); err != nil { if strings.HasPrefix(strings.ToLower(tokenString), "bearer ") { - return token, parts, newError("tokenstring should not contain 'bearer '", ErrTokenMalformed) + return token, parts, NewValidationError("tokenstring should not contain 'bearer '", ValidationErrorMalformed) } - return token, parts, newError("could not base64 decode header", ErrTokenMalformed, err) + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} } if err = json.Unmarshal(headerBytes, &token.Header); err != nil { - return token, parts, newError("could not JSON decode header", ErrTokenMalformed, err) + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} } // parse Claims @@ -134,10 +147,10 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke token.Claims = claims if claimBytes, err = DecodeSegment(parts[1]); err != nil { - return token, parts, newError("could not base64 decode claim", ErrTokenMalformed, err) + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} } dec := json.NewDecoder(bytes.NewBuffer(claimBytes)) - if p.useJSONNumber { + if p.UseJSONNumber { dec.UseNumber() } // JSON Decode. Special case for map type to avoid weird pointer behavior @@ -148,16 +161,16 @@ func (p *Parser) ParseUnverified(tokenString string, claims Claims) (token *Toke } // Handle decode error if err != nil { - return token, parts, newError("could not JSON decode claim", ErrTokenMalformed, err) + return token, parts, &ValidationError{Inner: err, Errors: ValidationErrorMalformed} } // Lookup signature method if method, ok := token.Header["alg"].(string); ok { if token.Method = GetSigningMethod(method); token.Method == nil { - return token, parts, newError("signing method (alg) is unavailable", ErrTokenUnverifiable) + return token, parts, NewValidationError("signing method (alg) is unavailable.", ValidationErrorUnverifiable) } } else { - return token, parts, newError("signing method (alg) is unspecified", ErrTokenUnverifiable) + return token, parts, NewValidationError("signing method (alg) is unspecified.", ValidationErrorUnverifiable) } return token, parts, nil diff --git a/vendor/github.com/golang-jwt/jwt/v4/parser_option.go b/vendor/github.com/golang-jwt/jwt/v4/parser_option.go new file mode 100644 index 0000000000..6ea6f9527d --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v4/parser_option.go @@ -0,0 +1,29 @@ +package jwt + +// ParserOption is used to implement functional-style options that modify the behavior of the parser. To add +// new options, just create a function (ideally beginning with With or Without) that returns an anonymous function that +// takes a *Parser type as input and manipulates its configuration accordingly. +type ParserOption func(*Parser) + +// WithValidMethods is an option to supply algorithm methods that the parser will check. Only those methods will be considered valid. +// It is heavily encouraged to use this option in order to prevent attacks such as https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/. +func WithValidMethods(methods []string) ParserOption { + return func(p *Parser) { + p.ValidMethods = methods + } +} + +// WithJSONNumber is an option to configure the underlying JSON parser with UseNumber +func WithJSONNumber() ParserOption { + return func(p *Parser) { + p.UseJSONNumber = true + } +} + +// WithoutClaimsValidation is an option to disable claims validation. This option should only be used if you exactly know +// what you are doing. +func WithoutClaimsValidation() ParserOption { + return func(p *Parser) { + p.SkipClaimsValidation = true + } +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/rsa.go b/vendor/github.com/golang-jwt/jwt/v4/rsa.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v5/rsa.go rename to vendor/github.com/golang-jwt/jwt/v4/rsa.go diff --git a/vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go b/vendor/github.com/golang-jwt/jwt/v4/rsa_pss.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v5/rsa_pss.go rename to vendor/github.com/golang-jwt/jwt/v4/rsa_pss.go diff --git a/vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go b/vendor/github.com/golang-jwt/jwt/v4/rsa_utils.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v5/rsa_utils.go rename to vendor/github.com/golang-jwt/jwt/v4/rsa_utils.go diff --git a/vendor/github.com/golang-jwt/jwt/v5/signing_method.go b/vendor/github.com/golang-jwt/jwt/v4/signing_method.go similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v5/signing_method.go rename to vendor/github.com/golang-jwt/jwt/v4/signing_method.go diff --git a/vendor/github.com/golang-jwt/jwt/v5/staticcheck.conf b/vendor/github.com/golang-jwt/jwt/v4/staticcheck.conf similarity index 100% rename from vendor/github.com/golang-jwt/jwt/v5/staticcheck.conf rename to vendor/github.com/golang-jwt/jwt/v4/staticcheck.conf diff --git a/vendor/github.com/golang-jwt/jwt/v4/token.go b/vendor/github.com/golang-jwt/jwt/v4/token.go new file mode 100644 index 0000000000..786b275ce0 --- /dev/null +++ b/vendor/github.com/golang-jwt/jwt/v4/token.go @@ -0,0 +1,143 @@ +package jwt + +import ( + "encoding/base64" + "encoding/json" + "strings" + "time" +) + +// DecodePaddingAllowed will switch the codec used for decoding JWTs respectively. Note that the JWS RFC7515 +// states that the tokens will utilize a Base64url encoding with no padding. Unfortunately, some implementations +// of JWT are producing non-standard tokens, and thus require support for decoding. Note that this is a global +// variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe. +// To use the non-recommended decoding, set this boolean to `true` prior to using this package. +var DecodePaddingAllowed bool + +// DecodeStrict will switch the codec used for decoding JWTs into strict mode. +// In this mode, the decoder requires that trailing padding bits are zero, as described in RFC 4648 section 3.5. +// Note that this is a global variable, and updating it will change the behavior on a package level, and is also NOT go-routine safe. +// To use strict decoding, set this boolean to `true` prior to using this package. +var DecodeStrict bool + +// TimeFunc provides the current time when parsing token to validate "exp" claim (expiration time). +// You can override it to use another time value. This is useful for testing or if your +// server uses a different time zone than your tokens. +var TimeFunc = time.Now + +// Keyfunc will be used by the Parse methods as a callback function to supply +// the key for verification. The function receives the parsed, +// but unverified Token. This allows you to use properties in the +// Header of the token (such as `kid`) to identify which key to use. +type Keyfunc func(*Token) (interface{}, error) + +// Token represents a JWT Token. Different fields will be used depending on whether you're +// creating or parsing/verifying a token. +type Token struct { + Raw string // The raw token. Populated when you Parse a token + Method SigningMethod // The signing method used or to be used + Header map[string]interface{} // The first segment of the token + Claims Claims // The second segment of the token + Signature string // The third segment of the token. Populated when you Parse a token + Valid bool // Is the token valid? Populated when you Parse/Verify a token +} + +// New creates a new Token with the specified signing method and an empty map of claims. +func New(method SigningMethod) *Token { + return NewWithClaims(method, MapClaims{}) +} + +// NewWithClaims creates a new Token with the specified signing method and claims. +func NewWithClaims(method SigningMethod, claims Claims) *Token { + return &Token{ + Header: map[string]interface{}{ + "typ": "JWT", + "alg": method.Alg(), + }, + Claims: claims, + Method: method, + } +} + +// SignedString creates and returns a complete, signed JWT. +// The token is signed using the SigningMethod specified in the token. +func (t *Token) SignedString(key interface{}) (string, error) { + var sig, sstr string + var err error + if sstr, err = t.SigningString(); err != nil { + return "", err + } + if sig, err = t.Method.Sign(sstr, key); err != nil { + return "", err + } + return strings.Join([]string{sstr, sig}, "."), nil +} + +// SigningString generates the signing string. This is the +// most expensive part of the whole deal. Unless you +// need this for something special, just go straight for +// the SignedString. +func (t *Token) SigningString() (string, error) { + var err error + var jsonValue []byte + + if jsonValue, err = json.Marshal(t.Header); err != nil { + return "", err + } + header := EncodeSegment(jsonValue) + + if jsonValue, err = json.Marshal(t.Claims); err != nil { + return "", err + } + claim := EncodeSegment(jsonValue) + + return strings.Join([]string{header, claim}, "."), nil +} + +// Parse parses, validates, verifies the signature and returns the parsed token. +// keyFunc will receive the parsed token and should return the cryptographic key +// for verifying the signature. +// The caller is strongly encouraged to set the WithValidMethods option to +// validate the 'alg' claim in the token matches the expected algorithm. +// For more details about the importance of validating the 'alg' claim, +// see https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/ +func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { + return NewParser(options...).Parse(tokenString, keyFunc) +} + +// ParseWithClaims is a shortcut for NewParser().ParseWithClaims(). +// +// Note: If you provide a custom claim implementation that embeds one of the standard claims (such as RegisteredClaims), +// make sure that a) you either embed a non-pointer version of the claims or b) if you are using a pointer, allocate the +// proper memory for it before passing in the overall claims, otherwise you might run into a panic. +func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { + return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc) +} + +// EncodeSegment encodes a JWT specific base64url encoding with padding stripped +// +// Deprecated: In a future release, we will demote this function to a non-exported function, since it +// should only be used internally +func EncodeSegment(seg []byte) string { + return base64.RawURLEncoding.EncodeToString(seg) +} + +// DecodeSegment decodes a JWT specific base64url encoding with padding stripped +// +// Deprecated: In a future release, we will demote this function to a non-exported function, since it +// should only be used internally +func DecodeSegment(seg string) ([]byte, error) { + encoding := base64.RawURLEncoding + + if DecodePaddingAllowed { + if l := len(seg) % 4; l > 0 { + seg += strings.Repeat("=", 4-l) + } + encoding = base64.URLEncoding + } + + if DecodeStrict { + encoding = encoding.Strict() + } + return encoding.DecodeString(seg) +} diff --git a/vendor/github.com/golang-jwt/jwt/v5/types.go b/vendor/github.com/golang-jwt/jwt/v4/types.go similarity index 76% rename from vendor/github.com/golang-jwt/jwt/v5/types.go rename to vendor/github.com/golang-jwt/jwt/v4/types.go index b82b38867d..ac8e140eb1 100644 --- a/vendor/github.com/golang-jwt/jwt/v5/types.go +++ b/vendor/github.com/golang-jwt/jwt/v4/types.go @@ -9,23 +9,22 @@ import ( "time" ) -// TimePrecision sets the precision of times and dates within this library. This -// has an influence on the precision of times when comparing expiry or other -// related time fields. Furthermore, it is also the precision of times when -// serializing. +// TimePrecision sets the precision of times and dates within this library. +// This has an influence on the precision of times when comparing expiry or +// other related time fields. Furthermore, it is also the precision of times +// when serializing. // // For backwards compatibility the default precision is set to seconds, so that // no fractional timestamps are generated. var TimePrecision = time.Second -// MarshalSingleStringAsArray modifies the behavior of the ClaimStrings type, -// especially its MarshalJSON function. +// MarshalSingleStringAsArray modifies the behaviour of the ClaimStrings type, especially +// its MarshalJSON function. // // If it is set to true (the default), it will always serialize the type as an -// array of strings, even if it just contains one element, defaulting to the -// behavior of the underlying []string. If it is set to false, it will serialize -// to a single string, if it contains one element. Otherwise, it will serialize -// to an array of strings. +// array of strings, even if it just contains one element, defaulting to the behaviour +// of the underlying []string. If it is set to false, it will serialize to a single +// string, if it contains one element. Otherwise, it will serialize to an array of strings. var MarshalSingleStringAsArray = true // NumericDate represents a JSON numeric date value, as referenced at @@ -59,10 +58,9 @@ func (date NumericDate) MarshalJSON() (b []byte, err error) { // For very large timestamps, UnixNano would overflow an int64, but this // function requires nanosecond level precision, so we have to use the // following technique to get round the issue: - // // 1. Take the normal unix timestamp to form the whole number part of the // output, - // 2. Take the result of the Nanosecond function, which returns the offset + // 2. Take the result of the Nanosecond function, which retuns the offset // within the second of the particular unix time instance, to form the // decimal part of the output // 3. Concatenate them to produce the final result @@ -74,10 +72,9 @@ func (date NumericDate) MarshalJSON() (b []byte, err error) { return output, nil } -// UnmarshalJSON is an implementation of the json.RawMessage interface and -// deserializes a [NumericDate] from a JSON representation, i.e. a -// [json.Number]. This number represents an UNIX epoch with either integer or -// non-integer seconds. +// UnmarshalJSON is an implementation of the json.RawMessage interface and deserializses a +// NumericDate from a JSON representation, i.e. a json.Number. This number represents an UNIX epoch +// with either integer or non-integer seconds. func (date *NumericDate) UnmarshalJSON(b []byte) (err error) { var ( number json.Number @@ -98,9 +95,8 @@ func (date *NumericDate) UnmarshalJSON(b []byte) (err error) { return nil } -// ClaimStrings is basically just a slice of strings, but it can be either -// serialized from a string array or just a string. This type is necessary, -// since the "aud" claim can either be a single string or an array. +// ClaimStrings is basically just a slice of strings, but it can be either serialized from a string array or just a string. +// This type is necessary, since the "aud" claim can either be a single string or an array. type ClaimStrings []string func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) { @@ -137,11 +133,10 @@ func (s *ClaimStrings) UnmarshalJSON(data []byte) (err error) { } func (s ClaimStrings) MarshalJSON() (b []byte, err error) { - // This handles a special case in the JWT RFC. If the string array, e.g. - // used by the "aud" field, only contains one element, it MAY be serialized - // as a single string. This may or may not be desired based on the ecosystem - // of other JWT library used, so we make it configurable by the variable - // MarshalSingleStringAsArray. + // This handles a special case in the JWT RFC. If the string array, e.g. used by the "aud" field, + // only contains one element, it MAY be serialized as a single string. This may or may not be + // desired based on the ecosystem of other JWT library used, so we make it configurable by the + // variable MarshalSingleStringAsArray. if len(s) == 1 && !MarshalSingleStringAsArray { return json.Marshal(s[0]) } diff --git a/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md b/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md deleted file mode 100644 index 1ee690f932..0000000000 --- a/vendor/github.com/golang-jwt/jwt/v5/MIGRATION_GUIDE.md +++ /dev/null @@ -1,100 +0,0 @@ -# Migration Guide (v5.0.0) - -Version `v5` contains a major rework of core functionalities in the `jwt-go` library. This includes support for several -validation options as well as a re-design of the `Claims` interface. Lastly, we reworked how errors work under the hood, -which should provide a better overall developer experience. - -Starting from [v5.0.0](https://github.com/golang-jwt/jwt/releases/tag/v5.0.0), the import path will be: - - "github.com/golang-jwt/jwt/v5" - -For most users, changing the import path *should* suffice. However, since we intentionally changed and cleaned some of -the public API, existing programs might need to be adopted. The following paragraphs go through the individual changes -and make suggestions how to change existing programs. - -## Parsing and Validation Options - -Under the hood, a new `validator` struct takes care of validating the claims. A long awaited feature has been the option -to fine-tune the validation of tokens. This is now possible with several `ParserOption` functions that can be appended -to most `Parse` functions, such as `ParseWithClaims`. The most important options and changes are: - * `WithLeeway`, which can be used to specific leeway that is taken into account when validating time-based claims, such as `exp` or `nbf`. - * The new default behavior now disables checking the `iat` claim by default. Usage of this claim is OPTIONAL according to the JWT RFC. The claim itself is also purely informational according to the RFC, so a strict validation failure is not recommended. If you want to check for sensible values in these claims, please use the `WithIssuedAt` parser option. - * New options have also been added to check for expected `aud`, `sub` and `iss`, namely `WithAudience`, `WithSubject` and `WithIssuer`. - -## Changes to the `Claims` interface - -### Complete Restructuring - -Previously, the claims interface was satisfied with an implementation of a `Valid() error` function. This had several issues: - * The different claim types (struct claims, map claims, etc.) then contained similar (but not 100 % identical) code of how this validation was done. This lead to a lot of (almost) duplicate code and was hard to maintain - * It was not really semantically close to what a "claim" (or a set of claims) really is; which is a list of defined key/value pairs with a certain semantic meaning. - -Since all the validation functionality is now extracted into the validator, all `VerifyXXX` and `Valid` functions have been removed from the `Claims` interface. Instead, the interface now represents a list of getters to retrieve values with a specific meaning. This allows us to completely decouple the validation logic with the underlying storage representation of the claim, which could be a struct, a map or even something stored in a database. - -```go -type Claims interface { - GetExpirationTime() (*NumericDate, error) - GetIssuedAt() (*NumericDate, error) - GetNotBefore() (*NumericDate, error) - GetIssuer() (string, error) - GetSubject() (string, error) - GetAudience() (ClaimStrings, error) -} -``` - -### Supported Claim Types and Removal of `StandardClaims` - -The two standard claim types supported by this library, `MapClaims` and `RegisteredClaims` both implement the necessary functions of this interface. The old `StandardClaims` struct, which has already been deprecated in `v4` is now removed. - -Users using custom claims, in most cases, will not experience any changes in the behavior as long as they embedded -`RegisteredClaims`. If they created a new claim type from scratch, they now need to implemented the proper getter -functions. - -### Migrating Application Specific Logic of the old `Valid` - -Previously, users could override the `Valid` method in a custom claim, for example to extend the validation with application-specific claims. However, this was always very dangerous, since once could easily disable the standard validation and signature checking. - -In order to avoid that, while still supporting the use-case, a new `ClaimsValidator` interface has been introduced. This interface consists of the `Validate() error` function. If the validator sees, that a `Claims` struct implements this interface, the errors returned to the `Validate` function will be *appended* to the regular standard validation. It is not possible to disable the standard validation anymore (even only by accident). - -Usage examples can be found in [example_test.go](./example_test.go), to build claims structs like the following. - -```go -// MyCustomClaims includes all registered claims, plus Foo. -type MyCustomClaims struct { - Foo string `json:"foo"` - jwt.RegisteredClaims -} - -// Validate can be used to execute additional application-specific claims -// validation. -func (m MyCustomClaims) Validate() error { - if m.Foo != "bar" { - return errors.New("must be foobar") - } - - return nil -} -``` - -# Migration Guide (v4.0.0) - -Starting from [v4.0.0](https://github.com/golang-jwt/jwt/releases/tag/v4.0.0), the import path will be: - - "github.com/golang-jwt/jwt/v4" - -The `/v4` version will be backwards compatible with existing `v3.x.y` tags in this repo, as well as -`github.com/dgrijalva/jwt-go`. For most users this should be a drop-in replacement, if you're having -troubles migrating, please open an issue. - -You can replace all occurrences of `github.com/dgrijalva/jwt-go` or `github.com/golang-jwt/jwt` with `github.com/golang-jwt/jwt/v5`, either manually or by using tools such as `sed` or `gofmt`. - -And then you'd typically run: - -``` -go get github.com/golang-jwt/jwt/v4 -go mod tidy -``` - -# Older releases (before v3.2.0) - -The original migration guide for older releases can be found at https://github.com/dgrijalva/jwt-go/blob/master/MIGRATION_GUIDE.md. diff --git a/vendor/github.com/golang-jwt/jwt/v5/claims.go b/vendor/github.com/golang-jwt/jwt/v5/claims.go deleted file mode 100644 index d50ff3dad8..0000000000 --- a/vendor/github.com/golang-jwt/jwt/v5/claims.go +++ /dev/null @@ -1,16 +0,0 @@ -package jwt - -// Claims represent any form of a JWT Claims Set according to -// https://datatracker.ietf.org/doc/html/rfc7519#section-4. In order to have a -// common basis for validation, it is required that an implementation is able to -// supply at least the claim names provided in -// https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 namely `exp`, -// `iat`, `nbf`, `iss`, `sub` and `aud`. -type Claims interface { - GetExpirationTime() (*NumericDate, error) - GetIssuedAt() (*NumericDate, error) - GetNotBefore() (*NumericDate, error) - GetIssuer() (string, error) - GetSubject() (string, error) - GetAudience() (ClaimStrings, error) -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/errors.go b/vendor/github.com/golang-jwt/jwt/v5/errors.go deleted file mode 100644 index 23bb616ddd..0000000000 --- a/vendor/github.com/golang-jwt/jwt/v5/errors.go +++ /dev/null @@ -1,49 +0,0 @@ -package jwt - -import ( - "errors" - "strings" -) - -var ( - ErrInvalidKey = errors.New("key is invalid") - ErrInvalidKeyType = errors.New("key is of invalid type") - ErrHashUnavailable = errors.New("the requested hash function is unavailable") - ErrTokenMalformed = errors.New("token is malformed") - ErrTokenUnverifiable = errors.New("token is unverifiable") - ErrTokenSignatureInvalid = errors.New("token signature is invalid") - ErrTokenRequiredClaimMissing = errors.New("token is missing required claim") - ErrTokenInvalidAudience = errors.New("token has invalid audience") - ErrTokenExpired = errors.New("token is expired") - ErrTokenUsedBeforeIssued = errors.New("token used before issued") - ErrTokenInvalidIssuer = errors.New("token has invalid issuer") - ErrTokenInvalidSubject = errors.New("token has invalid subject") - ErrTokenNotValidYet = errors.New("token is not valid yet") - ErrTokenInvalidId = errors.New("token has invalid id") - ErrTokenInvalidClaims = errors.New("token has invalid claims") - ErrInvalidType = errors.New("invalid type for claim") -) - -// joinedError is an error type that works similar to what [errors.Join] -// produces, with the exception that it has a nice error string; mainly its -// error messages are concatenated using a comma, rather than a newline. -type joinedError struct { - errs []error -} - -func (je joinedError) Error() string { - msg := []string{} - for _, err := range je.errs { - msg = append(msg, err.Error()) - } - - return strings.Join(msg, ", ") -} - -// joinErrors joins together multiple errors. Useful for scenarios where -// multiple errors next to each other occur, e.g., in claims validation. -func joinErrors(errs ...error) error { - return &joinedError{ - errs: errs, - } -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go b/vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go deleted file mode 100644 index a893d355e1..0000000000 --- a/vendor/github.com/golang-jwt/jwt/v5/errors_go1_20.go +++ /dev/null @@ -1,47 +0,0 @@ -//go:build go1.20 -// +build go1.20 - -package jwt - -import ( - "fmt" -) - -// Unwrap implements the multiple error unwrapping for this error type, which is -// possible in Go 1.20. -func (je joinedError) Unwrap() []error { - return je.errs -} - -// newError creates a new error message with a detailed error message. The -// message will be prefixed with the contents of the supplied error type. -// Additionally, more errors, that provide more context can be supplied which -// will be appended to the message. This makes use of Go 1.20's possibility to -// include more than one %w formatting directive in [fmt.Errorf]. -// -// For example, -// -// newError("no keyfunc was provided", ErrTokenUnverifiable) -// -// will produce the error string -// -// "token is unverifiable: no keyfunc was provided" -func newError(message string, err error, more ...error) error { - var format string - var args []any - if message != "" { - format = "%w: %s" - args = []any{err, message} - } else { - format = "%w" - args = []any{err} - } - - for _, e := range more { - format += ": %w" - args = append(args, e) - } - - err = fmt.Errorf(format, args...) - return err -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go b/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go deleted file mode 100644 index 3afb04e648..0000000000 --- a/vendor/github.com/golang-jwt/jwt/v5/errors_go_other.go +++ /dev/null @@ -1,78 +0,0 @@ -//go:build !go1.20 -// +build !go1.20 - -package jwt - -import ( - "errors" - "fmt" -) - -// Is implements checking for multiple errors using [errors.Is], since multiple -// error unwrapping is not possible in versions less than Go 1.20. -func (je joinedError) Is(err error) bool { - for _, e := range je.errs { - if errors.Is(e, err) { - return true - } - } - - return false -} - -// wrappedErrors is a workaround for wrapping multiple errors in environments -// where Go 1.20 is not available. It basically uses the already implemented -// functionatlity of joinedError to handle multiple errors with supplies a -// custom error message that is identical to the one we produce in Go 1.20 using -// multiple %w directives. -type wrappedErrors struct { - msg string - joinedError -} - -// Error returns the stored error string -func (we wrappedErrors) Error() string { - return we.msg -} - -// newError creates a new error message with a detailed error message. The -// message will be prefixed with the contents of the supplied error type. -// Additionally, more errors, that provide more context can be supplied which -// will be appended to the message. Since we cannot use of Go 1.20's possibility -// to include more than one %w formatting directive in [fmt.Errorf], we have to -// emulate that. -// -// For example, -// -// newError("no keyfunc was provided", ErrTokenUnverifiable) -// -// will produce the error string -// -// "token is unverifiable: no keyfunc was provided" -func newError(message string, err error, more ...error) error { - // We cannot wrap multiple errors here with %w, so we have to be a little - // bit creative. Basically, we are using %s instead of %w to produce the - // same error message and then throw the result into a custom error struct. - var format string - var args []any - if message != "" { - format = "%s: %s" - args = []any{err, message} - } else { - format = "%s" - args = []any{err} - } - errs := []error{err} - - for _, e := range more { - format += ": %s" - args = append(args, e) - errs = append(errs, e) - } - - err = &wrappedErrors{ - msg: fmt.Sprintf(format, args...), - joinedError: joinedError{errs: errs}, - } - return err -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/map_claims.go b/vendor/github.com/golang-jwt/jwt/v5/map_claims.go deleted file mode 100644 index b2b51a1f80..0000000000 --- a/vendor/github.com/golang-jwt/jwt/v5/map_claims.go +++ /dev/null @@ -1,109 +0,0 @@ -package jwt - -import ( - "encoding/json" - "fmt" -) - -// MapClaims is a claims type that uses the map[string]interface{} for JSON -// decoding. This is the default claims type if you don't supply one -type MapClaims map[string]interface{} - -// GetExpirationTime implements the Claims interface. -func (m MapClaims) GetExpirationTime() (*NumericDate, error) { - return m.parseNumericDate("exp") -} - -// GetNotBefore implements the Claims interface. -func (m MapClaims) GetNotBefore() (*NumericDate, error) { - return m.parseNumericDate("nbf") -} - -// GetIssuedAt implements the Claims interface. -func (m MapClaims) GetIssuedAt() (*NumericDate, error) { - return m.parseNumericDate("iat") -} - -// GetAudience implements the Claims interface. -func (m MapClaims) GetAudience() (ClaimStrings, error) { - return m.parseClaimsString("aud") -} - -// GetIssuer implements the Claims interface. -func (m MapClaims) GetIssuer() (string, error) { - return m.parseString("iss") -} - -// GetSubject implements the Claims interface. -func (m MapClaims) GetSubject() (string, error) { - return m.parseString("sub") -} - -// parseNumericDate tries to parse a key in the map claims type as a number -// date. This will succeed, if the underlying type is either a [float64] or a -// [json.Number]. Otherwise, nil will be returned. -func (m MapClaims) parseNumericDate(key string) (*NumericDate, error) { - v, ok := m[key] - if !ok { - return nil, nil - } - - switch exp := v.(type) { - case float64: - if exp == 0 { - return nil, nil - } - - return newNumericDateFromSeconds(exp), nil - case json.Number: - v, _ := exp.Float64() - - return newNumericDateFromSeconds(v), nil - } - - return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) -} - -// parseClaimsString tries to parse a key in the map claims type as a -// [ClaimsStrings] type, which can either be a string or an array of string. -func (m MapClaims) parseClaimsString(key string) (ClaimStrings, error) { - var cs []string - switch v := m[key].(type) { - case string: - cs = append(cs, v) - case []string: - cs = v - case []interface{}: - for _, a := range v { - vs, ok := a.(string) - if !ok { - return nil, newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) - } - cs = append(cs, vs) - } - } - - return cs, nil -} - -// parseString tries to parse a key in the map claims type as a [string] type. -// If the key does not exist, an empty string is returned. If the key has the -// wrong type, an error is returned. -func (m MapClaims) parseString(key string) (string, error) { - var ( - ok bool - raw interface{} - iss string - ) - raw, ok = m[key] - if !ok { - return "", nil - } - - iss, ok = raw.(string) - if !ok { - return "", newError(fmt.Sprintf("%s is invalid", key), ErrInvalidType) - } - - return iss, nil -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/parser_option.go b/vendor/github.com/golang-jwt/jwt/v5/parser_option.go deleted file mode 100644 index 8d5917e909..0000000000 --- a/vendor/github.com/golang-jwt/jwt/v5/parser_option.go +++ /dev/null @@ -1,101 +0,0 @@ -package jwt - -import "time" - -// ParserOption is used to implement functional-style options that modify the -// behavior of the parser. To add new options, just create a function (ideally -// beginning with With or Without) that returns an anonymous function that takes -// a *Parser type as input and manipulates its configuration accordingly. -type ParserOption func(*Parser) - -// WithValidMethods is an option to supply algorithm methods that the parser -// will check. Only those methods will be considered valid. It is heavily -// encouraged to use this option in order to prevent attacks such as -// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/. -func WithValidMethods(methods []string) ParserOption { - return func(p *Parser) { - p.validMethods = methods - } -} - -// WithJSONNumber is an option to configure the underlying JSON parser with -// UseNumber. -func WithJSONNumber() ParserOption { - return func(p *Parser) { - p.useJSONNumber = true - } -} - -// WithoutClaimsValidation is an option to disable claims validation. This -// option should only be used if you exactly know what you are doing. -func WithoutClaimsValidation() ParserOption { - return func(p *Parser) { - p.skipClaimsValidation = true - } -} - -// WithLeeway returns the ParserOption for specifying the leeway window. -func WithLeeway(leeway time.Duration) ParserOption { - return func(p *Parser) { - p.validator.leeway = leeway - } -} - -// WithTimeFunc returns the ParserOption for specifying the time func. The -// primary use-case for this is testing. If you are looking for a way to account -// for clock-skew, WithLeeway should be used instead. -func WithTimeFunc(f func() time.Time) ParserOption { - return func(p *Parser) { - p.validator.timeFunc = f - } -} - -// WithIssuedAt returns the ParserOption to enable verification -// of issued-at. -func WithIssuedAt() ParserOption { - return func(p *Parser) { - p.validator.verifyIat = true - } -} - -// WithAudience configures the validator to require the specified audience in -// the `aud` claim. Validation will fail if the audience is not listed in the -// token or the `aud` claim is missing. -// -// NOTE: While the `aud` claim is OPTIONAL in a JWT, the handling of it is -// application-specific. Since this validation API is helping developers in -// writing secure application, we decided to REQUIRE the existence of the claim, -// if an audience is expected. -func WithAudience(aud string) ParserOption { - return func(p *Parser) { - p.validator.expectedAud = aud - } -} - -// WithIssuer configures the validator to require the specified issuer in the -// `iss` claim. Validation will fail if a different issuer is specified in the -// token or the `iss` claim is missing. -// -// NOTE: While the `iss` claim is OPTIONAL in a JWT, the handling of it is -// application-specific. Since this validation API is helping developers in -// writing secure application, we decided to REQUIRE the existence of the claim, -// if an issuer is expected. -func WithIssuer(iss string) ParserOption { - return func(p *Parser) { - p.validator.expectedIss = iss - } -} - -// WithSubject configures the validator to require the specified subject in the -// `sub` claim. Validation will fail if a different subject is specified in the -// token or the `sub` claim is missing. -// -// NOTE: While the `sub` claim is OPTIONAL in a JWT, the handling of it is -// application-specific. Since this validation API is helping developers in -// writing secure application, we decided to REQUIRE the existence of the claim, -// if a subject is expected. -func WithSubject(sub string) ParserOption { - return func(p *Parser) { - p.validator.expectedSub = sub - } -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/registered_claims.go b/vendor/github.com/golang-jwt/jwt/v5/registered_claims.go deleted file mode 100644 index 77951a531d..0000000000 --- a/vendor/github.com/golang-jwt/jwt/v5/registered_claims.go +++ /dev/null @@ -1,63 +0,0 @@ -package jwt - -// RegisteredClaims are a structured version of the JWT Claims Set, -// restricted to Registered Claim Names, as referenced at -// https://datatracker.ietf.org/doc/html/rfc7519#section-4.1 -// -// This type can be used on its own, but then additional private and -// public claims embedded in the JWT will not be parsed. The typical use-case -// therefore is to embedded this in a user-defined claim type. -// -// See examples for how to use this with your own claim types. -type RegisteredClaims struct { - // the `iss` (Issuer) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.1 - Issuer string `json:"iss,omitempty"` - - // the `sub` (Subject) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.2 - Subject string `json:"sub,omitempty"` - - // the `aud` (Audience) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.3 - Audience ClaimStrings `json:"aud,omitempty"` - - // the `exp` (Expiration Time) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.4 - ExpiresAt *NumericDate `json:"exp,omitempty"` - - // the `nbf` (Not Before) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.5 - NotBefore *NumericDate `json:"nbf,omitempty"` - - // the `iat` (Issued At) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.6 - IssuedAt *NumericDate `json:"iat,omitempty"` - - // the `jti` (JWT ID) claim. See https://datatracker.ietf.org/doc/html/rfc7519#section-4.1.7 - ID string `json:"jti,omitempty"` -} - -// GetExpirationTime implements the Claims interface. -func (c RegisteredClaims) GetExpirationTime() (*NumericDate, error) { - return c.ExpiresAt, nil -} - -// GetNotBefore implements the Claims interface. -func (c RegisteredClaims) GetNotBefore() (*NumericDate, error) { - return c.NotBefore, nil -} - -// GetIssuedAt implements the Claims interface. -func (c RegisteredClaims) GetIssuedAt() (*NumericDate, error) { - return c.IssuedAt, nil -} - -// GetAudience implements the Claims interface. -func (c RegisteredClaims) GetAudience() (ClaimStrings, error) { - return c.Audience, nil -} - -// GetIssuer implements the Claims interface. -func (c RegisteredClaims) GetIssuer() (string, error) { - return c.Issuer, nil -} - -// GetSubject implements the Claims interface. -func (c RegisteredClaims) GetSubject() (string, error) { - return c.Subject, nil -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/token.go b/vendor/github.com/golang-jwt/jwt/v5/token.go deleted file mode 100644 index b3459427e8..0000000000 --- a/vendor/github.com/golang-jwt/jwt/v5/token.go +++ /dev/null @@ -1,145 +0,0 @@ -package jwt - -import ( - "encoding/base64" - "encoding/json" - "strings" -) - -// DecodePaddingAllowed will switch the codec used for decoding JWTs -// respectively. Note that the JWS RFC7515 states that the tokens will utilize a -// Base64url encoding with no padding. Unfortunately, some implementations of -// JWT are producing non-standard tokens, and thus require support for decoding. -// Note that this is a global variable, and updating it will change the behavior -// on a package level, and is also NOT go-routine safe. To use the -// non-recommended decoding, set this boolean to `true` prior to using this -// package. -var DecodePaddingAllowed bool - -// DecodeStrict will switch the codec used for decoding JWTs into strict mode. -// In this mode, the decoder requires that trailing padding bits are zero, as -// described in RFC 4648 section 3.5. Note that this is a global variable, and -// updating it will change the behavior on a package level, and is also NOT -// go-routine safe. To use strict decoding, set this boolean to `true` prior to -// using this package. -var DecodeStrict bool - -// Keyfunc will be used by the Parse methods as a callback function to supply -// the key for verification. The function receives the parsed, but unverified -// Token. This allows you to use properties in the Header of the token (such as -// `kid`) to identify which key to use. -type Keyfunc func(*Token) (interface{}, error) - -// Token represents a JWT Token. Different fields will be used depending on -// whether you're creating or parsing/verifying a token. -type Token struct { - Raw string // Raw contains the raw token. Populated when you [Parse] a token - Method SigningMethod // Method is the signing method used or to be used - Header map[string]interface{} // Header is the first segment of the token - Claims Claims // Claims is the second segment of the token - Signature string // Signature is the third segment of the token. Populated when you Parse a token - Valid bool // Valid specifies if the token is valid. Populated when you Parse/Verify a token -} - -// New creates a new [Token] with the specified signing method and an empty map of -// claims. -func New(method SigningMethod) *Token { - return NewWithClaims(method, MapClaims{}) -} - -// NewWithClaims creates a new [Token] with the specified signing method and -// claims. -func NewWithClaims(method SigningMethod, claims Claims) *Token { - return &Token{ - Header: map[string]interface{}{ - "typ": "JWT", - "alg": method.Alg(), - }, - Claims: claims, - Method: method, - } -} - -// SignedString creates and returns a complete, signed JWT. The token is signed -// using the SigningMethod specified in the token. -func (t *Token) SignedString(key interface{}) (string, error) { - var sig, sstr string - var err error - if sstr, err = t.SigningString(); err != nil { - return "", err - } - if sig, err = t.Method.Sign(sstr, key); err != nil { - return "", err - } - return strings.Join([]string{sstr, sig}, "."), nil -} - -// SigningString generates the signing string. This is the most expensive part -// of the whole deal. Unless you need this for something special, just go -// straight for the SignedString. -func (t *Token) SigningString() (string, error) { - var err error - var jsonValue []byte - - if jsonValue, err = json.Marshal(t.Header); err != nil { - return "", err - } - header := EncodeSegment(jsonValue) - - if jsonValue, err = json.Marshal(t.Claims); err != nil { - return "", err - } - claim := EncodeSegment(jsonValue) - - return strings.Join([]string{header, claim}, "."), nil -} - -// Parse parses, validates, verifies the signature and returns the parsed token. -// keyFunc will receive the parsed token and should return the cryptographic key -// for verifying the signature. The caller is strongly encouraged to set the -// WithValidMethods option to validate the 'alg' claim in the token matches the -// expected algorithm. For more details about the importance of validating the -// 'alg' claim, see -// https://auth0.com/blog/critical-vulnerabilities-in-json-web-token-libraries/ -func Parse(tokenString string, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { - return NewParser(options...).Parse(tokenString, keyFunc) -} - -// ParseWithClaims is a shortcut for NewParser().ParseWithClaims(). -// -// Note: If you provide a custom claim implementation that embeds one of the -// standard claims (such as RegisteredClaims), make sure that a) you either -// embed a non-pointer version of the claims or b) if you are using a pointer, -// allocate the proper memory for it before passing in the overall claims, -// otherwise you might run into a panic. -func ParseWithClaims(tokenString string, claims Claims, keyFunc Keyfunc, options ...ParserOption) (*Token, error) { - return NewParser(options...).ParseWithClaims(tokenString, claims, keyFunc) -} - -// EncodeSegment encodes a JWT specific base64url encoding with padding stripped -// -// Deprecated: In a future release, we will demote this function to a -// non-exported function, since it should only be used internally -func EncodeSegment(seg []byte) string { - return base64.RawURLEncoding.EncodeToString(seg) -} - -// DecodeSegment decodes a JWT specific base64url encoding with padding stripped -// -// Deprecated: In a future release, we will demote this function to a -// non-exported function, since it should only be used internally -func DecodeSegment(seg string) ([]byte, error) { - encoding := base64.RawURLEncoding - - if DecodePaddingAllowed { - if l := len(seg) % 4; l > 0 { - seg += strings.Repeat("=", 4-l) - } - encoding = base64.URLEncoding - } - - if DecodeStrict { - encoding = encoding.Strict() - } - return encoding.DecodeString(seg) -} diff --git a/vendor/github.com/golang-jwt/jwt/v5/validator.go b/vendor/github.com/golang-jwt/jwt/v5/validator.go deleted file mode 100644 index 3850438939..0000000000 --- a/vendor/github.com/golang-jwt/jwt/v5/validator.go +++ /dev/null @@ -1,301 +0,0 @@ -package jwt - -import ( - "crypto/subtle" - "fmt" - "time" -) - -// ClaimsValidator is an interface that can be implemented by custom claims who -// wish to execute any additional claims validation based on -// application-specific logic. The Validate function is then executed in -// addition to the regular claims validation and any error returned is appended -// to the final validation result. -// -// type MyCustomClaims struct { -// Foo string `json:"foo"` -// jwt.RegisteredClaims -// } -// -// func (m MyCustomClaims) Validate() error { -// if m.Foo != "bar" { -// return errors.New("must be foobar") -// } -// return nil -// } -type ClaimsValidator interface { - Claims - Validate() error -} - -// validator is the core of the new Validation API. It is automatically used by -// a [Parser] during parsing and can be modified with various parser options. -// -// Note: This struct is intentionally not exported (yet) as we want to -// internally finalize its API. In the future, we might make it publicly -// available. -type validator struct { - // leeway is an optional leeway that can be provided to account for clock skew. - leeway time.Duration - - // timeFunc is used to supply the current time that is needed for - // validation. If unspecified, this defaults to time.Now. - timeFunc func() time.Time - - // verifyIat specifies whether the iat (Issued At) claim will be verified. - // According to https://www.rfc-editor.org/rfc/rfc7519#section-4.1.6 this - // only specifies the age of the token, but no validation check is - // necessary. However, if wanted, it can be checked if the iat is - // unrealistic, i.e., in the future. - verifyIat bool - - // expectedAud contains the audience this token expects. Supplying an empty - // string will disable aud checking. - expectedAud string - - // expectedIss contains the issuer this token expects. Supplying an empty - // string will disable iss checking. - expectedIss string - - // expectedSub contains the subject this token expects. Supplying an empty - // string will disable sub checking. - expectedSub string -} - -// newValidator can be used to create a stand-alone validator with the supplied -// options. This validator can then be used to validate already parsed claims. -func newValidator(opts ...ParserOption) *validator { - p := NewParser(opts...) - return p.validator -} - -// Validate validates the given claims. It will also perform any custom -// validation if claims implements the [ClaimsValidator] interface. -func (v *validator) Validate(claims Claims) error { - var ( - now time.Time - errs []error = make([]error, 0, 6) - err error - ) - - // Check, if we have a time func - if v.timeFunc != nil { - now = v.timeFunc() - } else { - now = time.Now() - } - - // We always need to check the expiration time, but usage of the claim - // itself is OPTIONAL. - if err = v.verifyExpiresAt(claims, now, false); err != nil { - errs = append(errs, err) - } - - // We always need to check not-before, but usage of the claim itself is - // OPTIONAL. - if err = v.verifyNotBefore(claims, now, false); err != nil { - errs = append(errs, err) - } - - // Check issued-at if the option is enabled - if v.verifyIat { - if err = v.verifyIssuedAt(claims, now, false); err != nil { - errs = append(errs, err) - } - } - - // If we have an expected audience, we also require the audience claim - if v.expectedAud != "" { - if err = v.verifyAudience(claims, v.expectedAud, true); err != nil { - errs = append(errs, err) - } - } - - // If we have an expected issuer, we also require the issuer claim - if v.expectedIss != "" { - if err = v.verifyIssuer(claims, v.expectedIss, true); err != nil { - errs = append(errs, err) - } - } - - // If we have an expected subject, we also require the subject claim - if v.expectedSub != "" { - if err = v.verifySubject(claims, v.expectedSub, true); err != nil { - errs = append(errs, err) - } - } - - // Finally, we want to give the claim itself some possibility to do some - // additional custom validation based on a custom Validate function. - cvt, ok := claims.(ClaimsValidator) - if ok { - if err := cvt.Validate(); err != nil { - errs = append(errs, err) - } - } - - if len(errs) == 0 { - return nil - } - - return joinErrors(errs...) -} - -// verifyExpiresAt compares the exp claim in claims against cmp. This function -// will succeed if cmp < exp. Additional leeway is taken into account. -// -// If exp is not set, it will succeed if the claim is not required, -// otherwise ErrTokenRequiredClaimMissing will be returned. -// -// Additionally, if any error occurs while retrieving the claim, e.g., when its -// the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *validator) verifyExpiresAt(claims Claims, cmp time.Time, required bool) error { - exp, err := claims.GetExpirationTime() - if err != nil { - return err - } - - if exp == nil { - return errorIfRequired(required, "exp") - } - - return errorIfFalse(cmp.Before((exp.Time).Add(+v.leeway)), ErrTokenExpired) -} - -// verifyIssuedAt compares the iat claim in claims against cmp. This function -// will succeed if cmp >= iat. Additional leeway is taken into account. -// -// If iat is not set, it will succeed if the claim is not required, -// otherwise ErrTokenRequiredClaimMissing will be returned. -// -// Additionally, if any error occurs while retrieving the claim, e.g., when its -// the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *validator) verifyIssuedAt(claims Claims, cmp time.Time, required bool) error { - iat, err := claims.GetIssuedAt() - if err != nil { - return err - } - - if iat == nil { - return errorIfRequired(required, "iat") - } - - return errorIfFalse(!cmp.Before(iat.Add(-v.leeway)), ErrTokenUsedBeforeIssued) -} - -// verifyNotBefore compares the nbf claim in claims against cmp. This function -// will return true if cmp >= nbf. Additional leeway is taken into account. -// -// If nbf is not set, it will succeed if the claim is not required, -// otherwise ErrTokenRequiredClaimMissing will be returned. -// -// Additionally, if any error occurs while retrieving the claim, e.g., when its -// the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *validator) verifyNotBefore(claims Claims, cmp time.Time, required bool) error { - nbf, err := claims.GetNotBefore() - if err != nil { - return err - } - - if nbf == nil { - return errorIfRequired(required, "nbf") - } - - return errorIfFalse(!cmp.Before(nbf.Add(-v.leeway)), ErrTokenNotValidYet) -} - -// verifyAudience compares the aud claim against cmp. -// -// If aud is not set or an empty list, it will succeed if the claim is not required, -// otherwise ErrTokenRequiredClaimMissing will be returned. -// -// Additionally, if any error occurs while retrieving the claim, e.g., when its -// the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *validator) verifyAudience(claims Claims, cmp string, required bool) error { - aud, err := claims.GetAudience() - if err != nil { - return err - } - - if len(aud) == 0 { - return errorIfRequired(required, "aud") - } - - // use a var here to keep constant time compare when looping over a number of claims - result := false - - var stringClaims string - for _, a := range aud { - if subtle.ConstantTimeCompare([]byte(a), []byte(cmp)) != 0 { - result = true - } - stringClaims = stringClaims + a - } - - // case where "" is sent in one or many aud claims - if stringClaims == "" { - return errorIfRequired(required, "aud") - } - - return errorIfFalse(result, ErrTokenInvalidAudience) -} - -// verifyIssuer compares the iss claim in claims against cmp. -// -// If iss is not set, it will succeed if the claim is not required, -// otherwise ErrTokenRequiredClaimMissing will be returned. -// -// Additionally, if any error occurs while retrieving the claim, e.g., when its -// the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *validator) verifyIssuer(claims Claims, cmp string, required bool) error { - iss, err := claims.GetIssuer() - if err != nil { - return err - } - - if iss == "" { - return errorIfRequired(required, "iss") - } - - return errorIfFalse(iss == cmp, ErrTokenInvalidIssuer) -} - -// verifySubject compares the sub claim against cmp. -// -// If sub is not set, it will succeed if the claim is not required, -// otherwise ErrTokenRequiredClaimMissing will be returned. -// -// Additionally, if any error occurs while retrieving the claim, e.g., when its -// the wrong type, an ErrTokenUnverifiable error will be returned. -func (v *validator) verifySubject(claims Claims, cmp string, required bool) error { - sub, err := claims.GetSubject() - if err != nil { - return err - } - - if sub == "" { - return errorIfRequired(required, "sub") - } - - return errorIfFalse(sub == cmp, ErrTokenInvalidSubject) -} - -// errorIfFalse returns the error specified in err, if the value is true. -// Otherwise, nil is returned. -func errorIfFalse(value bool, err error) error { - if value { - return nil - } else { - return err - } -} - -// errorIfRequired returns an ErrTokenRequiredClaimMissing error if required is -// true. Otherwise, nil is returned. -func errorIfRequired(required bool, claim string) error { - if required { - return newError(fmt.Sprintf("%s claim is required", claim), ErrTokenRequiredClaimMissing) - } else { - return nil - } -} diff --git a/vendor/modules.txt b/vendor/modules.txt index 4afb51a110..bbfe3730c8 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -142,9 +142,11 @@ github.com/gofrs/uuid # github.com/gogo/protobuf v1.3.2 ## explicit; go 1.15 github.com/gogo/protobuf/proto +# github.com/golang-jwt/jwt/v4 v4.5.0 +## explicit; go 1.16 +github.com/golang-jwt/jwt/v4 # github.com/golang-jwt/jwt/v5 v5.0.0-rc.1 ## explicit; go 1.18 -github.com/golang-jwt/jwt/v5 # github.com/golang/protobuf v1.5.2 ## explicit; go 1.9 github.com/golang/protobuf/jsonpb From bfc1dcc3f603b37f2cb5ed4738ad0232a8fcc325 Mon Sep 17 00:00:00 2001 From: aryan Date: Sat, 4 Mar 2023 02:11:47 +0530 Subject: [PATCH 06/26] updated jwt tokenizer Signed-off-by: aryan --- auth/jwt/tokenizer.go | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/auth/jwt/tokenizer.go b/auth/jwt/tokenizer.go index 29a3231519..76d85e0487 100644 --- a/auth/jwt/tokenizer.go +++ b/auth/jwt/tokenizer.go @@ -4,8 +4,6 @@ package jwt import ( - "time" - "github.com/golang-jwt/jwt/v4" "github.com/mainflux/mainflux/auth" "github.com/mainflux/mainflux/pkg/errors" @@ -14,7 +12,7 @@ import ( const issuerName = "mainflux.auth" type claims struct { - jwt.StandardClaims + jwt.RegisteredClaims IssuerID string `json:"issuer_id,omitempty"` Type *uint32 `json:"type,omitempty"` } @@ -24,7 +22,7 @@ func (c claims) Valid() error { return errors.ErrMalformedEntity } - return c.StandardClaims.Valid() + return c.RegisteredClaims.Valid() } type tokenizer struct { @@ -38,20 +36,20 @@ func New(secret string) auth.Tokenizer { func (svc tokenizer) Issue(key auth.Key) (string, error) { claims := claims{ - StandardClaims: jwt.StandardClaims{ + RegisteredClaims: jwt.RegisteredClaims{ Issuer: issuerName, Subject: key.Subject, - IssuedAt: key.IssuedAt.UTC().Unix(), + IssuedAt: &jwt.NumericDate{Time: key.IssuedAt.UTC()}, }, IssuerID: key.IssuerID, Type: &key.Type, } if !key.ExpiresAt.IsZero() { - claims.ExpiresAt = key.ExpiresAt.UTC().Unix() + claims.ExpiresAt = &jwt.NumericDate{Time: key.ExpiresAt.UTC()} } if key.ID != "" { - claims.Id = key.ID + claims.ID = key.ID } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) @@ -83,13 +81,13 @@ func (svc tokenizer) Parse(token string) (auth.Key, error) { func (c claims) toKey() auth.Key { key := auth.Key{ - ID: c.Id, + ID: c.ID, IssuerID: c.IssuerID, Subject: c.Subject, - IssuedAt: time.Unix(c.IssuedAt, 0).UTC(), + IssuedAt: c.IssuedAt.Time.UTC(), } - if c.ExpiresAt != 0 { - key.ExpiresAt = time.Unix(c.ExpiresAt, 0).UTC() + if c.ExpiresAt.Time.UTC().Unix() != 0 { + key.ExpiresAt = c.ExpiresAt.Time.UTC() } // Default type is 0. From 21f797d86b4fab7db9d4be04e59200ee3fcfe2a3 Mon Sep 17 00:00:00 2001 From: aryan Date: Sat, 4 Mar 2023 02:36:41 +0530 Subject: [PATCH 07/26] resolve EOF error for httptest requests Signed-off-by: aryan --- auth/api/http/groups/endpoint_test.go | 1 + 1 file changed, 1 insertion(+) diff --git a/auth/api/http/groups/endpoint_test.go b/auth/api/http/groups/endpoint_test.go index b31b9e59f2..ad0f625d34 100644 --- a/auth/api/http/groups/endpoint_test.go +++ b/auth/api/http/groups/endpoint_test.go @@ -45,6 +45,7 @@ type testRequest struct { func (tr testRequest) make() (*http.Response, error) { req, err := http.NewRequest(tr.method, tr.url, tr.body) + req.Close = true if err != nil { return nil, err } From f089e415c0ea55b5052e7bef8cf0eb718e1b21cb Mon Sep 17 00:00:00 2001 From: aryan Date: Sun, 5 Mar 2023 00:41:10 +0530 Subject: [PATCH 08/26] fix auth jwt, update to registeredclaims Signed-off-by: aryan --- auth/jwt/tokenizer.go | 6 +++-- auth/service.go | 3 --- auth/service_test.go | 1 - things/postgres/channels.go | 44 +------------------------------- things/postgres/channels_test.go | 8 ------ 5 files changed, 5 insertions(+), 57 deletions(-) diff --git a/auth/jwt/tokenizer.go b/auth/jwt/tokenizer.go index 76d85e0487..3e8940e1e6 100644 --- a/auth/jwt/tokenizer.go +++ b/auth/jwt/tokenizer.go @@ -68,6 +68,7 @@ func (svc tokenizer) Parse(token string) (auth.Key, error) { if err != nil { if e, ok := err.(*jwt.ValidationError); ok && e.Errors == jwt.ValidationErrorExpired { // Expired User key needs to be revoked. + if c.Type != nil && *c.Type == auth.APIKey { return c.toKey(), auth.ErrAPIKeyExpired } @@ -86,13 +87,14 @@ func (c claims) toKey() auth.Key { Subject: c.Subject, IssuedAt: c.IssuedAt.Time.UTC(), } - if c.ExpiresAt.Time.UTC().Unix() != 0 { + + if c.ExpiresAt != nil && c.ExpiresAt.Time.UTC().Unix() != 0 { key.ExpiresAt = c.ExpiresAt.Time.UTC() } // Default type is 0. if c.Type != nil { - key.Type = *c.Type + key.Type = *(c.Type) } return key diff --git a/auth/service.go b/auth/service.go index ad95f0992e..546ad4a786 100644 --- a/auth/service.go +++ b/auth/service.go @@ -139,9 +139,6 @@ func (svc service) RetrieveKey(ctx context.Context, token, id string) (Key, erro func (svc service) Identify(ctx context.Context, token string) (Identity, error) { key, err := svc.tokenizer.Parse(token) - fmt.Println() - fmt.Println(err) - fmt.Println() if err == ErrAPIKeyExpired { err = svc.keys.Remove(ctx, key.IssuerID, key.ID) return Identity{}, errors.Wrap(ErrAPIKeyExpired, err) diff --git a/auth/service_test.go b/auth/service_test.go index 9903ab6721..310bba9f72 100644 --- a/auth/service_test.go +++ b/auth/service_test.go @@ -15,7 +15,6 @@ import ( "github.com/mainflux/mainflux/pkg/errors" "github.com/mainflux/mainflux/pkg/uuid" "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) var idProvider = uuid.New() diff --git a/things/postgres/channels.go b/things/postgres/channels.go index 652c3c0407..2f2d3a5961 100644 --- a/things/postgres/channels.go +++ b/things/postgres/channels.go @@ -40,9 +40,6 @@ func NewChannelRepository(db Database) things.ChannelRepository { func (cr channelRepository) Save(ctx context.Context, channels ...things.Channel) ([]things.Channel, error) { tx, err := cr.db.BeginTxx(ctx, nil) - fmt.Println() - fmt.Println("1 : ", err) - fmt.Println() if err != nil { return nil, errors.Wrap(errors.ErrCreateEntity, err) } @@ -54,51 +51,27 @@ func (cr channelRepository) Save(ctx context.Context, channels ...things.Channel dbch := toDBChannel(channel) _, err = tx.NamedExecContext(ctx, q, dbch) - fmt.Println() - fmt.Println("namedexeccontext error : ", err) - fmt.Println() if err != nil { if err := tx.Rollback(); err != nil { return []things.Channel{}, errors.Wrap(errors.ErrCreateEntity, err) } - // rollBackerr := tx.Rollback() - // fmt.Println() - // fmt.Println("2 : ", rollBackerr) - // fmt.Println() - // if rollBackerr != nil { - // return []things.Channel{}, errors.Wrap(errors.ErrCreateEntity, err) - // } pgErr, ok := err.(*pgconn.PgError) if ok { switch pgErr.Code { case pgerrcode.InvalidTextRepresentation: - fmt.Println() - fmt.Println("returning switch case 1") - fmt.Println() return []things.Channel{}, errors.Wrap(errors.ErrMalformedEntity, err) case pgerrcode.UniqueViolation: - fmt.Println() - fmt.Println("returning switch case 2") - fmt.Println() return []things.Channel{}, errors.Wrap(errors.ErrConflict, err) case pgerrcode.StringDataRightTruncationDataException: - fmt.Println() - fmt.Println("returning switch case 3") - fmt.Println() return []things.Channel{}, errors.Wrap(errors.ErrMalformedEntity, err) } } - fmt.Println() - fmt.Println("returning after switch case, not ok") - fmt.Println() + return []things.Channel{}, errors.Wrap(errors.ErrCreateEntity, err) } } if err = tx.Commit(); err != nil { - fmt.Println() - fmt.Println("4 : ", err) - fmt.Println() return []things.Channel{}, errors.Wrap(errors.ErrCreateEntity, err) } @@ -157,18 +130,12 @@ func (cr channelRepository) RetrieveByID(ctx context.Context, owner, id string) } func (cr channelRepository) RetrieveAll(ctx context.Context, owner string, pm things.PageMetadata) (things.ChannelsPage, error) { - fmt.Println() - fmt.Println("Is tjjhfkfk") - fmt.Println() nq, name := getNameQuery(pm.Name) oq := getOrderQuery(pm.Order) dq := getDirQuery(pm.Dir) ownerQuery := getOwnerQuery(pm.FetchSharedThings) meta, mq, err := getMetadataQuery(pm.Metadata) if err != nil { - fmt.Println() - fmt.Println("1 : ", err) - fmt.Println() return things.ChannelsPage{}, errors.Wrap(errors.ErrViewEntity, err) } @@ -200,9 +167,6 @@ func (cr channelRepository) RetrieveAll(ctx context.Context, owner string, pm th } rows, err := cr.db.NamedQueryContext(ctx, q, params) if err != nil { - fmt.Println() - fmt.Println("2 : ", err) - fmt.Println() return things.ChannelsPage{}, errors.Wrap(errors.ErrViewEntity, err) } defer rows.Close() @@ -211,9 +175,6 @@ func (cr channelRepository) RetrieveAll(ctx context.Context, owner string, pm th for rows.Next() { dbch := dbChannel{Owner: owner} if err := rows.StructScan(&dbch); err != nil { - fmt.Println() - fmt.Println("3 : ", err) - fmt.Println() return things.ChannelsPage{}, errors.Wrap(errors.ErrViewEntity, err) } ch := toChannel(dbch) @@ -225,9 +186,6 @@ func (cr channelRepository) RetrieveAll(ctx context.Context, owner string, pm th total, err := total(ctx, cr.db, cq, params) if err != nil { - fmt.Println() - fmt.Println("4 : ", err) - fmt.Println() return things.ChannelsPage{}, errors.Wrap(errors.ErrViewEntity, err) } diff --git a/things/postgres/channels_test.go b/things/postgres/channels_test.go index 040ffd42b0..b88b53689b 100644 --- a/things/postgres/channels_test.go +++ b/things/postgres/channels_test.go @@ -78,11 +78,7 @@ func TestChannelsSave(t *testing.T) { } for _, tc := range cases { - fmt.Printf("\n\n###\n%s\n###\n\n", tc.desc) _, err := channelRepo.Save(context.Background(), tc.channels...) - fmt.Println() - fmt.Println("returned error : ", err) - fmt.Println() assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) } } @@ -675,11 +671,7 @@ func TestConnect(t *testing.T) { } for _, tc := range cases { - fmt.Printf("\n\n###\n%s\n###\n\n", tc.desc) err := chanRepo.Connect(context.Background(), tc.owner, []string{tc.chID}, []string{tc.thID}) - fmt.Println() - fmt.Println("returned error : ", err) - fmt.Println() assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) } } From 6a48d7ae5bd078a19b74e1b0a6b0de72ae435a1a Mon Sep 17 00:00:00 2001 From: aryan Date: Sun, 5 Mar 2023 01:03:37 +0530 Subject: [PATCH 09/26] fix ineffective assignment, auth/api/grpc endpoint failing Signed-off-by: aryan --- things/postgres/channels.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/things/postgres/channels.go b/things/postgres/channels.go index 2f2d3a5961..27eaa8d8ce 100644 --- a/things/postgres/channels.go +++ b/things/postgres/channels.go @@ -439,13 +439,13 @@ type dbMetadata map[string]interface{} // If error occurs on casting data then m points to empty metadata. func (m *dbMetadata) Scan(value interface{}) error { if value == nil { - m = nil + *m = dbMetadata{} return nil } b, ok := value.([]byte) if !ok { - m = &dbMetadata{} + *m = dbMetadata{} return errors.ErrScanMetadata } From b9a8ffe8581a08fc6c180ecb3b1f7747a2c2c21b Mon Sep 17 00:00:00 2001 From: aryan Date: Wed, 29 Mar 2023 20:09:21 +0530 Subject: [PATCH 10/26] temp commit, remove later Signed-off-by: aryan --- auth/api/grpc/endpoint.go | 4 ++ auth/api/grpc/endpoint_test.go | 64 +++++++++++++++++++++++++++--- auth/api/grpc/setup_test.go | 37 ++++++++++++++--- auth/jwt/tokenizer.go | 10 +++++ auth/service.go | 13 ++++++ readers/cassandra/messages_test.go | 1 + 6 files changed, 118 insertions(+), 11 deletions(-) diff --git a/auth/api/grpc/endpoint.go b/auth/api/grpc/endpoint.go index c0e09c3621..a26ee22354 100644 --- a/auth/api/grpc/endpoint.go +++ b/auth/api/grpc/endpoint.go @@ -5,6 +5,7 @@ package grpc import ( "context" + "fmt" "time" "github.com/go-kit/kit/endpoint" @@ -35,6 +36,9 @@ func issueEndpoint(svc auth.Service) endpoint.Endpoint { } func identifyEndpoint(svc auth.Service) endpoint.Endpoint { + fmt.Println() + fmt.Println("reached endpoint") + fmt.Println() return func(ctx context.Context, request interface{}) (interface{}, error) { req := request.(identityReq) if err := req.validate(); err != nil { diff --git a/auth/api/grpc/endpoint_test.go b/auth/api/grpc/endpoint_test.go index 9638b733b7..1f67dba898 100644 --- a/auth/api/grpc/endpoint_test.go +++ b/auth/api/grpc/endpoint_test.go @@ -43,7 +43,9 @@ var svc auth.Service func TestIssue(t *testing.T) { authAddr := fmt.Sprintf("localhost:%d", port) - conn, _ := grpc.Dial(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, err := grpc.Dial(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + require.Nil(t, err, fmt.Sprintf("got unexpected error while creating client connection: %s", err)) + client := grpcapi.NewClient(mocktracer.New(), conn, time.Second) cases := []struct { @@ -105,17 +107,39 @@ func TestIssue(t *testing.T) { } func TestIdentify(t *testing.T) { + fmt.Println() + fmt.Println("reached 1") + fmt.Println() + _, loginSecret, err := svc.Issue(context.Background(), "", auth.Key{Type: auth.LoginKey, IssuedAt: time.Now(), IssuerID: id, Subject: email}) require.Nil(t, err, fmt.Sprintf("Issuing user key expected to succeed: %s", err)) + fmt.Println() + fmt.Println("reached 2") + fmt.Println() + _, recoverySecret, err := svc.Issue(context.Background(), "", auth.Key{Type: auth.RecoveryKey, IssuedAt: time.Now(), IssuerID: id, Subject: email}) require.Nil(t, err, fmt.Sprintf("Issuing recovery key expected to succeed: %s", err)) + fmt.Println() + fmt.Println("reached 3") + fmt.Println() + _, apiSecret, err := svc.Issue(context.Background(), loginSecret, auth.Key{Type: auth.APIKey, IssuedAt: time.Now(), ExpiresAt: time.Now().Add(time.Minute), IssuerID: id, Subject: email}) require.Nil(t, err, fmt.Sprintf("Issuing API key expected to succeed: %s", err)) + fmt.Println() + fmt.Println("reached 4") + fmt.Println() + authAddr := fmt.Sprintf("localhost:%d", port) - conn, _ := grpc.Dial(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, err := grpc.Dial(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + require.Nil(t, err, fmt.Sprintf("got unexpected error while creating client connection: %s", err)) + + fmt.Println() + fmt.Println("reached 5") + fmt.Println() + client := grpcapi.NewClient(mocktracer.New(), conn, time.Second) cases := []struct { @@ -163,14 +187,25 @@ func TestIdentify(t *testing.T) { } for _, tc := range cases { + fmt.Println() + fmt.Println("###") + fmt.Println(tc.desc) + fmt.Println("###") + fmt.Println() idt, err := client.Identify(context.Background(), &mainflux.Token{Value: tc.token}) + fmt.Println("idt : ", idt) + fmt.Println("err : ", err) if idt != nil { assert.Equal(t, tc.idt, idt, fmt.Sprintf("%s: expected %v got %v", tc.desc, tc.idt, idt)) } e, ok := status.FromError(err) + fmt.Println("e : ", e) + fmt.Println("ok : ", ok) assert.True(t, ok, "gRPC status can't be extracted from the error") assert.Equal(t, tc.code, e.Code(), fmt.Sprintf("%s: expected %s got %s", tc.desc, tc.code, e.Code())) } + + fmt.Println("Reached here") } func TestAuthorize(t *testing.T) { @@ -178,7 +213,9 @@ func TestAuthorize(t *testing.T) { require.Nil(t, err, fmt.Sprintf("Issuing user key expected to succeed: %s", err)) authAddr := fmt.Sprintf("localhost:%d", port) - conn, _ := grpc.Dial(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, err := grpc.Dial(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + require.Nil(t, err, fmt.Sprintf("got unexpected error while creating client connection: %s", err)) + client := grpcapi.NewClient(mocktracer.New(), conn, time.Second) cases := []struct { @@ -252,6 +289,10 @@ func TestAuthorize(t *testing.T) { assert.True(t, ok, "gRPC status can't be extracted from the error") assert.Equal(t, tc.code, e.Code(), fmt.Sprintf("%s: expected %s got %s", tc.desc, tc.code, e.Code())) } + + fmt.Println() + fmt.Println("Reached here") + fmt.Println() } func TestAddPolicy(t *testing.T) { @@ -259,7 +300,9 @@ func TestAddPolicy(t *testing.T) { require.Nil(t, err, fmt.Sprintf("Issuing user key expected to succeed: %s", err)) authAddr := fmt.Sprintf("localhost:%d", port) - conn, _ := grpc.Dial(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, err := grpc.Dial(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + require.Nil(t, err, fmt.Sprintf("got unexpected error while creating client connection: %s", err)) + client := grpcapi.NewClient(mocktracer.New(), conn, time.Second) groupAdminObj := "groupadmin" @@ -305,6 +348,8 @@ func TestAddPolicy(t *testing.T) { assert.True(t, ok, "gRPC status can't be extracted from the error") assert.Equal(t, tc.code, e.Code(), fmt.Sprintf("%s: expected %s got %s", tc.desc, tc.code, e.Code())) } + + fmt.Println("Reached here") } func TestDeletePolicy(t *testing.T) { @@ -312,7 +357,9 @@ func TestDeletePolicy(t *testing.T) { require.Nil(t, err, fmt.Sprintf("Issuing user key expected to succeed: %s", err)) authAddr := fmt.Sprintf("localhost:%d", port) - conn, _ := grpc.Dial(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, err := grpc.Dial(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) + require.Nil(t, err, fmt.Sprintf("got unexpected error while creating client connection: %s", err)) + client := grpcapi.NewClient(mocktracer.New(), conn, time.Second) readRelation := "read" @@ -357,6 +404,8 @@ func TestDeletePolicy(t *testing.T) { assert.Equal(t, tc.code, e.Code(), fmt.Sprintf("%s: expected %s got %s", tc.desc, tc.code, e.Code())) assert.Equal(t, tc.dpr.GetDeleted(), dpr.GetDeleted(), fmt.Sprintf("%s: expected %v got %v", tc.desc, tc.dpr.GetDeleted(), dpr.GetDeleted())) } + + fmt.Println("Reached here") } func TestMembers(t *testing.T) { @@ -429,7 +478,8 @@ func TestMembers(t *testing.T) { authAddr := fmt.Sprintf("localhost:%d", port) conn, err := grpc.Dial(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) - assert.Nil(t, err, fmt.Sprintf("got unexpected error while creating client connection: %s", err)) + require.Nil(t, err, fmt.Sprintf("got unexpected error while creating client connection: %s", err)) + client := grpcapi.NewClient(mocktracer.New(), conn, time.Second) for _, tc := range cases { @@ -439,4 +489,6 @@ func TestMembers(t *testing.T) { assert.Equal(t, tc.code, e.Code(), fmt.Sprintf("%s: expected %s got %s", tc.desc, tc.code, e.Code())) assert.True(t, ok, "OK expected to be true") } + + fmt.Println("Reached here") } diff --git a/auth/api/grpc/setup_test.go b/auth/api/grpc/setup_test.go index e8cb56f063..652853495f 100644 --- a/auth/api/grpc/setup_test.go +++ b/auth/api/grpc/setup_test.go @@ -9,6 +9,7 @@ import ( "net" "os" "testing" + "time" "github.com/mainflux/mainflux" "github.com/mainflux/mainflux/auth" @@ -17,7 +18,7 @@ import ( "github.com/mainflux/mainflux/auth/mocks" "github.com/mainflux/mainflux/pkg/uuid" "github.com/opentracing/opentracing-go/mocktracer" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" "google.golang.org/grpc" ) @@ -29,29 +30,55 @@ func TestMain(m *testing.M) { svc = newService(t) startGRPCServer(t, serverErr, svc, port) + fmt.Println("Calling for loop") for { select { case testRes <- m.Run(): + fmt.Println() + fmt.Println("test ended") + fmt.Println() code := <-testRes os.Exit(code) case err := <-serverErr: if err != nil { log.Fatalf("gPRC Server Terminated") } + case <-time.After(30 * time.Second): + log.Fatalf("Tests took to long to complete") } } } func startGRPCServer(t *testing.T, serverErr chan error, svc auth.Service, port int) { listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) - assert.Nil(t, err, fmt.Sprintf("got unexpected error while creating new listerner: %s", err)) + require.Nil(t, err, fmt.Sprintf("got unexpected error while creating new listerner: %s", err)) server := grpc.NewServer() mainflux.RegisterAuthServiceServer(server, grpcapi.NewServer(mocktracer.New(), svc)) - go func() { - serverErr <- server.Serve(listener) - }() + done := make(chan bool) + + t.Cleanup(func() { + fmt.Println() + fmt.Println("Test complete called t.cleanup") + fmt.Println() + close(done) + }) + + go func(done <-chan bool) { + for { + select { + case serverErr <- server.Serve(listener): + close(serverErr) + return + case <-done: + close(serverErr) + // serverErr <- nil + return + } + + } + }(done) } func newService(t *testing.T) auth.Service { diff --git a/auth/jwt/tokenizer.go b/auth/jwt/tokenizer.go index 3e8940e1e6..ccf2448b34 100644 --- a/auth/jwt/tokenizer.go +++ b/auth/jwt/tokenizer.go @@ -4,6 +4,9 @@ package jwt import ( + "fmt" + "time" + "github.com/golang-jwt/jwt/v4" "github.com/mainflux/mainflux/auth" "github.com/mainflux/mainflux/pkg/errors" @@ -35,6 +38,9 @@ func New(secret string) auth.Tokenizer { } func (svc tokenizer) Issue(key auth.Key) (string, error) { + fmt.Println() + fmt.Println("reached jwt issue") + fmt.Println() claims := claims{ RegisteredClaims: jwt.RegisteredClaims{ Issuer: issuerName, @@ -53,6 +59,8 @@ func (svc tokenizer) Issue(key auth.Key) (string, error) { } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) + a, b := token.SignedString([]byte(svc.secret)) + fmt.Println("returning : ", a, " : ", b) return token.SignedString([]byte(svc.secret)) } @@ -90,6 +98,8 @@ func (c claims) toKey() auth.Key { if c.ExpiresAt != nil && c.ExpiresAt.Time.UTC().Unix() != 0 { key.ExpiresAt = c.ExpiresAt.Time.UTC() + } else { + key.ExpiresAt = time.Time{} } // Default type is 0. diff --git a/auth/service.go b/auth/service.go index 546ad4a786..21b2a3a8a9 100644 --- a/auth/service.go +++ b/auth/service.go @@ -104,15 +104,28 @@ func New(keys KeyRepository, groups GroupRepository, idp mainflux.IDProvider, to } func (svc service) Issue(ctx context.Context, token string, key Key) (Key, string, error) { + fmt.Println("Inside endpoint") + fmt.Println("reached 1") + fmt.Println() if key.IssuedAt.IsZero() { return Key{}, "", ErrInvalidKeyIssuedAt } switch key.Type { + case APIKey: + fmt.Println() + fmt.Println("reached switch 1") + fmt.Println() return svc.userKey(ctx, token, key) case RecoveryKey: + fmt.Println() + fmt.Println("reached switch 1") + fmt.Println() return svc.tmpKey(recoveryDuration, key) default: + fmt.Println() + fmt.Println("reached default") + fmt.Println() return svc.tmpKey(svc.loginDuration, key) } } diff --git a/readers/cassandra/messages_test.go b/readers/cassandra/messages_test.go index 8a768fa088..b553d85c94 100644 --- a/readers/cassandra/messages_test.go +++ b/readers/cassandra/messages_test.go @@ -52,6 +52,7 @@ func TestReadSenml(t *testing.T) { }) require.Nil(t, err, fmt.Sprintf("failed to connect to Cassandra: %s", err)) defer session.Close() + err = casClient.InitDB(session, cwriter.Table) require.Nil(t, err, fmt.Sprintf("failed to initialize to Cassandra: %s", err)) writer := cwriter.New(session) From ea41d83bccaa4aff93b50684bd75aab434b4e5a1 Mon Sep 17 00:00:00 2001 From: aryan Date: Sun, 2 Apr 2023 03:16:32 +0530 Subject: [PATCH 11/26] fix grpc server setup Signed-off-by: aryan --- auth/api/grpc/setup_test.go | 28 ++++++++++++---------------- things/api/auth/grpc/setup_test.go | 21 ++++++++++++--------- 2 files changed, 24 insertions(+), 25 deletions(-) diff --git a/auth/api/grpc/setup_test.go b/auth/api/grpc/setup_test.go index 652853495f..18f96613a8 100644 --- a/auth/api/grpc/setup_test.go +++ b/auth/api/grpc/setup_test.go @@ -9,7 +9,6 @@ import ( "net" "os" "testing" - "time" "github.com/mainflux/mainflux" "github.com/mainflux/mainflux/auth" @@ -30,23 +29,20 @@ func TestMain(m *testing.M) { svc = newService(t) startGRPCServer(t, serverErr, svc, port) - fmt.Println("Calling for loop") - for { - select { - case testRes <- m.Run(): - fmt.Println() - fmt.Println("test ended") - fmt.Println() - code := <-testRes - os.Exit(code) - case err := <-serverErr: - if err != nil { - log.Fatalf("gPRC Server Terminated") + go func() { + for { + select { + case code := <-testRes: + os.Exit(code) + case err := <-serverErr: + if err != nil { + log.Fatalf("gPRC Server Terminated") + } } - case <-time.After(30 * time.Second): - log.Fatalf("Tests took to long to complete") } - } + }() + + testRes <- m.Run() } func startGRPCServer(t *testing.T, serverErr chan error, svc auth.Service, port int) { diff --git a/things/api/auth/grpc/setup_test.go b/things/api/auth/grpc/setup_test.go index f9de150a54..8731bbcb10 100644 --- a/things/api/auth/grpc/setup_test.go +++ b/things/api/auth/grpc/setup_test.go @@ -34,17 +34,20 @@ func TestMain(m *testing.M) { testRes := make(chan int) startServer(&testing.T{}, serverErr) - for { - select { - case testRes <- m.Run(): - code := <-testRes - os.Exit(code) - case err := <-serverErr: - if err != nil { - log.Fatalf("gPRC Server Terminated") + go func() { + for { + select { + case code := <-testRes: + os.Exit(code) + case err := <-serverErr: + if err != nil { + log.Fatalf("gPRC Server Terminated") + } } } - } + }() + + testRes <- m.Run() } func startServer(t *testing.T, serverErr chan error) { From 1709ad518449988a5572b0462a6065f5a81899b0 Mon Sep 17 00:00:00 2001 From: aryan Date: Mon, 3 Apr 2023 12:44:39 +0530 Subject: [PATCH 12/26] resolve golangci tests, remove debug statements Signed-off-by: aryan --- auth/api/grpc/endpoint.go | 4 --- auth/api/grpc/endpoint_test.go | 41 ------------------------ auth/api/grpc/setup_test.go | 3 -- auth/jwt/tokenizer.go | 6 ---- auth/service.go | 12 ------- bootstrap/redis/producer/streams.go | 11 ------- bootstrap/redis/producer/streams_test.go | 12 ------- bootstrap/service.go | 21 ------------ cmd/certs/main.go | 13 ++++---- logger/logger.go | 2 +- tools/mqtt-bench/bench.go | 10 +++--- tools/mqtt-bench/results.go | 3 +- ws/mocks/pubsub.go | 2 -- 13 files changed, 13 insertions(+), 127 deletions(-) diff --git a/auth/api/grpc/endpoint.go b/auth/api/grpc/endpoint.go index a26ee22354..c0e09c3621 100644 --- a/auth/api/grpc/endpoint.go +++ b/auth/api/grpc/endpoint.go @@ -5,7 +5,6 @@ package grpc import ( "context" - "fmt" "time" "github.com/go-kit/kit/endpoint" @@ -36,9 +35,6 @@ func issueEndpoint(svc auth.Service) endpoint.Endpoint { } func identifyEndpoint(svc auth.Service) endpoint.Endpoint { - fmt.Println() - fmt.Println("reached endpoint") - fmt.Println() return func(ctx context.Context, request interface{}) (interface{}, error) { req := request.(identityReq) if err := req.validate(); err != nil { diff --git a/auth/api/grpc/endpoint_test.go b/auth/api/grpc/endpoint_test.go index 1f67dba898..ff99439ea2 100644 --- a/auth/api/grpc/endpoint_test.go +++ b/auth/api/grpc/endpoint_test.go @@ -107,39 +107,19 @@ func TestIssue(t *testing.T) { } func TestIdentify(t *testing.T) { - fmt.Println() - fmt.Println("reached 1") - fmt.Println() - _, loginSecret, err := svc.Issue(context.Background(), "", auth.Key{Type: auth.LoginKey, IssuedAt: time.Now(), IssuerID: id, Subject: email}) require.Nil(t, err, fmt.Sprintf("Issuing user key expected to succeed: %s", err)) - fmt.Println() - fmt.Println("reached 2") - fmt.Println() - _, recoverySecret, err := svc.Issue(context.Background(), "", auth.Key{Type: auth.RecoveryKey, IssuedAt: time.Now(), IssuerID: id, Subject: email}) require.Nil(t, err, fmt.Sprintf("Issuing recovery key expected to succeed: %s", err)) - fmt.Println() - fmt.Println("reached 3") - fmt.Println() - _, apiSecret, err := svc.Issue(context.Background(), loginSecret, auth.Key{Type: auth.APIKey, IssuedAt: time.Now(), ExpiresAt: time.Now().Add(time.Minute), IssuerID: id, Subject: email}) require.Nil(t, err, fmt.Sprintf("Issuing API key expected to succeed: %s", err)) - fmt.Println() - fmt.Println("reached 4") - fmt.Println() - authAddr := fmt.Sprintf("localhost:%d", port) conn, err := grpc.Dial(authAddr, grpc.WithTransportCredentials(insecure.NewCredentials())) require.Nil(t, err, fmt.Sprintf("got unexpected error while creating client connection: %s", err)) - fmt.Println() - fmt.Println("reached 5") - fmt.Println() - client := grpcapi.NewClient(mocktracer.New(), conn, time.Second) cases := []struct { @@ -187,25 +167,14 @@ func TestIdentify(t *testing.T) { } for _, tc := range cases { - fmt.Println() - fmt.Println("###") - fmt.Println(tc.desc) - fmt.Println("###") - fmt.Println() idt, err := client.Identify(context.Background(), &mainflux.Token{Value: tc.token}) - fmt.Println("idt : ", idt) - fmt.Println("err : ", err) if idt != nil { assert.Equal(t, tc.idt, idt, fmt.Sprintf("%s: expected %v got %v", tc.desc, tc.idt, idt)) } e, ok := status.FromError(err) - fmt.Println("e : ", e) - fmt.Println("ok : ", ok) assert.True(t, ok, "gRPC status can't be extracted from the error") assert.Equal(t, tc.code, e.Code(), fmt.Sprintf("%s: expected %s got %s", tc.desc, tc.code, e.Code())) } - - fmt.Println("Reached here") } func TestAuthorize(t *testing.T) { @@ -289,10 +258,6 @@ func TestAuthorize(t *testing.T) { assert.True(t, ok, "gRPC status can't be extracted from the error") assert.Equal(t, tc.code, e.Code(), fmt.Sprintf("%s: expected %s got %s", tc.desc, tc.code, e.Code())) } - - fmt.Println() - fmt.Println("Reached here") - fmt.Println() } func TestAddPolicy(t *testing.T) { @@ -348,8 +313,6 @@ func TestAddPolicy(t *testing.T) { assert.True(t, ok, "gRPC status can't be extracted from the error") assert.Equal(t, tc.code, e.Code(), fmt.Sprintf("%s: expected %s got %s", tc.desc, tc.code, e.Code())) } - - fmt.Println("Reached here") } func TestDeletePolicy(t *testing.T) { @@ -404,8 +367,6 @@ func TestDeletePolicy(t *testing.T) { assert.Equal(t, tc.code, e.Code(), fmt.Sprintf("%s: expected %s got %s", tc.desc, tc.code, e.Code())) assert.Equal(t, tc.dpr.GetDeleted(), dpr.GetDeleted(), fmt.Sprintf("%s: expected %v got %v", tc.desc, tc.dpr.GetDeleted(), dpr.GetDeleted())) } - - fmt.Println("Reached here") } func TestMembers(t *testing.T) { @@ -489,6 +450,4 @@ func TestMembers(t *testing.T) { assert.Equal(t, tc.code, e.Code(), fmt.Sprintf("%s: expected %s got %s", tc.desc, tc.code, e.Code())) assert.True(t, ok, "OK expected to be true") } - - fmt.Println("Reached here") } diff --git a/auth/api/grpc/setup_test.go b/auth/api/grpc/setup_test.go index 18f96613a8..a0198a512a 100644 --- a/auth/api/grpc/setup_test.go +++ b/auth/api/grpc/setup_test.go @@ -55,9 +55,6 @@ func startGRPCServer(t *testing.T, serverErr chan error, svc auth.Service, port done := make(chan bool) t.Cleanup(func() { - fmt.Println() - fmt.Println("Test complete called t.cleanup") - fmt.Println() close(done) }) diff --git a/auth/jwt/tokenizer.go b/auth/jwt/tokenizer.go index ccf2448b34..7409c65e7f 100644 --- a/auth/jwt/tokenizer.go +++ b/auth/jwt/tokenizer.go @@ -4,7 +4,6 @@ package jwt import ( - "fmt" "time" "github.com/golang-jwt/jwt/v4" @@ -38,9 +37,6 @@ func New(secret string) auth.Tokenizer { } func (svc tokenizer) Issue(key auth.Key) (string, error) { - fmt.Println() - fmt.Println("reached jwt issue") - fmt.Println() claims := claims{ RegisteredClaims: jwt.RegisteredClaims{ Issuer: issuerName, @@ -59,8 +55,6 @@ func (svc tokenizer) Issue(key auth.Key) (string, error) { } token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - a, b := token.SignedString([]byte(svc.secret)) - fmt.Println("returning : ", a, " : ", b) return token.SignedString([]byte(svc.secret)) } diff --git a/auth/service.go b/auth/service.go index 21b2a3a8a9..d47f2ac2b9 100644 --- a/auth/service.go +++ b/auth/service.go @@ -104,28 +104,16 @@ func New(keys KeyRepository, groups GroupRepository, idp mainflux.IDProvider, to } func (svc service) Issue(ctx context.Context, token string, key Key) (Key, string, error) { - fmt.Println("Inside endpoint") - fmt.Println("reached 1") - fmt.Println() if key.IssuedAt.IsZero() { return Key{}, "", ErrInvalidKeyIssuedAt } switch key.Type { case APIKey: - fmt.Println() - fmt.Println("reached switch 1") - fmt.Println() return svc.userKey(ctx, token, key) case RecoveryKey: - fmt.Println() - fmt.Println("reached switch 1") - fmt.Println() return svc.tmpKey(recoveryDuration, key) default: - fmt.Println() - fmt.Println("reached default") - fmt.Println() return svc.tmpKey(svc.loginDuration, key) } } diff --git a/bootstrap/redis/producer/streams.go b/bootstrap/redis/producer/streams.go index 0c00be984b..784f250606 100644 --- a/bootstrap/redis/producer/streams.go +++ b/bootstrap/redis/producer/streams.go @@ -5,7 +5,6 @@ package producer import ( "context" - "fmt" "time" "github.com/go-redis/redis/v8" @@ -114,9 +113,6 @@ func (es eventStore) Remove(ctx context.Context, token, id string) error { } func (es eventStore) Bootstrap(ctx context.Context, externalKey, externalID string, secure bool) (bootstrap.Config, error) { - fmt.Println() - fmt.Println("Eventstore bootstrap called:") - fmt.Println() cfg, err := es.svc.Bootstrap(ctx, externalKey, externalID, secure) ev := bootstrapEvent{ @@ -127,17 +123,10 @@ func (es eventStore) Bootstrap(ctx context.Context, externalKey, externalID stri if err != nil { ev.success = false - fmt.Println() - fmt.Println("returning err 1: ", err) - fmt.Println() return cfg, err } err = es.add(ctx, ev) - fmt.Println() - fmt.Println("returning err 2: ", err) - fmt.Println() - return cfg, err } diff --git a/bootstrap/redis/producer/streams_test.go b/bootstrap/redis/producer/streams_test.go index a58769c43d..98dc033d73 100644 --- a/bootstrap/redis/producer/streams_test.go +++ b/bootstrap/redis/producer/streams_test.go @@ -421,9 +421,6 @@ func TestBootstrap(t *testing.T) { c := config saved, err := svc.Add(context.Background(), validToken, c) - fmt.Println() - fmt.Println("Saved : ", saved) - fmt.Println() require.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) err = redisClient.FlushAll(context.Background()).Err() assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) @@ -463,9 +460,7 @@ func TestBootstrap(t *testing.T) { lastID := "0" for _, tc := range cases { - fmt.Printf("\n\n\n%s\n\n\n", tc.desc) _, errr := svc.Bootstrap(context.Background(), tc.externalKey, tc.externalID, false) - fmt.Println("returned error : ", errr) assert.True(t, errors.Contains(errr, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, errr)) streams := redisClient.XRead(context.Background(), &redis.XReadArgs{ @@ -480,13 +475,6 @@ func TestBootstrap(t *testing.T) { event = msg.Values lastID = msg.ID } - fmt.Println() - fmt.Println("tc.event : ") - fmt.Println(tc.event) - fmt.Println() - fmt.Println("event from XRead: ") - fmt.Println(event) - fmt.Println() test(t, tc.event, event, tc.desc) } } diff --git a/bootstrap/service.go b/bootstrap/service.go index 28c8f3d656..09a08bbca3 100644 --- a/bootstrap/service.go +++ b/bootstrap/service.go @@ -8,7 +8,6 @@ import ( "crypto/aes" "crypto/cipher" "encoding/hex" - "fmt" "time" "github.com/mainflux/mainflux" @@ -273,38 +272,18 @@ func (bs bootstrapService) Remove(ctx context.Context, token, id string) error { func (bs bootstrapService) Bootstrap(ctx context.Context, externalKey, externalID string, secure bool) (Config, error) { cfg, err := bs.configs.RetrieveByExternalID(externalID) - fmt.Println() - fmt.Println("RetreivebyexternalId : : err 1", err) - fmt.Println() - fmt.Println("Received config : ", cfg.ExternalID) - fmt.Println("Received config : ", cfg.ExternalKey) - fmt.Println("Received config : ", cfg.Name) - fmt.Println("Received config : ", cfg.MFThing) - fmt.Println() if err != nil { - fmt.Println("returning err 2: : ", err) err = errors.Wrap(ErrBootstrap, err) - fmt.Println(err) return cfg, err } if secure { dec, err := bs.dec(externalKey) if err != nil { - fmt.Println() - fmt.Println("returnring err 3 : ", err) - fmt.Println() return Config{}, errors.Wrap(ErrExternalKeySecure, err) } externalKey = dec } - fmt.Println() - fmt.Println("key value : ", cfg.ExternalKey, " ", externalKey) - fmt.Println() if cfg.ExternalKey != externalKey { - fmt.Println() - fmt.Println("returning error 4 : ", err) - fmt.Println() - return Config{}, ErrExternalKey } diff --git a/cmd/certs/main.go b/cmd/certs/main.go index dc73e4f395..93fdd36432 100644 --- a/cmd/certs/main.go +++ b/cmd/certs/main.go @@ -169,13 +169,14 @@ func loadCertificates(conf config, logger mflog.Logger) (tls.Certificate, *x509. } block, _ := pem.Decode(b) - if block == nil { + switch block { + case nil: logger.Fatal("No PEM data found, failed to decode CA") - } - - caCert, err = x509.ParseCertificate(block.Bytes) - if err != nil { - return tlsCert, caCert, errors.Wrap(errFailedCertDecode, err) + default: + caCert, err = x509.ParseCertificate(block.Bytes) + if err != nil { + return tlsCert, caCert, errors.Wrap(errFailedCertDecode, err) + } } return tlsCert, caCert, nil diff --git a/logger/logger.go b/logger/logger.go index f8c2a335d1..8ea5fbc85c 100644 --- a/logger/logger.go +++ b/logger/logger.go @@ -70,6 +70,6 @@ func (l logger) Error(msg string) { } func (l logger) Fatal(msg string) { - l.kitLogger.Log("fatal", msg) + _ = l.kitLogger.Log("fatal", msg) os.Exit(1) } diff --git a/tools/mqtt-bench/bench.go b/tools/mqtt-bench/bench.go index b034852019..0acf625e24 100644 --- a/tools/mqtt-bench/bench.go +++ b/tools/mqtt-bench/bench.go @@ -28,13 +28,12 @@ func Benchmark(cfg Config) { caFile, err := os.Open(cfg.MQTT.TLS.CA) defer func() { - err = caFile.Close() - if err != nil { - fmt.Println(err) + if err = caFile.Close(); err != nil { + log.Printf("Could not close file: %s", err) } }() if err != nil { - fmt.Println(err) + log.Print(err) } caByte, _ = ioutil.ReadAll(caFile) } @@ -116,8 +115,7 @@ func getBytePayload(size int, m message) (handler, error) { sz := size - n for { b = make([]byte, sz) - _, err = rand.Read(b) - if err != nil { + if _, err = rand.Read(b); err != nil { return nil, err } m.Payload = b diff --git a/tools/mqtt-bench/results.go b/tools/mqtt-bench/results.go index 20b80df07e..aee70d695c 100644 --- a/tools/mqtt-bench/results.go +++ b/tools/mqtt-bench/results.go @@ -157,8 +157,7 @@ func printResults(results []*runResults, totals *totalResults, format string, qu log.Printf("Failed to prepare results for printing - %s\n", err.Error()) } var out bytes.Buffer - err = json.Indent(&out, data, "", "\t") - if err != nil { + if err = json.Indent(&out, data, "", "\t"); err != nil { return } diff --git a/ws/mocks/pubsub.go b/ws/mocks/pubsub.go index bc9d60d4a0..5294fcf404 100644 --- a/ws/mocks/pubsub.go +++ b/ws/mocks/pubsub.go @@ -6,7 +6,6 @@ package mocks import ( "context" "encoding/json" - "fmt" "github.com/gorilla/websocket" "github.com/mainflux/mainflux/pkg/messaging" @@ -37,7 +36,6 @@ func (pubsub *mockPubSub) Publish(ctx context.Context, s string, msg *messaging. if pubsub.conn != nil { data, err := json.Marshal(msg) if err != nil { - fmt.Println("can't marshall") return ws.ErrFailedMessagePublish } return pubsub.conn.WriteMessage(websocket.BinaryMessage, data) From a12b21c3efdfcc6bf087f8b7349a45589e3d8f0b Mon Sep 17 00:00:00 2001 From: aryan Date: Mon, 3 Apr 2023 19:29:58 +0530 Subject: [PATCH 13/26] update golangci version and modify linters used Signed-off-by: aryan --- scripts/ci.sh | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/ci.sh b/scripts/ci.sh index 8aa8393993..e2539e525f 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -4,6 +4,7 @@ GO_VERSION=1.19.4 PROTOC_VERSION=21.12 PROTOC_GEN_VERSION=v1.28.1 PROTOC_GRPC_VERSION=v1.2.0 +GOLANGCI_LINT_VERSION=v1.51.1 function version_gt() { test "$(printf '%s\n' "$@" | sort -V | head -n 1)" != "$1"; } @@ -71,7 +72,7 @@ setup_mf() { setup_lint() { # binary will be $(go env GOBIN)/golangci-lint - curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOBIN) v1.46.2 + curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOBIN) $GOLANGCI_LINT_VERSION } @@ -85,7 +86,7 @@ setup() { run_test() { echo "Running lint..." - golangci-lint run --no-config --disable-all --enable gosimple --enable govet --enable unused --enable deadcode --timeout 3m + golangci-lint run --no-config --disable-all --enable gosimple --enable errcheck --enable govet --enable unused --enable goconst --timeout 3m echo "Running tests..." echo "" > coverage.txt for d in $(go list ./... | grep -v 'vendor\|cmd'); do From 1cd3baad594cde38fc2aaf7dfa4d5e42cc98774a Mon Sep 17 00:00:00 2001 From: aryan Date: Tue, 4 Apr 2023 19:00:44 +0530 Subject: [PATCH 14/26] fix failing tests Signed-off-by: aryan --- auth/service_test.go | 7 ++-- cli/channels.go | 4 ++- cli/groups.go | 2 +- cli/things.go | 2 +- cli/users.go | 2 +- things/api/things/http/endpoint_test.go | 43 +++++++++++++------------ things/mocks/commons.go | 18 ++++++----- things/postgres/channels.go | 8 +++-- 8 files changed, 48 insertions(+), 38 deletions(-) diff --git a/auth/service_test.go b/auth/service_test.go index 310bba9f72..f0afbc6109 100644 --- a/auth/service_test.go +++ b/auth/service_test.go @@ -25,6 +25,7 @@ const ( id = "testID" groupName = "mfx" description = "Description" + read = "read" memberRelation = "member" authoritiesObj = "authorities" @@ -1081,7 +1082,7 @@ func TestAddPolicies(t *testing.T) { assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) tmpID := "tmpid" - readPolicy := "read" + readPolicy := read writePolicy := "write" deletePolicy := "delete" @@ -1166,7 +1167,7 @@ func TestDeletePolicies(t *testing.T) { assert.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) tmpID := "tmpid" - readPolicy := "read" + readPolicy := read writePolicy := "write" deletePolicy := "delete" memberPolicy := "member" @@ -1252,7 +1253,7 @@ func TestListPolicies(t *testing.T) { _, apiToken, err := svc.Issue(context.Background(), secret, key) assert.Nil(t, err, fmt.Sprintf("Issuing user's key expected to succeed: %s", err)) - readPolicy := "read" + readPolicy := read pageLen := 15 // Add arbitrary policies to the user. diff --git a/cli/channels.go b/cli/channels.go index c6c2421839..369c314921 100644 --- a/cli/channels.go +++ b/cli/channels.go @@ -10,6 +10,8 @@ import ( "github.com/spf13/cobra" ) +const all = "all" + var cmdChannels = []cobra.Command{ { Use: "create ", @@ -60,7 +62,7 @@ var cmdChannels = []cobra.Command{ Metadata: metadata, } - if args[0] == "all" { + if args[0] == all { l, err := sdk.Channels(pageMetadata, args[1]) if err != nil { logError(err) diff --git a/cli/groups.go b/cli/groups.go index 60419dbd95..d88aca9799 100644 --- a/cli/groups.go +++ b/cli/groups.go @@ -54,7 +54,7 @@ var cmdGroups = []cobra.Command{ logUsage(cmd.Use) return } - if args[0] == "all" { + if args[0] == all { if len(args) > 2 { logUsage(cmd.Use) return diff --git a/cli/things.go b/cli/things.go index 06be8071d9..715033d656 100644 --- a/cli/things.go +++ b/cli/things.go @@ -58,7 +58,7 @@ var cmdThings = []cobra.Command{ Limit: uint64(Limit), Metadata: metadata, } - if args[0] == "all" { + if args[0] == all { l, err := sdk.Things(pageMetadata, args[1]) if err != nil { logError(err) diff --git a/cli/users.go b/cli/users.go index e7aa57a0f5..e4b12c7274 100644 --- a/cli/users.go +++ b/cli/users.go @@ -60,7 +60,7 @@ var cmdUsers = []cobra.Command{ Metadata: metadata, Status: Status, } - if args[0] == "all" { + if args[0] == all { l, err := sdk.Users(pageMetadata, args[1]) if err != nil { logError(err) diff --git a/things/api/things/http/endpoint_test.go b/things/api/things/http/endpoint_test.go index 1e638dd68e..3ebdf17ca5 100644 --- a/things/api/things/http/endpoint_test.go +++ b/things/api/things/http/endpoint_test.go @@ -29,17 +29,20 @@ import ( ) const ( - contentType = "application/json" - email = "user@example.com" - adminEmail = "admin@example.com" - token = "token" - wrongValue = "wrong_value" - wrongID = 0 - maxNameSize = 1024 - nameKey = "name" - ascKey = "asc" - descKey = "desc" - prefix = "fe6b4e92-cc98-425e-b0aa-" + contentType = "application/json" + email = "user@example.com" + adminEmail = "admin@example.com" + otherExampleEmail = "other_user@example.com" + token = "token" + otherExampleToken = "other_token" + wrongValue = "wrong_value" + thingKey = "key" + wrongID = 0 + maxNameSize = 1024 + nameKey = "name" + ascKey = "asc" + descKey = "desc" + prefix = "fe6b4e92-cc98-425e-b0aa-" ) var ( @@ -116,7 +119,7 @@ func TestCreateThing(t *testing.T) { defer ts.Close() th := thing - th.Key = "key" + th.Key = thingKey data := toJSON(th) th.Name = invalidName @@ -2264,8 +2267,8 @@ func TestRemoveChannel(t *testing.T) { } func TestConnect(t *testing.T) { - otherToken := "other_token" - otherEmail := "other_user@example.com" + otherToken := otherExampleToken + otherEmail := otherExampleEmail svc := newService(map[string]string{ token: email, otherToken: otherEmail, @@ -2360,8 +2363,8 @@ func TestConnect(t *testing.T) { } func TestCreateConnections(t *testing.T) { - otherToken := "other_token" - otherEmail := "other_user@example.com" + otherToken := otherExampleToken + otherEmail := otherExampleEmail svc := newService(map[string]string{ token: email, otherToken: otherEmail, @@ -2549,8 +2552,8 @@ func TestCreateConnections(t *testing.T) { } func TestDisconnectList(t *testing.T) { - otherToken := "other_token" - otherEmail := "other_user@example.com" + otherToken := otherExampleToken + otherEmail := otherExampleEmail svc := newService(map[string]string{ token: email, otherToken: otherEmail, @@ -2742,8 +2745,8 @@ func TestDisconnectList(t *testing.T) { } func TestDisconnnect(t *testing.T) { - otherToken := "other_token" - otherEmail := "other_user@example.com" + otherToken := otherExampleToken + otherEmail := otherExampleEmail svc := newService(map[string]string{ token: email, otherToken: otherEmail, diff --git a/things/mocks/commons.go b/things/mocks/commons.go index 5177e6bc81..e498f12254 100644 --- a/things/mocks/commons.go +++ b/things/mocks/commons.go @@ -12,6 +12,8 @@ import ( ) const uuidLen = 36 +const asc = "asc" +const desc = "desc" // Since mocks will store data in map, and they need to resemble the real // identifiers as much as possible, a key will be created as combination of @@ -24,23 +26,23 @@ func key(owner string, id string) string { func sortThings(pm things.PageMetadata, ths []things.Thing) []things.Thing { switch pm.Order { case "name": - if pm.Dir == "asc" { + if pm.Dir == asc { sort.SliceStable(ths, func(i, j int) bool { return ths[i].Name < ths[j].Name }) } - if pm.Dir == "desc" { + if pm.Dir == desc { sort.SliceStable(ths, func(i, j int) bool { return ths[i].Name > ths[j].Name }) } case "id": - if pm.Dir == "asc" { + if pm.Dir == asc { sort.SliceStable(ths, func(i, j int) bool { return ths[i].ID < ths[j].ID }) } - if pm.Dir == "desc" { + if pm.Dir == desc { sort.SliceStable(ths, func(i, j int) bool { return ths[i].ID > ths[j].ID }) @@ -57,23 +59,23 @@ func sortThings(pm things.PageMetadata, ths []things.Thing) []things.Thing { func sortChannels(pm things.PageMetadata, chs []things.Channel) []things.Channel { switch pm.Order { case "name": - if pm.Dir == "asc" { + if pm.Dir == asc { sort.SliceStable(chs, func(i, j int) bool { return chs[i].Name < chs[j].Name }) } - if pm.Dir == "desc" { + if pm.Dir == desc { sort.SliceStable(chs, func(i, j int) bool { return chs[i].Name > chs[j].Name }) } case "id": - if pm.Dir == "asc" { + if pm.Dir == asc { sort.SliceStable(chs, func(i, j int) bool { return chs[i].ID < chs[j].ID }) } - if pm.Dir == "desc" { + if pm.Dir == desc { sort.SliceStable(chs, func(i, j int) bool { return chs[i].ID > chs[j].ID }) diff --git a/things/postgres/channels.go b/things/postgres/channels.go index 27eaa8d8ce..a4c2e5853f 100644 --- a/things/postgres/channels.go +++ b/things/postgres/channels.go @@ -20,6 +20,8 @@ import ( var _ things.ChannelRepository = (*channelRepository)(nil) +const name = "name" + type channelRepository struct { db Database } @@ -505,8 +507,8 @@ func getNameQuery(name string) (string, string) { func getOrderQuery(order string) string { switch order { - case "name": - return "name" + case name: + return name default: return "id" } @@ -514,7 +516,7 @@ func getOrderQuery(order string) string { func getConnOrderQuery(order string, level string) string { switch order { - case "name": + case name: return level + ".name" default: return level + ".id" From 9b15e301ae2b0bf347a99f2f83e2791f98e75170 Mon Sep 17 00:00:00 2001 From: aryan Date: Thu, 6 Apr 2023 02:07:28 +0530 Subject: [PATCH 15/26] fix grpc server for setup tests Signed-off-by: aryan --- auth/api/grpc/setup_test.go | 26 +++++++++++--------------- things/api/auth/grpc/setup_test.go | 27 +++++++++++++++++++++------ 2 files changed, 32 insertions(+), 21 deletions(-) diff --git a/auth/api/grpc/setup_test.go b/auth/api/grpc/setup_test.go index a0198a512a..a5a67ead8a 100644 --- a/auth/api/grpc/setup_test.go +++ b/auth/api/grpc/setup_test.go @@ -25,15 +25,16 @@ func TestMain(m *testing.M) { t := &testing.T{} serverErr := make(chan error) testRes := make(chan int) + done := make(chan int) svc = newService(t) - startGRPCServer(t, serverErr, svc, port) - + startGRPCServer(t, serverErr, svc, port, done) go func() { for { select { case code := <-testRes: - os.Exit(code) + done <- code + return case err := <-serverErr: if err != nil { log.Fatalf("gPRC Server Terminated") @@ -45,33 +46,28 @@ func TestMain(m *testing.M) { testRes <- m.Run() } -func startGRPCServer(t *testing.T, serverErr chan error, svc auth.Service, port int) { +func startGRPCServer(t *testing.T, serverErr chan error, svc auth.Service, port int, done chan int) { listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) require.Nil(t, err, fmt.Sprintf("got unexpected error while creating new listerner: %s", err)) server := grpc.NewServer() mainflux.RegisterAuthServiceServer(server, grpcapi.NewServer(mocktracer.New(), svc)) - done := make(chan bool) - - t.Cleanup(func() { - close(done) - }) - - go func(done <-chan bool) { + go func(done chan int, server *grpc.Server) { for { select { case serverErr <- server.Serve(listener): close(serverErr) return - case <-done: + case code := <-done: + server.Stop() close(serverErr) - // serverErr <- nil - return + close(done) + os.Exit(code) } } - }(done) + }(done, server) } func newService(t *testing.T) auth.Service { diff --git a/things/api/auth/grpc/setup_test.go b/things/api/auth/grpc/setup_test.go index 8731bbcb10..f86cefe2e5 100644 --- a/things/api/auth/grpc/setup_test.go +++ b/things/api/auth/grpc/setup_test.go @@ -32,13 +32,16 @@ var svc things.Service func TestMain(m *testing.M) { serverErr := make(chan error) testRes := make(chan int) - startServer(&testing.T{}, serverErr) + done := make(chan int) + + startServer(&testing.T{}, serverErr, done) go func() { for { select { case code := <-testRes: - os.Exit(code) + done <- code + return case err := <-serverErr: if err != nil { log.Fatalf("gPRC Server Terminated") @@ -50,7 +53,7 @@ func TestMain(m *testing.M) { testRes <- m.Run() } -func startServer(t *testing.T, serverErr chan error) { +func startServer(t *testing.T, serverErr chan error, done chan int) { svc = newService(map[string]string{token: email}) listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) assert.Nil(t, err, fmt.Sprintf("got unexpected error while creating new listener: %s", err)) @@ -58,9 +61,21 @@ func startServer(t *testing.T, serverErr chan error) { server := grpc.NewServer() mainflux.RegisterThingsServiceServer(server, grpcapi.NewServer(mocktracer.New(), svc)) - go func() { - serverErr <- server.Serve(listener) - }() + go func(done chan int, server *grpc.Server) { + for { + select { + case serverErr <- server.Serve(listener): + close(serverErr) + return + case code := <-done: + server.Stop() + close(serverErr) + close(done) + os.Exit(code) + } + + } + }(done, server) } func newService(tokens map[string]string) things.Service { From c79f2172447529d27b73ed65af253b40337b226b Mon Sep 17 00:00:00 2001 From: aryan Date: Thu, 6 Apr 2023 02:40:31 +0530 Subject: [PATCH 16/26] fix logging and errors inlined Signed-off-by: aryan --- auth/postgres/groups.go | 7 ++++--- readers/mongodb/messages.go | 3 +-- readers/timescale/messages.go | 3 +-- things/postgres/things.go | 3 ++- tools/mqtt-bench/bench.go | 18 +++++++++++------- 5 files changed, 19 insertions(+), 15 deletions(-) diff --git a/auth/postgres/groups.go b/auth/postgres/groups.go index 079a8bdf23..41f46ca3a4 100644 --- a/auth/postgres/groups.go +++ b/auth/postgres/groups.go @@ -440,7 +440,8 @@ func (gr groupRepository) Assign(ctx context.Context, groupID, groupType string, dbg.UpdatedAt = created if _, err := tx.NamedExecContext(ctx, qIns, dbg); err != nil { - if err := tx.Rollback(); err != nil { + if rollbackErr := tx.Rollback(); rollbackErr != nil { + err = errors.Wrap(err, rollbackErr) return errors.Wrap(auth.ErrAssignToGroup, err) } @@ -482,8 +483,8 @@ func (gr groupRepository) Unassign(ctx context.Context, groupID string, ids ...s } if _, err := tx.NamedExecContext(ctx, qDel, dbg); err != nil { - err = tx.Rollback() - if err != nil { + if rollbackErr := tx.Rollback(); rollbackErr != nil { + err = errors.Wrap(err, rollbackErr) return errors.Wrap(auth.ErrAssignToGroup, err) } diff --git a/readers/mongodb/messages.go b/readers/mongodb/messages.go index 7e1257736c..3d27dad55a 100644 --- a/readers/mongodb/messages.go +++ b/readers/mongodb/messages.go @@ -101,8 +101,7 @@ func fmtCondition(chanID string, rpm readers.PageMetadata) bson.D { if err != nil { return filter } - err = json.Unmarshal(meta, &query) - if err != nil { + if err = json.Unmarshal(meta, &query); err != nil { return filter } diff --git a/readers/timescale/messages.go b/readers/timescale/messages.go index ad44118d06..34a8d202a0 100644 --- a/readers/timescale/messages.go +++ b/readers/timescale/messages.go @@ -121,8 +121,7 @@ func fmtCondition(chanID string, rpm readers.PageMetadata) string { if err != nil { return condition } - err = json.Unmarshal(meta, &query) - if err != nil { + if err = json.Unmarshal(meta, &query); err != nil { return condition } diff --git a/things/postgres/things.go b/things/postgres/things.go index 854c997f61..ddf91f4328 100644 --- a/things/postgres/things.go +++ b/things/postgres/things.go @@ -48,7 +48,8 @@ func (tr thingRepository) Save(ctx context.Context, ths ...things.Thing) ([]thin } if _, err := tx.NamedExecContext(ctx, q, dbth); err != nil { - if err := tx.Rollback(); err != nil { + if rollbackErr := tx.Rollback(); rollbackErr != nil { + err = errors.Wrap(err, rollbackErr) return []things.Thing{}, errors.Wrap(errors.ErrCreateEntity, err) } pgErr, ok := err.(*pgconn.PgError) diff --git a/tools/mqtt-bench/bench.go b/tools/mqtt-bench/bench.go index 0acf625e24..254c91b153 100644 --- a/tools/mqtt-bench/bench.go +++ b/tools/mqtt-bench/bench.go @@ -14,14 +14,18 @@ import ( "strconv" "time" + mainflux_log "github.com/mainflux/mainflux/logger" "github.com/pelletier/go-toml" ) // Benchmark - main benchmarking function func Benchmark(cfg Config) { checkConnection(cfg.MQTT.Broker.URL, 1) + logger, err := mainflux_log.New(os.Stdout, mainflux_log.Debug.String()) + if err != nil { + log.Fatalf(err.Error()) + } - var err error subsResults := map[string](*[]float64){} var caByte []byte if cfg.MQTT.TLS.MTLS { @@ -29,23 +33,23 @@ func Benchmark(cfg Config) { defer func() { if err = caFile.Close(); err != nil { - log.Printf("Could not close file: %s", err) + logger.Warn(fmt.Sprintf("Could not close file: %s", err)) } }() if err != nil { - log.Print(err) + logger.Warn(err.Error()) } caByte, _ = ioutil.ReadAll(caFile) } data, err := ioutil.ReadFile(cfg.Mf.ConnFile) if err != nil { - log.Fatalf("Error loading connections file: %s", err) + logger.Fatal(fmt.Sprintf("Error loading connections file: %s", err)) } mf := mainflux{} if err := toml.Unmarshal(data, &mf); err != nil { - log.Fatalf("Cannot load Mainflux connections config %s \nUse tools/provision to create file", cfg.Mf.ConnFile) + logger.Fatal(fmt.Sprintf("Cannot load Mainflux connections config %s \nUse tools/provision to create file", cfg.Mf.ConnFile)) } resCh := make(chan *runResults) @@ -66,12 +70,12 @@ func Benchmark(cfg Config) { if cfg.MQTT.TLS.MTLS { cert, err = tls.X509KeyPair([]byte(mfThing.MTLSCert), []byte(mfThing.MTLSKey)) if err != nil { - log.Fatal(err) + logger.Fatal(err.Error()) } } c, err := makeClient(i, cfg, mfChan, mfThing, startStamp, caByte, cert) if err != nil { - log.Fatalf("Unable to create message payload %s", err.Error()) + logger.Fatal(fmt.Sprintf("Unable to create message payload %s", err.Error())) } go c.publish(resCh) From 84b982ba86884a5a27b6485af75080b178b2ad60 Mon Sep 17 00:00:00 2001 From: aryan Date: Fri, 7 Apr 2023 18:25:54 +0530 Subject: [PATCH 17/26] fix remarks, update grpc setup_test Signed-off-by: aryan --- auth/api/grpc/setup_test.go | 47 +++++++++++++++++++---------------- lora/mqtt/sub.go | 3 +-- opcua/gopcua/subscribe.go | 3 +-- readers/cassandra/messages.go | 3 +-- readers/mocks/messages.go | 3 +-- readers/postgres/messages.go | 3 +-- things/redis/streams.go | 12 +++------ tools/mqtt-bench/bench.go | 4 +-- 8 files changed, 36 insertions(+), 42 deletions(-) diff --git a/auth/api/grpc/setup_test.go b/auth/api/grpc/setup_test.go index a5a67ead8a..cb9b5c71b7 100644 --- a/auth/api/grpc/setup_test.go +++ b/auth/api/grpc/setup_test.go @@ -26,9 +26,28 @@ func TestMain(m *testing.M) { serverErr := make(chan error) testRes := make(chan int) done := make(chan int) + endTest := make(chan int) svc = newService(t) - startGRPCServer(t, serverErr, svc, port, done) + listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) + require.Nil(t, err, fmt.Sprintf("got unexpected error while creating new listerner: %s", err)) + + server := grpc.NewServer() + mainflux.RegisterAuthServiceServer(server, grpcapi.NewServer(mocktracer.New(), svc)) + + go func(done chan int, endTest chan int, server *grpc.Server) { + for { + select { + case serverErr <- server.Serve(listener): + close(serverErr) + return + case code := <-done: + endTest <- code + } + + } + }(done, endTest, server) + go func() { for { select { @@ -44,30 +63,14 @@ func TestMain(m *testing.M) { }() testRes <- m.Run() -} + code := <-endTest -func startGRPCServer(t *testing.T, serverErr chan error, svc auth.Service, port int, done chan int) { - listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) - require.Nil(t, err, fmt.Sprintf("got unexpected error while creating new listerner: %s", err)) + server.Stop() - server := grpc.NewServer() - mainflux.RegisterAuthServiceServer(server, grpcapi.NewServer(mocktracer.New(), svc)) + close(serverErr) + close(done) - go func(done chan int, server *grpc.Server) { - for { - select { - case serverErr <- server.Serve(listener): - close(serverErr) - return - case code := <-done: - server.Stop() - close(serverErr) - close(done) - os.Exit(code) - } - - } - }(done, server) + os.Exit(code) } func newService(t *testing.T) auth.Service { diff --git a/lora/mqtt/sub.go b/lora/mqtt/sub.go index 58b7d7b679..4ec1cdb9c2 100644 --- a/lora/mqtt/sub.go +++ b/lora/mqtt/sub.go @@ -54,8 +54,7 @@ func (b broker) handleMsg(c mqtt.Client, msg mqtt.Message) { return } - err := b.svc.Publish(context.Background(), &m) - if err != nil { + if err := b.svc.Publish(context.Background(), &m); err != nil { b.logger.Error(fmt.Sprintf("got error while publishing messages: %s", err)) } } diff --git a/opcua/gopcua/subscribe.go b/opcua/gopcua/subscribe.go index afc980838f..21e4461d6b 100644 --- a/opcua/gopcua/subscribe.go +++ b/opcua/gopcua/subscribe.go @@ -112,8 +112,7 @@ func (c client) Subscribe(ctx context.Context, cfg opcua.Config) error { return errors.Wrap(errFailedSub, err) } defer func() { - err = sub.Cancel() - if err != nil { + if err = sub.Cancel(); err != nil { c.logger.Error(fmt.Sprintf("subscription could not be cancelled: %s", err)) } }() diff --git a/readers/cassandra/messages.go b/readers/cassandra/messages.go index 33f06d3dad..f0c2966505 100644 --- a/readers/cassandra/messages.go +++ b/readers/cassandra/messages.go @@ -128,8 +128,7 @@ func buildQuery(chanID string, rpm readers.PageMetadata) (string, []interface{}) if err != nil { return condCQL, vals } - err = json.Unmarshal(meta, &query) - if err != nil { + if err = json.Unmarshal(meta, &query); err != nil { return condCQL, vals } diff --git a/readers/mocks/messages.go b/readers/mocks/messages.go index a1c5f68865..feaeaeb732 100644 --- a/readers/mocks/messages.go +++ b/readers/mocks/messages.go @@ -43,8 +43,7 @@ func (repo *messageRepositoryMock) ReadAll(chanID string, rpm readers.PageMetada if err != nil { return readers.MessagesPage{}, err } - err = json.Unmarshal(meta, &query) - if err != nil { + if err = json.Unmarshal(meta, &query); err != nil { return readers.MessagesPage{}, err } diff --git a/readers/postgres/messages.go b/readers/postgres/messages.go index 3b72139f50..c2e307be2a 100644 --- a/readers/postgres/messages.go +++ b/readers/postgres/messages.go @@ -123,8 +123,7 @@ func fmtCondition(chanID string, rpm readers.PageMetadata) string { if err != nil { return condition } - err = json.Unmarshal(meta, &query) - if err != nil { + if err = json.Unmarshal(meta, &query); err != nil { return condition } diff --git a/things/redis/streams.go b/things/redis/streams.go index 2617bd2286..4ff8b7e47d 100644 --- a/things/redis/streams.go +++ b/things/redis/streams.go @@ -50,8 +50,7 @@ func (es eventStore) CreateThings(ctx context.Context, token string, ths ...thin Values: event.Encode(), } - err = es.client.XAdd(ctx, record).Err() - if err != nil { + if err = es.client.XAdd(ctx, record).Err(); err != nil { return sths, err } } @@ -136,8 +135,7 @@ func (es eventStore) CreateChannels(ctx context.Context, token string, channels MaxLenApprox: streamLen, Values: event.Encode(), } - err = es.client.XAdd(ctx, record).Err() - if err != nil { + if err = es.client.XAdd(ctx, record).Err(); err != nil { return schs, err } } @@ -207,8 +205,7 @@ func (es eventStore) Connect(ctx context.Context, token string, chIDs, thIDs []s MaxLenApprox: streamLen, Values: event.Encode(), } - err := es.client.XAdd(ctx, record).Err() - if err != nil { + if err := es.client.XAdd(ctx, record).Err(); err != nil { return err } } @@ -233,8 +230,7 @@ func (es eventStore) Disconnect(ctx context.Context, token string, chIDs, thIDs MaxLenApprox: streamLen, Values: event.Encode(), } - err := es.client.XAdd(ctx, record).Err() - if err != nil { + if err := es.client.XAdd(ctx, record).Err(); err != nil { return err } } diff --git a/tools/mqtt-bench/bench.go b/tools/mqtt-bench/bench.go index 254c91b153..570f100e39 100644 --- a/tools/mqtt-bench/bench.go +++ b/tools/mqtt-bench/bench.go @@ -14,14 +14,14 @@ import ( "strconv" "time" - mainflux_log "github.com/mainflux/mainflux/logger" + mf_log "github.com/mainflux/mainflux/logger" "github.com/pelletier/go-toml" ) // Benchmark - main benchmarking function func Benchmark(cfg Config) { checkConnection(cfg.MQTT.Broker.URL, 1) - logger, err := mainflux_log.New(os.Stdout, mainflux_log.Debug.String()) + logger, err := mf_log.New(os.Stdout, mf_log.Debug.String()) if err != nil { log.Fatalf(err.Error()) } From b40e835a221633a3a50efa4d83286ad80b5a9f27 Mon Sep 17 00:00:00 2001 From: aryan Date: Fri, 7 Apr 2023 18:46:15 +0530 Subject: [PATCH 18/26] fix setup_test Signed-off-by: aryan --- auth/api/grpc/setup_test.go | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/auth/api/grpc/setup_test.go b/auth/api/grpc/setup_test.go index cb9b5c71b7..5d767ba302 100644 --- a/auth/api/grpc/setup_test.go +++ b/auth/api/grpc/setup_test.go @@ -25,7 +25,7 @@ func TestMain(m *testing.M) { t := &testing.T{} serverErr := make(chan error) testRes := make(chan int) - done := make(chan int) + done := make(chan bool) endTest := make(chan int) svc = newService(t) @@ -35,14 +35,14 @@ func TestMain(m *testing.M) { server := grpc.NewServer() mainflux.RegisterAuthServiceServer(server, grpcapi.NewServer(mocktracer.New(), svc)) - go func(done chan int, endTest chan int, server *grpc.Server) { + go func(done chan bool, endTest chan int, server *grpc.Server) { for { select { case serverErr <- server.Serve(listener): close(serverErr) return - case code := <-done: - endTest <- code + case <-done: + return } } @@ -51,8 +51,7 @@ func TestMain(m *testing.M) { go func() { for { select { - case code := <-testRes: - done <- code + case <-testRes: return case err := <-serverErr: if err != nil { @@ -62,8 +61,8 @@ func TestMain(m *testing.M) { } }() - testRes <- m.Run() - code := <-endTest + code := m.Run() + testRes <- code server.Stop() From 27fd8c544ffd35cbc614d12f939daf0f634374c0 Mon Sep 17 00:00:00 2001 From: aryan Date: Sun, 9 Apr 2023 22:21:00 +0530 Subject: [PATCH 19/26] update setup_test grpc Signed-off-by: aryan --- auth/api/grpc/setup_test.go | 49 +++++++++++++++++------------- things/api/auth/grpc/setup_test.go | 38 ++++++++++++++--------- 2 files changed, 51 insertions(+), 36 deletions(-) diff --git a/auth/api/grpc/setup_test.go b/auth/api/grpc/setup_test.go index 5d767ba302..bfefa9fb12 100644 --- a/auth/api/grpc/setup_test.go +++ b/auth/api/grpc/setup_test.go @@ -17,36 +17,18 @@ import ( "github.com/mainflux/mainflux/auth/mocks" "github.com/mainflux/mainflux/pkg/uuid" "github.com/opentracing/opentracing-go/mocktracer" - "github.com/stretchr/testify/require" "google.golang.org/grpc" ) func TestMain(m *testing.M) { - t := &testing.T{} serverErr := make(chan error) testRes := make(chan int) done := make(chan bool) endTest := make(chan int) - svc = newService(t) - listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) - require.Nil(t, err, fmt.Sprintf("got unexpected error while creating new listerner: %s", err)) - - server := grpc.NewServer() - mainflux.RegisterAuthServiceServer(server, grpcapi.NewServer(mocktracer.New(), svc)) - - go func(done chan bool, endTest chan int, server *grpc.Server) { - for { - select { - case serverErr <- server.Serve(listener): - close(serverErr) - return - case <-done: - return - } + svc = newService() - } - }(done, endTest, server) + server := startGRPCServer(serverErr, done, endTest) go func() { for { @@ -72,7 +54,32 @@ func TestMain(m *testing.M) { os.Exit(code) } -func newService(t *testing.T) auth.Service { +func startGRPCServer(serverErr chan error, done chan bool, endTest chan int) *grpc.Server { + listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) + if err != nil { + log.Fatalf("got unexpected error while creating new listerner: %s", err) + } + + server := grpc.NewServer() + mainflux.RegisterAuthServiceServer(server, grpcapi.NewServer(mocktracer.New(), svc)) + + go func(done chan bool, endTest chan int, server *grpc.Server) { + for { + select { + case serverErr <- server.Serve(listener): + close(serverErr) + return + case <-done: + return + } + + } + }(done, endTest, server) + + return server +} + +func newService() auth.Service { repo := mocks.NewKeyRepository() groupRepo := mocks.NewGroupRepository() idProvider := uuid.NewMock() diff --git a/things/api/auth/grpc/setup_test.go b/things/api/auth/grpc/setup_test.go index f86cefe2e5..6377a0757e 100644 --- a/things/api/auth/grpc/setup_test.go +++ b/things/api/auth/grpc/setup_test.go @@ -16,7 +16,6 @@ import ( grpcapi "github.com/mainflux/mainflux/things/api/auth/grpc" "github.com/mainflux/mainflux/things/mocks" "github.com/opentracing/opentracing-go/mocktracer" - "github.com/stretchr/testify/assert" "google.golang.org/grpc" ) @@ -32,15 +31,15 @@ var svc things.Service func TestMain(m *testing.M) { serverErr := make(chan error) testRes := make(chan int) - done := make(chan int) + done := make(chan bool) + endTest := make(chan int) - startServer(&testing.T{}, serverErr, done) + server := startServer(serverErr, done, endTest) go func() { for { select { - case code := <-testRes: - done <- code + case <-testRes: return case err := <-serverErr: if err != nil { @@ -50,32 +49,41 @@ func TestMain(m *testing.M) { } }() - testRes <- m.Run() + code := m.Run() + testRes <- code + + server.Stop() + + close(serverErr) + close(done) + + os.Exit(code) } -func startServer(t *testing.T, serverErr chan error, done chan int) { +func startServer(serverErr chan error, done chan bool, endTest chan int) *grpc.Server { svc = newService(map[string]string{token: email}) listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) - assert.Nil(t, err, fmt.Sprintf("got unexpected error while creating new listener: %s", err)) + if err != nil { + log.Fatalf("got unexpected error while creating new listerner: %s", err) + } server := grpc.NewServer() mainflux.RegisterThingsServiceServer(server, grpcapi.NewServer(mocktracer.New(), svc)) - go func(done chan int, server *grpc.Server) { + go func(done chan bool, endTest chan int, server *grpc.Server) { for { select { case serverErr <- server.Serve(listener): close(serverErr) return - case code := <-done: - server.Stop() - close(serverErr) - close(done) - os.Exit(code) + case <-done: + return } } - }(done, server) + }(done, endTest, server) + + return server } func newService(tokens map[string]string) things.Service { From 90b745477677be264fbf8b05bdeb30d24492298e Mon Sep 17 00:00:00 2001 From: aryan Date: Sun, 9 Apr 2023 23:01:44 +0530 Subject: [PATCH 20/26] fix data race Signed-off-by: aryan --- auth/api/grpc/setup_test.go | 4 ---- things/api/auth/grpc/setup_test.go | 8 ++------ 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/auth/api/grpc/setup_test.go b/auth/api/grpc/setup_test.go index bfefa9fb12..cbd935b1f8 100644 --- a/auth/api/grpc/setup_test.go +++ b/auth/api/grpc/setup_test.go @@ -47,10 +47,6 @@ func TestMain(m *testing.M) { testRes <- code server.Stop() - - close(serverErr) - close(done) - os.Exit(code) } diff --git a/things/api/auth/grpc/setup_test.go b/things/api/auth/grpc/setup_test.go index 6377a0757e..591ee7f450 100644 --- a/things/api/auth/grpc/setup_test.go +++ b/things/api/auth/grpc/setup_test.go @@ -34,7 +34,7 @@ func TestMain(m *testing.M) { done := make(chan bool) endTest := make(chan int) - server := startServer(serverErr, done, endTest) + server := startGRPCServer(serverErr, done, endTest) go func() { for { @@ -53,14 +53,10 @@ func TestMain(m *testing.M) { testRes <- code server.Stop() - - close(serverErr) - close(done) - os.Exit(code) } -func startServer(serverErr chan error, done chan bool, endTest chan int) *grpc.Server { +func startGRPCServer(serverErr chan error, done chan bool, endTest chan int) *grpc.Server { svc = newService(map[string]string{token: email}) listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) if err != nil { From bf0fb2420446ced94a643558086fbf1682ad8b82 Mon Sep 17 00:00:00 2001 From: aryan Date: Wed, 12 Apr 2023 18:11:03 +0530 Subject: [PATCH 21/26] update setup_test grpc Signed-off-by: aryan --- auth/api/grpc/setup_test.go | 22 +++++++++------------- things/api/auth/grpc/setup_test.go | 20 +++++++++----------- 2 files changed, 18 insertions(+), 24 deletions(-) diff --git a/auth/api/grpc/setup_test.go b/auth/api/grpc/setup_test.go index cbd935b1f8..90a3aa4a6e 100644 --- a/auth/api/grpc/setup_test.go +++ b/auth/api/grpc/setup_test.go @@ -22,35 +22,32 @@ import ( func TestMain(m *testing.M) { serverErr := make(chan error) - testRes := make(chan int) - done := make(chan bool) - endTest := make(chan int) - + done := make(chan interface{}, 1) svc = newService() - - server := startGRPCServer(serverErr, done, endTest) + server := startGRPCServer(serverErr, done) go func() { for { select { - case <-testRes: + case <-done: return case err := <-serverErr: if err != nil { - log.Fatalf("gPRC Server Terminated") + log.Fatalln("gPRC Server Terminated : ", err) } } } }() code := m.Run() - testRes <- code + done <- true + done <- true server.Stop() os.Exit(code) } -func startGRPCServer(serverErr chan error, done chan bool, endTest chan int) *grpc.Server { +func startGRPCServer(serverErr chan error, done chan interface{}) *grpc.Server { listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) if err != nil { log.Fatalf("got unexpected error while creating new listerner: %s", err) @@ -59,18 +56,17 @@ func startGRPCServer(serverErr chan error, done chan bool, endTest chan int) *gr server := grpc.NewServer() mainflux.RegisterAuthServiceServer(server, grpcapi.NewServer(mocktracer.New(), svc)) - go func(done chan bool, endTest chan int, server *grpc.Server) { + go func(done chan interface{}, server *grpc.Server) { for { select { case serverErr <- server.Serve(listener): - close(serverErr) return case <-done: return } } - }(done, endTest, server) + }(done, server) return server } diff --git a/things/api/auth/grpc/setup_test.go b/things/api/auth/grpc/setup_test.go index 591ee7f450..7e5772559e 100644 --- a/things/api/auth/grpc/setup_test.go +++ b/things/api/auth/grpc/setup_test.go @@ -30,33 +30,32 @@ var svc things.Service func TestMain(m *testing.M) { serverErr := make(chan error) - testRes := make(chan int) - done := make(chan bool) - endTest := make(chan int) + done := make(chan interface{}, 1) - server := startGRPCServer(serverErr, done, endTest) + server := startGRPCServer(serverErr, done) go func() { for { select { - case <-testRes: + case <-done: return case err := <-serverErr: if err != nil { - log.Fatalf("gPRC Server Terminated") + log.Fatalln("gPRC Server Terminated : ", err) } } } }() code := m.Run() - testRes <- code + done <- true + done <- true server.Stop() os.Exit(code) } -func startGRPCServer(serverErr chan error, done chan bool, endTest chan int) *grpc.Server { +func startGRPCServer(serverErr chan error, done chan interface{}) *grpc.Server { svc = newService(map[string]string{token: email}) listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) if err != nil { @@ -66,18 +65,17 @@ func startGRPCServer(serverErr chan error, done chan bool, endTest chan int) *gr server := grpc.NewServer() mainflux.RegisterThingsServiceServer(server, grpcapi.NewServer(mocktracer.New(), svc)) - go func(done chan bool, endTest chan int, server *grpc.Server) { + go func(done chan interface{}, server *grpc.Server) { for { select { case serverErr <- server.Serve(listener): - close(serverErr) return case <-done: return } } - }(done, endTest, server) + }(done, server) return server } From 5ac65589179807eea4599bdd36b5572c97e2a66e Mon Sep 17 00:00:00 2001 From: aryan Date: Thu, 13 Apr 2023 03:26:53 +0530 Subject: [PATCH 22/26] fix grpc setup down to single simple function Signed-off-by: aryan --- auth/api/grpc/setup_test.go | 49 ++++++++--------------------- things/api/auth/grpc/setup_test.go | 50 ++++++++---------------------- 2 files changed, 26 insertions(+), 73 deletions(-) diff --git a/auth/api/grpc/setup_test.go b/auth/api/grpc/setup_test.go index 90a3aa4a6e..e490469f8b 100644 --- a/auth/api/grpc/setup_test.go +++ b/auth/api/grpc/setup_test.go @@ -22,53 +22,30 @@ import ( func TestMain(m *testing.M) { serverErr := make(chan error) - done := make(chan interface{}, 1) - svc = newService() - server := startGRPCServer(serverErr, done) - - go func() { - for { - select { - case <-done: - return - case err := <-serverErr: - if err != nil { - log.Fatalln("gPRC Server Terminated : ", err) - } - } - } - }() - - code := m.Run() - done <- true - done <- true - - server.Stop() - os.Exit(code) -} -func startGRPCServer(serverErr chan error, done chan interface{}) *grpc.Server { listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) if err != nil { log.Fatalf("got unexpected error while creating new listerner: %s", err) } + svc = newService() server := grpc.NewServer() mainflux.RegisterAuthServiceServer(server, grpcapi.NewServer(mocktracer.New(), svc)) - go func(done chan interface{}, server *grpc.Server) { - for { - select { - case serverErr <- server.Serve(listener): - return - case <-done: - return - } + // Start gRPC server in detached mode. + go func() { + serverErr <- server.Serve(listener) + }() - } - }(done, server) + code := m.Run() - return server + server.GracefulStop() + err = <-serverErr + if err != nil { + log.Fatalln("gPRC Server Terminated : ", err) + } + close(serverErr) + os.Exit(code) } func newService() auth.Service { diff --git a/things/api/auth/grpc/setup_test.go b/things/api/auth/grpc/setup_test.go index 7e5772559e..594f49195d 100644 --- a/things/api/auth/grpc/setup_test.go +++ b/things/api/auth/grpc/setup_test.go @@ -30,54 +30,30 @@ var svc things.Service func TestMain(m *testing.M) { serverErr := make(chan error) - done := make(chan interface{}, 1) - server := startGRPCServer(serverErr, done) - - go func() { - for { - select { - case <-done: - return - case err := <-serverErr: - if err != nil { - log.Fatalln("gPRC Server Terminated : ", err) - } - } - } - }() - - code := m.Run() - done <- true - done <- true - - server.Stop() - os.Exit(code) -} - -func startGRPCServer(serverErr chan error, done chan interface{}) *grpc.Server { - svc = newService(map[string]string{token: email}) listener, err := net.Listen("tcp", fmt.Sprintf(":%d", port)) if err != nil { log.Fatalf("got unexpected error while creating new listerner: %s", err) } + svc = newService(map[string]string{token: email}) server := grpc.NewServer() mainflux.RegisterThingsServiceServer(server, grpcapi.NewServer(mocktracer.New(), svc)) - go func(done chan interface{}, server *grpc.Server) { - for { - select { - case serverErr <- server.Serve(listener): - return - case <-done: - return - } + // Start gRPC server in detached mode. + go func() { + serverErr <- server.Serve(listener) + }() - } - }(done, server) + code := m.Run() - return server + server.GracefulStop() + err = <-serverErr + if err != nil { + log.Fatalln("gPRC Server Terminated : ", err) + } + close(serverErr) + os.Exit(code) } func newService(tokens map[string]string) things.Service { From e903ec35dafbb688984c7d198c45e21b65b38229 Mon Sep 17 00:00:00 2001 From: aryan Date: Thu, 13 Apr 2023 04:39:10 +0530 Subject: [PATCH 23/26] fix linting issues Signed-off-by: aryan --- auth/service_test.go | 1 + things/postgres/things.go | 3 --- tools/mqtt-bench/bench.go | 4 ++-- 3 files changed, 3 insertions(+), 5 deletions(-) diff --git a/auth/service_test.go b/auth/service_test.go index f0afbc6109..26fb12e305 100644 --- a/auth/service_test.go +++ b/auth/service_test.go @@ -15,6 +15,7 @@ import ( "github.com/mainflux/mainflux/pkg/errors" "github.com/mainflux/mainflux/pkg/uuid" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) var idProvider = uuid.New() diff --git a/things/postgres/things.go b/things/postgres/things.go index ddf91f4328..d021b5f025 100644 --- a/things/postgres/things.go +++ b/things/postgres/things.go @@ -161,9 +161,6 @@ func (tr thingRepository) RetrieveByID(ctx context.Context, owner, id string) (t } return things.Thing{}, errors.Wrap(errors.ErrViewEntity, err) } - fmt.Println() - fmt.Println(dbth) - fmt.Println() return toThing(dbth) } diff --git a/tools/mqtt-bench/bench.go b/tools/mqtt-bench/bench.go index 570f100e39..c5aafcd82c 100644 --- a/tools/mqtt-bench/bench.go +++ b/tools/mqtt-bench/bench.go @@ -14,14 +14,14 @@ import ( "strconv" "time" - mf_log "github.com/mainflux/mainflux/logger" + mflog "github.com/mainflux/mainflux/logger" "github.com/pelletier/go-toml" ) // Benchmark - main benchmarking function func Benchmark(cfg Config) { checkConnection(cfg.MQTT.Broker.URL, 1) - logger, err := mf_log.New(os.Stdout, mf_log.Debug.String()) + logger, err := mflog.New(os.Stdout, mflog.Debug.String()) if err != nil { log.Fatalf(err.Error()) } From ad060b6f9a908991d8ffdbc81bd777a9852c83b6 Mon Sep 17 00:00:00 2001 From: aryan Date: Sat, 15 Apr 2023 02:09:44 +0530 Subject: [PATCH 24/26] resolve pr comments Signed-off-by: aryan --- bootstrap/api/endpoint_test.go | 4 +--- bootstrap/redis/producer/streams_test.go | 4 ++-- bootstrap/service.go | 3 +-- scripts/ci.sh | 2 +- twins/api/http/endpoint_twins_test.go | 2 +- 5 files changed, 6 insertions(+), 9 deletions(-) diff --git a/bootstrap/api/endpoint_test.go b/bootstrap/api/endpoint_test.go index 162bfcc5c0..05965135f9 100644 --- a/bootstrap/api/endpoint_test.go +++ b/bootstrap/api/endpoint_test.go @@ -1159,9 +1159,7 @@ func TestBootstrap(t *testing.T) { assert.Nil(t, err, fmt.Sprintf("%s: unexpected error %s", tc.desc, err)) if tc.secure && tc.status == http.StatusOK { body, err = dec(body) - if err != nil { - assert.Nil(t, err, fmt.Sprintf("%s: unexpected error while decoding body: %s", tc.desc, err)) - } + assert.Nil(t, err, fmt.Sprintf("%s: unexpected error while decoding body: %s", tc.desc, err)) } data := strings.Trim(string(body), "\n") diff --git a/bootstrap/redis/producer/streams_test.go b/bootstrap/redis/producer/streams_test.go index 98dc033d73..4546c3c3f8 100644 --- a/bootstrap/redis/producer/streams_test.go +++ b/bootstrap/redis/producer/streams_test.go @@ -460,8 +460,8 @@ func TestBootstrap(t *testing.T) { lastID := "0" for _, tc := range cases { - _, errr := svc.Bootstrap(context.Background(), tc.externalKey, tc.externalID, false) - assert.True(t, errors.Contains(errr, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, errr)) + _, err = svc.Bootstrap(context.Background(), tc.externalKey, tc.externalID, false) + assert.True(t, errors.Contains(err, tc.err), fmt.Sprintf("%s: expected %s got %s\n", tc.desc, tc.err, err)) streams := redisClient.XRead(context.Background(), &redis.XReadArgs{ Streams: []string{streamID, lastID}, diff --git a/bootstrap/service.go b/bootstrap/service.go index 09a08bbca3..0c2d7011f0 100644 --- a/bootstrap/service.go +++ b/bootstrap/service.go @@ -273,8 +273,7 @@ func (bs bootstrapService) Remove(ctx context.Context, token, id string) error { func (bs bootstrapService) Bootstrap(ctx context.Context, externalKey, externalID string, secure bool) (Config, error) { cfg, err := bs.configs.RetrieveByExternalID(externalID) if err != nil { - err = errors.Wrap(ErrBootstrap, err) - return cfg, err + return cfg, errors.Wrap(ErrBootstrap, err) } if secure { dec, err := bs.dec(externalKey) diff --git a/scripts/ci.sh b/scripts/ci.sh index e2539e525f..669e053ece 100755 --- a/scripts/ci.sh +++ b/scripts/ci.sh @@ -4,7 +4,7 @@ GO_VERSION=1.19.4 PROTOC_VERSION=21.12 PROTOC_GEN_VERSION=v1.28.1 PROTOC_GRPC_VERSION=v1.2.0 -GOLANGCI_LINT_VERSION=v1.51.1 +GOLANGCI_LINT_VERSION=v1.52.1 function version_gt() { test "$(printf '%s\n' "$@" | sort -V | head -n 1)" != "$1"; } diff --git a/twins/api/http/endpoint_twins_test.go b/twins/api/http/endpoint_twins_test.go index 56d7202b97..e86282c172 100644 --- a/twins/api/http/endpoint_twins_test.go +++ b/twins/api/http/endpoint_twins_test.go @@ -392,7 +392,7 @@ func TestViewTwin(t *testing.T) { var resData twinRes err = json.NewDecoder(res.Body).Decode(&resData) - assert.Nil(t, err, fmt.Sprintf("%s: gotunexpected error while decoding response body: %s\n", tc.desc, err)) + assert.Nil(t, err, fmt.Sprintf("%s: got unexpected error while decoding response body: %s\n", tc.desc, err)) assert.Equal(t, tc.res, resData, fmt.Sprintf("%s: expected body %v got %v", tc.desc, tc.res, resData)) } } From 51bd182ca0c280010483bc59c146e2998422c283 Mon Sep 17 00:00:00 2001 From: aryan Date: Wed, 19 Apr 2023 02:13:55 +0530 Subject: [PATCH 25/26] fix tests, handle returned errors, go mod tidy vendor Signed-off-by: aryan --- auth/jwt/tokenizer.go | 3 +-- auth/postgres/groups.go | 2 +- auth/service.go | 1 - auth/service_test.go | 4 ++-- bootstrap/redis/producer/streams.go | 3 +-- bootstrap/redis/producer/streams_test.go | 4 ++-- cmd/certs/main.go | 22 +++++++++++++++------- go.mod | 3 +-- go.sum | 2 -- readers/cassandra/messages.go | 10 ++++------ readers/influxdb/messages.go | 2 +- readers/mocks/messages.go | 2 +- readers/mongodb/messages.go | 2 +- readers/postgres/messages.go | 2 +- readers/timescale/messages.go | 2 +- vendor/modules.txt | 2 -- 16 files changed, 32 insertions(+), 34 deletions(-) diff --git a/auth/jwt/tokenizer.go b/auth/jwt/tokenizer.go index 7409c65e7f..c39dd37784 100644 --- a/auth/jwt/tokenizer.go +++ b/auth/jwt/tokenizer.go @@ -90,10 +90,9 @@ func (c claims) toKey() auth.Key { IssuedAt: c.IssuedAt.Time.UTC(), } + key.ExpiresAt = time.Time{} if c.ExpiresAt != nil && c.ExpiresAt.Time.UTC().Unix() != 0 { key.ExpiresAt = c.ExpiresAt.Time.UTC() - } else { - key.ExpiresAt = time.Time{} } // Default type is 0. diff --git a/auth/postgres/groups.go b/auth/postgres/groups.go index 41f46ca3a4..7068156810 100644 --- a/auth/postgres/groups.go +++ b/auth/postgres/groups.go @@ -484,7 +484,7 @@ func (gr groupRepository) Unassign(ctx context.Context, groupID string, ids ...s if _, err := tx.NamedExecContext(ctx, qDel, dbg); err != nil { if rollbackErr := tx.Rollback(); rollbackErr != nil { - err = errors.Wrap(err, rollbackErr) + err = errors.Wrap(rollbackErr, err) return errors.Wrap(auth.ErrAssignToGroup, err) } diff --git a/auth/service.go b/auth/service.go index d47f2ac2b9..546ad4a786 100644 --- a/auth/service.go +++ b/auth/service.go @@ -108,7 +108,6 @@ func (svc service) Issue(ctx context.Context, token string, key Key) (Key, strin return Key{}, "", ErrInvalidKeyIssuedAt } switch key.Type { - case APIKey: return svc.userKey(ctx, token, key) case RecoveryKey: diff --git a/auth/service_test.go b/auth/service_test.go index 26fb12e305..e40e81c4ec 100644 --- a/auth/service_test.go +++ b/auth/service_test.go @@ -940,8 +940,8 @@ func TestAssign(t *testing.T) { // check access control policies things members. subjectSet := fmt.Sprintf("%s:%s#%s", "members", group.ID, memberRelation) - err = svc.Authorize(context.Background(), auth.PolicyReq{Object: mid, Relation: "read", Subject: subjectSet}) - assert.Nil(t, err, fmt.Sprintf("entites having an access to group %s must have %s policy on %s: %s", group.ID, "read", mid, err)) + err = svc.Authorize(context.Background(), auth.PolicyReq{Object: mid, Relation: read, Subject: subjectSet}) + assert.Nil(t, err, fmt.Sprintf("entites having an access to group %s must have %s policy on %s: %s", group.ID, read, mid, err)) err = svc.Authorize(context.Background(), auth.PolicyReq{Object: mid, Relation: "write", Subject: subjectSet}) assert.Nil(t, err, fmt.Sprintf("entites having an access to group %s must have %s policy on %s: %s", group.ID, "write", mid, err)) err = svc.Authorize(context.Background(), auth.PolicyReq{Object: mid, Relation: "delete", Subject: subjectSet}) diff --git a/bootstrap/redis/producer/streams.go b/bootstrap/redis/producer/streams.go index 784f250606..e44dee43eb 100644 --- a/bootstrap/redis/producer/streams.go +++ b/bootstrap/redis/producer/streams.go @@ -123,10 +123,9 @@ func (es eventStore) Bootstrap(ctx context.Context, externalKey, externalID stri if err != nil { ev.success = false - return cfg, err } + _ = es.add(ctx, ev) - err = es.add(ctx, ev) return cfg, err } diff --git a/bootstrap/redis/producer/streams_test.go b/bootstrap/redis/producer/streams_test.go index 4546c3c3f8..04cb2d150d 100644 --- a/bootstrap/redis/producer/streams_test.go +++ b/bootstrap/redis/producer/streams_test.go @@ -447,10 +447,10 @@ func TestBootstrap(t *testing.T) { { desc: "bootstrap with an error", externalID: saved.ExternalID, - externalKey: "external", + externalKey: "external_id", err: bootstrap.ErrExternalKey, event: map[string]interface{}{ - "external_id": "external", + "external_id": "external_id", "success": "0", "timestamp": time.Now().Unix(), "operation": thingBootstrap, diff --git a/cmd/certs/main.go b/cmd/certs/main.go index 93fdd36432..a5987653c3 100644 --- a/cmd/certs/main.go +++ b/cmd/certs/main.go @@ -169,15 +169,23 @@ func loadCertificates(conf config, logger mflog.Logger) (tls.Certificate, *x509. } block, _ := pem.Decode(b) - switch block { - case nil: + if block == nil { logger.Fatal("No PEM data found, failed to decode CA") - default: - caCert, err = x509.ParseCertificate(block.Bytes) - if err != nil { - return tlsCert, caCert, errors.Wrap(errFailedCertDecode, err) - } } + caCert, err = x509.ParseCertificate(block.Bytes) + if err != nil { + return tlsCert, caCert, errors.Wrap(errFailedCertDecode, err) + } + // switch block { + // case nil: + // logger.Fatal("No PEM data found, failed to decode CA") + // default: + // caCert, err = x509.ParseCertificate(block.Bytes) + // if err != nil { + // return tlsCert, caCert, errors.Wrap(errFailedCertDecode, err) + // } + // } + return tlsCert, caCert, nil } diff --git a/go.mod b/go.mod index aec15644b0..4fa4099653 100644 --- a/go.mod +++ b/go.mod @@ -15,7 +15,7 @@ require ( github.com/go-zoo/bone v1.3.0 github.com/gocql/gocql v1.2.1 github.com/gofrs/uuid v4.3.0+incompatible - github.com/golang-jwt/jwt/v5 v5.0.0-rc.1 + github.com/golang-jwt/jwt/v4 v4.5.0 github.com/golang/protobuf v1.5.2 github.com/gopcua/opcua v0.1.6 github.com/gorilla/websocket v1.5.0 @@ -76,7 +76,6 @@ require ( github.com/go-gorp/gorp/v3 v3.1.0 // indirect github.com/go-logfmt/logfmt v0.5.1 // indirect github.com/gogo/protobuf v1.3.2 // indirect - github.com/golang-jwt/jwt/v4 v4.5.0 // indirect github.com/golang/snappy v0.0.4 // indirect github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect github.com/hailocab/go-hostpool v0.0.0-20160125115350-e80d13ce29ed // indirect diff --git a/go.sum b/go.sum index 100474c2dc..05251b50d2 100644 --- a/go.sum +++ b/go.sum @@ -219,8 +219,6 @@ github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= -github.com/golang-jwt/jwt/v5 v5.0.0-rc.1 h1:tDQ1LjKga657layZ4JLsRdxgvupebc0xuPwRNuTfUgs= -github.com/golang-jwt/jwt/v5 v5.0.0-rc.1/go.mod h1:pqrtFR0X4osieyHYxtmOUWsAWrfe1Q5UVIyoH402zdk= github.com/golang-sql/civil v0.0.0-20190719163853-cb61b32ac6fe/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= github.com/golang/groupcache v0.0.0-20190702054246-869f871628b6/go.mod h1:cIg4eruTrX1D+g88fzRXU5OdNfaM+9IcxsU14FzY7Hc= diff --git a/readers/cassandra/messages.go b/readers/cassandra/messages.go index f0c2966505..ccf6f55595 100644 --- a/readers/cassandra/messages.go +++ b/readers/cassandra/messages.go @@ -74,10 +74,9 @@ func (cr cassandraRepository) ReadAll(chanID string, rpm readers.PageMetadata) ( case defTable: for scanner.Next() { var msg senml.Message - err := scanner.Scan(&msg.Channel, &msg.Subtopic, &msg.Publisher, &msg.Protocol, + if err := scanner.Scan(&msg.Channel, &msg.Subtopic, &msg.Publisher, &msg.Protocol, &msg.Name, &msg.Unit, &msg.Value, &msg.StringValue, &msg.BoolValue, - &msg.DataValue, &msg.Sum, &msg.Time, &msg.UpdateTime) - if err != nil { + &msg.DataValue, &msg.Sum, &msg.Time, &msg.UpdateTime); err != nil { if e, ok := err.(gocql.RequestError); ok { if e.Code() == undefinedTableCode { return readers.MessagesPage{}, nil @@ -90,8 +89,7 @@ func (cr cassandraRepository) ReadAll(chanID string, rpm readers.PageMetadata) ( default: for scanner.Next() { var msg jsonMessage - err := scanner.Scan(&msg.Channel, &msg.Subtopic, &msg.Publisher, &msg.Protocol, &msg.Created, &msg.Payload) - if err != nil { + if err := scanner.Scan(&msg.Channel, &msg.Subtopic, &msg.Publisher, &msg.Protocol, &msg.Created, &msg.Payload); err != nil { if e, ok := err.(gocql.RequestError); ok { if e.Code() == undefinedTableCode { return readers.MessagesPage{}, nil @@ -128,7 +126,7 @@ func buildQuery(chanID string, rpm readers.PageMetadata) (string, []interface{}) if err != nil { return condCQL, vals } - if err = json.Unmarshal(meta, &query); err != nil { + if err := json.Unmarshal(meta, &query); err != nil { return condCQL, vals } diff --git a/readers/influxdb/messages.go b/readers/influxdb/messages.go index 3d34b2aaad..f4f8eccf8d 100644 --- a/readers/influxdb/messages.go +++ b/readers/influxdb/messages.go @@ -119,8 +119,8 @@ func (repo *influxRepository) count(measurement, condition string, timeRange str measurement, condition) queryAPI := repo.client.QueryAPI(repo.cfg.Org) - resp, err := queryAPI.Query(context.Background(), cmd) + resp, err := queryAPI.Query(context.Background(), cmd) if err != nil { return 0, err } diff --git a/readers/mocks/messages.go b/readers/mocks/messages.go index feaeaeb732..ad6fb3b2c7 100644 --- a/readers/mocks/messages.go +++ b/readers/mocks/messages.go @@ -43,7 +43,7 @@ func (repo *messageRepositoryMock) ReadAll(chanID string, rpm readers.PageMetada if err != nil { return readers.MessagesPage{}, err } - if err = json.Unmarshal(meta, &query); err != nil { + if err := json.Unmarshal(meta, &query); err != nil { return readers.MessagesPage{}, err } diff --git a/readers/mongodb/messages.go b/readers/mongodb/messages.go index 3d27dad55a..37f847a660 100644 --- a/readers/mongodb/messages.go +++ b/readers/mongodb/messages.go @@ -101,7 +101,7 @@ func fmtCondition(chanID string, rpm readers.PageMetadata) bson.D { if err != nil { return filter } - if err = json.Unmarshal(meta, &query); err != nil { + if err := json.Unmarshal(meta, &query); err != nil { return filter } diff --git a/readers/postgres/messages.go b/readers/postgres/messages.go index c2e307be2a..9fe113c7b0 100644 --- a/readers/postgres/messages.go +++ b/readers/postgres/messages.go @@ -123,7 +123,7 @@ func fmtCondition(chanID string, rpm readers.PageMetadata) string { if err != nil { return condition } - if err = json.Unmarshal(meta, &query); err != nil { + if err := json.Unmarshal(meta, &query); err != nil { return condition } diff --git a/readers/timescale/messages.go b/readers/timescale/messages.go index 34a8d202a0..d1cd988dbe 100644 --- a/readers/timescale/messages.go +++ b/readers/timescale/messages.go @@ -121,7 +121,7 @@ func fmtCondition(chanID string, rpm readers.PageMetadata) string { if err != nil { return condition } - if err = json.Unmarshal(meta, &query); err != nil { + if err := json.Unmarshal(meta, &query); err != nil { return condition } diff --git a/vendor/modules.txt b/vendor/modules.txt index bbfe3730c8..6c6b7a8fd3 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -145,8 +145,6 @@ github.com/gogo/protobuf/proto # github.com/golang-jwt/jwt/v4 v4.5.0 ## explicit; go 1.16 github.com/golang-jwt/jwt/v4 -# github.com/golang-jwt/jwt/v5 v5.0.0-rc.1 -## explicit; go 1.18 # github.com/golang/protobuf v1.5.2 ## explicit; go 1.9 github.com/golang/protobuf/jsonpb From d121bd080f68a3d06c282dfc404a43badfbd1794 Mon Sep 17 00:00:00 2001 From: aryan Date: Thu, 20 Apr 2023 17:35:36 +0530 Subject: [PATCH 26/26] fix errors from new linters Signed-off-by: aryan --- auth/keys.go | 2 +- auth/postgres/groups_test.go | 2 +- auth/service.go | 4 ++-- bootstrap/postgres/configs_test.go | 2 +- certs/mocks/certs.go | 2 +- cli/config.go | 3 +-- cmd/certs/main.go | 9 --------- coap/client.go | 2 +- lora/adapter.go | 2 +- lora/message.go | 2 +- lora/redis/routemap.go | 6 +----- mqtt/redis/doc.go | 2 +- mqtt/redis/streams.go | 6 +----- opcua/db/subs.go | 2 +- pkg/auth/client.go | 2 +- pkg/messaging/nats/publisher.go | 6 +----- pkg/sdk/go/keys.go | 2 +- readers/influxdb/messages.go | 2 +- things/service.go | 2 +- tools/mqtt-bench/cmd/main.go | 4 ++-- twins/redis/twins.go | 2 +- users/service_test.go | 2 +- ws/adapter.go | 1 - 23 files changed, 23 insertions(+), 46 deletions(-) diff --git a/auth/keys.go b/auth/keys.go index 80c71565fc..4fa5d57700 100644 --- a/auth/keys.go +++ b/auth/keys.go @@ -22,7 +22,7 @@ var ( ) const ( - // LoginKey is temporary User key received on successfull login. + // LoginKey is temporary User key received on successful login. LoginKey uint32 = iota // RecoveryKey represents a key for resseting password. RecoveryKey diff --git a/auth/postgres/groups_test.go b/auth/postgres/groups_test.go index 39cf4a5cbb..e3db3aad11 100644 --- a/auth/postgres/groups_test.go +++ b/auth/postgres/groups_test.go @@ -154,7 +154,7 @@ func TestGroupRetrieveByID(t *testing.T) { require.Nil(t, err, fmt.Sprintf("got unexpected error: %s", err)) assert.True(t, retrieved.ID == group1.ID, fmt.Sprintf("Save group, ID: expected %s got %s\n", group1.ID, retrieved.ID)) - // Round to milliseconds as otherwise saving and retriving from DB + // Round to milliseconds as otherwise saving and retrieving from DB // adds rounding error. creationTime := time.Now().UTC().Round(time.Millisecond) group2 := auth.Group{ diff --git a/auth/service.go b/auth/service.go index 546ad4a786..46790e61aa 100644 --- a/auth/service.go +++ b/auth/service.go @@ -183,7 +183,7 @@ func (svc service) AddPolicies(ctx context.Context, token, object string, subjec for _, subjectID := range subjectIDs { for _, relation := range relations { if err := svc.AddPolicy(ctx, PolicyReq{Object: object, Relation: relation, Subject: subjectID}); err != nil { - errs = errors.Wrap(fmt.Errorf("cannot add '%s' policy on object '%s' for subject '%s': %s", relation, object, subjectID, err), errs) + errs = errors.Wrap(fmt.Errorf("cannot add '%s' policy on object '%s' for subject '%s': %w", relation, object, subjectID, err), errs) } } } @@ -209,7 +209,7 @@ func (svc service) DeletePolicies(ctx context.Context, token, object string, sub for _, subjectID := range subjectIDs { for _, relation := range relations { if err := svc.DeletePolicy(ctx, PolicyReq{Object: object, Relation: relation, Subject: subjectID}); err != nil { - errs = errors.Wrap(fmt.Errorf("cannot delete '%s' policy on object '%s' for subject '%s': %s", relation, object, subjectID, err), errs) + errs = errors.Wrap(fmt.Errorf("cannot delete '%s' policy on object '%s' for subject '%s': %w", relation, object, subjectID, err), errs) } } } diff --git a/bootstrap/postgres/configs_test.go b/bootstrap/postgres/configs_test.go index a546f60765..23ff366ccb 100644 --- a/bootstrap/postgres/configs_test.go +++ b/bootstrap/postgres/configs_test.go @@ -598,7 +598,7 @@ func TestRemoveThing(t *testing.T) { assert.Nil(t, err, fmt.Sprintf("Saving config expected to succeed: %s.\n", err)) for i := 0; i < 2; i++ { err := repo.RemoveThing(saved) - assert.Nil(t, err, fmt.Sprintf("an unexpected error occured: %s\n", err)) + assert.Nil(t, err, fmt.Sprintf("an unexpected error occurred: %s\n", err)) } } diff --git a/certs/mocks/certs.go b/certs/mocks/certs.go index 01f75af0fb..3a8f435ecb 100644 --- a/certs/mocks/certs.go +++ b/certs/mocks/certs.go @@ -43,7 +43,7 @@ func (c *certsRepoMock) Save(ctx context.Context, cert certs.Cert) (string, erro switch ok { case false: c.certsByThingID[cert.OwnerID] = map[string][]certs.Cert{ - cert.ThingID: []certs.Cert{crt}, + cert.ThingID: {crt}, } default: c.certsByThingID[cert.OwnerID][cert.ThingID] = append(c.certsByThingID[cert.OwnerID][cert.ThingID], crt) diff --git a/cli/config.go b/cli/config.go index 031e5f7514..ec7823f14b 100644 --- a/cli/config.go +++ b/cli/config.go @@ -2,7 +2,6 @@ package cli import ( "fmt" - "io/ioutil" "log" "os" @@ -19,7 +18,7 @@ type Config struct { // read - retrieve config from a file func read(file string) (Config, error) { - data, err := ioutil.ReadFile(file) + data, err := os.ReadFile(file) c := Config{} if err != nil { return c, errors.New(fmt.Sprintf("failed to read config file: %s", err)) diff --git a/cmd/certs/main.go b/cmd/certs/main.go index a5987653c3..dc73e4f395 100644 --- a/cmd/certs/main.go +++ b/cmd/certs/main.go @@ -177,15 +177,6 @@ func loadCertificates(conf config, logger mflog.Logger) (tls.Certificate, *x509. if err != nil { return tlsCert, caCert, errors.Wrap(errFailedCertDecode, err) } - // switch block { - // case nil: - // logger.Fatal("No PEM data found, failed to decode CA") - // default: - // caCert, err = x509.ParseCertificate(block.Bytes) - // if err != nil { - // return tlsCert, caCert, errors.Wrap(errFailedCertDecode, err) - // } - // } return tlsCert, caCert, nil } diff --git a/coap/client.go b/coap/client.go index d616bb6555..0b77085445 100644 --- a/coap/client.go +++ b/coap/client.go @@ -88,7 +88,7 @@ func (c *client) Handle(msg *messaging.Message) error { return errors.Wrap(ErrOption, err) } opts = append(opts, message.Option{ID: message.Observe, Value: []byte{byte(c.observe)}}) - opts, n, err = opts.SetObserve(buff, uint32(c.observe)) + opts, n, err = opts.SetObserve(buff, c.observe) if err == message.ErrTooSmall { buff = append(buff, make([]byte, n)...) opts, _, err = opts.SetObserve(buff, uint32(c.observe)) diff --git a/lora/adapter.go b/lora/adapter.go index 02a50aad3e..94c7c95c75 100644 --- a/lora/adapter.go +++ b/lora/adapter.go @@ -110,7 +110,7 @@ func (as *adapterService) Publish(ctx context.Context, m *Message) error { if err != nil { return err } - payload = []byte(jo) + payload = jo } // Publish on Mainflux Message broker diff --git a/lora/message.go b/lora/message.go index 0af42dce16..3ff7efff5e 100644 --- a/lora/message.go +++ b/lora/message.go @@ -15,7 +15,7 @@ type RxInfo []struct { // DataRate lora data rate type DataRate struct { Modulation string `json:"modulation"` - Bandwith float64 `json:"bandwith"` + Bandwidth float64 `json:"bandwidth"` SpreadFactor int64 `json:"spreadFactor"` } diff --git a/lora/redis/routemap.go b/lora/redis/routemap.go index f47679ba3b..5f4e38101f 100644 --- a/lora/redis/routemap.go +++ b/lora/redis/routemap.go @@ -33,11 +33,7 @@ func (mr *routerMap) Save(ctx context.Context, mfxID, loraID string) error { } lkey := fmt.Sprintf("%s:%s", mr.prefix, loraID) - if err := mr.client.Set(ctx, lkey, mfxID, 0).Err(); err != nil { - return err - } - - return nil + return mr.client.Set(ctx, lkey, mfxID, 0).Err() } func (mr *routerMap) Get(ctx context.Context, id string) (string, error) { diff --git a/mqtt/redis/doc.go b/mqtt/redis/doc.go index d7c75632f7..3b7b7486ae 100644 --- a/mqtt/redis/doc.go +++ b/mqtt/redis/doc.go @@ -3,4 +3,4 @@ // Package redis contains cache implementations using Redis as // the underlying database. -package redis \ No newline at end of file +package redis diff --git a/mqtt/redis/streams.go b/mqtt/redis/streams.go index 91eb2df38d..cac90e4818 100644 --- a/mqtt/redis/streams.go +++ b/mqtt/redis/streams.go @@ -52,11 +52,7 @@ func (es eventStore) storeEvent(clientID, eventType string) error { Values: event.Encode(), } - if err := es.client.XAdd(context.Background(), record).Err(); err != nil { - return err - } - - return nil + return es.client.XAdd(context.Background(), record).Err() } // Connect issues event on MQTT CONNECT diff --git a/opcua/db/subs.go b/opcua/db/subs.go index c92f534fe5..8094f3e0e2 100644 --- a/opcua/db/subs.go +++ b/opcua/db/subs.go @@ -28,7 +28,7 @@ type Node struct { NodeID string } -// Save stores a successfull subscription +// Save stores a successful subscription func Save(serverURI, nodeID string) error { file, err := os.OpenFile(path, os.O_CREATE|os.O_APPEND|os.O_WRONLY, os.ModePerm) if err != nil { diff --git a/pkg/auth/client.go b/pkg/auth/client.go index 6ff85b15a3..23757c2632 100644 --- a/pkg/auth/client.go +++ b/pkg/auth/client.go @@ -39,7 +39,7 @@ func (c client) Identify(ctx context.Context, thingKey string) (string, error) { thingID, err := c.redisClient.Get(ctx, tkey).Result() if err != nil { t := &mainflux.Token{ - Value: string(thingKey), + Value: thingKey, } thid, err := c.thingsClient.Identify(context.TODO(), t) diff --git a/pkg/messaging/nats/publisher.go b/pkg/messaging/nats/publisher.go index b07eb8c5d9..492fa84ad3 100644 --- a/pkg/messaging/nats/publisher.go +++ b/pkg/messaging/nats/publisher.go @@ -53,11 +53,7 @@ func (pub *publisher) Publish(ctx context.Context, topic string, msg *messaging. subject = fmt.Sprintf("%s.%s", subject, msg.Subtopic) } - if err := pub.conn.Publish(subject, data); err != nil { - return err - } - - return nil + return pub.conn.Publish(subject, data) } func (pub *publisher) Close() error { diff --git a/pkg/sdk/go/keys.go b/pkg/sdk/go/keys.go index 64a9d75705..a768709e57 100644 --- a/pkg/sdk/go/keys.go +++ b/pkg/sdk/go/keys.go @@ -20,7 +20,7 @@ type keyReq struct { const keysEndpoint = "keys" const ( - // LoginKey is temporary User key received on successfull login. + // LoginKey is temporary User key received on successful login. LoginKey uint32 = iota // RecoveryKey represents a key for resseting password. RecoveryKey diff --git a/readers/influxdb/messages.go b/readers/influxdb/messages.go index f4f8eccf8d..6e553ed1f9 100644 --- a/readers/influxdb/messages.go +++ b/readers/influxdb/messages.go @@ -168,7 +168,7 @@ func fmtCondition(chanID string, rpm readers.PageMetadata) (string, string) { toValue := int64(value.(float64) * 1e9) to = fmt.Sprintf(`, stop: time(v: %d )`, toValue) } - // timeRange returned seperately because + // timeRange returned separately because // in FluxQL time range must be at the // beginning of the query. timeRange = fmt.Sprintf(`|> range(%s %s)`, from, to) diff --git a/things/service.go b/things/service.go index ef98c2da3c..990757e7ee 100644 --- a/things/service.go +++ b/things/service.go @@ -244,7 +244,7 @@ func (ts *thingsService) claimOwnership(ctx context.Context, objectID string, ac for _, action := range actions { apr, err := ts.auth.AddPolicy(ctx, &mainflux.AddPolicyReq{Obj: objectID, Act: action, Sub: userID}) if err != nil { - errs = errors.Wrap(fmt.Errorf("cannot claim ownership on object '%s' by user '%s': %s", objectID, userID, err), errs) + errs = errors.Wrap(fmt.Errorf("cannot claim ownership on object '%s' by user '%s': %w", objectID, userID, err), errs) } if !apr.GetAuthorized() { errs = errors.Wrap(fmt.Errorf("cannot claim ownership on object '%s' by user '%s': unauthorized", objectID, userID), errs) diff --git a/tools/mqtt-bench/cmd/main.go b/tools/mqtt-bench/cmd/main.go index bca3371420..fd47bcbb81 100644 --- a/tools/mqtt-bench/cmd/main.go +++ b/tools/mqtt-bench/cmd/main.go @@ -19,7 +19,7 @@ func main() { var rootCmd = &cobra.Command{ Use: "mqtt-bench", Short: "mqtt-bench is MQTT benchmark tool for Mainflux", - Long: `Tool for exctensive load and benchmarking of MQTT brokers used withing Mainflux platform. + Long: `Tool for exctensive load and benchmarking of MQTT brokers used within the Mainflux platform. Complete documentation is available at https://docs.mainflux.io`, Run: func(cmd *cobra.Command, args []string) { if confFile != "" { @@ -62,7 +62,7 @@ Complete documentation is available at https://docs.mainflux.io`, rootCmd.PersistentFlags().IntVarP(&bconf.Test.Pubs, "pubs", "p", 10, "Number of publishers") // Log params - rootCmd.PersistentFlags().BoolVarP(&bconf.Log.Quiet, "quiet", "", false, "Supress messages") + rootCmd.PersistentFlags().BoolVarP(&bconf.Log.Quiet, "quiet", "", false, "Suppress messages") // Config file rootCmd.PersistentFlags().StringVarP(&confFile, "config", "c", "config.toml", "config file for mqtt-bench") diff --git a/twins/redis/twins.go b/twins/redis/twins.go index 6d13002fed..406a72bf79 100644 --- a/twins/redis/twins.go +++ b/twins/redis/twins.go @@ -23,7 +23,7 @@ var ( // ErrRedisTwinUpdate indicates error while saving Twin in redis cache ErrRedisTwinUpdate = errors.New("failed to update twin in redis cache") - // ErrRedisTwinIDs indicates error while geting Twin IDs from redis cache + // ErrRedisTwinIDs indicates error while getting Twin IDs from redis cache ErrRedisTwinIDs = errors.New("failed to get twin id from redis cache") // ErrRedisTwinRemove indicates error while removing Twin from redis cache diff --git a/users/service_test.go b/users/service_test.go index 3fd458b4be..dbc98fcb65 100644 --- a/users/service_test.go +++ b/users/service_test.go @@ -273,7 +273,7 @@ func TestListUsers(t *testing.T) { err: errors.ErrAuthorization, }, { - desc: "list user with emtpy token", + desc: "list user with empty token", token: "", size: 0, err: errors.ErrAuthentication, diff --git a/ws/adapter.go b/ws/adapter.go index fe706f1c99..23a70a4474 100644 --- a/ws/adapter.go +++ b/ws/adapter.go @@ -3,7 +3,6 @@ // Package ws contains the domain concept definitions needed to support // Mainflux ws adapter service functionality - package ws import (