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.

branches.go 16KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. // Copyright 2016 The Gitea Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package models
  5. import (
  6. "context"
  7. "fmt"
  8. "time"
  9. "code.gitea.io/gitea/modules/base"
  10. "code.gitea.io/gitea/modules/log"
  11. "code.gitea.io/gitea/modules/setting"
  12. "code.gitea.io/gitea/modules/timeutil"
  13. "code.gitea.io/gitea/modules/util"
  14. "github.com/unknwon/com"
  15. )
  16. const (
  17. // ProtectedBranchRepoID protected Repo ID
  18. ProtectedBranchRepoID = "GITEA_REPO_ID"
  19. // ProtectedBranchPRID protected Repo PR ID
  20. ProtectedBranchPRID = "GITEA_PR_ID"
  21. )
  22. // ProtectedBranch struct
  23. type ProtectedBranch struct {
  24. ID int64 `xorm:"pk autoincr"`
  25. RepoID int64 `xorm:"UNIQUE(s)"`
  26. BranchName string `xorm:"UNIQUE(s)"`
  27. CanPush bool `xorm:"NOT NULL DEFAULT false"`
  28. EnableWhitelist bool
  29. WhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  30. WhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  31. EnableMergeWhitelist bool `xorm:"NOT NULL DEFAULT false"`
  32. WhitelistDeployKeys bool `xorm:"NOT NULL DEFAULT false"`
  33. MergeWhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  34. MergeWhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  35. EnableStatusCheck bool `xorm:"NOT NULL DEFAULT false"`
  36. StatusCheckContexts []string `xorm:"JSON TEXT"`
  37. EnableApprovalsWhitelist bool `xorm:"NOT NULL DEFAULT false"`
  38. ApprovalsWhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  39. ApprovalsWhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  40. RequiredApprovals int64 `xorm:"NOT NULL DEFAULT 0"`
  41. BlockOnRejectedReviews bool `xorm:"NOT NULL DEFAULT false"`
  42. DismissStaleApprovals bool `xorm:"NOT NULL DEFAULT false"`
  43. RequireSignedCommits bool `xorm:"NOT NULL DEFAULT false"`
  44. CreatedUnix timeutil.TimeStamp `xorm:"created"`
  45. UpdatedUnix timeutil.TimeStamp `xorm:"updated"`
  46. }
  47. // IsProtected returns if the branch is protected
  48. func (protectBranch *ProtectedBranch) IsProtected() bool {
  49. return protectBranch.ID > 0
  50. }
  51. // CanUserPush returns if some user could push to this protected branch
  52. func (protectBranch *ProtectedBranch) CanUserPush(userID int64) bool {
  53. if !protectBranch.CanPush {
  54. return false
  55. }
  56. if !protectBranch.EnableWhitelist {
  57. if user, err := GetUserByID(userID); err != nil {
  58. log.Error("GetUserByID: %v", err)
  59. return false
  60. } else if repo, err := GetRepositoryByID(protectBranch.RepoID); err != nil {
  61. log.Error("GetRepositoryByID: %v", err)
  62. return false
  63. } else if writeAccess, err := HasAccessUnit(user, repo, UnitTypeCode, AccessModeWrite); err != nil {
  64. log.Error("HasAccessUnit: %v", err)
  65. return false
  66. } else {
  67. return writeAccess
  68. }
  69. }
  70. if base.Int64sContains(protectBranch.WhitelistUserIDs, userID) {
  71. return true
  72. }
  73. if len(protectBranch.WhitelistTeamIDs) == 0 {
  74. return false
  75. }
  76. in, err := IsUserInTeams(userID, protectBranch.WhitelistTeamIDs)
  77. if err != nil {
  78. log.Error("IsUserInTeams: %v", err)
  79. return false
  80. }
  81. return in
  82. }
  83. // IsUserMergeWhitelisted checks if some user is whitelisted to merge to this branch
  84. func (protectBranch *ProtectedBranch) IsUserMergeWhitelisted(userID int64) bool {
  85. if !protectBranch.EnableMergeWhitelist {
  86. return true
  87. }
  88. if base.Int64sContains(protectBranch.MergeWhitelistUserIDs, userID) {
  89. return true
  90. }
  91. if len(protectBranch.MergeWhitelistTeamIDs) == 0 {
  92. return false
  93. }
  94. in, err := IsUserInTeams(userID, protectBranch.MergeWhitelistTeamIDs)
  95. if err != nil {
  96. log.Error("IsUserInTeams: %v", err)
  97. return false
  98. }
  99. return in
  100. }
  101. // IsUserOfficialReviewer check if user is official reviewer for the branch (counts towards required approvals)
  102. func (protectBranch *ProtectedBranch) IsUserOfficialReviewer(user *User) (bool, error) {
  103. return protectBranch.isUserOfficialReviewer(x, user)
  104. }
  105. func (protectBranch *ProtectedBranch) isUserOfficialReviewer(e Engine, user *User) (bool, error) {
  106. repo, err := getRepositoryByID(e, protectBranch.RepoID)
  107. if err != nil {
  108. return false, err
  109. }
  110. if !protectBranch.EnableApprovalsWhitelist {
  111. // Anyone with write access is considered official reviewer
  112. writeAccess, err := hasAccessUnit(e, user, repo, UnitTypeCode, AccessModeWrite)
  113. if err != nil {
  114. return false, err
  115. }
  116. return writeAccess, nil
  117. }
  118. if base.Int64sContains(protectBranch.ApprovalsWhitelistUserIDs, user.ID) {
  119. return true, nil
  120. }
  121. inTeam, err := isUserInTeams(e, user.ID, protectBranch.ApprovalsWhitelistTeamIDs)
  122. if err != nil {
  123. return false, err
  124. }
  125. return inTeam, nil
  126. }
  127. // HasEnoughApprovals returns true if pr has enough granted approvals.
  128. func (protectBranch *ProtectedBranch) HasEnoughApprovals(pr *PullRequest) bool {
  129. if protectBranch.RequiredApprovals == 0 {
  130. return true
  131. }
  132. return protectBranch.GetGrantedApprovalsCount(pr) >= protectBranch.RequiredApprovals
  133. }
  134. // GetGrantedApprovalsCount returns the number of granted approvals for pr. A granted approval must be authored by a user in an approval whitelist.
  135. func (protectBranch *ProtectedBranch) GetGrantedApprovalsCount(pr *PullRequest) int64 {
  136. sess := x.Where("issue_id = ?", pr.IssueID).
  137. And("type = ?", ReviewTypeApprove).
  138. And("official = ?", true)
  139. if protectBranch.DismissStaleApprovals {
  140. sess = sess.And("stale = ?", false)
  141. }
  142. approvals, err := sess.Count(new(Review))
  143. if err != nil {
  144. log.Error("GetGrantedApprovalsCount: %v", err)
  145. return 0
  146. }
  147. return approvals
  148. }
  149. // MergeBlockedByRejectedReview returns true if merge is blocked by rejected reviews
  150. func (protectBranch *ProtectedBranch) MergeBlockedByRejectedReview(pr *PullRequest) bool {
  151. if !protectBranch.BlockOnRejectedReviews {
  152. return false
  153. }
  154. rejectExist, err := x.Where("issue_id = ?", pr.IssueID).
  155. And("type = ?", ReviewTypeReject).
  156. And("official = ?", true).
  157. Exist(new(Review))
  158. if err != nil {
  159. log.Error("MergeBlockedByRejectedReview: %v", err)
  160. return true
  161. }
  162. return rejectExist
  163. }
  164. // GetProtectedBranchByRepoID getting protected branch by repo ID
  165. func GetProtectedBranchByRepoID(repoID int64) ([]*ProtectedBranch, error) {
  166. protectedBranches := make([]*ProtectedBranch, 0)
  167. return protectedBranches, x.Where("repo_id = ?", repoID).Desc("updated_unix").Find(&protectedBranches)
  168. }
  169. // GetProtectedBranchBy getting protected branch by ID/Name
  170. func GetProtectedBranchBy(repoID int64, branchName string) (*ProtectedBranch, error) {
  171. return getProtectedBranchBy(x, repoID, branchName)
  172. }
  173. func getProtectedBranchBy(e Engine, repoID int64, branchName string) (*ProtectedBranch, error) {
  174. rel := &ProtectedBranch{RepoID: repoID, BranchName: branchName}
  175. has, err := e.Get(rel)
  176. if err != nil {
  177. return nil, err
  178. }
  179. if !has {
  180. return nil, nil
  181. }
  182. return rel, nil
  183. }
  184. // GetProtectedBranchByID getting protected branch by ID
  185. func GetProtectedBranchByID(id int64) (*ProtectedBranch, error) {
  186. rel := &ProtectedBranch{ID: id}
  187. has, err := x.Get(rel)
  188. if err != nil {
  189. return nil, err
  190. }
  191. if !has {
  192. return nil, nil
  193. }
  194. return rel, nil
  195. }
  196. // WhitelistOptions represent all sorts of whitelists used for protected branches
  197. type WhitelistOptions struct {
  198. UserIDs []int64
  199. TeamIDs []int64
  200. MergeUserIDs []int64
  201. MergeTeamIDs []int64
  202. ApprovalsUserIDs []int64
  203. ApprovalsTeamIDs []int64
  204. }
  205. // UpdateProtectBranch saves branch protection options of repository.
  206. // If ID is 0, it creates a new record. Otherwise, updates existing record.
  207. // This function also performs check if whitelist user and team's IDs have been changed
  208. // to avoid unnecessary whitelist delete and regenerate.
  209. func UpdateProtectBranch(repo *Repository, protectBranch *ProtectedBranch, opts WhitelistOptions) (err error) {
  210. if err = repo.GetOwner(); err != nil {
  211. return fmt.Errorf("GetOwner: %v", err)
  212. }
  213. whitelist, err := updateUserWhitelist(repo, protectBranch.WhitelistUserIDs, opts.UserIDs)
  214. if err != nil {
  215. return err
  216. }
  217. protectBranch.WhitelistUserIDs = whitelist
  218. whitelist, err = updateUserWhitelist(repo, protectBranch.MergeWhitelistUserIDs, opts.MergeUserIDs)
  219. if err != nil {
  220. return err
  221. }
  222. protectBranch.MergeWhitelistUserIDs = whitelist
  223. whitelist, err = updateApprovalWhitelist(repo, protectBranch.ApprovalsWhitelistUserIDs, opts.ApprovalsUserIDs)
  224. if err != nil {
  225. return err
  226. }
  227. protectBranch.ApprovalsWhitelistUserIDs = whitelist
  228. // if the repo is in an organization
  229. whitelist, err = updateTeamWhitelist(repo, protectBranch.WhitelistTeamIDs, opts.TeamIDs)
  230. if err != nil {
  231. return err
  232. }
  233. protectBranch.WhitelistTeamIDs = whitelist
  234. whitelist, err = updateTeamWhitelist(repo, protectBranch.MergeWhitelistTeamIDs, opts.MergeTeamIDs)
  235. if err != nil {
  236. return err
  237. }
  238. protectBranch.MergeWhitelistTeamIDs = whitelist
  239. whitelist, err = updateTeamWhitelist(repo, protectBranch.ApprovalsWhitelistTeamIDs, opts.ApprovalsTeamIDs)
  240. if err != nil {
  241. return err
  242. }
  243. protectBranch.ApprovalsWhitelistTeamIDs = whitelist
  244. // Make sure protectBranch.ID is not 0 for whitelists
  245. if protectBranch.ID == 0 {
  246. if _, err = x.Insert(protectBranch); err != nil {
  247. return fmt.Errorf("Insert: %v", err)
  248. }
  249. return nil
  250. }
  251. if _, err = x.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
  252. return fmt.Errorf("Update: %v", err)
  253. }
  254. return nil
  255. }
  256. // GetProtectedBranches get all protected branches
  257. func (repo *Repository) GetProtectedBranches() ([]*ProtectedBranch, error) {
  258. protectedBranches := make([]*ProtectedBranch, 0)
  259. return protectedBranches, x.Find(&protectedBranches, &ProtectedBranch{RepoID: repo.ID})
  260. }
  261. // GetBranchProtection get the branch protection of a branch
  262. func (repo *Repository) GetBranchProtection(branchName string) (*ProtectedBranch, error) {
  263. return GetProtectedBranchBy(repo.ID, branchName)
  264. }
  265. // IsProtectedBranch checks if branch is protected
  266. func (repo *Repository) IsProtectedBranch(branchName string, doer *User) (bool, error) {
  267. if doer == nil {
  268. return true, nil
  269. }
  270. protectedBranch := &ProtectedBranch{
  271. RepoID: repo.ID,
  272. BranchName: branchName,
  273. }
  274. has, err := x.Exist(protectedBranch)
  275. if err != nil {
  276. return true, err
  277. }
  278. return has, nil
  279. }
  280. // IsProtectedBranchForPush checks if branch is protected for push
  281. func (repo *Repository) IsProtectedBranchForPush(branchName string, doer *User) (bool, error) {
  282. if doer == nil {
  283. return true, nil
  284. }
  285. protectedBranch := &ProtectedBranch{
  286. RepoID: repo.ID,
  287. BranchName: branchName,
  288. }
  289. has, err := x.Get(protectedBranch)
  290. if err != nil {
  291. return true, err
  292. } else if has {
  293. return !protectedBranch.CanUserPush(doer.ID), nil
  294. }
  295. return false, nil
  296. }
  297. // updateApprovalWhitelist checks whether the user whitelist changed and returns a whitelist with
  298. // the users from newWhitelist which have explicit read or write access to the repo.
  299. func updateApprovalWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  300. hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  301. if !hasUsersChanged {
  302. return currentWhitelist, nil
  303. }
  304. whitelist = make([]int64, 0, len(newWhitelist))
  305. for _, userID := range newWhitelist {
  306. if reader, err := repo.IsReader(userID); err != nil {
  307. return nil, err
  308. } else if !reader {
  309. continue
  310. }
  311. whitelist = append(whitelist, userID)
  312. }
  313. return
  314. }
  315. // updateUserWhitelist checks whether the user whitelist changed and returns a whitelist with
  316. // the users from newWhitelist which have write access to the repo.
  317. func updateUserWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  318. hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  319. if !hasUsersChanged {
  320. return currentWhitelist, nil
  321. }
  322. whitelist = make([]int64, 0, len(newWhitelist))
  323. for _, userID := range newWhitelist {
  324. user, err := GetUserByID(userID)
  325. if err != nil {
  326. return nil, fmt.Errorf("GetUserByID [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  327. }
  328. perm, err := GetUserRepoPermission(repo, user)
  329. if err != nil {
  330. return nil, fmt.Errorf("GetUserRepoPermission [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  331. }
  332. if !perm.CanWrite(UnitTypeCode) {
  333. continue // Drop invalid user ID
  334. }
  335. whitelist = append(whitelist, userID)
  336. }
  337. return
  338. }
  339. // updateTeamWhitelist checks whether the team whitelist changed and returns a whitelist with
  340. // the teams from newWhitelist which have write access to the repo.
  341. func updateTeamWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  342. hasTeamsChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  343. if !hasTeamsChanged {
  344. return currentWhitelist, nil
  345. }
  346. teams, err := GetTeamsWithAccessToRepo(repo.OwnerID, repo.ID, AccessModeRead)
  347. if err != nil {
  348. return nil, fmt.Errorf("GetTeamsWithAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
  349. }
  350. whitelist = make([]int64, 0, len(teams))
  351. for i := range teams {
  352. if com.IsSliceContainsInt64(newWhitelist, teams[i].ID) {
  353. whitelist = append(whitelist, teams[i].ID)
  354. }
  355. }
  356. return
  357. }
  358. // DeleteProtectedBranch removes ProtectedBranch relation between the user and repository.
  359. func (repo *Repository) DeleteProtectedBranch(id int64) (err error) {
  360. protectedBranch := &ProtectedBranch{
  361. RepoID: repo.ID,
  362. ID: id,
  363. }
  364. sess := x.NewSession()
  365. defer sess.Close()
  366. if err = sess.Begin(); err != nil {
  367. return err
  368. }
  369. if affected, err := sess.Delete(protectedBranch); err != nil {
  370. return err
  371. } else if affected != 1 {
  372. return fmt.Errorf("delete protected branch ID(%v) failed", id)
  373. }
  374. return sess.Commit()
  375. }
  376. // DeletedBranch struct
  377. type DeletedBranch struct {
  378. ID int64 `xorm:"pk autoincr"`
  379. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  380. Name string `xorm:"UNIQUE(s) NOT NULL"`
  381. Commit string `xorm:"UNIQUE(s) NOT NULL"`
  382. DeletedByID int64 `xorm:"INDEX"`
  383. DeletedBy *User `xorm:"-"`
  384. DeletedUnix timeutil.TimeStamp `xorm:"INDEX created"`
  385. }
  386. // AddDeletedBranch adds a deleted branch to the database
  387. func (repo *Repository) AddDeletedBranch(branchName, commit string, deletedByID int64) error {
  388. deletedBranch := &DeletedBranch{
  389. RepoID: repo.ID,
  390. Name: branchName,
  391. Commit: commit,
  392. DeletedByID: deletedByID,
  393. }
  394. sess := x.NewSession()
  395. defer sess.Close()
  396. if err := sess.Begin(); err != nil {
  397. return err
  398. }
  399. if _, err := sess.InsertOne(deletedBranch); err != nil {
  400. return err
  401. }
  402. return sess.Commit()
  403. }
  404. // GetDeletedBranches returns all the deleted branches
  405. func (repo *Repository) GetDeletedBranches() ([]*DeletedBranch, error) {
  406. deletedBranches := make([]*DeletedBranch, 0)
  407. return deletedBranches, x.Where("repo_id = ?", repo.ID).Desc("deleted_unix").Find(&deletedBranches)
  408. }
  409. // GetDeletedBranchByID get a deleted branch by its ID
  410. func (repo *Repository) GetDeletedBranchByID(ID int64) (*DeletedBranch, error) {
  411. deletedBranch := &DeletedBranch{ID: ID}
  412. has, err := x.Get(deletedBranch)
  413. if err != nil {
  414. return nil, err
  415. }
  416. if !has {
  417. return nil, nil
  418. }
  419. return deletedBranch, nil
  420. }
  421. // RemoveDeletedBranch removes a deleted branch from the database
  422. func (repo *Repository) RemoveDeletedBranch(id int64) (err error) {
  423. deletedBranch := &DeletedBranch{
  424. RepoID: repo.ID,
  425. ID: id,
  426. }
  427. sess := x.NewSession()
  428. defer sess.Close()
  429. if err = sess.Begin(); err != nil {
  430. return err
  431. }
  432. if affected, err := sess.Delete(deletedBranch); err != nil {
  433. return err
  434. } else if affected != 1 {
  435. return fmt.Errorf("remove deleted branch ID(%v) failed", id)
  436. }
  437. return sess.Commit()
  438. }
  439. // LoadUser loads the user that deleted the branch
  440. // When there's no user found it returns a NewGhostUser
  441. func (deletedBranch *DeletedBranch) LoadUser() {
  442. user, err := GetUserByID(deletedBranch.DeletedByID)
  443. if err != nil {
  444. user = NewGhostUser()
  445. }
  446. deletedBranch.DeletedBy = user
  447. }
  448. // RemoveDeletedBranch removes all deleted branches
  449. func RemoveDeletedBranch(repoID int64, branch string) error {
  450. _, err := x.Where("repo_id=? AND name=?", repoID, branch).Delete(new(DeletedBranch))
  451. return err
  452. }
  453. // RemoveOldDeletedBranches removes old deleted branches
  454. func RemoveOldDeletedBranches(ctx context.Context) {
  455. // Nothing to do for shutdown or terminate
  456. log.Trace("Doing: DeletedBranchesCleanup")
  457. deleteBefore := time.Now().Add(-setting.Cron.DeletedBranchesCleanup.OlderThan)
  458. _, err := x.Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch))
  459. if err != nil {
  460. log.Error("DeletedBranchesCleanup: %v", err)
  461. }
  462. }