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 17KB

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