Skip to content

Commit

Permalink
Added support for jwt secret creation of each user upon user login (#…
Browse files Browse the repository at this point in the history
…4719)

* Added support for jwt secret creation of each user upon logic

Signed-off-by: Saranya-jena <saranya.jena@harness.io>

* Fixed imports

Signed-off-by: Saranya-jena <saranya.jena@harness.io>

* Add fixes in dex service

Signed-off-by: Saranya-jena <saranya.jena@harness.io>

* Fixed UTs

Signed-off-by: Saranya-jena <saranya.jena@harness.io>

* resolved comments

Signed-off-by: Saranya-jena <saranya.jena@harness.io>

* updated logic

Signed-off-by: Saranya-jena <saranya.jena@harness.io>

* fixed UTs and removed unecessary test cases

Signed-off-by: Saranya-jena <saranya.jena@harness.io>

* fixed imports

Signed-off-by: Saranya-jena <saranya.jena@harness.io>

* fixed imports

Signed-off-by: Saranya-jena <saranya.jena@harness.io>

* resolved comments

Signed-off-by: Saranya-jena <saranya.jena@harness.io>

* fixed imports

Signed-off-by: Saranya-jena <saranya.jena@harness.io>

* resolved comments

Signed-off-by: Saranya-jena <saranya.jena@harness.io>

* added server endpoint in allowed origins

Signed-off-by: Saranya-jena <saranya.jena@harness.io>

* fixed imports

Signed-off-by: Saranya-jena <saranya.jena@harness.io>

* minor chnages

Signed-off-by: Saranya-jena <saranya.jena@harness.io>

* minor chnages

Signed-off-by: Saranya-jena <saranya.jena@harness.io>

* fixed imports

Signed-off-by: Saranya-jena <saranya.jena@harness.io>

---------

Signed-off-by: Saranya-jena <saranya.jena@harness.io>
  • Loading branch information
Saranya-jena committed Jul 5, 2024
1 parent fb46bb9 commit 9d58d8b
Show file tree
Hide file tree
Showing 38 changed files with 455 additions and 270 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,15 @@ func DexCallback(userService services.ApplicationService) gin.HandlerFunc {
c.JSON(utils.ErrorStatusCodes[utils.ErrServerError], presenter.CreateErrorResponse(utils.ErrServerError))
return
}
jwtToken, err := userService.GetSignedJWT(signedInUser)

salt, err := userService.GetConfig("salt")
if err != nil {
log.Error(err)
c.JSON(utils.ErrorStatusCodes[utils.ErrServerError], presenter.CreateErrorResponse(utils.ErrServerError))
return
}

jwtToken, err := userService.GetSignedJWT(signedInUser, salt.Value)
if err != nil {
log.Error(err)
c.JSON(utils.ErrorStatusCodes[utils.ErrServerError], presenter.CreateErrorResponse(utils.ErrServerError))
Expand Down
11 changes: 8 additions & 3 deletions chaoscenter/authentication/api/handlers/rest/user_handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,11 @@ import (
"strings"
"time"

"github.com/litmuschaos/litmus/chaoscenter/authentication/pkg/validations"

"github.com/litmuschaos/litmus/chaoscenter/authentication/api/presenter"
"github.com/litmuschaos/litmus/chaoscenter/authentication/pkg/entities"
"github.com/litmuschaos/litmus/chaoscenter/authentication/pkg/services"
"github.com/litmuschaos/litmus/chaoscenter/authentication/pkg/utils"
"github.com/litmuschaos/litmus/chaoscenter/authentication/pkg/validations"

"github.com/gin-gonic/gin"
"github.com/google/uuid"
Expand Down Expand Up @@ -305,7 +304,13 @@ func LoginUser(service services.ApplicationService) gin.HandlerFunc {
return
}

token, err := service.GetSignedJWT(user)
salt, err := service.GetConfig("salt")
if err != nil {
c.JSON(utils.ErrorStatusCodes[utils.ErrServerError], presenter.CreateErrorResponse(utils.ErrServerError))
return
}

token, err := service.GetSignedJWT(user, salt.Value)
if err != nil {
log.Error(err)
c.JSON(utils.ErrorStatusCodes[utils.ErrServerError], presenter.CreateErrorResponse(utils.ErrServerError))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import (
"strings"
"testing"

"github.com/litmuschaos/litmus/chaoscenter/authentication/pkg/authConfig"

"go.mongodb.org/mongo-driver/bson/primitive"

"github.com/gin-gonic/gin"
Expand Down Expand Up @@ -408,9 +410,11 @@ func TestLoginUser(t *testing.T) {
Password: "hashedPassword",
Email: "test@example.com",
}
service.On("GetConfig", "salt").Return(&authConfig.AuthConfig{}, nil)
service.On("FindUserByUsername", "testUser").Return(userFromDB, nil)
service.On("CheckPasswordHash", "hashedPassword", "testPassword").Return(nil)
service.On("GetSignedJWT", userFromDB).Return("someJWTToken", nil)
service.On("UpdateUserByQuery", mock.Anything, mock.Anything).Return(nil)
service.On("GetSignedJWT", userFromDB, mock.Anything).Return("someJWTToken", nil)
project := &entities.Project{
ID: "someProjectID",
}
Expand Down
44 changes: 44 additions & 0 deletions chaoscenter/authentication/api/handlers/salt.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
package response

import (
"encoding/base64"

"github.com/litmuschaos/litmus/chaoscenter/authentication/pkg/authConfig"
"github.com/litmuschaos/litmus/chaoscenter/authentication/pkg/services"
"github.com/litmuschaos/litmus/chaoscenter/authentication/pkg/utils"
log "github.com/sirupsen/logrus"
"go.mongodb.org/mongo-driver/mongo"
)

func AddSalt(service services.ApplicationService) error {
// generate salt and add/update to user collection
// pass the salt in the below func which will act as jwt secret
getSalt, err := service.GetConfig("salt")
if err != nil && err != mongo.ErrNoDocuments {
log.Error(err)
return err
}
if getSalt != nil {
return nil
}

salt, err := utils.RandomString(6)
if err != nil {
log.Error(err)
return err
}
encodedSalt := base64.StdEncoding.EncodeToString([]byte(salt))

config := authConfig.AuthConfig{
Key: "salt",
Value: encodedSalt,
}

err = service.CreateConfig(config)
if err != nil {
log.Error(err)
return err
}

return nil
}
21 changes: 19 additions & 2 deletions chaoscenter/authentication/api/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import (
"runtime"
"time"

response "github.com/litmuschaos/litmus/chaoscenter/authentication/api/handlers"
"github.com/litmuschaos/litmus/chaoscenter/authentication/pkg/authConfig"

grpcHandler "github.com/litmuschaos/litmus/chaoscenter/authentication/api/handlers/grpc"
"github.com/litmuschaos/litmus/chaoscenter/authentication/api/middleware"
grpcPresenter "github.com/litmuschaos/litmus/chaoscenter/authentication/api/presenter/protos"
Expand Down Expand Up @@ -82,6 +85,12 @@ func main() {
log.Errorf("failed to create collection %s", err)
}

// Creating AuthConfig Collection
err = utils.CreateCollection(utils.AuthConfigCollection, db)
if err != nil {
log.Errorf("failed to create collection %s", err)
}

// Creating RevokedToken Collection
if err = utils.CreateCollection(utils.RevokedTokenCollection, db); err != nil {
log.Errorf("failed to create collection %s", err)
Expand All @@ -108,9 +117,17 @@ func main() {
apiTokenCollection := db.Collection(utils.ApiTokenCollection)
apiTokenRepo := session.NewApiTokenRepo(apiTokenCollection)

authConfigCollection := db.Collection(utils.AuthConfigCollection)
authConfigRepo := authConfig.NewAuthConfigRepo(authConfigCollection)

miscRepo := misc.NewRepo(db, client)

applicationService := services.NewService(userRepo, projectRepo, miscRepo, revokedTokenRepo, apiTokenRepo, db)
applicationService := services.NewService(userRepo, projectRepo, miscRepo, revokedTokenRepo, apiTokenRepo, authConfigRepo, db)

err = response.AddSalt(applicationService)
if err != nil {
log.Fatal("couldn't create salt $s", err)
}

validatedAdminSetup(applicationService)

Expand Down Expand Up @@ -163,10 +180,10 @@ func runRestServer(applicationService services.ApplicationService) {
if utils.DexEnabled {
routes.DexRouter(app, applicationService)
}
routes.CapabilitiesRouter(app)
routes.MiscRouter(app, applicationService)
routes.UserRouter(app, applicationService)
routes.ProjectRouter(app, applicationService)
routes.CapabilitiesRouter(app)

log.Infof("Listening and serving HTTP on %s", utils.Port)
err := app.Run(utils.Port)
Expand Down
26 changes: 24 additions & 2 deletions chaoscenter/authentication/api/mocks/rest_mocks.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package mocks
import (
"context"

"github.com/litmuschaos/litmus/chaoscenter/authentication/pkg/authConfig"

"github.com/golang-jwt/jwt"
"github.com/litmuschaos/litmus/chaoscenter/authentication/pkg/entities"
"github.com/stretchr/testify/mock"
Expand Down Expand Up @@ -70,6 +72,11 @@ func (m *MockedApplicationService) UpdateUser(user *entities.UserDetails) error
return args.Error(0)
}

func (m *MockedApplicationService) UpdateUserByQuery(filter bson.D, updateQuery bson.D) error {
args := m.Called(filter, updateQuery)
return args.Error(0)
}

func (m *MockedApplicationService) UpdateUserState(ctx context.Context, username string, isDeactivate bool, deactivateTime int64) error {
args := m.Called(ctx, username, isDeactivate, deactivateTime)
return args.Error(0)
Expand Down Expand Up @@ -160,8 +167,8 @@ func (m *MockedApplicationService) ValidateToken(encodedToken string) (*jwt.Toke
return args.Get(0).(*jwt.Token), args.Error(1)
}

func (m *MockedApplicationService) GetSignedJWT(user *entities.User) (string, error) {
args := m.Called(user)
func (m *MockedApplicationService) GetSignedJWT(user *entities.User, jwtSecret string) (string, error) {
args := m.Called(user, jwtSecret)
return args.String(0), args.Error(1)
}

Expand Down Expand Up @@ -199,3 +206,18 @@ func (m *MockedApplicationService) RbacValidator(userID, resourceID string, rule
args := m.Called(userID, resourceID, rules, invitationStatus)
return args.Error(0)
}

func (m *MockedApplicationService) CreateConfig(config authConfig.AuthConfig) error {
args := m.Called(config)
return args.Error(0)
}

func (m *MockedApplicationService) GetConfig(key string) (*authConfig.AuthConfig, error) {
args := m.Called(key)
return args.Get(0).(*authConfig.AuthConfig), args.Error(1)
}

func (m *MockedApplicationService) UpdateConfig(ctx context.Context, key string, value interface{}) error {
args := m.Called(ctx, key, value)
return args.Error(0)
}
67 changes: 67 additions & 0 deletions chaoscenter/authentication/pkg/authConfig/repository.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package authConfig

import (
"context"
"encoding/base64"

"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
)

type Repository interface {
CreateConfig(config AuthConfig) error
GetConfig(key string) (*AuthConfig, error)
UpdateConfig(ctx context.Context, key string, value interface{}) error
}

type repository struct {
Collection *mongo.Collection
}

func (r repository) CreateConfig(config AuthConfig) error {
_, err := r.Collection.InsertOne(context.Background(), config)
if err != nil {
return err
}

return nil
}

func (r repository) GetConfig(key string) (*AuthConfig, error) {
results := r.Collection.FindOne(context.Background(), bson.D{
{"key", key},
})

var config AuthConfig
err := results.Decode(&config)
if err != nil {
return nil, err
}
decodedValue, err := base64.URLEncoding.DecodeString(config.Value)
if err != nil {
return nil, err
}
config.Value = string(decodedValue)
return &config, nil
}

func (r repository) UpdateConfig(ctx context.Context, key string, value interface{}) error {
query := bson.D{
{"key", key},
}
update := bson.D{{"$set", bson.D{{
"value", value}},
}}
_, err := r.Collection.UpdateOne(ctx, query, update)
if err != nil {
return err
}
return nil
}

// NewAuthConfigRepo creates a new instance of this repository
func NewAuthConfigRepo(collection *mongo.Collection) Repository {
return &repository{
Collection: collection,
}
}
6 changes: 6 additions & 0 deletions chaoscenter/authentication/pkg/authConfig/schema.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package authConfig

type AuthConfig struct {
Key string `bson:"key"`
Value string `bson:"value"`
}
1 change: 1 addition & 0 deletions chaoscenter/authentication/pkg/entities/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ type User struct {
ID string `bson:"_id,omitempty" json:"userID"`
Username string `bson:"username,omitempty" json:"username"`
Password string `bson:"password,omitempty" json:"password,omitempty"`
Salt string `bson:"salt" json:"salt"`
Email string `bson:"email,omitempty" json:"email,omitempty"`
Name string `bson:"name,omitempty" json:"name,omitempty"`
Role Role `bson:"role,omitempty" json:"role"`
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package services

import (
authConfig2 "github.com/litmuschaos/litmus/chaoscenter/authentication/pkg/authConfig"
"github.com/litmuschaos/litmus/chaoscenter/authentication/pkg/misc"
"github.com/litmuschaos/litmus/chaoscenter/authentication/pkg/project"
"github.com/litmuschaos/litmus/chaoscenter/authentication/pkg/session"
Expand All @@ -14,6 +15,7 @@ type ApplicationService interface {
transactionService
miscService
sessionService
authConfigService
}

type applicationService struct {
Expand All @@ -22,17 +24,19 @@ type applicationService struct {
miscRepository misc.Repository
revokedTokenRepository session.RevokedTokenRepository
apiTokenRepository session.ApiTokenRepository
authConfigRepo authConfig2.Repository
db *mongo.Database
}

// NewService creates a new instance of this service
func NewService(userRepo user.Repository, projectRepo project.Repository, miscRepo misc.Repository, revokedTokenRepo session.RevokedTokenRepository, apiTokenRepo session.ApiTokenRepository, db *mongo.Database) ApplicationService {
func NewService(userRepo user.Repository, projectRepo project.Repository, miscRepo misc.Repository, revokedTokenRepo session.RevokedTokenRepository, apiTokenRepo session.ApiTokenRepository, authConfigRepo authConfig2.Repository, db *mongo.Database) ApplicationService {
return &applicationService{
userRepository: userRepo,
projectRepository: projectRepo,
revokedTokenRepository: revokedTokenRepo,
apiTokenRepository: apiTokenRepo,
db: db,
authConfigRepo: authConfigRepo,
miscRepository: miscRepo,
}
}
25 changes: 25 additions & 0 deletions chaoscenter/authentication/pkg/services/auth_config_service.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package services

import (
"context"

"github.com/litmuschaos/litmus/chaoscenter/authentication/pkg/authConfig"
)

type authConfigService interface {
CreateConfig(config authConfig.AuthConfig) error
GetConfig(key string) (*authConfig.AuthConfig, error)
UpdateConfig(ctx context.Context, key string, value interface{}) error
}

func (a applicationService) CreateConfig(config authConfig.AuthConfig) error {
return a.authConfigRepo.CreateConfig(config)
}

func (a applicationService) GetConfig(key string) (*authConfig.AuthConfig, error) {
return a.authConfigRepo.GetConfig(key)
}

func (a applicationService) UpdateConfig(ctx context.Context, key string, value interface{}) error {
return a.authConfigRepo.UpdateConfig(ctx, key, value)
}
Loading

0 comments on commit 9d58d8b

Please sign in to comment.