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

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