This commit is contained in:
Prashant Andoriya 2025-06-23 11:24:37 +02:00 committed by GitHub
commit 8d24b3eed5
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
19 changed files with 147 additions and 73 deletions

View File

@ -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.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 h1:zY54UmvipHiNd+pm+m0x9KhZ9hl1/7QNMyxXbc6ICqA=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c= 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-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-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=

View File

@ -13,7 +13,7 @@ import (
) )
// CreateEnvironment is the resolver for the createEnvironment field. // 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{ logFields := logrus.Fields{
"projectId": projectID, "projectId": projectID,
} }
@ -26,7 +26,7 @@ func (r *mutationResolver) CreateEnvironment(ctx context.Context, projectID stri
} }
tkn := ctx.Value(authorization.AuthKey).(string) tkn := ctx.Value(authorization.AuthKey).(string)
username, err := authorization.GetUsername(tkn) username, err := authConfigOperator.GetUsername(tkn)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -35,7 +35,7 @@ func (r *mutationResolver) CreateEnvironment(ctx context.Context, projectID stri
} }
// UpdateEnvironment is the resolver for the updateEnvironment field. // 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{ logFields := logrus.Fields{
"projectId": projectID, "projectId": projectID,
"environmentId": request.EnvironmentID, "environmentId": request.EnvironmentID,
@ -49,7 +49,7 @@ func (r *mutationResolver) UpdateEnvironment(ctx context.Context, projectID stri
} }
tkn := ctx.Value(authorization.AuthKey).(string) tkn := ctx.Value(authorization.AuthKey).(string)
username, err := authorization.GetUsername(tkn) username, err := authConfigOperator.GetUsername(tkn)
if err != nil { if err != nil {
return "", err return "", err
} }
@ -58,7 +58,7 @@ func (r *mutationResolver) UpdateEnvironment(ctx context.Context, projectID stri
} }
// DeleteEnvironment is the resolver for the deleteEnvironment field. // 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{ logFields := logrus.Fields{
"projectId": projectID, "projectId": projectID,
"environmentId": environmentID, "environmentId": environmentID,
@ -72,7 +72,7 @@ func (r *mutationResolver) DeleteEnvironment(ctx context.Context, projectID stri
} }
tkn := ctx.Value(authorization.AuthKey).(string) tkn := ctx.Value(authorization.AuthKey).(string)
username, err := authorization.GetUsername(tkn) username, err := authConfigOperator.GetUsername(tkn)
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@ -58,6 +58,7 @@ func generateJWTTokenFromClaims(claims jwt.MapClaims) (string, error) {
} }
func FuzzUserValidateJWT(f *testing.F) { func FuzzUserValidateJWT(f *testing.F) {
operator := &Operator{}
f.Fuzz(func(t *testing.T, data []byte) { f.Fuzz(func(t *testing.T, data []byte) {
fuzzConsumer := fuzz.NewConsumer(data) fuzzConsumer := fuzz.NewConsumer(data)
inputClaims := &jwt.MapClaims{} inputClaims := &jwt.MapClaims{}
@ -72,7 +73,7 @@ func FuzzUserValidateJWT(f *testing.F) {
} }
// Run the test with the generated JWT token // Run the test with the generated JWT token
claims, err := UserValidateJWT(tokenString, "") claims, err := operator.UserValidateJWT(tokenString, "")
if err != nil { if err != nil {
t.Errorf("Error encountered: %v", err) t.Errorf("Error encountered: %v", err)
} }

View File

@ -12,8 +12,18 @@ import (
"github.com/golang-jwt/jwt" "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 // 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) { tkn, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
if _, isValid := token.Method.(*jwt.SigningMethodHMAC); !isValid { if _, isValid := token.Method.(*jwt.SigningMethodHMAC); !isValid {
return nil, fmt.Errorf("invalid token %s", token.Header["alg"]) 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 // GetUsername returns the username from the jwt token
func GetUsername(token string) (string, error) { func (o *Operator) GetUsername(token string) (string, error) {
salt, err := authConfig.NewAuthConfigOperator(mongodb.Operator).GetAuthConfig(context.Background()) salt, err := o.authConfigOperator.GetAuthConfig(context.Background())
if err != nil { if err != nil {
return "", err return "", err
} }

View File

@ -1361,7 +1361,7 @@ func (c *ChaosExperimentHandler) GetProbesInExperimentRun(ctx context.Context, p
} }
for _, probeName := range _probe.ProbeNames { 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 { if err != nil {
return nil, err return nil, err
} }

View File

@ -10,6 +10,7 @@ import (
"reflect" "reflect"
"testing" "testing"
"github.com/litmuschaos/litmus/chaoscenter/graphql/server/pkg/authorization"
dbSchemaProbe "github.com/litmuschaos/litmus/chaoscenter/graphql/server/pkg/database/mongodb/probe" dbSchemaProbe "github.com/litmuschaos/litmus/chaoscenter/graphql/server/pkg/database/mongodb/probe"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@ -30,11 +31,12 @@ import (
var ( var (
mongodbMockOperator = new(dbMocks.MongoOperator) mongodbMockOperator = new(dbMocks.MongoOperator)
probeOperator = dbSchemaProbe.NewChaosProbeOperator(mongodbMockOperator) probeOperator = dbSchemaProbe.NewProbeOperator(mongodbMockOperator)
infraOperator = dbChaosInfra.NewInfrastructureOperator(mongodbMockOperator) infraOperator = dbChaosInfra.NewInfrastructureOperator(mongodbMockOperator)
chaosExperimentOperator = dbChaosExperiment.NewChaosExperimentOperator(mongodbMockOperator) chaosExperimentOperator = dbChaosExperiment.NewChaosExperimentOperator(mongodbMockOperator)
chaosExperimentRunOperator = dbChaosExperimentRun.NewChaosExperimentRunOperator(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) var chaosExperimentRunTestService = NewChaosExperimentService(chaosExperimentOperator, infraOperator, chaosExperimentRunOperator, probeService)

View File

@ -56,6 +56,7 @@ type ChaosExperimentRunHandler struct {
chaosExperimentRunOperator *dbChaosExperimentRun.Operator chaosExperimentRunOperator *dbChaosExperimentRun.Operator
probeService probe.Service probeService probe.Service
mongodbOperator mongodb.MongoOperator mongodbOperator mongodb.MongoOperator
authConfigOperator *authorization.Operator
} }
// NewChaosExperimentRunHandler returns a new instance of ChaosWorkflowHandler // NewChaosExperimentRunHandler returns a new instance of ChaosWorkflowHandler
@ -67,6 +68,7 @@ func NewChaosExperimentRunHandler(
chaosExperimentRunOperator *dbChaosExperimentRun.Operator, chaosExperimentRunOperator *dbChaosExperimentRun.Operator,
probeService probe.Service, probeService probe.Service,
mongodbOperator mongodb.MongoOperator, mongodbOperator mongodb.MongoOperator,
authConfigOperator *authorization.Operator,
) *ChaosExperimentRunHandler { ) *ChaosExperimentRunHandler {
return &ChaosExperimentRunHandler{ return &ChaosExperimentRunHandler{
chaosExperimentRunService: chaosExperimentRunService, chaosExperimentRunService: chaosExperimentRunService,
@ -76,6 +78,7 @@ func NewChaosExperimentRunHandler(
chaosExperimentRunOperator: chaosExperimentRunOperator, chaosExperimentRunOperator: chaosExperimentRunOperator,
probeService: probeService, probeService: probeService,
mongodbOperator: mongodbOperator, mongodbOperator: mongodbOperator,
authConfigOperator: authConfigOperator,
} }
} }
@ -811,7 +814,7 @@ func (c *ChaosExperimentRunHandler) RunChaosWorkFlow(ctx context.Context, projec
) )
tkn := ctx.Value(authorization.AuthKey).(string) tkn := ctx.Value(authorization.AuthKey).(string)
username, err := authorization.GetUsername(tkn) username, err := c.authConfigOperator.GetUsername(tkn)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -1015,7 +1018,7 @@ func (c *ChaosExperimentRunHandler) RunCronExperiment(ctx context.Context, proje
} }
tkn := ctx.Value(authorization.AuthKey).(string) tkn := ctx.Value(authorization.AuthKey).(string)
username, err := authorization.GetUsername(tkn) username, err := c.authConfigOperator.GetUsername(tkn)
if err != nil { if err != nil {
return err return err
} }

View File

@ -11,12 +11,22 @@ import (
"github.com/golang-jwt/jwt" "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 // 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 := jwt.MapClaims{}
claims["chaos_infra_id"] = id claims["chaos_infra_id"] = id
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) 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 { if err != nil {
return "", err return "", err
} }
@ -29,12 +39,12 @@ func InfraCreateJWT(id string) (string, error) {
} }
// InfraValidateJWT validates the chaos_infra jwt // 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) { tkn, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"]) 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 { if err != nil {
return "", err return "", err
} }

View File

@ -59,13 +59,15 @@ type Service interface {
type infraService struct { type infraService struct {
infraOperator *dbChaosInfra.Operator infraOperator *dbChaosInfra.Operator
envOperator *dbEnvironments.Operator envOperator *dbEnvironments.Operator
authConfigOperator *authorization.Operator
} }
// NewChaosInfrastructureService returns a new instance of Service // 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{ return &infraService{
infraOperator: infraOperator, infraOperator: infraOperator,
envOperator: envOperator, envOperator: envOperator,
authConfigOperator: authConfigOperator,
} }
} }
@ -100,12 +102,16 @@ func (in *infraService) RegisterInfra(c context.Context, projectID string, input
) )
tkn := c.Value(authorization.AuthKey).(string) tkn := c.Value(authorization.AuthKey).(string)
username, err := authorization.GetUsername(tkn) username, err := in.authConfigOperator.GetUsername(tkn)
if err != nil { if err != nil {
return nil, err return nil, err
} }
token, err := InfraCreateJWT(infraID) var mongodbOperator mongodb.MongoOperator
operator := NewChaosInfrastructureOperator(mongodbOperator)
token, err := operator.InfraCreateJWT(infraID)
if err != nil { if err != nil {
return &model.RegisterInfraResponse{}, err 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 // 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) { func (in *infraService) DeleteInfra(ctx context.Context, projectID string, infraId string, r store.StateData) (string, error) {
tkn := ctx.Value(authorization.AuthKey).(string) tkn := ctx.Value(authorization.AuthKey).(string)
username, err := authorization.GetUsername(tkn) username, err := in.authConfigOperator.GetUsername(tkn)
if err != nil { if err != nil {
return "", err 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) { func (in *infraService) GetInfra(ctx context.Context, projectID string, infraID string) (*model.Infra, error) {
tkn := ctx.Value(authorization.AuthKey).(string) tkn := ctx.Value(authorization.AuthKey).(string)
username, err := authorization.GetUsername(tkn) username, err := in.authConfigOperator.GetUsername(tkn)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -950,7 +956,11 @@ func updateVersionFormat(str string) (int, error) {
// QueryServerVersion is used to fetch the version of the server // QueryServerVersion is used to fetch the version of the server
func (in *infraService) QueryServerVersion(ctx context.Context) (*model.ServerVersionResponse, error) { 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 { if err != nil {
return nil, err return nil, err
} }

View File

@ -51,12 +51,14 @@ type Service interface {
type chaosHubService struct { type chaosHubService struct {
chaosHubOperator *dbSchemaChaosHub.Operator chaosHubOperator *dbSchemaChaosHub.Operator
authConfigOperator *authorization.Operator
} }
// NewService returns a new instance of Service // NewService returns a new instance of Service
func NewService(chaosHubOperator *dbSchemaChaosHub.Operator) Service { func NewService(chaosHubOperator *dbSchemaChaosHub.Operator, authConfigOperator *authorization.Operator) Service {
return &chaosHubService{ 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) tkn := ctx.Value(authorization.AuthKey).(string)
username, err := authorization.GetUsername(tkn) username, err := c.authConfigOperator.GetUsername(tkn)
if err != nil { if err != nil {
log.Error("error getting username: ", err) log.Error("error getting username: ", err)
return nil, err return nil, err
@ -144,7 +146,7 @@ func (c *chaosHubService) AddRemoteChaosHub(ctx context.Context, chaosHub model.
currentTime := time.Now() currentTime := time.Now()
tkn := ctx.Value(authorization.AuthKey).(string) tkn := ctx.Value(authorization.AuthKey).(string)
username, err := authorization.GetUsername(tkn) username, err := c.authConfigOperator.GetUsername(tkn)
if err != nil { if err != nil {
log.Error("error getting userID: ", err) 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. // Initialize a UID for new Hub.
uuid := uuid.New() uuid := uuid.New()
tkn := ctx.Value(authorization.AuthKey).(string) tkn := ctx.Value(authorization.AuthKey).(string)
username, err := authorization.GetUsername(tkn) username, err := c.authConfigOperator.GetUsername(tkn)
if err != nil { if err != nil {
log.Error("error getting userID: ", err) log.Error("error getting userID: ", err)
@ -367,7 +369,7 @@ func (c *chaosHubService) UpdateChaosHub(ctx context.Context, chaosHub model.Upd
time := time.Now().UnixMilli() time := time.Now().UnixMilli()
tkn := ctx.Value(authorization.AuthKey).(string) 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}} query := bson.D{{"hub_id", chaosHub.ID}, {"is_removed", false}}
update := bson.D{ 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) { func (c *chaosHubService) DeleteChaosHub(ctx context.Context, hubID string, projectID string) (bool, error) {
tkn := ctx.Value(authorization.AuthKey).(string) tkn := ctx.Value(authorization.AuthKey).(string)
username, err := authorization.GetUsername(tkn) username, err := c.authConfigOperator.GetUsername(tkn)
if err != nil { if err != nil {
return false, err return false, err
} }

View File

@ -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 // 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) { 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 { if err != nil {
return nil, fmt.Errorf("error on getting the chaos hubs : %v", err) return nil, fmt.Errorf("error on getting the chaos hubs : %v", err)
} }

View File

@ -9,9 +9,19 @@ import (
"go.mongodb.org/mongo-driver/mongo" "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 // CreateConfig creates a new server config with unique key
func CreateConfig(ctx context.Context, config *ServerConfig) error { func (o *Operator) CreateConfig(ctx context.Context, config *ServerConfig) error {
err := mongodb.Operator.Create(ctx, mongodb.ServerConfigCollection, config) err := o.operator.Create(ctx, mongodb.ServerConfigCollection, config)
if err != nil { if err != nil {
return err return err
} }
@ -19,11 +29,11 @@ func CreateConfig(ctx context.Context, config *ServerConfig) error {
} }
// GetConfig returns the requested server config // 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{ query := bson.D{
{"key", key}, {"key", key},
} }
results, err := mongodb.Operator.Get(ctx, mongodb.ServerConfigCollection, query) results, err := o.operator.Get(ctx, mongodb.ServerConfigCollection, query)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -39,14 +49,14 @@ func GetConfig(ctx context.Context, key string) (*ServerConfig, error) {
} }
// UpdateConfig updates the required server config // 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{ query := bson.D{
{"key", key}, {"key", key},
} }
update := bson.D{{"$set", bson.D{{ update := bson.D{{"$set", bson.D{{
"value", value}}, "value", value}},
}} }}
_, err := mongodb.Operator.Update(ctx, mongodb.ServerConfigCollection, query, update) _, err := o.operator.Update(ctx, mongodb.ServerConfigCollection, query, update)
if err != nil { if err != nil {
return err return err
} }

View File

@ -90,7 +90,7 @@ func (e *Operator) GetEnvironmentWithProjectID(projectID string) ([]*Environment
defer cancel() defer cancel()
var environments []*Environment var environments []*Environment
results, err := mongodb.Operator.List(ctx, mongodb.EnvironmentCollection, query) results, err := e.operator.List(ctx, mongodb.EnvironmentCollection, query)
if err != nil { if err != nil {
return []*Environment{}, err return []*Environment{}, err
} }

View File

@ -33,11 +33,6 @@ type MongoOperations struct {
MongoClient *MongoClient MongoClient *MongoClient
} }
var (
// Operator contains all the CRUD operations of the mongo database
Operator MongoOperator = &MongoOperations{}
)
func NewMongoOperations(mongoClient *MongoClient) *MongoOperations { func NewMongoOperations(mongoClient *MongoClient) *MongoOperations {
return &MongoOperations{ return &MongoOperations{
MongoClient: mongoClient, MongoClient: mongoClient,

View File

@ -10,13 +10,13 @@ import (
"go.mongodb.org/mongo-driver/mongo" "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 { type Operator struct {
operator mongodb.MongoOperator operator mongodb.MongoOperator
} }
// NewChaosProbeOperator returns a new instance of Operator // NewProbeOperator returns a new instance of Operator
func NewChaosProbeOperator(mongodbOperator mongodb.MongoOperator) *Operator { func NewProbeOperator(mongodbOperator mongodb.MongoOperator) *Operator {
return &Operator{ return &Operator{
operator: mongodbOperator, operator: mongodbOperator,
} }

View File

@ -19,45 +19,45 @@ import (
func FileHandler(mongodbOperator mongodb.MongoOperator) gin.HandlerFunc { func FileHandler(mongodbOperator mongodb.MongoOperator) gin.HandlerFunc {
return func(c *gin.Context) { return func(c *gin.Context) {
token := strings.TrimSuffix(c.Param("key"), ".yaml") token := strings.TrimSuffix(c.Param("key"), ".yaml")
chaosInfraOperator := chaos_infrastructure.NewChaosInfrastructureOperator(mongodbOperator)
infraId, err := chaos_infrastructure.InfraValidateJWT(token) infraId, err := chaosInfraOperator.InfraValidateJWT(token)
if err != nil { if err != nil {
logrus.Error(err) logrus.Error("Error validating JWT: ", err)
utils.WriteHeaders(&c.Writer, 500) utils.WriteHeaders(&c.Writer, 500)
c.Writer.Write([]byte(err.Error())) c.Writer.Write([]byte(err.Error()))
} }
infra, err := dbChaosInfra.NewInfrastructureOperator(mongodbOperator).GetInfra(infraId) infra, err := dbChaosInfra.NewInfrastructureOperator(mongodbOperator).GetInfra(infraId)
if err != nil { if err != nil {
logrus.Error(err) logrus.Error("Error fetching infra details: ", err)
utils.WriteHeaders(&c.Writer, 500) utils.WriteHeaders(&c.Writer, 500)
c.Writer.Write([]byte(err.Error())) c.Writer.Write([]byte(err.Error()))
} }
reqHeader, ok := c.Value("request-header").(http.Header) reqHeader, ok := c.Value("request-header").(http.Header)
if !ok { if !ok {
logrus.Error("unable to parse referer header") logrus.Error("Unable to parse Referer header")
utils.WriteHeaders(&c.Writer, 500) 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") referrer := reqHeader.Get("Referer")
if referrer == "" { if referrer == "" {
logrus.Error("unable to parse referer header") logrus.Error("Referer header is empty")
utils.WriteHeaders(&c.Writer, 500) 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) referrerURL, err := url.Parse(referrer)
if err != nil { if err != nil {
logrus.Error(err) logrus.Error("Error parsing Referer URL: ", err)
utils.WriteHeaders(&c.Writer, 500) utils.WriteHeaders(&c.Writer, 500)
c.Writer.Write([]byte(err.Error())) c.Writer.Write([]byte(err.Error()))
} }
response, err := chaos_infrastructure.GetK8sInfraYaml(fmt.Sprintf("%s://%s", referrerURL.Scheme, referrerURL.Host), infra) response, err := chaos_infrastructure.GetK8sInfraYaml(fmt.Sprintf("%s://%s", referrerURL.Scheme, referrerURL.Host), infra)
if err != nil { if err != nil {
logrus.Error(err) logrus.Error("Error generating Kubernetes infra YAML: ", err)
utils.WriteHeaders(&c.Writer, 500) utils.WriteHeaders(&c.Writer, 500)
c.Writer.Write([]byte(err.Error())) c.Writer.Write([]byte(err.Error()))
} }

View File

@ -9,6 +9,19 @@ import (
"github.com/litmuschaos/litmus/chaoscenter/graphql/server/pkg/database/mongodb" "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 { type ReadinessAPIStatus struct {
DataBase string `json:"database"` DataBase string `json:"database"`
Collections string `json:"collections"` Collections string `json:"collections"`
@ -24,10 +37,11 @@ func contains(s []string, str string) bool {
return false 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) { return func(c *gin.Context) {
var dbFlag = "up" var dbFlag = "up"
dbs, err := mongodb.Operator.ListDataBase(context.Background(), mongodb.MgoClient) dbs, err := r.mongoOperator.ListDataBase(context.Background(), mongodb.MgoClient)
if err != nil { if err != nil {
dbFlag = "down" dbFlag = "down"
} }

View File

@ -44,11 +44,25 @@ type Service interface {
type probeService struct { 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{ 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") return nil, errors.New("JWT token not found")
} }
username, err := authorization.GetUsername(tkn) username, err := p.authConfigOperator.GetUsername(tkn)
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -139,7 +153,7 @@ func (p *probeService) AddProbe(ctx context.Context, probe model.ProbeRequest, p
// UpdateProbe - Update a new Probe // UpdateProbe - Update a new Probe
func (p *probeService) UpdateProbe(ctx context.Context, request model.ProbeRequest, projectID string) (string, error) { func (p *probeService) UpdateProbe(ctx context.Context, request model.ProbeRequest, projectID string) (string, error) {
tkn := ctx.Value(authorization.AuthKey).(string) tkn := ctx.Value(authorization.AuthKey).(string)
username, err := authorization.GetUsername(tkn) username, err := p.authConfigOperator.GetUsername(tkn)
if err != nil { if err != nil {
return "", err 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) { func GetProbeExecutionHistoryInExperimentRuns(projectID string, probeName string) ([]*model.ProbeRecentExecutions, error) {
var mongodbOperator mongodb.MongoOperator
var ( var (
pipeline mongo.Pipeline pipeline mongo.Pipeline
expRuns []dbChaosExperimentRun.ChaosExperimentRun expRuns []dbChaosExperimentRun.ChaosExperimentRun
@ -405,7 +421,7 @@ func GetProbeExecutionHistoryInExperimentRuns(projectID string, probeName string
pipeline = append(pipeline, matchIdentifierStage) pipeline = append(pipeline, matchIdentifierStage)
// Call aggregation on pipeline // Call aggregation on pipeline
experimentRunOperator := dbChaosExperimentRun.NewChaosExperimentRunOperator(mongodb.Operator) experimentRunOperator := dbChaosExperimentRun.NewChaosExperimentRunOperator(NewProbeOperator(mongodbOperator).operator)
expRunCursor, err := experimentRunOperator.GetAggregateExperimentRuns(pipeline) expRunCursor, err := experimentRunOperator.GetAggregateExperimentRuns(pipeline)
if err != nil { if err != nil {
return nil, errors.New("DB aggregate stage error: " + err.Error()) 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 return false, err
} }
tkn := ctx.Value(authorization.AuthKey).(string) tkn := ctx.Value(authorization.AuthKey).(string)
username, err := authorization.GetUsername(tkn) username, err := p.authConfigOperator.GetUsername(tkn)
Time := time.Now().UnixMilli() Time := time.Now().UnixMilli()

View File

@ -90,7 +90,6 @@ func main() {
mongoClient := mongodb.Client.Initialize(mongodb.MgoClient) mongoClient := mongodb.Client.Initialize(mongodb.MgoClient)
var mongodbOperator mongodb.MongoOperator = mongodb.NewMongoOperations(mongoClient) var mongodbOperator mongodb.MongoOperator = mongodb.NewMongoOperations(mongoClient)
mongodb.Operator = mongodbOperator
if err := validateVersion(); err != nil { if err := validateVersion(); err != nil {
log.Fatal(err) log.Fatal(err)