code
stringlengths
14
2.05k
label
int64
0
1
programming_language
stringclasses
7 values
cwe_id
stringlengths
6
14
cwe_name
stringlengths
5
98
description
stringlengths
36
379
url
stringlengths
36
48
label_name
stringclasses
2 values
func (vc *VoteController) VoteUp(ctx *gin.Context) { req := &schema.VoteReq{} if handler.BindAndCheck(ctx, req) { return } req.ObjectID = uid.DeShortID(req.ObjectID) req.UserID = middleware.GetLoginUserIDFromContext(ctx) can, needRank, err := vc.rankService.CheckVotePermission(ctx, req.UserID, req.ObjectID, true) if err != nil { handler.HandleResponse(ctx, err, nil) return } if !can { lang := handler.GetLang(ctx) msg := translator.TrWithData(lang, reason.NoEnoughRankToOperate, &schema.PermissionTrTplData{Rank: needRank}) handler.HandleResponse(ctx, errors.Forbidden(reason.NoEnoughRankToOperate).WithMsg(msg), nil) return } resp, err := vc.VoteService.VoteUp(ctx, req) if err != nil { handler.HandleResponse(ctx, err, schema.ErrTypeToast) } else { handler.HandleResponse(ctx, err, resp) } }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (ar *FollowRepo) FollowCancel(ctx context.Context, objectID, userID string) error { objectTypeStr, err := obj.GetObjectTypeStrByObjectID(objectID) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } activityType, err := ar.activityRepo.GetActivityTypeByObjectType(ctx, objectTypeStr, "follow") if err != nil { return err } _, err = ar.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { session = session.Context(ctx) var ( existsActivity entity.Activity has bool ) result = nil has, err = session.Where(builder.Eq{"activity_type": activityType}). And(builder.Eq{"user_id": userID}). And(builder.Eq{"object_id": objectID}). Get(&existsActivity) if err != nil || !has { return } if has && existsActivity.Cancelled == entity.ActivityCancelled { return } if _, err = session.Where("id = ?", existsActivity.ID). Cols("cancelled"). Update(&entity.Activity{ Cancelled: entity.ActivityCancelled, CancelledAt: time.Now(), }); err != nil { return } err = ar.updateFollows(ctx, session, objectID, -1) return }) return err }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (ar *FollowRepo) Follow(ctx context.Context, objectID, userID string) error { objectTypeStr, err := obj.GetObjectTypeStrByObjectID(objectID) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } activityType, err := ar.activityRepo.GetActivityTypeByObjectType(ctx, objectTypeStr, "follow") if err != nil { return err } _, err = ar.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { session = session.Context(ctx) var ( existsActivity entity.Activity has bool ) result = nil has, err = session.Where(builder.Eq{"activity_type": activityType}). And(builder.Eq{"user_id": userID}). And(builder.Eq{"object_id": objectID}). Get(&existsActivity) if err != nil { return } if has && existsActivity.Cancelled == entity.ActivityAvailable { return } if has { _, err = session.Where(builder.Eq{"id": existsActivity.ID}). Cols(`cancelled`). Update(&entity.Activity{ Cancelled: entity.ActivityAvailable, }) } else { // update existing activity with new user id and u object id _, err = session.Insert(&entity.Activity{ UserID: userID, ObjectID: objectID, OriginalObjectID: objectID, ActivityType: activityType, Cancelled: entity.ActivityAvailable, Rank: 0, HasRank: 0, }) } if err != nil { log.Error(err) return } // start update followers when everything is fine err = ar.updateFollows(ctx, session, objectID, 1) if err != nil { log.Error(err) } return }) return err }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (ar *UserActiveActivityRepo) UserActive(ctx context.Context, userID string) (err error) { cfg, err := ar.configService.GetConfigByKey(ctx, UserActivated) if err != nil { return err } addActivity := &entity.Activity{ UserID: userID, ObjectID: "0", OriginalObjectID: "0", ActivityType: cfg.ID, Rank: cfg.GetIntValue(), HasRank: 1, } _, err = ar.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { session = session.Context(ctx) user := &entity.User{} exist, err := session.ID(userID).ForUpdate().Get(user) if err != nil { return nil, err } if !exist { return nil, fmt.Errorf("user not exist") } existsActivity := &entity.Activity{} exist, err = session. And(builder.Eq{"user_id": addActivity.UserID}). And(builder.Eq{"activity_type": addActivity.ActivityType}). Get(existsActivity) if err != nil { return nil, err } if exist { return nil, nil } err = ar.userRankRepo.ChangeUserRank(ctx, session, addActivity.UserID, user.Rank, addActivity.Rank) if err != nil { return nil, err } _, err = session.Insert(addActivity) if err != nil { return nil, err } return nil, nil }) if err != nil { return errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } return nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vr *VoteRepo) ListUserVotes(ctx context.Context, userID string, page int, pageSize int, activityTypes []int) (voteList []*entity.Activity, total int64, err error) { session := vr.data.DB.Context(ctx) cond := builder. And( builder.Eq{"user_id": userID}, builder.Eq{"cancelled": 0}, builder.In("activity_type", activityTypes), ) session.Where(cond).Desc("updated_at") total, err = pager.Help(page, pageSize, &voteList, &entity.Activity{}, session) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } return }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vr *VoteRepo) setActivityRankToZeroIfUserReachLimit(ctx context.Context, session *xorm.Session, op *schema.VoteOperationInfo, maxDailyRank int) (err error) { // check if user reach daily rank limit for _, activity := range op.Activities { reach, err := vr.userRankRepo.CheckReachLimit(ctx, session, activity.ActivityUserID, maxDailyRank) if err != nil { log.Error(err) return err } if reach { activity.Rank = 0 } } return nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vr *VoteRepo) changeUserRank(ctx context.Context, session *xorm.Session, op *schema.VoteOperationInfo, userInfoMapping map[string]*entity.User) (err error) { for _, activity := range op.Activities { if activity.Rank == 0 { continue } user := userInfoMapping[activity.ActivityUserID] if user == nil { continue } if err = vr.userRankRepo.ChangeUserRank(ctx, session, activity.ActivityUserID, user.Rank, activity.Rank); err != nil { log.Error(err) return err } } return nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vr *VoteRepo) countVoteDown(ctx context.Context, objectID, objectType string) (count int64) { count, err := vr.countVote(ctx, objectID, objectType, constant.ActVoteDown) if err != nil { log.Errorf("get vote down count error: %v", err) } return count }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vr *VoteRepo) GetAndSaveVoteResult(ctx context.Context, objectID, objectType string) ( up, down int64, err error) { up = vr.countVoteUp(ctx, objectID, objectType) down = vr.countVoteDown(ctx, objectID, objectType) err = vr.updateVotes(ctx, objectID, objectType, int(up-down)) return }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vr *VoteRepo) Vote(ctx context.Context, op *schema.VoteOperationInfo) (err error) { noNeedToVote, err := vr.votePreCheck(ctx, op) if err != nil { return err } if noNeedToVote { return nil } sendInboxNotification := false maxDailyRank, err := vr.userRankRepo.GetMaxDailyRank(ctx) if err != nil { return err } var userIDs []string for _, activity := range op.Activities { userIDs = append(userIDs, activity.ActivityUserID) } _, err = vr.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { session = session.Context(ctx) userInfoMapping, err := vr.acquireUserInfo(session, userIDs) if err != nil { return nil, err } err = vr.setActivityRankToZeroIfUserReachLimit(ctx, session, op, maxDailyRank) if err != nil { return nil, err } sendInboxNotification, err = vr.saveActivitiesAvailable(session, op) if err != nil { return nil, err } err = vr.changeUserRank(ctx, session, op, userInfoMapping) if err != nil { return nil, err } return nil, nil }) if err != nil { return err } for _, activity := range op.Activities { if activity.Rank == 0 { continue } vr.sendAchievementNotification(ctx, activity.ActivityUserID, op.ObjectCreatorUserID, op.ObjectID) } if sendInboxNotification { vr.sendVoteInboxNotification(ctx, op.OperatingUserID, op.ObjectCreatorUserID, op.ObjectID, op.VoteUp) } return nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vr *VoteRepo) acquireUserInfo(session *xorm.Session, userIDs []string) (map[string]*entity.User, error) { us := make([]*entity.User, 0) err := session.In("id", userIDs).ForUpdate().Find(&us) if err != nil { log.Error(err) return nil, err } users := make(map[string]*entity.User, 0) for _, u := range us { users[u.ID] = u } return users, nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vr *VoteRepo) saveActivitiesAvailable(session *xorm.Session, op *schema.VoteOperationInfo) (newAct bool, err error) { for _, activity := range op.Activities { existsActivity := &entity.Activity{} exist, err := session. Where(builder.Eq{"object_id": op.ObjectID}). And(builder.Eq{"user_id": activity.ActivityUserID}). And(builder.Eq{"trigger_user_id": activity.TriggerUserID}). And(builder.Eq{"activity_type": activity.ActivityType}). Get(existsActivity) if err != nil { return false, err } if exist && existsActivity.Cancelled == entity.ActivityAvailable { activity.Rank = 0 continue } if exist { if _, err = session.Where("id = ?", existsActivity.ID).Cols("`cancelled`"). Update(&entity.Activity{Cancelled: entity.ActivityAvailable}); err != nil { return false, err } } else { insertActivity := entity.Activity{ ObjectID: op.ObjectID, OriginalObjectID: op.ObjectID, UserID: activity.ActivityUserID, TriggerUserID: converter.StringToInt64(activity.TriggerUserID), ActivityType: activity.ActivityType, Rank: activity.Rank, HasRank: activity.HasRank(), Cancelled: entity.ActivityAvailable, } _, err = session.Insert(&insertActivity) if err != nil { return false, err } newAct = true } } return newAct, nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vr *VoteRepo) getExistActivity(ctx context.Context, op *schema.VoteOperationInfo) ([]*entity.Activity, error) { var activities []*entity.Activity for _, action := range op.Activities { t := &entity.Activity{} exist, err := vr.data.DB.Context(ctx). Where(builder.Eq{"user_id": action.ActivityUserID}). And(builder.Eq{"trigger_user_id": action.TriggerUserID}). And(builder.Eq{"activity_type": action.ActivityType}). And(builder.Eq{"object_id": op.ObjectID}). Get(t) if err != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } if exist { activities = append(activities, t) } } return activities, nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vr *VoteRepo) rollbackUserRank(ctx context.Context, session *xorm.Session, activities []*entity.Activity, userInfoMapping map[string]*entity.User) (err error) { for _, activity := range activities { if activity.Rank == 0 { continue } user := userInfoMapping[activity.UserID] if user == nil { continue } if err = vr.userRankRepo.ChangeUserRank(ctx, session, activity.UserID, user.Rank, -activity.Rank); err != nil { log.Error(err) return err } } return nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vr *VoteRepo) cancelActivities(session *xorm.Session, activities []*entity.Activity) (err error) { for _, activity := range activities { t := &entity.Activity{} exist, err := session.ID(activity.ID).Get(t) if err != nil { log.Error(err) return err } if !exist { log.Error(fmt.Errorf("%s activity not exist", activity.ID)) return fmt.Errorf("%s activity not exist", activity.ID) } // If this activity is already cancelled, set activity rank to 0 if t.Cancelled == entity.ActivityCancelled { activity.Rank = 0 } if _, err = session.ID(activity.ID).Cols("cancelled", "cancelled_at"). Update(&entity.Activity{ Cancelled: entity.ActivityCancelled, CancelledAt: time.Now(), }); err != nil { log.Error(err) return err } } return nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vr *VoteRepo) sendAchievementNotification(ctx context.Context, activityUserID, objectUserID, objectID string) { objectType, err := obj.GetObjectTypeStrByObjectID(objectID) if err != nil { return } msg := &schema.NotificationMsg{ ReceiverUserID: activityUserID, TriggerUserID: objectUserID, Type: schema.NotificationTypeAchievement, ObjectID: objectID, ObjectType: objectType, } vr.notificationQueueService.Send(ctx, msg) }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vr *VoteRepo) countVoteUp(ctx context.Context, objectID, objectType string) (count int64) { count, err := vr.countVote(ctx, objectID, objectType, constant.ActVoteUp) if err != nil { log.Errorf("get vote up count error: %v", err) } return count }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vr *VoteRepo) CancelVote(ctx context.Context, op *schema.VoteOperationInfo) (err error) { // Pre-Check // 1. check if the activity exist // 2. check if the activity is not cancelled // 3. if all activities are cancelled, return directly activities, err := vr.getExistActivity(ctx, op) if err != nil { return err } var userIDs []string for _, activity := range activities { if activity.Cancelled == entity.ActivityCancelled { continue } userIDs = append(userIDs, activity.UserID) } if len(userIDs) == 0 { return nil } _, err = vr.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { session = session.Context(ctx) userInfoMapping, err := vr.acquireUserInfo(session, userIDs) if err != nil { return nil, err } err = vr.cancelActivities(session, activities) if err != nil { return nil, err } err = vr.rollbackUserRank(ctx, session, activities, userInfoMapping) if err != nil { return nil, err } return nil, nil }) if err != nil { return err } for _, activity := range activities { if activity.Rank == 0 { continue } vr.sendAchievementNotification(ctx, activity.UserID, op.ObjectCreatorUserID, op.ObjectID) } return nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vr *VoteRepo) updateVotes(ctx context.Context, objectID, objectType string, voteCount int) (err error) { session := vr.data.DB.Context(ctx) switch objectType { case constant.QuestionObjectType: _, err = session.ID(objectID).Cols("vote_count").Update(&entity.Question{VoteCount: voteCount}) case constant.AnswerObjectType: _, err = session.ID(objectID).Cols("vote_count").Update(&entity.Answer{VoteCount: voteCount}) case constant.CommentObjectType: _, err = session.ID(objectID).Cols("vote_count").Update(&entity.Comment{VoteCount: voteCount}) } if err != nil { log.Error(err) } return }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vr *VoteRepo) votePreCheck(ctx context.Context, op *schema.VoteOperationInfo) (noNeedToVote bool, err error) { activities, err := vr.getExistActivity(ctx, op) if err != nil { return false, err } done := 0 for _, activity := range activities { if activity.Cancelled == entity.ActivityAvailable { done++ } } return done == len(op.Activities), nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vr *VoteRepo) countVote(ctx context.Context, objectID, objectType, action string) (count int64, err error) { activity := &entity.Activity{} activityType, _ := vr.activityRepo.GetActivityTypeByObjectType(ctx, objectType, action) count, err = vr.data.DB.Context(ctx).Where(builder.Eq{"object_id": objectID}). And(builder.Eq{"activity_type": activityType}). And(builder.Eq{"cancelled": 0}). Count(activity) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } return count, err }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (ar *ActivityRepo) GetActivityTypeByObjID(ctx context.Context, objectID string, action string) ( activityType, rank, hasRank int, err error) { objectType, err := obj.GetObjectTypeStrByObjectID(objectID) if err != nil { return } confKey := fmt.Sprintf("%s.%s", objectType, action) cfg, err := ar.configService.GetConfigByKey(ctx, confKey) if err != nil { return } activityType, rank = cfg.ID, cfg.GetIntValue() hasRank = 0 if rank != 0 { hasRank = 1 } return }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (ar *ActivityRepo) GetActivityTypeByObjectType(ctx context.Context, objectType, action string) (activityType int, err error) { configKey := fmt.Sprintf("%s.%s", objectType, action) cfg, err := ar.configService.GetConfigByKey(ctx, configKey) if err != nil { return 0, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } return cfg.ID, nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (ar *FollowRepo) IsFollowed(ctx context.Context, userID, objectID string) (followed bool, err error) { objectKey, err := obj.GetObjectTypeStrByObjectID(objectID) if err != nil { return false, err } activityType, err := ar.activityRepo.GetActivityTypeByObjectType(ctx, objectKey, "follow") if err != nil { return false, err } at := &entity.Activity{} has, err := ar.data.DB.Context(ctx).Where("user_id = ? AND object_id = ? AND activity_type = ?", userID, objectID, activityType).Get(at) if err != nil { return false, err } if !has { return false, nil } if at.Cancelled == entity.ActivityCancelled { return false, nil } else { return true, nil } }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (ar *FollowRepo) GetFollowUserIDs(ctx context.Context, objectID string) (userIDs []string, err error) { objectTypeStr, err := obj.GetObjectTypeStrByObjectID(objectID) if err != nil { return nil, err } activityType, err := ar.activityRepo.GetActivityTypeByObjectType(ctx, objectTypeStr, "follow") if err != nil { log.Errorf("can't get activity type by object key: %s", objectTypeStr) return nil, err } userIDs = make([]string, 0) session := ar.data.DB.Context(ctx).Select("user_id") session.Table(entity.Activity{}.TableName()) session.Where("object_id = ?", objectID) session.Where("activity_type = ?", activityType) session.Where("cancelled = 0") err = session.Find(&userIDs) if err != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } return userIDs, nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (ar *FollowRepo) GetFollowIDs(ctx context.Context, userID, objectKey string) (followIDs []string, err error) { followIDs = make([]string, 0) activityType, err := ar.activityRepo.GetActivityTypeByObjectType(ctx, objectKey, "follow") if err != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } session := ar.data.DB.Context(ctx).Select("object_id") session.Table(entity.Activity{}.TableName()) session.Where("user_id = ? AND activity_type = ?", userID, activityType) session.Where("cancelled = 0") err = session.Find(&followIDs) if err != nil { return nil, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } return followIDs, nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (ur *UserRankRepo) GetMaxDailyRank(ctx context.Context) (maxDailyRank int, err error) { maxDailyRank, err = ur.configService.GetIntValue(ctx, "daily_rank_limit") if err != nil { return 0, err } return maxDailyRank, nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (ur *UserRankRepo) TriggerUserRank(ctx context.Context, session *xorm.Session, userID string, deltaRank int, activityType int, ) (isReachStandard bool, err error) { // IMPORTANT: If user center enabled the rank agent, then we should not change user rank. if plugin.RankAgentEnabled() || deltaRank == 0 { return false, nil } if deltaRank < 0 { // if user rank is lower than 1 after this action, then user rank will be set to 1 only. var isReachMin bool isReachMin, err = ur.checkUserMinRank(ctx, session, userID, deltaRank) if err != nil { return false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } if isReachMin { _, err = session.Where(builder.Eq{"id": userID}).Update(&entity.User{Rank: 1}) if err != nil { return false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } return true, nil } } else { isReachStandard, err = ur.checkUserTodayRank(ctx, session, userID, activityType) if err != nil { return false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } if isReachStandard { return isReachStandard, nil } } _, err = session.Where(builder.Eq{"id": userID}).Incr("`rank`", deltaRank).Update(&entity.User{}) if err != nil { return false, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } return false, nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (ur *UserRankRepo) ChangeUserRank( ctx context.Context, session *xorm.Session, userID string, userCurrentScore, deltaRank int) (err error) { // IMPORTANT: If user center enabled the rank agent, then we should not change user rank. if plugin.RankAgentEnabled() || deltaRank == 0 { return nil } // If user rank is lower than 1 after this action, then user rank will be set to 1 only. if deltaRank < 0 && userCurrentScore+deltaRank < 1 { deltaRank = 1 - userCurrentScore } _, err = session.ID(userID).Incr("`rank`", deltaRank).Update(&entity.User{}) if err != nil { return err } return nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (ur *UserRankRepo) CheckReachLimit(ctx context.Context, session *xorm.Session, userID string, maxDailyRank int) ( reach bool, err error) { session.Where(builder.Eq{"user_id": userID}) session.Where(builder.Eq{"cancelled": 0}) session.Where(builder.Between{ Col: "updated_at", LessVal: now.BeginningOfDay(), MoreVal: now.EndOfDay(), }) earned, err := session.Sum(&entity.Activity{}, "`rank`") if err != nil { return false, err } if int(earned) <= maxDailyRank { return false, nil } log.Infof("user %s today has rank %d is reach stand %d", userID, earned, maxDailyRank) return true, nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (ur *userRepo) GetByUsernames(ctx context.Context, usernames []string) ([]*entity.User, error) { list := make([]*entity.User, 0) err := ur.data.DB.Context(ctx).Where("status =?", entity.UserStatusAvailable).In("username", usernames).Find(&list) if err != nil { err = errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() return list, err } tryToDecorateUserListFromUserCenter(ctx, ur.data, list) return list, nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (v *VoteActivity) HasRank() int { if v.Rank != 0 { return 1 } return 0 }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func NewAnswerActivityService( answerActivityRepo AnswerActivityRepo) *AnswerActivityService { return &AnswerActivityService{ answerActivityRepo: answerActivityRepo, } }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vs *VoteService) getActivities(ctx context.Context, op *schema.VoteOperationInfo) ( activities []*schema.VoteActivity) { activities = make([]*schema.VoteActivity, 0) var actions []string switch op.ObjectType { case constant.QuestionObjectType: if op.VoteUp { actions = []string{activity_type.QuestionVoteUp, activity_type.QuestionVotedUp} } else { actions = []string{activity_type.QuestionVoteDown, activity_type.QuestionVotedDown} } case constant.AnswerObjectType: if op.VoteUp { actions = []string{activity_type.AnswerVoteUp, activity_type.AnswerVotedUp} } else { actions = []string{activity_type.AnswerVoteDown, activity_type.AnswerVotedDown} } case constant.CommentObjectType: actions = []string{activity_type.CommentVoteUp} } for _, action := range actions { t := &schema.VoteActivity{} cfg, err := vs.configService.GetConfigByKey(ctx, action) if err != nil { log.Warnf("get config by key error: %v", err) continue } t.ActivityType, t.Rank = cfg.ID, cfg.GetIntValue() if strings.Contains(action, "voted") { t.ActivityUserID = op.ObjectCreatorUserID t.TriggerUserID = op.OperatingUserID } else { t.ActivityUserID = op.OperatingUserID t.TriggerUserID = "0" } activities = append(activities, t) } return activities }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vs *VoteService) VoteDown(ctx context.Context, req *schema.VoteReq) (resp *schema.VoteResp, err error) { objectInfo, err := vs.objectService.GetInfo(ctx, req.ObjectID) if err != nil { return nil, err } // make object id must be decoded objectInfo.ObjectID = req.ObjectID // check user is voting self or not if objectInfo.ObjectCreatorUserID == req.UserID { return nil, errors.BadRequest(reason.DisallowVoteYourSelf) } // vote operation voteDownOperationInfo := vs.createVoteOperationInfo(ctx, req.UserID, false, objectInfo) if req.IsCancel { err = vs.voteRepo.CancelVote(ctx, voteDownOperationInfo) } else { // cancel vote up if exist err = vs.voteRepo.CancelVote(ctx, vs.createVoteOperationInfo(ctx, req.UserID, true, objectInfo)) if err != nil { return nil, err } err = vs.voteRepo.Vote(ctx, voteDownOperationInfo) } resp = &schema.VoteResp{} resp.UpVotes, resp.DownVotes, err = vs.voteRepo.GetAndSaveVoteResult(ctx, req.ObjectID, objectInfo.ObjectType) if err != nil { log.Error(err) } resp.Votes = resp.UpVotes - resp.DownVotes if !req.IsCancel { resp.VoteStatus = constant.ActVoteDown } return resp, nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func NewVoteService( voteRepo VoteRepo, configService *config.ConfigService, questionRepo questioncommon.QuestionRepo, answerRepo answercommon.AnswerRepo, commentCommonRepo comment_common.CommentCommonRepo, objectService *object_info.ObjService, ) *VoteService { return &VoteService{ voteRepo: voteRepo, configService: configService, questionRepo: questionRepo, answerRepo: answerRepo, commentCommonRepo: commentCommonRepo, objectService: objectService, } }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vs *VoteService) createVoteOperationInfo(ctx context.Context, userID string, voteUp bool, objectInfo *schema.SimpleObjectInfo) *schema.VoteOperationInfo { // warp vote operation voteOperationInfo := &schema.VoteOperationInfo{ ObjectID: objectInfo.ObjectID, ObjectType: objectInfo.ObjectType, ObjectCreatorUserID: objectInfo.ObjectCreatorUserID, OperatingUserID: userID, VoteUp: voteUp, VoteDown: !voteUp, } voteOperationInfo.Activities = vs.getActivities(ctx, voteOperationInfo) return voteOperationInfo }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (vs *VoteService) VoteUp(ctx context.Context, req *schema.VoteReq) (resp *schema.VoteResp, err error) { objectInfo, err := vs.objectService.GetInfo(ctx, req.ObjectID) if err != nil { return nil, err } // make object id must be decoded objectInfo.ObjectID = req.ObjectID // check user is voting self or not if objectInfo.ObjectCreatorUserID == req.UserID { return nil, errors.BadRequest(reason.DisallowVoteYourSelf) } voteUpOperationInfo := vs.createVoteOperationInfo(ctx, req.UserID, true, objectInfo) // vote operation if req.IsCancel { err = vs.voteRepo.CancelVote(ctx, voteUpOperationInfo) } else { // cancel vote down if exist voteOperationInfo := vs.createVoteOperationInfo(ctx, req.UserID, false, objectInfo) err = vs.voteRepo.CancelVote(ctx, voteOperationInfo) if err != nil { return nil, err } err = vs.voteRepo.Vote(ctx, voteUpOperationInfo) } resp = &schema.VoteResp{} resp.UpVotes, resp.DownVotes, err = vs.voteRepo.GetAndSaveVoteResult(ctx, req.ObjectID, objectInfo.ObjectType) if err != nil { log.Error(err) } resp.Votes = resp.UpVotes - resp.DownVotes if !req.IsCancel { resp.VoteStatus = constant.ActVoteUp } return resp, nil }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe
func (m *Mentor) initSiteInfoPrivilegeRank() { privilegeRankData := map[string]interface{}{ "level": schema.PrivilegeLevel2, } privilegeRankDataBytes, _ := json.Marshal(privilegeRankData) _, m.err = m.engine.Context(m.ctx).Insert(&entity.SiteInfo{ Type: "privileges", Content: string(privilegeRankDataBytes), Status: 1, }) }
1
Go
CWE-862
Missing Authorization
The product does not perform an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/862.html
safe
func (m *Mentor) InitDB() error { m.do("check table exist", m.checkTableExist) m.do("sync table", m.syncTable) m.do("init version table", m.initVersionTable) m.do("init admin user", m.initAdminUser) m.do("init config", m.initConfig) m.do("init default privileges config", m.initDefaultRankPrivileges) m.do("init role", m.initRole) m.do("init power", m.initPower) m.do("init role power rel", m.initRolePowerRel) m.do("init admin user role rel", m.initAdminUserRoleRel) m.do("init site info interface", m.initSiteInfoInterface) m.do("init site info general config", m.initSiteInfoGeneralData) m.do("init site info login config", m.initSiteInfoLoginConfig) m.do("init site info theme config", m.initSiteInfoThemeConfig) m.do("init site info seo config", m.initSiteInfoSEOConfig) m.do("init site info user config", m.initSiteInfoUsersConfig) m.do("init site info privilege rank", m.initSiteInfoPrivilegeRank) return m.err }
1
Go
CWE-862
Missing Authorization
The product does not perform an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/862.html
safe
func (m *Mentor) initDefaultRankPrivileges() { chooseOption := schema.DefaultPrivilegeOptions.Choose(schema.PrivilegeLevel2) for _, privilege := range chooseOption.Privileges { _, err := m.engine.Context(m.ctx).Update( &entity.Config{Value: fmt.Sprintf("%d", privilege.Value)}, &entity.Config{Key: privilege.Key}, ) if err != nil { log.Error(err) } } }
1
Go
CWE-862
Missing Authorization
The product does not perform an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/862.html
safe
func (p PrivilegeOptions) Choose(level PrivilegeLevel) (option *PrivilegeOption) { for _, op := range p { if op.Level == level { return op } } return nil }
1
Go
CWE-862
Missing Authorization
The product does not perform an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/862.html
safe
func (am *AuthUserMiddleware) AdminAuth() gin.HandlerFunc { return func(ctx *gin.Context) { token := ExtractToken(ctx) if len(token) == 0 { handler.HandleResponse(ctx, errors.Unauthorized(reason.UnauthorizedError), nil) ctx.Abort() return } userInfo, err := am.authService.GetAdminUserCacheInfo(ctx, token) if err != nil || userInfo == nil { handler.HandleResponse(ctx, errors.Forbidden(reason.UnauthorizedError), nil) ctx.Abort() return } if userInfo != nil { if userInfo.UserStatus == entity.UserStatusDeleted { handler.HandleResponse(ctx, errors.Unauthorized(reason.UnauthorizedError), nil) ctx.Abort() return } ctx.Set(ctxUUIDKey, userInfo) } ctx.Next() } }
1
Go
CWE-306
Missing Authentication for Critical Function
The product does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.
https://cwe.mitre.org/data/definitions/306.html
safe
func (ar *AnswerActivityRepo) sendAcceptAnswerNotification( ctx context.Context, op *schema.AcceptAnswerOperationInfo) { for _, act := range op.Activities { msg := &schema.NotificationMsg{ Type: schema.NotificationTypeAchievement, ObjectID: op.AnswerObjectID, ReceiverUserID: act.ActivityUserID, TriggerUserID: act.TriggerUserID, } if act.ActivityUserID == op.QuestionUserID { msg.ObjectType = constant.AnswerObjectType } else { msg.ObjectType = constant.AnswerObjectType } if msg.TriggerUserID != msg.ReceiverUserID { ar.notificationQueueService.Send(ctx, msg) } } for _, act := range op.Activities { msg := &schema.NotificationMsg{ ReceiverUserID: act.ActivityUserID, Type: schema.NotificationTypeInbox, ObjectID: op.AnswerObjectID, TriggerUserID: op.TriggerUserID, } if act.ActivityUserID != op.QuestionUserID { msg.ObjectType = constant.AnswerObjectType msg.NotificationAction = constant.NotificationAcceptAnswer ar.notificationQueueService.Send(ctx, msg) } } }
1
Go
CWE-306
Missing Authentication for Critical Function
The product does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.
https://cwe.mitre.org/data/definitions/306.html
safe
func (ar *AnswerActivityRepo) sendCancelAcceptAnswerNotification( ctx context.Context, op *schema.AcceptAnswerOperationInfo) { for _, act := range op.Activities { msg := &schema.NotificationMsg{ TriggerUserID: act.TriggerUserID, ReceiverUserID: act.ActivityUserID, Type: schema.NotificationTypeAchievement, ObjectID: op.AnswerObjectID, } if act.ActivityUserID == op.QuestionObjectID { msg.ObjectType = constant.QuestionObjectType } else { msg.ObjectType = constant.AnswerObjectType } if msg.TriggerUserID != msg.ReceiverUserID { ar.notificationQueueService.Send(ctx, msg) } } }
1
Go
CWE-306
Missing Authentication for Critical Function
The product does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.
https://cwe.mitre.org/data/definitions/306.html
safe
func (hs *HTTPServer) GetPluginMarkdown(c *models.ReqContext) response.Response { pluginID := web.Params(c.Req)[":pluginId"] name := web.Params(c.Req)[":name"] content, err := hs.pluginMarkdown(c.Req.Context(), pluginID, name) if err != nil { var notFound plugins.NotFoundError if errors.As(err, &notFound) { return response.Error(404, notFound.Error(), nil) } return response.Error(500, "Could not get markdown file", err) } // fallback try readme if len(content) == 0 { content, err = hs.pluginMarkdown(c.Req.Context(), pluginID, "readme") if err != nil { return response.Error(501, "Could not get markdown file", err) } } resp := response.Respond(http.StatusOK, content) resp.SetHeader("Content-Type", "text/plain; charset=utf-8") return resp }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
safe
func NewHandler() *Handler { return &Handler{ clusterService: cluster.NewService(), userService: user.NewService(), roleService: role.NewService(), rolebindingService: rolebinding.NewService(), ldapService: ldap.NewService(), jwtSigner: jwt.NewSigner(jwt.HS256, server.Config().Spec.Jwt.Key, jwtMaxAge), } }
1
Go
CWE-798
Use of Hard-coded Credentials
The product contains hard-coded credentials, such as a password or cryptographic key, which it uses for its own inbound authentication, outbound communication to external components, or encryption of internal data.
https://cwe.mitre.org/data/definitions/798.html
safe
func generate(length int) string { const base = 36 size := big.NewInt(base) n := make([]byte, length) for i := range n { c, _ := rand.Int(rand.Reader, size) n[i] = strconv.FormatInt(c.Int64(), base)[0] } return string(n) }
1
Go
CWE-798
Use of Hard-coded Credentials
The product contains hard-coded credentials, such as a password or cryptographic key, which it uses for its own inbound authentication, outbound communication to external components, or encryption of internal data.
https://cwe.mitre.org/data/definitions/798.html
safe
func ReadConfig(c *config.Config, path ...string) error { v := viper.New() v.SetConfigName("app") v.SetConfigType("yaml") for i := range path { configFilePaths = append(configFilePaths, path[i]) } for i := range configFilePaths { realDir := file.ReplaceHomeDir(configFilePaths[i]) if exists := fileutil.Exist(realDir); !exists { fmt.Println(fmt.Sprintf(configNotFoundSkipErr, realDir)) continue } v.AddConfigPath(realDir) if err := v.ReadInConfig(); err != nil { fmt.Println(fmt.Sprintf(configReadErr, realDir, err.Error())) continue } if err := v.MergeInConfig(); err != nil { fmt.Println(fmt.Sprintf(configMergeErr, configFilePaths)) } } var configMap map[string]interface{} if err := v.Unmarshal(&configMap); err != nil { return err } str, err := json.Marshal(&configMap) if err != nil { return err } if err := json.Unmarshal(str, &c); err != nil { return nil } if c.Spec.Jwt.Key == "" { v.Set("spec.jwt.key", generate(32)) if err := v.WriteConfig(); err != nil { return err } } return nil }
1
Go
CWE-798
Use of Hard-coded Credentials
The product contains hard-coded credentials, such as a password or cryptographic key, which it uses for its own inbound authentication, outbound communication to external components, or encryption of internal data.
https://cwe.mitre.org/data/definitions/798.html
safe
func AddV1Route(app iris.Party) { v1Party := app.Party("/v1") session.Install(v1Party) mfa.Install(v1Party) authParty := v1Party.Party("") v1Party.Use(langHandler()) v1Party.Use(pageHandler()) authParty.Use(WarpedJwtHandler()) authParty.Use(authHandler()) authParty.Use(resourceExtractHandler()) authParty.Use(roleHandler()) authParty.Use(roleAccessHandler()) authParty.Use(resourceNameInvalidHandler()) authParty.Use(logHandler()) authParty.Get("/", apiResourceHandler(authParty)) user.Install(authParty) cluster.Install(authParty) role.Install(authParty) system.Install(authParty) proxy.Install(authParty) ws.Install(authParty) chart.Install(authParty) webkubectl.Install(authParty, v1Party) ldap.Install(authParty) imagerepo.Install(authParty) file.Install(authParty) }
1
Go
CWE-862
Missing Authorization
The product does not perform an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/862.html
safe
func (wm *HumanPasswordWriteModel) Query() *eventstore.SearchQueryBuilder { query := eventstore.NewSearchQueryBuilder(eventstore.ColumnsEvent). AddQuery(). AggregateTypes(user.AggregateType). AggregateIDs(wm.AggregateID). EventTypes(user.HumanAddedType, user.HumanRegisteredType, user.HumanInitialCodeAddedType, user.HumanInitializedCheckSucceededType, user.HumanPasswordChangedType, user.HumanPasswordCodeAddedType, user.HumanEmailVerifiedType, user.HumanPasswordCheckFailedType, user.HumanPasswordCheckSucceededType, user.HumanPasswordHashUpdatedType, user.UserRemovedType, user.UserLockedType, user.UserUnlockedType, user.UserV1AddedType, user.UserV1RegisteredType, user.UserV1InitialCodeAddedType, user.UserV1InitializedCheckSucceededType, user.UserV1PasswordChangedType, user.UserV1PasswordCodeAddedType, user.UserV1EmailVerifiedType, user.UserV1PasswordCheckFailedType, user.UserV1PasswordCheckSucceededType, ). Builder() if wm.ResourceOwner != "" { query.ResourceOwner(wm.ResourceOwner) } if wm.WriteModel.ProcessedSequence != 0 { query.SequenceGreater(wm.WriteModel.ProcessedSequence) } return query }
1
Go
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The product contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.
https://cwe.mitre.org/data/definitions/362.html
safe
func (wm *HumanPasswordWriteModel) Reduce() error { for _, event := range wm.Events { switch e := event.(type) { case *user.HumanAddedEvent: wm.EncodedHash = user.SecretOrEncodedHash(e.Secret, e.EncodedHash) wm.SecretChangeRequired = e.ChangeRequired wm.UserState = domain.UserStateActive case *user.HumanRegisteredEvent: wm.EncodedHash = user.SecretOrEncodedHash(e.Secret, e.EncodedHash) wm.SecretChangeRequired = e.ChangeRequired wm.UserState = domain.UserStateActive case *user.HumanInitialCodeAddedEvent: wm.UserState = domain.UserStateInitial case *user.HumanInitializedCheckSucceededEvent: wm.UserState = domain.UserStateActive case *user.HumanPasswordChangedEvent: wm.EncodedHash = user.SecretOrEncodedHash(e.Secret, e.EncodedHash) wm.SecretChangeRequired = e.ChangeRequired wm.Code = nil wm.PasswordCheckFailedCount = 0 case *user.HumanPasswordCodeAddedEvent: wm.Code = e.Code wm.CodeCreationDate = e.CreationDate() wm.CodeExpiry = e.Expiry case *user.HumanEmailVerifiedEvent: if wm.UserState == domain.UserStateInitial { wm.UserState = domain.UserStateActive } case *user.HumanPasswordCheckFailedEvent: wm.PasswordCheckFailedCount += 1 case *user.HumanPasswordCheckSucceededEvent: wm.PasswordCheckFailedCount = 0 case *user.UserLockedEvent: wm.UserState = domain.UserStateLocked case *user.UserUnlockedEvent: wm.PasswordCheckFailedCount = 0 if wm.UserState != domain.UserStateDeleted { wm.UserState = domain.UserStateActive } case *user.UserRemovedEvent: wm.UserState = domain.UserStateDeleted case *user.HumanPasswordHashUpdatedEvent: wm.EncodedHash = e.EncodedHash } } return wm.WriteModel.Reduce() }
1
Go
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The product contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.
https://cwe.mitre.org/data/definitions/362.html
safe
func (wm *HumanPasswordReadModel) Query() *eventstore.SearchQueryBuilder { query := eventstore.NewSearchQueryBuilder(eventstore.ColumnsEvent). AwaitOpenTransactions(). AllowTimeTravel(). AddQuery(). AggregateTypes(user.AggregateType). AggregateIDs(wm.AggregateID). EventTypes(user.HumanAddedType, user.HumanRegisteredType, user.HumanInitialCodeAddedType, user.HumanInitializedCheckSucceededType, user.HumanPasswordChangedType, user.HumanPasswordCodeAddedType, user.HumanEmailVerifiedType, user.HumanPasswordCheckFailedType, user.HumanPasswordCheckSucceededType, user.HumanPasswordHashUpdatedType, user.UserRemovedType, user.UserLockedType, user.UserUnlockedType, user.UserV1AddedType, user.UserV1RegisteredType, user.UserV1InitialCodeAddedType, user.UserV1InitializedCheckSucceededType, user.UserV1PasswordChangedType, user.UserV1PasswordCodeAddedType, user.UserV1EmailVerifiedType, user.UserV1PasswordCheckFailedType, user.UserV1PasswordCheckSucceededType, ). Builder() if wm.ResourceOwner != "" { query.ResourceOwner(wm.ResourceOwner) } return query }
1
Go
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The product contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.
https://cwe.mitre.org/data/definitions/362.html
safe
func (wm *HumanPasswordReadModel) Reduce() error { for _, event := range wm.Events { switch e := event.(type) { case *user.HumanAddedEvent: wm.EncodedHash = user.SecretOrEncodedHash(e.Secret, e.EncodedHash) wm.SecretChangeRequired = e.ChangeRequired wm.UserState = domain.UserStateActive case *user.HumanRegisteredEvent: wm.EncodedHash = user.SecretOrEncodedHash(e.Secret, e.EncodedHash) wm.SecretChangeRequired = e.ChangeRequired wm.UserState = domain.UserStateActive case *user.HumanInitialCodeAddedEvent: wm.UserState = domain.UserStateInitial case *user.HumanInitializedCheckSucceededEvent: wm.UserState = domain.UserStateActive case *user.HumanPasswordChangedEvent: wm.EncodedHash = user.SecretOrEncodedHash(e.Secret, e.EncodedHash) wm.SecretChangeRequired = e.ChangeRequired wm.Code = nil wm.PasswordCheckFailedCount = 0 case *user.HumanPasswordCodeAddedEvent: wm.Code = e.Code wm.CodeCreationDate = e.CreationDate() wm.CodeExpiry = e.Expiry case *user.HumanEmailVerifiedEvent: if wm.UserState == domain.UserStateInitial { wm.UserState = domain.UserStateActive } case *user.HumanPasswordCheckFailedEvent: wm.PasswordCheckFailedCount += 1 case *user.HumanPasswordCheckSucceededEvent: wm.PasswordCheckFailedCount = 0 case *user.UserLockedEvent: wm.UserState = domain.UserStateLocked case *user.UserUnlockedEvent: wm.PasswordCheckFailedCount = 0 if wm.UserState != domain.UserStateDeleted { wm.UserState = domain.UserStateActive } case *user.UserRemovedEvent: wm.UserState = domain.UserStateDeleted case *user.HumanPasswordHashUpdatedEvent: wm.EncodedHash = e.EncodedHash } } return wm.ReadModel.Reduce() }
1
Go
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The product contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.
https://cwe.mitre.org/data/definitions/362.html
safe
func Serve(ctx context.Context, artifactPath string, addr string, port string) context.CancelFunc { serverContext, cancel := context.WithCancel(ctx) logger := common.Logger(serverContext) if artifactPath == "" { return cancel } router := httprouter.New() logger.Debugf("Artifacts base path '%s'", artifactPath) fsys := readWriteFSImpl{} uploads(router, artifactPath, fsys) downloads(router, artifactPath, fsys) server := &http.Server{ Addr: fmt.Sprintf("%s:%s", addr, port), ReadHeaderTimeout: 2 * time.Second, Handler: router, } // run server go func() { logger.Infof("Start server on http://%s:%s", addr, port) if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed { logger.Fatal(err) } }() // wait for cancel to gracefully shutdown server go func() { <-serverContext.Done() if err := server.Shutdown(ctx); err != nil { logger.Errorf("Failed shutdown gracefully - force shutdown: %v", err) server.Close() } }() return cancel }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func (fwfs readWriteFSImpl) Open(name string) (fs.File, error) { return os.Open(name) }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func (fwfs readWriteFSImpl) OpenAppendable(name string) (WritableFile, error) { if err := os.MkdirAll(filepath.Dir(name), os.ModePerm); err != nil { return nil, err } file, err := os.OpenFile(name, os.O_CREATE|os.O_RDWR, 0644) if err != nil { return nil, err } _, err = file.Seek(0, os.SEEK_END) if err != nil { return nil, err } return file, nil }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func uploads(router *httprouter.Router, baseDir string, fsys WriteFS) { router.POST("/_apis/pipelines/workflows/:runId/artifacts", func(w http.ResponseWriter, req *http.Request, params httprouter.Params) { runID := params.ByName("runId") json, err := json.Marshal(FileContainerResourceURL{ FileContainerResourceURL: fmt.Sprintf("http://%s/upload/%s", req.Host, runID), }) if err != nil { panic(err) } _, err = w.Write(json) if err != nil { panic(err) } }) router.PUT("/upload/:runId", func(w http.ResponseWriter, req *http.Request, params httprouter.Params) { itemPath := req.URL.Query().Get("itemPath") runID := params.ByName("runId") if req.Header.Get("Content-Encoding") == "gzip" { itemPath += gzipExtension } safeRunPath := safeResolve(baseDir, runID) safePath := safeResolve(safeRunPath, itemPath) file, err := func() (WritableFile, error) { contentRange := req.Header.Get("Content-Range") if contentRange != "" && !strings.HasPrefix(contentRange, "bytes 0-") { return fsys.OpenAppendable(safePath) } return fsys.OpenWritable(safePath) }() if err != nil { panic(err) } defer file.Close() writer, ok := file.(io.Writer) if !ok { panic(errors.New("File is not writable")) } if req.Body == nil { panic(errors.New("No body given")) } _, err = io.Copy(writer, req.Body) if err != nil { panic(err) } json, err := json.Marshal(ResponseMessage{ Message: "success", }) if err != nil { panic(err) } _, err = w.Write(json) if err != nil { panic(err) } }) router.PATCH("/_apis/pipelines/workflows/:runId/artifacts", func(w http.ResponseWriter, req *http.Request, params httprouter.Params) { json, err := json.Marshal(ResponseMessage{ Message: "success", }) if err != nil { panic(err) } _, err = w.Write(json) if err != nil { panic(err) } }) }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func (fwfs readWriteFSImpl) OpenWritable(name string) (WritableFile, error) { if err := os.MkdirAll(filepath.Dir(name), os.ModePerm); err != nil { return nil, err } return os.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0644) }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func safeResolve(baseDir string, relPath string) string { return filepath.Join(baseDir, filepath.Clean(filepath.Join(string(os.PathSeparator), relPath))) }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
err := fs.WalkDir(fsys, safePath, func(path string, entry fs.DirEntry, err error) error { if !entry.IsDir() { rel, err := filepath.Rel(safePath, path) if err != nil { panic(err) } // if it was upload as gzip rel = strings.TrimSuffix(rel, gzipExtension) files = append(files, ContainerItem{ Path: filepath.Join(itemPath, rel), ItemType: "file", ContentLocation: fmt.Sprintf("http://%s/artifact/%s/%s/%s", req.Host, container, itemPath, rel), }) } return nil })
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func TestListArtifactContainer(t *testing.T) { assert := assert.New(t) var memfs = fstest.MapFS(map[string]*fstest.MapFile{ "artifact/server/path/1/some/file": { Data: []byte(""), }, }) router := httprouter.New() downloads(router, "artifact/server/path", memfs) req, _ := http.NewRequest("GET", "http://localhost/download/1?itemPath=some/file", nil) rr := httptest.NewRecorder() router.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { assert.FailNow(fmt.Sprintf("Wrong status: %d", status)) } response := ContainerItemResponse{} err := json.Unmarshal(rr.Body.Bytes(), &response) if err != nil { panic(err) } assert.Equal(1, len(response.Value)) assert.Equal("some/file", response.Value[0].Path) assert.Equal("file", response.Value[0].ItemType) assert.Equal("http://localhost/artifact/1/some/file/.", response.Value[0].ContentLocation) }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func TestArtifactFlow(t *testing.T) { if testing.Short() { t.Skip("skipping integration test") } ctx := context.Background() cancel := Serve(ctx, artifactsPath, artifactsAddr, artifactsPort) defer cancel() platforms := map[string]string{ "ubuntu-latest": "node:16-buster-slim", } tables := []TestJobFileInfo{ {"testdata", "upload-and-download", "push", "", platforms, ""}, {"testdata", "GHSL-2023-004", "push", "", platforms, ""}, } log.SetLevel(log.DebugLevel) for _, table := range tables { runTestJobFile(ctx, t, table) } }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func (fsys writeMapFS) OpenAppendable(name string) (WritableFile, error) { var file = &writableMapFile{ MapFile: fstest.MapFile{ Data: []byte("content2"), }, } fsys.MapFS[name] = &file.MapFile return file, nil }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func TestDownloadArtifactFile(t *testing.T) { assert := assert.New(t) var memfs = fstest.MapFS(map[string]*fstest.MapFile{ "artifact/server/path/1/some/file": { Data: []byte("content"), }, }) router := httprouter.New() downloads(router, "artifact/server/path", memfs) req, _ := http.NewRequest("GET", "http://localhost/artifact/1/some/file", nil) rr := httptest.NewRecorder() router.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { assert.FailNow(fmt.Sprintf("Wrong status: %d", status)) } data := rr.Body.Bytes() assert.Equal("content", string(data)) }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func TestArtifactUploadBlobUnsafePath(t *testing.T) { assert := assert.New(t) var memfs = fstest.MapFS(map[string]*fstest.MapFile{}) router := httprouter.New() uploads(router, "artifact/server/path", writeMapFS{memfs}) req, _ := http.NewRequest("PUT", "http://localhost/upload/1?itemPath=../../some/file", strings.NewReader("content")) rr := httptest.NewRecorder() router.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { assert.Fail("Wrong status") } response := ResponseMessage{} err := json.Unmarshal(rr.Body.Bytes(), &response) if err != nil { panic(err) } assert.Equal("success", response.Message) assert.Equal("content", string(memfs["artifact/server/path/1/some/file"].Data)) }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func (fsys writeMapFS) OpenWritable(name string) (WritableFile, error) { var file = &writableMapFile{ MapFile: fstest.MapFile{ Data: []byte("content2"), }, } fsys.MapFS[name] = &file.MapFile return file, nil }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func TestFinalizeArtifactUpload(t *testing.T) { assert := assert.New(t) var memfs = fstest.MapFS(map[string]*fstest.MapFile{}) router := httprouter.New() uploads(router, "artifact/server/path", writeMapFS{memfs}) req, _ := http.NewRequest("PATCH", "http://localhost/_apis/pipelines/workflows/1/artifacts", nil) rr := httptest.NewRecorder() router.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { assert.Fail("Wrong status") } response := ResponseMessage{} err := json.Unmarshal(rr.Body.Bytes(), &response) if err != nil { panic(err) } assert.Equal("success", response.Message) }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func TestListArtifacts(t *testing.T) { assert := assert.New(t) var memfs = fstest.MapFS(map[string]*fstest.MapFile{ "artifact/server/path/1/file.txt": { Data: []byte(""), }, }) router := httprouter.New() downloads(router, "artifact/server/path", memfs) req, _ := http.NewRequest("GET", "http://localhost/_apis/pipelines/workflows/1/artifacts", nil) rr := httptest.NewRecorder() router.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { assert.FailNow(fmt.Sprintf("Wrong status: %d", status)) } response := NamedFileContainerResourceURLResponse{} err := json.Unmarshal(rr.Body.Bytes(), &response) if err != nil { panic(err) } assert.Equal(1, response.Count) assert.Equal("file.txt", response.Value[0].Name) assert.Equal("http://localhost/download/1", response.Value[0].FileContainerResourceURL) }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func (f *writableMapFile) Write(data []byte) (int, error) { f.Data = data return len(data), nil }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func (f *writableMapFile) Close() error { return nil }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func TestDownloadArtifactFileUnsafePath(t *testing.T) { assert := assert.New(t) var memfs = fstest.MapFS(map[string]*fstest.MapFile{ "artifact/server/path/some/file": { Data: []byte("content"), }, }) router := httprouter.New() downloads(router, "artifact/server/path", memfs) req, _ := http.NewRequest("GET", "http://localhost/artifact/2/../../some/file", nil) rr := httptest.NewRecorder() router.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { assert.FailNow(fmt.Sprintf("Wrong status: %d", status)) } data := rr.Body.Bytes() assert.Equal("content", string(data)) }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func TestMkdirFsImplSafeResolve(t *testing.T) { assert := assert.New(t) baseDir := "/foo/bar" tests := map[string]struct { input string want string }{ "simple": {input: "baz", want: "/foo/bar/baz"}, "nested": {input: "baz/blue", want: "/foo/bar/baz/blue"}, "dots in middle": {input: "baz/../../blue", want: "/foo/bar/blue"}, "leading dots": {input: "../../parent", want: "/foo/bar/parent"}, "root path": {input: "/root", want: "/foo/bar/root"}, "root": {input: "/", want: "/foo/bar"}, "empty": {input: "", want: "/foo/bar"}, } for name, tc := range tests { t.Run(name, func(t *testing.T) { assert.Equal(tc.want, safeResolve(baseDir, tc.input)) }) } }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func TestArtifactUploadBlob(t *testing.T) { assert := assert.New(t) var memfs = fstest.MapFS(map[string]*fstest.MapFile{}) router := httprouter.New() uploads(router, "artifact/server/path", writeMapFS{memfs}) req, _ := http.NewRequest("PUT", "http://localhost/upload/1?itemPath=some/file", strings.NewReader("content")) rr := httptest.NewRecorder() router.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { assert.Fail("Wrong status") } response := ResponseMessage{} err := json.Unmarshal(rr.Body.Bytes(), &response) if err != nil { panic(err) } assert.Equal("success", response.Message) assert.Equal("content", string(memfs["artifact/server/path/1/some/file"].Data)) }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
func TestNewArtifactUploadPrepare(t *testing.T) { assert := assert.New(t) var memfs = fstest.MapFS(map[string]*fstest.MapFile{}) router := httprouter.New() uploads(router, "artifact/server/path", writeMapFS{memfs}) req, _ := http.NewRequest("POST", "http://localhost/_apis/pipelines/workflows/1/artifacts", nil) rr := httptest.NewRecorder() router.ServeHTTP(rr, req) if status := rr.Code; status != http.StatusOK { assert.Fail("Wrong status") } response := FileContainerResourceURL{} err := json.Unmarshal(rr.Body.Bytes(), &response) if err != nil { panic(err) } assert.Equal("http://localhost/upload/1", response.FileContainerResourceURL) }
1
Go
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
function lazyFunc() {}
1
Go
CWE-476
NULL Pointer Dereference
A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.
https://cwe.mitre.org/data/definitions/476.html
safe
func FromBytes(size int, bits []byte) (Bitfield, error) { bf, err := NewBitfield(size) if err != nil { return nil, err } start := len(bf) - len(bits) if start < 0 { return nil, fmt.Errorf("bitfield too small: got %d; need %d", size, len(bits)*8) } copy(bf[start:], bits) return bf, nil }
1
Go
CWE-1284
Improper Validation of Specified Quantity in Input
The product receives input that is expected to specify a quantity (such as size or length), but it does not validate or incorrectly validates that the quantity has the required properties.
https://cwe.mitre.org/data/definitions/1284.html
safe
func NewBitfield(size int) (Bitfield, error) { if size < 0 { return nil, fmt.Errorf("bitfield size must be positive; got %d", size) } if size%8 != 0 { return nil, fmt.Errorf("bitfield size must be a multiple of 8; got %d", size) } return make([]byte, size/8), nil }
1
Go
CWE-1284
Improper Validation of Specified Quantity in Input
The product receives input that is expected to specify a quantity (such as size or length), but it does not validate or incorrectly validates that the quantity has the required properties.
https://cwe.mitre.org/data/definitions/1284.html
safe
func BenchmarkBitfield(t *testing.B) { bf, err := NewBitfield(benchmarkSize) assertNoError(t, err) t.ResetTimer() for i := 0; i < t.N; i++ { if bf.Bit(i % benchmarkSize) { t.Fatal("bad", i) } bf.SetBit(i % benchmarkSize) bf.UnsetBit(i % benchmarkSize) bf.SetBit(i % benchmarkSize) bf.UnsetBit(i % benchmarkSize) bf.SetBit(i % benchmarkSize) bf.UnsetBit(i % benchmarkSize) bf.SetBit(i % benchmarkSize) if !bf.Bit(i % benchmarkSize) { t.Fatal("bad", i) } bf.UnsetBit(i % benchmarkSize) bf.SetBit(i % benchmarkSize) bf.UnsetBit(i % benchmarkSize) bf.SetBit(i % benchmarkSize) bf.UnsetBit(i % benchmarkSize) bf.SetBit(i % benchmarkSize) bf.UnsetBit(i % benchmarkSize) if bf.Bit(i % benchmarkSize) { t.Fatal("bad", i) } } }
1
Go
CWE-1284
Improper Validation of Specified Quantity in Input
The product receives input that is expected to specify a quantity (such as size or length), but it does not validate or incorrectly validates that the quantity has the required properties.
https://cwe.mitre.org/data/definitions/1284.html
safe
func TestExhaustive24(t *testing.T) { bf, err := NewBitfield(24) assertNoError(t, err) max := 1 << 24 bint := new(big.Int) bts := make([]byte, 4) for j := 0; j < max; j++ { binary.BigEndian.PutUint32(bts, uint32(j)) bint.SetBytes(bts[1:]) bf.SetBytes(nil) for i := 0; i < 24; i++ { if bf.Bit(i) { t.Fatalf("bit %d should have been false", i) } if bint.Bit(i) == 1 { bf.SetBit(i) bf.SetBit(i) } else { bf.UnsetBit(i) bf.UnsetBit(i) } if bf.Bit(i) != (bint.Bit(i) == 1) { t.Fatalf("bit %d should have been true", i) } } if !bytes.Equal(bint.Bytes(), bf.Bytes()) { t.Logf("%v %v", bint.Bytes(), bf.Bytes()) t.Fatal("big int and bitfield not equal") } for i := 0; i < 24; i++ { if (bint.Bit(i) == 1) != bf.Bit(i) { t.Fatalf("bit %d wrong", i) } } for i := 0; i < 24; i++ { if bf.OnesBefore(i) != bits.OnesCount32(uint32(j)<<(32-uint(i))) { t.Fatalf("wrong bit count") } if bf.OnesAfter(i) != bits.OnesCount32(uint32(j)>>uint(i)) { t.Fatalf("wrong bit count") } if bf.Ones() != bits.OnesCount32(uint32(j)) { t.Fatalf("wrong bit count") } } } }
1
Go
CWE-1284
Improper Validation of Specified Quantity in Input
The product receives input that is expected to specify a quantity (such as size or length), but it does not validate or incorrectly validates that the quantity has the required properties.
https://cwe.mitre.org/data/definitions/1284.html
safe
func assertNoError(t testing.TB, e error) { if e != nil { t.Fatal(e) } }
1
Go
CWE-1284
Improper Validation of Specified Quantity in Input
The product receives input that is expected to specify a quantity (such as size or length), but it does not validate or incorrectly validates that the quantity has the required properties.
https://cwe.mitre.org/data/definitions/1284.html
safe
func TestBitfield(t *testing.T) { bf, err := NewBitfield(128) assertNoError(t, err) if bf.OnesBefore(20) != 0 { t.Fatal("expected no bits set") } bf.SetBit(10) if bf.OnesBefore(20) != 1 { t.Fatal("expected 1 bit set") } bf.SetBit(12) if bf.OnesBefore(20) != 2 { t.Fatal("expected 2 bit set") } bf.SetBit(30) if bf.OnesBefore(20) != 2 { t.Fatal("expected 2 bit set") } bf.SetBit(100) if bf.OnesBefore(20) != 2 { t.Fatal("expected 2 bit set") } bf.UnsetBit(10) if bf.OnesBefore(20) != 1 { t.Fatal("expected 1 bit set") } bint := new(big.Int).SetBytes(bf.Bytes()) for i := 0; i < 128; i++ { if bf.Bit(i) != (bint.Bit(i) == 1) { t.Fatalf("expected bit %d to be %v", i, bf.Bit(i)) } } }
1
Go
CWE-1284
Improper Validation of Specified Quantity in Input
The product receives input that is expected to specify a quantity (such as size or length), but it does not validate or incorrectly validates that the quantity has the required properties.
https://cwe.mitre.org/data/definitions/1284.html
safe
func FuzzFromBytes(f *testing.F) { f.Fuzz(func(_ *testing.T, size int, bytes []byte) { if size > 1<<20 { // We relly on consumers for limit checks, hopefully they understand that a New... factory allocates memory. return } FromBytes(size, bytes) }) }
1
Go
CWE-1284
Improper Validation of Specified Quantity in Input
The product receives input that is expected to specify a quantity (such as size or length), but it does not validate or incorrectly validates that the quantity has the required properties.
https://cwe.mitre.org/data/definitions/1284.html
safe
func BenchmarkOnes(b *testing.B) { bf, err := NewBitfield(benchmarkSize) assertNoError(b, err) b.ResetTimer() for i := 0; i < b.N; i++ { for j := 0; j*4 < benchmarkSize; j++ { if bf.Ones() != j { b.Fatal("bad", i) } bf.SetBit(j * 4) } for j := 0; j*4 < benchmarkSize; j++ { bf.UnsetBit(j * 4) } } }
1
Go
CWE-1284
Improper Validation of Specified Quantity in Input
The product receives input that is expected to specify a quantity (such as size or length), but it does not validate or incorrectly validates that the quantity has the required properties.
https://cwe.mitre.org/data/definitions/1284.html
safe
func TestBadSizeFails(t *testing.T) { for _, size := range [...]int{-8, 2, 1337, -3} { _, err := NewBitfield(size) if err == nil { t.Fatalf("missing error for %d sized bitfield", size) } } }
1
Go
CWE-1284
Improper Validation of Specified Quantity in Input
The product receives input that is expected to specify a quantity (such as size or length), but it does not validate or incorrectly validates that the quantity has the required properties.
https://cwe.mitre.org/data/definitions/1284.html
safe
func BenchmarkBytes(b *testing.B) { bfa, err := NewBitfield(216) assertNoError(b, err) bfb, err := NewBitfield(216) assertNoError(b, err) for j := 0; j*4 < 216; j++ { bfa.SetBit(j * 4) } b.ResetTimer() for i := 0; i < b.N; i++ { bfb.SetBytes(bfa.Bytes()) } }
1
Go
CWE-1284
Improper Validation of Specified Quantity in Input
The product receives input that is expected to specify a quantity (such as size or length), but it does not validate or incorrectly validates that the quantity has the required properties.
https://cwe.mitre.org/data/definitions/1284.html
safe
func NewUnixFSHAMTShard(ctx context.Context, substrate dagpb.PBNode, data data.UnixFSData, lsys *ipld.LinkSystem) (ipld.Node, error) { if err := validateHAMTData(data); err != nil { return nil, err } shardCache := make(map[ipld.Link]*_UnixFSHAMTShard, substrate.FieldLinks().Length()) bf, err := bitField(data) if err != nil { return nil, err } return &_UnixFSHAMTShard{ ctx: ctx, _substrate: substrate, data: data, lsys: lsys, shardCache: shardCache, bitfield: bf, cachedLength: -1, }, nil }
1
Go
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
func bitField(nd data.UnixFSData) (bitfield.Bitfield, error) { fanout := int(nd.FieldFanout().Must().Int()) if fanout > maximumHamtWidth { return nil, fmt.Errorf("hamt witdh (%d) exceed maximum allowed (%d)", fanout, maximumHamtWidth) } bf := bitfield.NewBitfield(fanout) bf.SetBytes(nd.FieldData().Must().Bytes()) return bf, nil }
1
Go
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
func (s *shard) bitmap() ([]byte, error) { bm, err := bitfield.NewBitfield(s.size) if err != nil { return nil, err } for i := 0; i < s.size; i++ { if _, ok := s.children[i]; ok { bm.SetBit(i) } } return bm.Bytes(), nil }
1
Go
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
func (s *shard) serialize(ls *ipld.LinkSystem) (ipld.Link, uint64, error) { bm, err := s.bitmap() if err != nil { return nil, 0, err } ufd, err := BuildUnixFS(func(b *Builder) { DataType(b, data.Data_HAMTShard) HashType(b, s.hasher) Data(b, bm) Fanout(b, uint64(s.size)) }) if err != nil { return nil, 0, err } pbb := dagpb.Type.PBNode.NewBuilder() pbm, err := pbb.BeginMap(2) if err != nil { return nil, 0, err } if err = pbm.AssembleKey().AssignString("Data"); err != nil { return nil, 0, err } if err = pbm.AssembleValue().AssignBytes(data.EncodeUnixFSData(ufd)); err != nil { return nil, 0, err } if err = pbm.AssembleKey().AssignString("Links"); err != nil { return nil, 0, err } lnkBuilder := dagpb.Type.PBLinks.NewBuilder() lnks, err := lnkBuilder.BeginList(int64(len(s.children))) if err != nil { return nil, 0, err } // sorting happens in codec-dagpb var totalSize uint64 for idx, e := range s.children { var lnk dagpb.PBLink if e.shard != nil { ipldLnk, sz, err := e.shard.serialize(ls) if err != nil { return nil, 0, err } totalSize += sz fullName := s.formatLinkName("", idx) lnk, err = BuildUnixFSDirectoryEntry(fullName, int64(sz), ipldLnk) if err != nil { return nil, 0, err } } else { fullName := s.formatLinkName(e.Name.Must().String(), idx) sz := e.Tsize.Must().Int() totalSize += uint64(sz) lnk, err = BuildUnixFSDirectoryEntry(fullName, sz, e.Hash.Link()) } if err != nil { return nil, 0, err } if err := lnks.AssembleValue().AssignNode(lnk); err != nil { return nil, 0, err } } if err := lnks.Finish(); err != nil { return nil, 0, err } pbm.AssembleValue().AssignNode(lnkBuilder.Build()) if err := pbm.Finish(); err != nil { return nil, 0, err } node := pbb.Build() lnk, sz, err := sizedStore(ls, fileLinkProto, node) if err != nil { return nil, 0, err } return lnk, totalSize + sz, nil }
1
Go
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
func makeDirWidth(ds format.DAGService, size, width int) ([]string, *legacy.Shard, error) { ctx := context.Background() s, err := legacy.NewShard(ds, width) if err != nil { return nil, nil, err } var dirs []string for i := 0; i < size; i++ { dirs = append(dirs, fmt.Sprintf("DIRNAME%d", i)) } shuffle(time.Now().UnixNano(), dirs) for i := 0; i < len(dirs); i++ { nd := ft.EmptyDirNode() err := ds.Add(ctx, nd) if err != nil { return nil, nil, err } err = s.Set(ctx, dirs[i], nd) if err != nil { return nil, nil, err } } return dirs, s, nil }
1
Go
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
func TestBasicSet(t *testing.T) { ds, lsys := mockDag() for _, w := range []int{128, 256, 512, 1024} { t.Run(fmt.Sprintf("BasicSet%d", w), func(t *testing.T) { names, s, err := makeDirWidth(ds, 1000, w) require.NoError(t, err) ctx := context.Background() legacyNode, err := s.Node() require.NoError(t, err) nd, err := lsys.Load(ipld.LinkContext{Ctx: ctx}, cidlink.Link{Cid: legacyNode.Cid()}, dagpb.Type.PBNode) require.NoError(t, err) hamtShard, err := hamt.AttemptHAMTShardFromNode(ctx, nd, lsys) require.NoError(t, err) for _, d := range names { _, err := hamtShard.LookupByString(d) require.NoError(t, err) } }) } }
1
Go
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
func bitField(nd data.UnixFSData) (bitfield.Bitfield, error) { fanout := int(nd.FieldFanout().Must().Int()) if fanout > maximumHamtWidth { return nil, fmt.Errorf("hamt witdh (%d) exceed maximum allowed (%d)", fanout, maximumHamtWidth) } bf, err := bitfield.NewBitfield(fanout) if err != nil { return nil, err } bf.SetBytes(nd.FieldData().Must().Bytes()) return bf, nil }
1
Go
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
func(ctx context.Context) error { return nil },
1
Go
CWE-863
Incorrect Authorization
The product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.
https://cwe.mitre.org/data/definitions/863.html
safe
func NewHandler(appLister applisters.ApplicationLister, namespace string, enabledNamespaces []string, db db.ArgoDB, enf *rbac.Enforcer, cache *servercache.Cache, appResourceTree AppResourceTreeFn, allowedShells []string, sessionManager util_session.SessionManager) *terminalHandler { return &terminalHandler{ appLister: appLister, db: db, enf: enf, cache: cache, appResourceTreeFn: appResourceTree, allowedShells: allowedShells, namespace: namespace, enabledNamespaces: enabledNamespaces, sessionManager: sessionManager, } }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func getToken(r *http.Request) (string, error) { cookies := r.Cookies() return httputil.JoinCookies(common.AuthCookieName, cookies) }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func newTerminalSession(w http.ResponseWriter, r *http.Request, responseHeader http.Header, sessionManager util_session.SessionManager) (*terminalSession, error) { token, err := getToken(r) if err != nil { return nil, err } conn, err := upgrader.Upgrade(w, r, responseHeader) if err != nil { return nil, err } session := &terminalSession{ wsConn: conn, tty: true, sizeChan: make(chan remotecommand.TerminalSize), doneChan: make(chan struct{}), sessionManager: sessionManager, token: &token, } return session, nil }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func reconnect(w http.ResponseWriter, r *http.Request) { var upgrader = websocket.Upgrader{} c, err := upgrader.Upgrade(w, r, nil) if err != nil { return } ts := terminalSession{wsConn: c} _, _ = ts.reconnect() }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func TestReconnect(t *testing.T) { s := httptest.NewServer(http.HandlerFunc(reconnect)) defer s.Close() u := "ws" + strings.TrimPrefix(s.URL, "http") // Connect to the server ws, _, err := websocket.DefaultDialer.Dial(u, nil) assert.NoError(t, err) defer ws.Close() _, p, _ := ws.ReadMessage() var message TerminalMessage err = json.Unmarshal(p, &message) assert.NoError(t, err) assert.Equal(t, message.Data, ReconnectMessage) }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func untarChart(tempDir string, cachedChartPath string, manifestMaxExtractedSize int64, disableManifestMaxExtractedSize bool) error { if disableManifestMaxExtractedSize { cmd := exec.Command("tar", "-zxvf", cachedChartPath) cmd.Dir = tempDir _, err := executil.Run(cmd) return err } reader, err := os.Open(cachedChartPath) if err != nil { return err } return files.Untgz(tempDir, reader, manifestMaxExtractedSize, false) }
1
Go
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe