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

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