You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

protected_branch.go 16KB

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