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

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