code.gitea.io/gitea@v1.21.7/models/git/protected_branch.go (about)

     1  // Copyright 2022 The Gitea Authors. All rights reserved.
     2  // SPDX-License-Identifier: MIT
     3  
     4  package git
     5  
     6  import (
     7  	"context"
     8  	"errors"
     9  	"fmt"
    10  	"slices"
    11  	"strings"
    12  
    13  	"code.gitea.io/gitea/models/db"
    14  	"code.gitea.io/gitea/models/organization"
    15  	"code.gitea.io/gitea/models/perm"
    16  	access_model "code.gitea.io/gitea/models/perm/access"
    17  	repo_model "code.gitea.io/gitea/models/repo"
    18  	"code.gitea.io/gitea/models/unit"
    19  	user_model "code.gitea.io/gitea/models/user"
    20  	"code.gitea.io/gitea/modules/base"
    21  	"code.gitea.io/gitea/modules/log"
    22  	"code.gitea.io/gitea/modules/timeutil"
    23  	"code.gitea.io/gitea/modules/util"
    24  
    25  	"github.com/gobwas/glob"
    26  	"github.com/gobwas/glob/syntax"
    27  )
    28  
    29  var ErrBranchIsProtected = errors.New("branch is protected")
    30  
    31  // ProtectedBranch struct
    32  type ProtectedBranch struct {
    33  	ID                            int64                  `xorm:"pk autoincr"`
    34  	RepoID                        int64                  `xorm:"UNIQUE(s)"`
    35  	Repo                          *repo_model.Repository `xorm:"-"`
    36  	RuleName                      string                 `xorm:"'branch_name' UNIQUE(s)"` // a branch name or a glob match to branch name
    37  	globRule                      glob.Glob              `xorm:"-"`
    38  	isPlainName                   bool                   `xorm:"-"`
    39  	CanPush                       bool                   `xorm:"NOT NULL DEFAULT false"`
    40  	EnableWhitelist               bool
    41  	WhitelistUserIDs              []int64  `xorm:"JSON TEXT"`
    42  	WhitelistTeamIDs              []int64  `xorm:"JSON TEXT"`
    43  	EnableMergeWhitelist          bool     `xorm:"NOT NULL DEFAULT false"`
    44  	WhitelistDeployKeys           bool     `xorm:"NOT NULL DEFAULT false"`
    45  	MergeWhitelistUserIDs         []int64  `xorm:"JSON TEXT"`
    46  	MergeWhitelistTeamIDs         []int64  `xorm:"JSON TEXT"`
    47  	EnableStatusCheck             bool     `xorm:"NOT NULL DEFAULT false"`
    48  	StatusCheckContexts           []string `xorm:"JSON TEXT"`
    49  	EnableApprovalsWhitelist      bool     `xorm:"NOT NULL DEFAULT false"`
    50  	ApprovalsWhitelistUserIDs     []int64  `xorm:"JSON TEXT"`
    51  	ApprovalsWhitelistTeamIDs     []int64  `xorm:"JSON TEXT"`
    52  	RequiredApprovals             int64    `xorm:"NOT NULL DEFAULT 0"`
    53  	BlockOnRejectedReviews        bool     `xorm:"NOT NULL DEFAULT false"`
    54  	BlockOnOfficialReviewRequests bool     `xorm:"NOT NULL DEFAULT false"`
    55  	BlockOnOutdatedBranch         bool     `xorm:"NOT NULL DEFAULT false"`
    56  	DismissStaleApprovals         bool     `xorm:"NOT NULL DEFAULT false"`
    57  	RequireSignedCommits          bool     `xorm:"NOT NULL DEFAULT false"`
    58  	ProtectedFilePatterns         string   `xorm:"TEXT"`
    59  	UnprotectedFilePatterns       string   `xorm:"TEXT"`
    60  
    61  	CreatedUnix timeutil.TimeStamp `xorm:"created"`
    62  	UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
    63  }
    64  
    65  func init() {
    66  	db.RegisterModel(new(ProtectedBranch))
    67  }
    68  
    69  // IsRuleNameSpecial return true if it contains special character
    70  func IsRuleNameSpecial(ruleName string) bool {
    71  	for i := 0; i < len(ruleName); i++ {
    72  		if syntax.Special(ruleName[i]) {
    73  			return true
    74  		}
    75  	}
    76  	return false
    77  }
    78  
    79  func (protectBranch *ProtectedBranch) loadGlob() {
    80  	if protectBranch.globRule == nil {
    81  		var err error
    82  		protectBranch.globRule, err = glob.Compile(protectBranch.RuleName, '/')
    83  		if err != nil {
    84  			log.Warn("Invalid glob rule for ProtectedBranch[%d]: %s %v", protectBranch.ID, protectBranch.RuleName, err)
    85  			protectBranch.globRule = glob.MustCompile(glob.QuoteMeta(protectBranch.RuleName), '/')
    86  		}
    87  		protectBranch.isPlainName = !IsRuleNameSpecial(protectBranch.RuleName)
    88  	}
    89  }
    90  
    91  // Match tests if branchName matches the rule
    92  func (protectBranch *ProtectedBranch) Match(branchName string) bool {
    93  	protectBranch.loadGlob()
    94  	if protectBranch.isPlainName {
    95  		return strings.EqualFold(protectBranch.RuleName, branchName)
    96  	}
    97  
    98  	return protectBranch.globRule.Match(branchName)
    99  }
   100  
   101  func (protectBranch *ProtectedBranch) LoadRepo(ctx context.Context) (err error) {
   102  	if protectBranch.Repo != nil {
   103  		return nil
   104  	}
   105  	protectBranch.Repo, err = repo_model.GetRepositoryByID(ctx, protectBranch.RepoID)
   106  	return err
   107  }
   108  
   109  // CanUserPush returns if some user could push to this protected branch
   110  func (protectBranch *ProtectedBranch) CanUserPush(ctx context.Context, user *user_model.User) bool {
   111  	if !protectBranch.CanPush {
   112  		return false
   113  	}
   114  
   115  	if !protectBranch.EnableWhitelist {
   116  		if err := protectBranch.LoadRepo(ctx); err != nil {
   117  			log.Error("LoadRepo: %v", err)
   118  			return false
   119  		}
   120  
   121  		writeAccess, err := access_model.HasAccessUnit(ctx, user, protectBranch.Repo, unit.TypeCode, perm.AccessModeWrite)
   122  		if err != nil {
   123  			log.Error("HasAccessUnit: %v", err)
   124  			return false
   125  		}
   126  		return writeAccess
   127  	}
   128  
   129  	if base.Int64sContains(protectBranch.WhitelistUserIDs, user.ID) {
   130  		return true
   131  	}
   132  
   133  	if len(protectBranch.WhitelistTeamIDs) == 0 {
   134  		return false
   135  	}
   136  
   137  	in, err := organization.IsUserInTeams(ctx, user.ID, protectBranch.WhitelistTeamIDs)
   138  	if err != nil {
   139  		log.Error("IsUserInTeams: %v", err)
   140  		return false
   141  	}
   142  	return in
   143  }
   144  
   145  // IsUserMergeWhitelisted checks if some user is whitelisted to merge to this branch
   146  func IsUserMergeWhitelisted(ctx context.Context, protectBranch *ProtectedBranch, userID int64, permissionInRepo access_model.Permission) bool {
   147  	if !protectBranch.EnableMergeWhitelist {
   148  		// Then we need to fall back on whether the user has write permission
   149  		return permissionInRepo.CanWrite(unit.TypeCode)
   150  	}
   151  
   152  	if base.Int64sContains(protectBranch.MergeWhitelistUserIDs, userID) {
   153  		return true
   154  	}
   155  
   156  	if len(protectBranch.MergeWhitelistTeamIDs) == 0 {
   157  		return false
   158  	}
   159  
   160  	in, err := organization.IsUserInTeams(ctx, userID, protectBranch.MergeWhitelistTeamIDs)
   161  	if err != nil {
   162  		log.Error("IsUserInTeams: %v", err)
   163  		return false
   164  	}
   165  	return in
   166  }
   167  
   168  // IsUserOfficialReviewer check if user is official reviewer for the branch (counts towards required approvals)
   169  func IsUserOfficialReviewer(ctx context.Context, protectBranch *ProtectedBranch, user *user_model.User) (bool, error) {
   170  	repo, err := repo_model.GetRepositoryByID(ctx, protectBranch.RepoID)
   171  	if err != nil {
   172  		return false, err
   173  	}
   174  
   175  	if !protectBranch.EnableApprovalsWhitelist {
   176  		// Anyone with write access is considered official reviewer
   177  		writeAccess, err := access_model.HasAccessUnit(ctx, user, repo, unit.TypeCode, perm.AccessModeWrite)
   178  		if err != nil {
   179  			return false, err
   180  		}
   181  		return writeAccess, nil
   182  	}
   183  
   184  	if base.Int64sContains(protectBranch.ApprovalsWhitelistUserIDs, user.ID) {
   185  		return true, nil
   186  	}
   187  
   188  	inTeam, err := organization.IsUserInTeams(ctx, user.ID, protectBranch.ApprovalsWhitelistTeamIDs)
   189  	if err != nil {
   190  		return false, err
   191  	}
   192  
   193  	return inTeam, nil
   194  }
   195  
   196  // GetProtectedFilePatterns parses a semicolon separated list of protected file patterns and returns a glob.Glob slice
   197  func (protectBranch *ProtectedBranch) GetProtectedFilePatterns() []glob.Glob {
   198  	return getFilePatterns(protectBranch.ProtectedFilePatterns)
   199  }
   200  
   201  // GetUnprotectedFilePatterns parses a semicolon separated list of unprotected file patterns and returns a glob.Glob slice
   202  func (protectBranch *ProtectedBranch) GetUnprotectedFilePatterns() []glob.Glob {
   203  	return getFilePatterns(protectBranch.UnprotectedFilePatterns)
   204  }
   205  
   206  func getFilePatterns(filePatterns string) []glob.Glob {
   207  	extarr := make([]glob.Glob, 0, 10)
   208  	for _, expr := range strings.Split(strings.ToLower(filePatterns), ";") {
   209  		expr = strings.TrimSpace(expr)
   210  		if expr != "" {
   211  			if g, err := glob.Compile(expr, '.', '/'); err != nil {
   212  				log.Info("Invalid glob expression '%s' (skipped): %v", expr, err)
   213  			} else {
   214  				extarr = append(extarr, g)
   215  			}
   216  		}
   217  	}
   218  	return extarr
   219  }
   220  
   221  // MergeBlockedByProtectedFiles returns true if merge is blocked by protected files change
   222  func (protectBranch *ProtectedBranch) MergeBlockedByProtectedFiles(changedProtectedFiles []string) bool {
   223  	glob := protectBranch.GetProtectedFilePatterns()
   224  	if len(glob) == 0 {
   225  		return false
   226  	}
   227  
   228  	return len(changedProtectedFiles) > 0
   229  }
   230  
   231  // IsProtectedFile return if path is protected
   232  func (protectBranch *ProtectedBranch) IsProtectedFile(patterns []glob.Glob, path string) bool {
   233  	if len(patterns) == 0 {
   234  		patterns = protectBranch.GetProtectedFilePatterns()
   235  		if len(patterns) == 0 {
   236  			return false
   237  		}
   238  	}
   239  
   240  	lpath := strings.ToLower(strings.TrimSpace(path))
   241  
   242  	r := false
   243  	for _, pat := range patterns {
   244  		if pat.Match(lpath) {
   245  			r = true
   246  			break
   247  		}
   248  	}
   249  
   250  	return r
   251  }
   252  
   253  // IsUnprotectedFile return if path is unprotected
   254  func (protectBranch *ProtectedBranch) IsUnprotectedFile(patterns []glob.Glob, path string) bool {
   255  	if len(patterns) == 0 {
   256  		patterns = protectBranch.GetUnprotectedFilePatterns()
   257  		if len(patterns) == 0 {
   258  			return false
   259  		}
   260  	}
   261  
   262  	lpath := strings.ToLower(strings.TrimSpace(path))
   263  
   264  	r := false
   265  	for _, pat := range patterns {
   266  		if pat.Match(lpath) {
   267  			r = true
   268  			break
   269  		}
   270  	}
   271  
   272  	return r
   273  }
   274  
   275  // GetProtectedBranchRuleByName getting protected branch rule by name
   276  func GetProtectedBranchRuleByName(ctx context.Context, repoID int64, ruleName string) (*ProtectedBranch, error) {
   277  	rel := &ProtectedBranch{RepoID: repoID, RuleName: ruleName}
   278  	has, err := db.GetByBean(ctx, rel)
   279  	if err != nil {
   280  		return nil, err
   281  	}
   282  	if !has {
   283  		return nil, nil
   284  	}
   285  	return rel, nil
   286  }
   287  
   288  // GetProtectedBranchRuleByID getting protected branch rule by rule ID
   289  func GetProtectedBranchRuleByID(ctx context.Context, repoID, ruleID int64) (*ProtectedBranch, error) {
   290  	rel := &ProtectedBranch{ID: ruleID, RepoID: repoID}
   291  	has, err := db.GetByBean(ctx, rel)
   292  	if err != nil {
   293  		return nil, err
   294  	}
   295  	if !has {
   296  		return nil, nil
   297  	}
   298  	return rel, nil
   299  }
   300  
   301  // WhitelistOptions represent all sorts of whitelists used for protected branches
   302  type WhitelistOptions struct {
   303  	UserIDs []int64
   304  	TeamIDs []int64
   305  
   306  	MergeUserIDs []int64
   307  	MergeTeamIDs []int64
   308  
   309  	ApprovalsUserIDs []int64
   310  	ApprovalsTeamIDs []int64
   311  }
   312  
   313  // UpdateProtectBranch saves branch protection options of repository.
   314  // If ID is 0, it creates a new record. Otherwise, updates existing record.
   315  // This function also performs check if whitelist user and team's IDs have been changed
   316  // to avoid unnecessary whitelist delete and regenerate.
   317  func UpdateProtectBranch(ctx context.Context, repo *repo_model.Repository, protectBranch *ProtectedBranch, opts WhitelistOptions) (err error) {
   318  	if err = repo.LoadOwner(ctx); err != nil {
   319  		return fmt.Errorf("LoadOwner: %v", err)
   320  	}
   321  
   322  	whitelist, err := updateUserWhitelist(ctx, repo, protectBranch.WhitelistUserIDs, opts.UserIDs)
   323  	if err != nil {
   324  		return err
   325  	}
   326  	protectBranch.WhitelistUserIDs = whitelist
   327  
   328  	whitelist, err = updateUserWhitelist(ctx, repo, protectBranch.MergeWhitelistUserIDs, opts.MergeUserIDs)
   329  	if err != nil {
   330  		return err
   331  	}
   332  	protectBranch.MergeWhitelistUserIDs = whitelist
   333  
   334  	whitelist, err = updateApprovalWhitelist(ctx, repo, protectBranch.ApprovalsWhitelistUserIDs, opts.ApprovalsUserIDs)
   335  	if err != nil {
   336  		return err
   337  	}
   338  	protectBranch.ApprovalsWhitelistUserIDs = whitelist
   339  
   340  	// if the repo is in an organization
   341  	whitelist, err = updateTeamWhitelist(ctx, repo, protectBranch.WhitelistTeamIDs, opts.TeamIDs)
   342  	if err != nil {
   343  		return err
   344  	}
   345  	protectBranch.WhitelistTeamIDs = whitelist
   346  
   347  	whitelist, err = updateTeamWhitelist(ctx, repo, protectBranch.MergeWhitelistTeamIDs, opts.MergeTeamIDs)
   348  	if err != nil {
   349  		return err
   350  	}
   351  	protectBranch.MergeWhitelistTeamIDs = whitelist
   352  
   353  	whitelist, err = updateTeamWhitelist(ctx, repo, protectBranch.ApprovalsWhitelistTeamIDs, opts.ApprovalsTeamIDs)
   354  	if err != nil {
   355  		return err
   356  	}
   357  	protectBranch.ApprovalsWhitelistTeamIDs = whitelist
   358  
   359  	// Make sure protectBranch.ID is not 0 for whitelists
   360  	if protectBranch.ID == 0 {
   361  		if _, err = db.GetEngine(ctx).Insert(protectBranch); err != nil {
   362  			return fmt.Errorf("Insert: %v", err)
   363  		}
   364  		return nil
   365  	}
   366  
   367  	if _, err = db.GetEngine(ctx).ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
   368  		return fmt.Errorf("Update: %v", err)
   369  	}
   370  
   371  	return nil
   372  }
   373  
   374  // updateApprovalWhitelist checks whether the user whitelist changed and returns a whitelist with
   375  // the users from newWhitelist which have explicit read or write access to the repo.
   376  func updateApprovalWhitelist(ctx context.Context, repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
   377  	hasUsersChanged := !util.SliceSortedEqual(currentWhitelist, newWhitelist)
   378  	if !hasUsersChanged {
   379  		return currentWhitelist, nil
   380  	}
   381  
   382  	whitelist = make([]int64, 0, len(newWhitelist))
   383  	for _, userID := range newWhitelist {
   384  		if reader, err := access_model.IsRepoReader(ctx, repo, userID); err != nil {
   385  			return nil, err
   386  		} else if !reader {
   387  			continue
   388  		}
   389  		whitelist = append(whitelist, userID)
   390  	}
   391  
   392  	return whitelist, err
   393  }
   394  
   395  // updateUserWhitelist checks whether the user whitelist changed and returns a whitelist with
   396  // the users from newWhitelist which have write access to the repo.
   397  func updateUserWhitelist(ctx context.Context, repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
   398  	hasUsersChanged := !util.SliceSortedEqual(currentWhitelist, newWhitelist)
   399  	if !hasUsersChanged {
   400  		return currentWhitelist, nil
   401  	}
   402  
   403  	whitelist = make([]int64, 0, len(newWhitelist))
   404  	for _, userID := range newWhitelist {
   405  		user, err := user_model.GetUserByID(ctx, userID)
   406  		if err != nil {
   407  			return nil, fmt.Errorf("GetUserByID [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
   408  		}
   409  		perm, err := access_model.GetUserRepoPermission(ctx, repo, user)
   410  		if err != nil {
   411  			return nil, fmt.Errorf("GetUserRepoPermission [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
   412  		}
   413  
   414  		if !perm.CanWrite(unit.TypeCode) {
   415  			continue // Drop invalid user ID
   416  		}
   417  
   418  		whitelist = append(whitelist, userID)
   419  	}
   420  
   421  	return whitelist, err
   422  }
   423  
   424  // updateTeamWhitelist checks whether the team whitelist changed and returns a whitelist with
   425  // the teams from newWhitelist which have write access to the repo.
   426  func updateTeamWhitelist(ctx context.Context, repo *repo_model.Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
   427  	hasTeamsChanged := !util.SliceSortedEqual(currentWhitelist, newWhitelist)
   428  	if !hasTeamsChanged {
   429  		return currentWhitelist, nil
   430  	}
   431  
   432  	teams, err := organization.GetTeamsWithAccessToRepo(ctx, repo.OwnerID, repo.ID, perm.AccessModeRead)
   433  	if err != nil {
   434  		return nil, fmt.Errorf("GetTeamsWithAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
   435  	}
   436  
   437  	whitelist = make([]int64, 0, len(teams))
   438  	for i := range teams {
   439  		if slices.Contains(newWhitelist, teams[i].ID) {
   440  			whitelist = append(whitelist, teams[i].ID)
   441  		}
   442  	}
   443  
   444  	return whitelist, err
   445  }
   446  
   447  // DeleteProtectedBranch removes ProtectedBranch relation between the user and repository.
   448  func DeleteProtectedBranch(ctx context.Context, repoID, id int64) (err error) {
   449  	protectedBranch := &ProtectedBranch{
   450  		RepoID: repoID,
   451  		ID:     id,
   452  	}
   453  
   454  	if affected, err := db.GetEngine(ctx).Delete(protectedBranch); err != nil {
   455  		return err
   456  	} else if affected != 1 {
   457  		return fmt.Errorf("delete protected branch ID(%v) failed", id)
   458  	}
   459  
   460  	return nil
   461  }
   462  
   463  // RemoveUserIDFromProtectedBranch remove all user ids from protected branch options
   464  func RemoveUserIDFromProtectedBranch(ctx context.Context, p *ProtectedBranch, userID int64) error {
   465  	lenIDs, lenApprovalIDs, lenMergeIDs := len(p.WhitelistUserIDs), len(p.ApprovalsWhitelistUserIDs), len(p.MergeWhitelistUserIDs)
   466  	p.WhitelistUserIDs = util.SliceRemoveAll(p.WhitelistUserIDs, userID)
   467  	p.ApprovalsWhitelistUserIDs = util.SliceRemoveAll(p.ApprovalsWhitelistUserIDs, userID)
   468  	p.MergeWhitelistUserIDs = util.SliceRemoveAll(p.MergeWhitelistUserIDs, userID)
   469  
   470  	if lenIDs != len(p.WhitelistUserIDs) || lenApprovalIDs != len(p.ApprovalsWhitelistUserIDs) ||
   471  		lenMergeIDs != len(p.MergeWhitelistUserIDs) {
   472  		if _, err := db.GetEngine(ctx).ID(p.ID).Cols(
   473  			"whitelist_user_i_ds",
   474  			"merge_whitelist_user_i_ds",
   475  			"approvals_whitelist_user_i_ds",
   476  		).Update(p); err != nil {
   477  			return fmt.Errorf("updateProtectedBranches: %v", err)
   478  		}
   479  	}
   480  	return nil
   481  }
   482  
   483  // RemoveTeamIDFromProtectedBranch remove all team ids from protected branch options
   484  func RemoveTeamIDFromProtectedBranch(ctx context.Context, p *ProtectedBranch, teamID int64) error {
   485  	lenIDs, lenApprovalIDs, lenMergeIDs := len(p.WhitelistTeamIDs), len(p.ApprovalsWhitelistTeamIDs), len(p.MergeWhitelistTeamIDs)
   486  	p.WhitelistTeamIDs = util.SliceRemoveAll(p.WhitelistTeamIDs, teamID)
   487  	p.ApprovalsWhitelistTeamIDs = util.SliceRemoveAll(p.ApprovalsWhitelistTeamIDs, teamID)
   488  	p.MergeWhitelistTeamIDs = util.SliceRemoveAll(p.MergeWhitelistTeamIDs, teamID)
   489  
   490  	if lenIDs != len(p.WhitelistTeamIDs) ||
   491  		lenApprovalIDs != len(p.ApprovalsWhitelistTeamIDs) ||
   492  		lenMergeIDs != len(p.MergeWhitelistTeamIDs) {
   493  		if _, err := db.GetEngine(ctx).ID(p.ID).Cols(
   494  			"whitelist_team_i_ds",
   495  			"merge_whitelist_team_i_ds",
   496  			"approvals_whitelist_team_i_ds",
   497  		).Update(p); err != nil {
   498  			return fmt.Errorf("updateProtectedBranches: %v", err)
   499  		}
   500  	}
   501  	return nil
   502  }