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.

384 lines
11 KiB

  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/util"
  12. "github.com/Unknwon/com"
  13. )
  14. const (
  15. // ProtectedBranchRepoID protected Repo ID
  16. ProtectedBranchRepoID = "GITEA_REPO_ID"
  17. )
  18. // ProtectedBranch struct
  19. type ProtectedBranch struct {
  20. ID int64 `xorm:"pk autoincr"`
  21. RepoID int64 `xorm:"UNIQUE(s)"`
  22. BranchName string `xorm:"UNIQUE(s)"`
  23. CanPush bool `xorm:"NOT NULL DEFAULT false"`
  24. EnableWhitelist bool
  25. WhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  26. WhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  27. EnableMergeWhitelist bool `xorm:"NOT NULL DEFAULT false"`
  28. MergeWhitelistUserIDs []int64 `xorm:"JSON TEXT"`
  29. MergeWhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
  30. CreatedUnix util.TimeStamp `xorm:"created"`
  31. UpdatedUnix util.TimeStamp `xorm:"updated"`
  32. }
  33. // IsProtected returns if the branch is protected
  34. func (protectBranch *ProtectedBranch) IsProtected() bool {
  35. return protectBranch.ID > 0
  36. }
  37. // CanUserPush returns if some user could push to this protected branch
  38. func (protectBranch *ProtectedBranch) CanUserPush(userID int64) bool {
  39. if !protectBranch.EnableWhitelist {
  40. return false
  41. }
  42. if base.Int64sContains(protectBranch.WhitelistUserIDs, userID) {
  43. return true
  44. }
  45. if len(protectBranch.WhitelistTeamIDs) == 0 {
  46. return false
  47. }
  48. in, err := IsUserInTeams(userID, protectBranch.WhitelistTeamIDs)
  49. if err != nil {
  50. log.Error(1, "IsUserInTeams:", err)
  51. return false
  52. }
  53. return in
  54. }
  55. // CanUserMerge returns if some user could merge a pull request to this protected branch
  56. func (protectBranch *ProtectedBranch) CanUserMerge(userID int64) bool {
  57. if !protectBranch.EnableMergeWhitelist {
  58. return true
  59. }
  60. if base.Int64sContains(protectBranch.MergeWhitelistUserIDs, userID) {
  61. return true
  62. }
  63. if len(protectBranch.WhitelistTeamIDs) == 0 {
  64. return false
  65. }
  66. in, err := IsUserInTeams(userID, protectBranch.MergeWhitelistTeamIDs)
  67. if err != nil {
  68. log.Error(1, "IsUserInTeams:", err)
  69. return false
  70. }
  71. return in
  72. }
  73. // GetProtectedBranchByRepoID getting protected branch by repo ID
  74. func GetProtectedBranchByRepoID(RepoID int64) ([]*ProtectedBranch, error) {
  75. protectedBranches := make([]*ProtectedBranch, 0)
  76. return protectedBranches, x.Where("repo_id = ?", RepoID).Desc("updated_unix").Find(&protectedBranches)
  77. }
  78. // GetProtectedBranchBy getting protected branch by ID/Name
  79. func GetProtectedBranchBy(repoID int64, BranchName string) (*ProtectedBranch, error) {
  80. rel := &ProtectedBranch{RepoID: repoID, BranchName: BranchName}
  81. has, err := x.Get(rel)
  82. if err != nil {
  83. return nil, err
  84. }
  85. if !has {
  86. return nil, nil
  87. }
  88. return rel, nil
  89. }
  90. // GetProtectedBranchByID getting protected branch by ID
  91. func GetProtectedBranchByID(id int64) (*ProtectedBranch, error) {
  92. rel := &ProtectedBranch{ID: id}
  93. has, err := x.Get(rel)
  94. if err != nil {
  95. return nil, err
  96. }
  97. if !has {
  98. return nil, nil
  99. }
  100. return rel, nil
  101. }
  102. // UpdateProtectBranch saves branch protection options of repository.
  103. // If ID is 0, it creates a new record. Otherwise, updates existing record.
  104. // This function also performs check if whitelist user and team's IDs have been changed
  105. // to avoid unnecessary whitelist delete and regenerate.
  106. func UpdateProtectBranch(repo *Repository, protectBranch *ProtectedBranch, whitelistUserIDs, whitelistTeamIDs, mergeWhitelistUserIDs, mergeWhitelistTeamIDs []int64) (err error) {
  107. if err = repo.GetOwner(); err != nil {
  108. return fmt.Errorf("GetOwner: %v", err)
  109. }
  110. whitelist, err := updateUserWhitelist(repo, protectBranch.WhitelistUserIDs, whitelistUserIDs)
  111. if err != nil {
  112. return err
  113. }
  114. protectBranch.WhitelistUserIDs = whitelist
  115. whitelist, err = updateUserWhitelist(repo, protectBranch.MergeWhitelistUserIDs, mergeWhitelistUserIDs)
  116. if err != nil {
  117. return err
  118. }
  119. protectBranch.MergeWhitelistUserIDs = whitelist
  120. // if the repo is in an organization
  121. whitelist, err = updateTeamWhitelist(repo, protectBranch.WhitelistTeamIDs, whitelistTeamIDs)
  122. if err != nil {
  123. return err
  124. }
  125. protectBranch.WhitelistTeamIDs = whitelist
  126. whitelist, err = updateTeamWhitelist(repo, protectBranch.MergeWhitelistTeamIDs, mergeWhitelistTeamIDs)
  127. if err != nil {
  128. return err
  129. }
  130. protectBranch.MergeWhitelistTeamIDs = whitelist
  131. // Make sure protectBranch.ID is not 0 for whitelists
  132. if protectBranch.ID == 0 {
  133. if _, err = x.Insert(protectBranch); err != nil {
  134. return fmt.Errorf("Insert: %v", err)
  135. }
  136. return nil
  137. }
  138. if _, err = x.ID(protectBranch.ID).AllCols().Update(protectBranch); err != nil {
  139. return fmt.Errorf("Update: %v", err)
  140. }
  141. return nil
  142. }
  143. // GetProtectedBranches get all protected branches
  144. func (repo *Repository) GetProtectedBranches() ([]*ProtectedBranch, error) {
  145. protectedBranches := make([]*ProtectedBranch, 0)
  146. return protectedBranches, x.Find(&protectedBranches, &ProtectedBranch{RepoID: repo.ID})
  147. }
  148. // IsProtectedBranch checks if branch is protected
  149. func (repo *Repository) IsProtectedBranch(branchName string, doer *User) (bool, error) {
  150. if doer == nil {
  151. return true, nil
  152. }
  153. protectedBranch := &ProtectedBranch{
  154. RepoID: repo.ID,
  155. BranchName: branchName,
  156. }
  157. has, err := x.Get(protectedBranch)
  158. if err != nil {
  159. return true, err
  160. } else if has {
  161. return !protectedBranch.CanUserPush(doer.ID), nil
  162. }
  163. return false, nil
  164. }
  165. // IsProtectedBranchForMerging checks if branch is protected for merging
  166. func (repo *Repository) IsProtectedBranchForMerging(branchName string, doer *User) (bool, error) {
  167. if doer == nil {
  168. return true, nil
  169. }
  170. protectedBranch := &ProtectedBranch{
  171. RepoID: repo.ID,
  172. BranchName: branchName,
  173. }
  174. has, err := x.Get(protectedBranch)
  175. if err != nil {
  176. return true, err
  177. } else if has {
  178. return !protectedBranch.CanUserMerge(doer.ID), nil
  179. }
  180. return false, nil
  181. }
  182. // updateUserWhitelist checks whether the user whitelist changed and returns a whitelist with
  183. // the users from newWhitelist which have write access to the repo.
  184. func updateUserWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  185. hasUsersChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  186. if !hasUsersChanged {
  187. return currentWhitelist, nil
  188. }
  189. whitelist = make([]int64, 0, len(newWhitelist))
  190. for _, userID := range newWhitelist {
  191. has, err := hasAccess(x, userID, repo, AccessModeWrite)
  192. if err != nil {
  193. return nil, fmt.Errorf("HasAccess [user_id: %d, repo_id: %d]: %v", userID, repo.ID, err)
  194. } else if !has {
  195. continue // Drop invalid user ID
  196. }
  197. whitelist = append(whitelist, userID)
  198. }
  199. return
  200. }
  201. // updateTeamWhitelist checks whether the team whitelist changed and returns a whitelist with
  202. // the teams from newWhitelist which have write access to the repo.
  203. func updateTeamWhitelist(repo *Repository, currentWhitelist, newWhitelist []int64) (whitelist []int64, err error) {
  204. hasTeamsChanged := !util.IsSliceInt64Eq(currentWhitelist, newWhitelist)
  205. if !hasTeamsChanged {
  206. return currentWhitelist, nil
  207. }
  208. teams, err := GetTeamsWithAccessToRepo(repo.OwnerID, repo.ID, AccessModeWrite)
  209. if err != nil {
  210. return nil, fmt.Errorf("GetTeamsWithAccessToRepo [org_id: %d, repo_id: %d]: %v", repo.OwnerID, repo.ID, err)
  211. }
  212. whitelist = make([]int64, 0, len(teams))
  213. for i := range teams {
  214. if teams[i].HasWriteAccess() && com.IsSliceContainsInt64(newWhitelist, teams[i].ID) {
  215. whitelist = append(whitelist, teams[i].ID)
  216. }
  217. }
  218. return
  219. }
  220. // DeleteProtectedBranch removes ProtectedBranch relation between the user and repository.
  221. func (repo *Repository) DeleteProtectedBranch(id int64) (err error) {
  222. protectedBranch := &ProtectedBranch{
  223. RepoID: repo.ID,
  224. ID: id,
  225. }
  226. sess := x.NewSession()
  227. defer sess.Close()
  228. if err = sess.Begin(); err != nil {
  229. return err
  230. }
  231. if affected, err := sess.Delete(protectedBranch); err != nil {
  232. return err
  233. } else if affected != 1 {
  234. return fmt.Errorf("delete protected branch ID(%v) failed", id)
  235. }
  236. return sess.Commit()
  237. }
  238. // DeletedBranch struct
  239. type DeletedBranch struct {
  240. ID int64 `xorm:"pk autoincr"`
  241. RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
  242. Name string `xorm:"UNIQUE(s) NOT NULL"`
  243. Commit string `xorm:"UNIQUE(s) NOT NULL"`
  244. DeletedByID int64 `xorm:"INDEX"`
  245. DeletedBy *User `xorm:"-"`
  246. DeletedUnix util.TimeStamp `xorm:"INDEX created"`
  247. }
  248. // AddDeletedBranch adds a deleted branch to the database
  249. func (repo *Repository) AddDeletedBranch(branchName, commit string, deletedByID int64) error {
  250. deletedBranch := &DeletedBranch{
  251. RepoID: repo.ID,
  252. Name: branchName,
  253. Commit: commit,
  254. DeletedByID: deletedByID,
  255. }
  256. sess := x.NewSession()
  257. defer sess.Close()
  258. if err := sess.Begin(); err != nil {
  259. return err
  260. }
  261. if _, err := sess.InsertOne(deletedBranch); err != nil {
  262. return err
  263. }
  264. return sess.Commit()
  265. }
  266. // GetDeletedBranches returns all the deleted branches
  267. func (repo *Repository) GetDeletedBranches() ([]*DeletedBranch, error) {
  268. deletedBranches := make([]*DeletedBranch, 0)
  269. return deletedBranches, x.Where("repo_id = ?", repo.ID).Desc("deleted_unix").Find(&deletedBranches)
  270. }
  271. // GetDeletedBranchByID get a deleted branch by its ID
  272. func (repo *Repository) GetDeletedBranchByID(ID int64) (*DeletedBranch, error) {
  273. deletedBranch := &DeletedBranch{ID: ID}
  274. has, err := x.Get(deletedBranch)
  275. if err != nil {
  276. return nil, err
  277. }
  278. if !has {
  279. return nil, nil
  280. }
  281. return deletedBranch, nil
  282. }
  283. // RemoveDeletedBranch removes a deleted branch from the database
  284. func (repo *Repository) RemoveDeletedBranch(id int64) (err error) {
  285. deletedBranch := &DeletedBranch{
  286. RepoID: repo.ID,
  287. ID: id,
  288. }
  289. sess := x.NewSession()
  290. defer sess.Close()
  291. if err = sess.Begin(); err != nil {
  292. return err
  293. }
  294. if affected, err := sess.Delete(deletedBranch); err != nil {
  295. return err
  296. } else if affected != 1 {
  297. return fmt.Errorf("remove deleted branch ID(%v) failed", id)
  298. }
  299. return sess.Commit()
  300. }
  301. // LoadUser loads the user that deleted the branch
  302. // When there's no user found it returns a NewGhostUser
  303. func (deletedBranch *DeletedBranch) LoadUser() {
  304. user, err := GetUserByID(deletedBranch.DeletedByID)
  305. if err != nil {
  306. user = NewGhostUser()
  307. }
  308. deletedBranch.DeletedBy = user
  309. }
  310. // RemoveOldDeletedBranches removes old deleted branches
  311. func RemoveOldDeletedBranches() {
  312. if !taskStatusTable.StartIfNotRunning(`deleted_branches_cleanup`) {
  313. return
  314. }
  315. defer taskStatusTable.Stop(`deleted_branches_cleanup`)
  316. log.Trace("Doing: DeletedBranchesCleanup")
  317. deleteBefore := time.Now().Add(-setting.Cron.DeletedBranchesCleanup.OlderThan)
  318. _, err := x.Where("deleted_unix < ?", deleteBefore.Unix()).Delete(new(DeletedBranch))
  319. if err != nil {
  320. log.Error(4, "DeletedBranchesCleanup: %v", err)
  321. }
  322. }