diff --git a/chaoscenter/authentication/go.sum b/chaoscenter/authentication/go.sum index 2b3ba537a..271fe212c 100644 --- a/chaoscenter/authentication/go.sum +++ b/chaoscenter/authentication/go.sum @@ -131,6 +131,8 @@ golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ss golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.17.0 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA= golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= +golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic= +golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= diff --git a/chaoscenter/graphql/server/graph/environment.resolvers.go b/chaoscenter/graphql/server/graph/environment.resolvers.go index 7cbfdd03e..883bd54b2 100644 --- a/chaoscenter/graphql/server/graph/environment.resolvers.go +++ b/chaoscenter/graphql/server/graph/environment.resolvers.go @@ -13,7 +13,7 @@ import ( ) // CreateEnvironment is the resolver for the createEnvironment field. -func (r *mutationResolver) CreateEnvironment(ctx context.Context, projectID string, request *model.CreateEnvironmentRequest) (*model.Environment, error) { +func (r *mutationResolver) CreateEnvironment(ctx context.Context, projectID string, request *model.CreateEnvironmentRequest, authConfigOperator *authorization.Operator) (*model.Environment, error) { logFields := logrus.Fields{ "projectId": projectID, } @@ -26,7 +26,7 @@ func (r *mutationResolver) CreateEnvironment(ctx context.Context, projectID stri } tkn := ctx.Value(authorization.AuthKey).(string) - username, err := authorization.GetUsername(tkn) + username, err := authConfigOperator.GetUsername(tkn) if err != nil { return nil, err } @@ -35,7 +35,7 @@ func (r *mutationResolver) CreateEnvironment(ctx context.Context, projectID stri } // UpdateEnvironment is the resolver for the updateEnvironment field. -func (r *mutationResolver) UpdateEnvironment(ctx context.Context, projectID string, request *model.UpdateEnvironmentRequest) (string, error) { +func (r *mutationResolver) UpdateEnvironment(ctx context.Context, projectID string, request *model.UpdateEnvironmentRequest, authConfigOperator *authorization.Operator) (string, error) { logFields := logrus.Fields{ "projectId": projectID, "environmentId": request.EnvironmentID, @@ -49,7 +49,7 @@ func (r *mutationResolver) UpdateEnvironment(ctx context.Context, projectID stri } tkn := ctx.Value(authorization.AuthKey).(string) - username, err := authorization.GetUsername(tkn) + username, err := authConfigOperator.GetUsername(tkn) if err != nil { return "", err } @@ -58,7 +58,7 @@ func (r *mutationResolver) UpdateEnvironment(ctx context.Context, projectID stri } // DeleteEnvironment is the resolver for the deleteEnvironment field. -func (r *mutationResolver) DeleteEnvironment(ctx context.Context, projectID string, environmentID string) (string, error) { +func (r *mutationResolver) DeleteEnvironment(ctx context.Context, projectID string, environmentID string, authConfigOperator *authorization.Operator) (string, error) { logFields := logrus.Fields{ "projectId": projectID, "environmentId": environmentID, @@ -72,7 +72,7 @@ func (r *mutationResolver) DeleteEnvironment(ctx context.Context, projectID stri } tkn := ctx.Value(authorization.AuthKey).(string) - username, err := authorization.GetUsername(tkn) + username, err := authConfigOperator.GetUsername(tkn) if err != nil { return "", err } diff --git a/chaoscenter/graphql/server/pkg/authorization/authorization_fuzz_test.go b/chaoscenter/graphql/server/pkg/authorization/authorization_fuzz_test.go index 2df965d78..745b7585c 100644 --- a/chaoscenter/graphql/server/pkg/authorization/authorization_fuzz_test.go +++ b/chaoscenter/graphql/server/pkg/authorization/authorization_fuzz_test.go @@ -58,6 +58,7 @@ func generateJWTTokenFromClaims(claims jwt.MapClaims) (string, error) { } func FuzzUserValidateJWT(f *testing.F) { + operator := &Operator{} f.Fuzz(func(t *testing.T, data []byte) { fuzzConsumer := fuzz.NewConsumer(data) inputClaims := &jwt.MapClaims{} @@ -72,7 +73,7 @@ func FuzzUserValidateJWT(f *testing.F) { } // Run the test with the generated JWT token - claims, err := UserValidateJWT(tokenString, "") + claims, err := operator.UserValidateJWT(tokenString, "") if err != nil { t.Errorf("Error encountered: %v", err) } diff --git a/chaoscenter/graphql/server/pkg/authorization/user_jwt.go b/chaoscenter/graphql/server/pkg/authorization/user_jwt.go index 500dbf3ab..4003f05ff 100644 --- a/chaoscenter/graphql/server/pkg/authorization/user_jwt.go +++ b/chaoscenter/graphql/server/pkg/authorization/user_jwt.go @@ -12,8 +12,18 @@ import ( "github.com/golang-jwt/jwt" ) +type Operator struct { + authConfigOperator *authConfig.Operator +} + +func NewAuthorizationOperator(mongodbOperator mongodb.MongoOperator) *Operator { + return &Operator{ + authConfigOperator: authConfig.NewAuthConfigOperator(mongodbOperator), + } +} + // UserValidateJWT validates the cluster jwt -func UserValidateJWT(token string, salt string) (jwt.MapClaims, error) { +func (o *Operator) UserValidateJWT(token string, salt string) (jwt.MapClaims, error) { tkn, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) { if _, isValid := token.Method.(*jwt.SigningMethodHMAC); !isValid { return nil, fmt.Errorf("invalid token %s", token.Header["alg"]) @@ -39,8 +49,8 @@ func UserValidateJWT(token string, salt string) (jwt.MapClaims, error) { } // GetUsername returns the username from the jwt token -func GetUsername(token string) (string, error) { - salt, err := authConfig.NewAuthConfigOperator(mongodb.Operator).GetAuthConfig(context.Background()) +func (o *Operator) GetUsername(token string) (string, error) { + salt, err := o.authConfigOperator.GetAuthConfig(context.Background()) if err != nil { return "", err } diff --git a/chaoscenter/graphql/server/pkg/chaos_experiment/handler/handler.go b/chaoscenter/graphql/server/pkg/chaos_experiment/handler/handler.go index 6c18a5f94..64d129b00 100644 --- a/chaoscenter/graphql/server/pkg/chaos_experiment/handler/handler.go +++ b/chaoscenter/graphql/server/pkg/chaos_experiment/handler/handler.go @@ -1361,7 +1361,7 @@ func (c *ChaosExperimentHandler) GetProbesInExperimentRun(ctx context.Context, p } for _, probeName := range _probe.ProbeNames { - singleProbe, err := dbSchemaProbe.NewChaosProbeOperator(c.mongodbOperator).GetProbeByName(ctx, probeName, projectID) + singleProbe, err := dbSchemaProbe.NewProbeOperator(c.mongodbOperator).GetProbeByName(ctx, probeName, projectID) if err != nil { return nil, err } diff --git a/chaoscenter/graphql/server/pkg/chaos_experiment/ops/service_test.go b/chaoscenter/graphql/server/pkg/chaos_experiment/ops/service_test.go index 71bd89da8..6e4e1dbfa 100644 --- a/chaoscenter/graphql/server/pkg/chaos_experiment/ops/service_test.go +++ b/chaoscenter/graphql/server/pkg/chaos_experiment/ops/service_test.go @@ -10,6 +10,7 @@ import ( "reflect" "testing" + "github.com/litmuschaos/litmus/chaoscenter/graphql/server/pkg/authorization" dbSchemaProbe "github.com/litmuschaos/litmus/chaoscenter/graphql/server/pkg/database/mongodb/probe" "github.com/gin-gonic/gin" @@ -30,11 +31,12 @@ import ( var ( mongodbMockOperator = new(dbMocks.MongoOperator) - probeOperator = dbSchemaProbe.NewChaosProbeOperator(mongodbMockOperator) + probeOperator = dbSchemaProbe.NewProbeOperator(mongodbMockOperator) infraOperator = dbChaosInfra.NewInfrastructureOperator(mongodbMockOperator) chaosExperimentOperator = dbChaosExperiment.NewChaosExperimentOperator(mongodbMockOperator) chaosExperimentRunOperator = dbChaosExperimentRun.NewChaosExperimentRunOperator(mongodbMockOperator) - probeService = probe.NewProbeService(probeOperator) + authConfigOperator = authorization.NewAuthorizationOperator(mongodbMockOperator) + probeService = probe.NewProbeService(probeOperator, authConfigOperator) ) var chaosExperimentRunTestService = NewChaosExperimentService(chaosExperimentOperator, infraOperator, chaosExperimentRunOperator, probeService) diff --git a/chaoscenter/graphql/server/pkg/chaos_experiment_run/handler/handler.go b/chaoscenter/graphql/server/pkg/chaos_experiment_run/handler/handler.go index cca64b118..8749a2604 100644 --- a/chaoscenter/graphql/server/pkg/chaos_experiment_run/handler/handler.go +++ b/chaoscenter/graphql/server/pkg/chaos_experiment_run/handler/handler.go @@ -56,6 +56,7 @@ type ChaosExperimentRunHandler struct { chaosExperimentRunOperator *dbChaosExperimentRun.Operator probeService probe.Service mongodbOperator mongodb.MongoOperator + authConfigOperator *authorization.Operator } // NewChaosExperimentRunHandler returns a new instance of ChaosWorkflowHandler @@ -67,6 +68,7 @@ func NewChaosExperimentRunHandler( chaosExperimentRunOperator *dbChaosExperimentRun.Operator, probeService probe.Service, mongodbOperator mongodb.MongoOperator, + authConfigOperator *authorization.Operator, ) *ChaosExperimentRunHandler { return &ChaosExperimentRunHandler{ chaosExperimentRunService: chaosExperimentRunService, @@ -76,6 +78,7 @@ func NewChaosExperimentRunHandler( chaosExperimentRunOperator: chaosExperimentRunOperator, probeService: probeService, mongodbOperator: mongodbOperator, + authConfigOperator: authConfigOperator, } } @@ -811,7 +814,7 @@ func (c *ChaosExperimentRunHandler) RunChaosWorkFlow(ctx context.Context, projec ) tkn := ctx.Value(authorization.AuthKey).(string) - username, err := authorization.GetUsername(tkn) + username, err := c.authConfigOperator.GetUsername(tkn) if err != nil { return nil, err } @@ -1015,7 +1018,7 @@ func (c *ChaosExperimentRunHandler) RunCronExperiment(ctx context.Context, proje } tkn := ctx.Value(authorization.AuthKey).(string) - username, err := authorization.GetUsername(tkn) + username, err := c.authConfigOperator.GetUsername(tkn) if err != nil { return err } diff --git a/chaoscenter/graphql/server/pkg/chaos_infrastructure/cluster_jwt.go b/chaoscenter/graphql/server/pkg/chaos_infrastructure/cluster_jwt.go index bb001e80c..2a93e666d 100644 --- a/chaoscenter/graphql/server/pkg/chaos_infrastructure/cluster_jwt.go +++ b/chaoscenter/graphql/server/pkg/chaos_infrastructure/cluster_jwt.go @@ -11,12 +11,22 @@ import ( "github.com/golang-jwt/jwt" ) +type Operator struct { + authConfigOperator *authConfig.Operator +} + +func NewChaosInfrastructureOperator(mongodbOperator mongodb.MongoOperator) *Operator { + return &Operator{ + authConfigOperator: authConfig.NewAuthConfigOperator(mongodbOperator), + } +} + // InfraCreateJWT generates jwt used in chaos_infra registration -func InfraCreateJWT(id string) (string, error) { +func (o *Operator) InfraCreateJWT(id string) (string, error) { claims := jwt.MapClaims{} claims["chaos_infra_id"] = id token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) - config, err := authConfig.NewAuthConfigOperator(mongodb.Operator).GetAuthConfig(context.Background()) + config, err := o.authConfigOperator.GetAuthConfig(context.Background()) if err != nil { return "", err } @@ -29,12 +39,12 @@ func InfraCreateJWT(id string) (string, error) { } // InfraValidateJWT validates the chaos_infra jwt -func InfraValidateJWT(token string) (string, error) { +func (o *Operator) InfraValidateJWT(token string) (string, error) { tkn, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) } - config, err := authConfig.NewAuthConfigOperator(mongodb.Operator).GetAuthConfig(context.Background()) + config, err := o.authConfigOperator.GetAuthConfig(context.Background()) if err != nil { return "", err } diff --git a/chaoscenter/graphql/server/pkg/chaos_infrastructure/service.go b/chaoscenter/graphql/server/pkg/chaos_infrastructure/service.go index 8c9663d24..23b78cdf4 100644 --- a/chaoscenter/graphql/server/pkg/chaos_infrastructure/service.go +++ b/chaoscenter/graphql/server/pkg/chaos_infrastructure/service.go @@ -57,15 +57,17 @@ type Service interface { } type infraService struct { - infraOperator *dbChaosInfra.Operator - envOperator *dbEnvironments.Operator + infraOperator *dbChaosInfra.Operator + envOperator *dbEnvironments.Operator + authConfigOperator *authorization.Operator } // NewChaosInfrastructureService returns a new instance of Service -func NewChaosInfrastructureService(infraOperator *dbChaosInfra.Operator, envOperator *dbEnvironments.Operator) Service { +func NewChaosInfrastructureService(infraOperator *dbChaosInfra.Operator, envOperator *dbEnvironments.Operator, authConfigOperator *authorization.Operator) Service { return &infraService{ - infraOperator: infraOperator, - envOperator: envOperator, + infraOperator: infraOperator, + envOperator: envOperator, + authConfigOperator: authConfigOperator, } } @@ -100,12 +102,16 @@ func (in *infraService) RegisterInfra(c context.Context, projectID string, input ) tkn := c.Value(authorization.AuthKey).(string) - username, err := authorization.GetUsername(tkn) + username, err := in.authConfigOperator.GetUsername(tkn) if err != nil { return nil, err } - token, err := InfraCreateJWT(infraID) + var mongodbOperator mongodb.MongoOperator + + operator := NewChaosInfrastructureOperator(mongodbOperator) + + token, err := operator.InfraCreateJWT(infraID) if err != nil { return &model.RegisterInfraResponse{}, err } @@ -221,7 +227,7 @@ func (in *infraService) RegisterInfra(c context.Context, projectID string, input // DeleteInfra takes infraIDs and r parameters, deletes the infras from the database and sends a request to the subscriber for clean-up func (in *infraService) DeleteInfra(ctx context.Context, projectID string, infraId string, r store.StateData) (string, error) { tkn := ctx.Value(authorization.AuthKey).(string) - username, err := authorization.GetUsername(tkn) + username, err := in.authConfigOperator.GetUsername(tkn) if err != nil { return "", err } @@ -306,7 +312,7 @@ func (in *infraService) DeleteInfra(ctx context.Context, projectID string, infra func (in *infraService) GetInfra(ctx context.Context, projectID string, infraID string) (*model.Infra, error) { tkn := ctx.Value(authorization.AuthKey).(string) - username, err := authorization.GetUsername(tkn) + username, err := in.authConfigOperator.GetUsername(tkn) if err != nil { return nil, err } @@ -950,7 +956,11 @@ func updateVersionFormat(str string) (int, error) { // QueryServerVersion is used to fetch the version of the server func (in *infraService) QueryServerVersion(ctx context.Context) (*model.ServerVersionResponse, error) { - dbVersion, err := config.GetConfig(ctx, "version") + var mongodbOperator mongodb.MongoOperator + + configOperator := config.NewConfigOperator(mongodbOperator) + + dbVersion, err := configOperator.GetConfig(ctx, "version") if err != nil { return nil, err } diff --git a/chaoscenter/graphql/server/pkg/chaoshub/service.go b/chaoscenter/graphql/server/pkg/chaoshub/service.go index 53f46cc97..12886f711 100644 --- a/chaoscenter/graphql/server/pkg/chaoshub/service.go +++ b/chaoscenter/graphql/server/pkg/chaoshub/service.go @@ -50,13 +50,15 @@ type Service interface { } type chaosHubService struct { - chaosHubOperator *dbSchemaChaosHub.Operator + chaosHubOperator *dbSchemaChaosHub.Operator + authConfigOperator *authorization.Operator } // NewService returns a new instance of Service -func NewService(chaosHubOperator *dbSchemaChaosHub.Operator) Service { +func NewService(chaosHubOperator *dbSchemaChaosHub.Operator, authConfigOperator *authorization.Operator) Service { return &chaosHubService{ - chaosHubOperator: chaosHubOperator, + chaosHubOperator: chaosHubOperator, + authConfigOperator: authConfigOperator, } } @@ -75,7 +77,7 @@ func (c *chaosHubService) AddChaosHub(ctx context.Context, chaosHub model.Create } tkn := ctx.Value(authorization.AuthKey).(string) - username, err := authorization.GetUsername(tkn) + username, err := c.authConfigOperator.GetUsername(tkn) if err != nil { log.Error("error getting username: ", err) return nil, err @@ -144,7 +146,7 @@ func (c *chaosHubService) AddRemoteChaosHub(ctx context.Context, chaosHub model. currentTime := time.Now() tkn := ctx.Value(authorization.AuthKey).(string) - username, err := authorization.GetUsername(tkn) + username, err := c.authConfigOperator.GetUsername(tkn) if err != nil { log.Error("error getting userID: ", err) @@ -211,7 +213,7 @@ func (c *chaosHubService) SaveChaosHub(ctx context.Context, chaosHub model.Creat // Initialize a UID for new Hub. uuid := uuid.New() tkn := ctx.Value(authorization.AuthKey).(string) - username, err := authorization.GetUsername(tkn) + username, err := c.authConfigOperator.GetUsername(tkn) if err != nil { log.Error("error getting userID: ", err) @@ -367,7 +369,7 @@ func (c *chaosHubService) UpdateChaosHub(ctx context.Context, chaosHub model.Upd time := time.Now().UnixMilli() tkn := ctx.Value(authorization.AuthKey).(string) - username, err := authorization.GetUsername(tkn) + username, err := c.authConfigOperator.GetUsername(tkn) query := bson.D{{"hub_id", chaosHub.ID}, {"is_removed", false}} update := bson.D{ @@ -410,7 +412,7 @@ func (c *chaosHubService) UpdateChaosHub(ctx context.Context, chaosHub model.Upd func (c *chaosHubService) DeleteChaosHub(ctx context.Context, hubID string, projectID string) (bool, error) { tkn := ctx.Value(authorization.AuthKey).(string) - username, err := authorization.GetUsername(tkn) + username, err := c.authConfigOperator.GetUsername(tkn) if err != nil { return false, err } diff --git a/chaoscenter/graphql/server/pkg/database/mongodb/chaos_hub/operations.go b/chaoscenter/graphql/server/pkg/database/mongodb/chaos_hub/operations.go index faa8c1faf..ca5550ab6 100644 --- a/chaoscenter/graphql/server/pkg/database/mongodb/chaos_hub/operations.go +++ b/chaoscenter/graphql/server/pkg/database/mongodb/chaos_hub/operations.go @@ -92,7 +92,7 @@ func (c *Operator) UpdateChaosHub(ctx context.Context, query bson.D, update bson // GetAggregateChaosHubs takes a mongo pipeline to retrieve the project details from the database func (c *Operator) GetAggregateChaosHubs(ctx context.Context, pipeline mongo.Pipeline) (*mongo.Cursor, error) { - results, err := mongodb.Operator.Aggregate(ctx, mongodb.ChaosHubCollection, pipeline) + results, err := c.operator.Aggregate(ctx, mongodb.ChaosHubCollection, pipeline) if err != nil { return nil, fmt.Errorf("error on getting the chaos hubs : %v", err) } diff --git a/chaoscenter/graphql/server/pkg/database/mongodb/config/operations.go b/chaoscenter/graphql/server/pkg/database/mongodb/config/operations.go index 7033b8227..6fe31724c 100644 --- a/chaoscenter/graphql/server/pkg/database/mongodb/config/operations.go +++ b/chaoscenter/graphql/server/pkg/database/mongodb/config/operations.go @@ -9,9 +9,19 @@ import ( "go.mongodb.org/mongo-driver/mongo" ) +type Operator struct { + operator mongodb.MongoOperator +} + +func NewConfigOperator(mongodbOperator mongodb.MongoOperator) *Operator { + return &Operator{ + operator: mongodbOperator, + } +} + // CreateConfig creates a new server config with unique key -func CreateConfig(ctx context.Context, config *ServerConfig) error { - err := mongodb.Operator.Create(ctx, mongodb.ServerConfigCollection, config) +func (o *Operator) CreateConfig(ctx context.Context, config *ServerConfig) error { + err := o.operator.Create(ctx, mongodb.ServerConfigCollection, config) if err != nil { return err } @@ -19,11 +29,11 @@ func CreateConfig(ctx context.Context, config *ServerConfig) error { } // GetConfig returns the requested server config -func GetConfig(ctx context.Context, key string) (*ServerConfig, error) { +func (o *Operator) GetConfig(ctx context.Context, key string) (*ServerConfig, error) { query := bson.D{ {"key", key}, } - results, err := mongodb.Operator.Get(ctx, mongodb.ServerConfigCollection, query) + results, err := o.operator.Get(ctx, mongodb.ServerConfigCollection, query) if err != nil { return nil, err } @@ -39,14 +49,14 @@ func GetConfig(ctx context.Context, key string) (*ServerConfig, error) { } // UpdateConfig updates the required server config -func UpdateConfig(ctx context.Context, key string, value interface{}) error { +func (o *Operator) UpdateConfig(ctx context.Context, key string, value interface{}) error { query := bson.D{ {"key", key}, } update := bson.D{{"$set", bson.D{{ "value", value}}, }} - _, err := mongodb.Operator.Update(ctx, mongodb.ServerConfigCollection, query, update) + _, err := o.operator.Update(ctx, mongodb.ServerConfigCollection, query, update) if err != nil { return err } diff --git a/chaoscenter/graphql/server/pkg/database/mongodb/environments/operations.go b/chaoscenter/graphql/server/pkg/database/mongodb/environments/operations.go index 6cff68e14..72f98abb9 100644 --- a/chaoscenter/graphql/server/pkg/database/mongodb/environments/operations.go +++ b/chaoscenter/graphql/server/pkg/database/mongodb/environments/operations.go @@ -90,7 +90,7 @@ func (e *Operator) GetEnvironmentWithProjectID(projectID string) ([]*Environment defer cancel() var environments []*Environment - results, err := mongodb.Operator.List(ctx, mongodb.EnvironmentCollection, query) + results, err := e.operator.List(ctx, mongodb.EnvironmentCollection, query) if err != nil { return []*Environment{}, err } diff --git a/chaoscenter/graphql/server/pkg/database/mongodb/operations.go b/chaoscenter/graphql/server/pkg/database/mongodb/operations.go index cecd1395f..c5ad23a12 100644 --- a/chaoscenter/graphql/server/pkg/database/mongodb/operations.go +++ b/chaoscenter/graphql/server/pkg/database/mongodb/operations.go @@ -33,11 +33,6 @@ type MongoOperations struct { MongoClient *MongoClient } -var ( - // Operator contains all the CRUD operations of the mongo database - Operator MongoOperator = &MongoOperations{} -) - func NewMongoOperations(mongoClient *MongoClient) *MongoOperations { return &MongoOperations{ MongoClient: mongoClient, diff --git a/chaoscenter/graphql/server/pkg/database/mongodb/probe/operations.go b/chaoscenter/graphql/server/pkg/database/mongodb/probe/operations.go index 1860d3dae..d9b11c999 100644 --- a/chaoscenter/graphql/server/pkg/database/mongodb/probe/operations.go +++ b/chaoscenter/graphql/server/pkg/database/mongodb/probe/operations.go @@ -10,13 +10,13 @@ import ( "go.mongodb.org/mongo-driver/mongo" ) -// Operator is the model for probe collection +// Operator is the model for probe operations and collection type Operator struct { operator mongodb.MongoOperator } -// NewChaosProbeOperator returns a new instance of Operator -func NewChaosProbeOperator(mongodbOperator mongodb.MongoOperator) *Operator { +// NewProbeOperator returns a new instance of Operator +func NewProbeOperator(mongodbOperator mongodb.MongoOperator) *Operator { return &Operator{ operator: mongodbOperator, } diff --git a/chaoscenter/graphql/server/pkg/handlers/file_handler.go b/chaoscenter/graphql/server/pkg/handlers/file_handler.go index 8ccf6f178..2ca8d5dca 100644 --- a/chaoscenter/graphql/server/pkg/handlers/file_handler.go +++ b/chaoscenter/graphql/server/pkg/handlers/file_handler.go @@ -19,45 +19,45 @@ import ( func FileHandler(mongodbOperator mongodb.MongoOperator) gin.HandlerFunc { return func(c *gin.Context) { token := strings.TrimSuffix(c.Param("key"), ".yaml") - - infraId, err := chaos_infrastructure.InfraValidateJWT(token) + chaosInfraOperator := chaos_infrastructure.NewChaosInfrastructureOperator(mongodbOperator) + infraId, err := chaosInfraOperator.InfraValidateJWT(token) if err != nil { - logrus.Error(err) + logrus.Error("Error validating JWT: ", err) utils.WriteHeaders(&c.Writer, 500) c.Writer.Write([]byte(err.Error())) } infra, err := dbChaosInfra.NewInfrastructureOperator(mongodbOperator).GetInfra(infraId) if err != nil { - logrus.Error(err) + logrus.Error("Error fetching infra details: ", err) utils.WriteHeaders(&c.Writer, 500) c.Writer.Write([]byte(err.Error())) } reqHeader, ok := c.Value("request-header").(http.Header) if !ok { - logrus.Error("unable to parse referer header") + logrus.Error("Unable to parse Referer header") utils.WriteHeaders(&c.Writer, 500) - c.Writer.Write([]byte("unable to parse referer header")) + c.Writer.Write([]byte("Unable to parse Referer header")) } referrer := reqHeader.Get("Referer") if referrer == "" { - logrus.Error("unable to parse referer header") + logrus.Error("Referer header is empty") utils.WriteHeaders(&c.Writer, 500) - c.Writer.Write([]byte("unable to parse referer header")) + c.Writer.Write([]byte("Referer header is empty")) } referrerURL, err := url.Parse(referrer) if err != nil { - logrus.Error(err) + logrus.Error("Error parsing Referer URL: ", err) utils.WriteHeaders(&c.Writer, 500) c.Writer.Write([]byte(err.Error())) } response, err := chaos_infrastructure.GetK8sInfraYaml(fmt.Sprintf("%s://%s", referrerURL.Scheme, referrerURL.Host), infra) if err != nil { - logrus.Error(err) + logrus.Error("Error generating Kubernetes infra YAML: ", err) utils.WriteHeaders(&c.Writer, 500) c.Writer.Write([]byte(err.Error())) } diff --git a/chaoscenter/graphql/server/pkg/handlers/readiness_handler.go b/chaoscenter/graphql/server/pkg/handlers/readiness_handler.go index 98ce02200..c9349f61a 100644 --- a/chaoscenter/graphql/server/pkg/handlers/readiness_handler.go +++ b/chaoscenter/graphql/server/pkg/handlers/readiness_handler.go @@ -9,6 +9,19 @@ import ( "github.com/litmuschaos/litmus/chaoscenter/graphql/server/pkg/database/mongodb" ) +// Operator encapsulates the MongoDB operations +type Operator struct { + mongoOperator mongodb.MongoOperator +} + +// NewOperator returns a new instance of Operator +func NewOperator(mongoOperator mongodb.MongoOperator) *Operator { + return &Operator{ + mongoOperator: mongoOperator, + } +} + +// ReadinessAPIStatus represents the readiness status of the API type ReadinessAPIStatus struct { DataBase string `json:"database"` Collections string `json:"collections"` @@ -24,10 +37,11 @@ func contains(s []string, str string) bool { return false } -func ReadinessHandler() gin.HandlerFunc { +// ReadinessHandler returns a handler function for readiness checks +func (r *Operator) ReadinessHandler() gin.HandlerFunc { return func(c *gin.Context) { var dbFlag = "up" - dbs, err := mongodb.Operator.ListDataBase(context.Background(), mongodb.MgoClient) + dbs, err := r.mongoOperator.ListDataBase(context.Background(), mongodb.MgoClient) if err != nil { dbFlag = "down" } diff --git a/chaoscenter/graphql/server/pkg/probe/handler/handler.go b/chaoscenter/graphql/server/pkg/probe/handler/handler.go index 559e57e7b..3512b08d0 100644 --- a/chaoscenter/graphql/server/pkg/probe/handler/handler.go +++ b/chaoscenter/graphql/server/pkg/probe/handler/handler.go @@ -43,12 +43,26 @@ type Service interface { } type probeService struct { - probeOperator *dbSchemaProbe.Operator + probeOperator *dbSchemaProbe.Operator + authConfigOperator *authorization.Operator } -func NewProbeService(probeOperator *dbSchemaProbe.Operator) Service { +type Operator struct { + operator mongodb.MongoOperator +} + +// NewProbeOperator returns a new instance of Operator +func NewProbeOperator(mongodbOperator mongodb.MongoOperator) *Operator { + return &Operator{ + operator: mongodbOperator, + } +} + +// NewProbeService returns a new instance of probeService +func NewProbeService(probeOperator *dbSchemaProbe.Operator, authConfigOperator *authorization.Operator) Service { return &probeService{ - probeOperator: probeOperator, + probeOperator: probeOperator, + authConfigOperator: authConfigOperator, } } @@ -69,7 +83,7 @@ func (p *probeService) AddProbe(ctx context.Context, probe model.ProbeRequest, p return nil, errors.New("JWT token not found") } - username, err := authorization.GetUsername(tkn) + username, err := p.authConfigOperator.GetUsername(tkn) if err != nil { return nil, err } @@ -139,7 +153,7 @@ func (p *probeService) AddProbe(ctx context.Context, probe model.ProbeRequest, p // UpdateProbe - Update a new Probe func (p *probeService) UpdateProbe(ctx context.Context, request model.ProbeRequest, projectID string) (string, error) { tkn := ctx.Value(authorization.AuthKey).(string) - username, err := authorization.GetUsername(tkn) + username, err := p.authConfigOperator.GetUsername(tkn) if err != nil { return "", err } @@ -386,6 +400,8 @@ func (p *probeService) ListProbes(ctx context.Context, probeNames []string, infr } func GetProbeExecutionHistoryInExperimentRuns(projectID string, probeName string) ([]*model.ProbeRecentExecutions, error) { + var mongodbOperator mongodb.MongoOperator + var ( pipeline mongo.Pipeline expRuns []dbChaosExperimentRun.ChaosExperimentRun @@ -405,7 +421,7 @@ func GetProbeExecutionHistoryInExperimentRuns(projectID string, probeName string pipeline = append(pipeline, matchIdentifierStage) // Call aggregation on pipeline - experimentRunOperator := dbChaosExperimentRun.NewChaosExperimentRunOperator(mongodb.Operator) + experimentRunOperator := dbChaosExperimentRun.NewChaosExperimentRunOperator(NewProbeOperator(mongodbOperator).operator) expRunCursor, err := experimentRunOperator.GetAggregateExperimentRuns(pipeline) if err != nil { return nil, errors.New("DB aggregate stage error: " + err.Error()) @@ -491,7 +507,7 @@ func (p *probeService) DeleteProbe(ctx context.Context, probeName, projectID str return false, err } tkn := ctx.Value(authorization.AuthKey).(string) - username, err := authorization.GetUsername(tkn) + username, err := p.authConfigOperator.GetUsername(tkn) Time := time.Now().UnixMilli() diff --git a/chaoscenter/graphql/server/server.go b/chaoscenter/graphql/server/server.go index 78e8b00ba..eb5b32ac7 100644 --- a/chaoscenter/graphql/server/server.go +++ b/chaoscenter/graphql/server/server.go @@ -90,7 +90,6 @@ func main() { mongoClient := mongodb.Client.Initialize(mongodb.MgoClient) var mongodbOperator mongodb.MongoOperator = mongodb.NewMongoOperations(mongoClient) - mongodb.Operator = mongodbOperator if err := validateVersion(); err != nil { log.Fatal(err)