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.

git_test.go 14KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  1. // Copyright 2017 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 integrations
  5. import (
  6. "crypto/rand"
  7. "fmt"
  8. "io/ioutil"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "strconv"
  15. "testing"
  16. "time"
  17. "code.gitea.io/gitea/models"
  18. "code.gitea.io/gitea/modules/git"
  19. "code.gitea.io/gitea/modules/setting"
  20. api "code.gitea.io/gitea/modules/structs"
  21. "github.com/stretchr/testify/assert"
  22. )
  23. const (
  24. littleSize = 1024 //1ko
  25. bigSize = 128 * 1024 * 1024 //128Mo
  26. )
  27. func TestGit(t *testing.T) {
  28. onGiteaRun(t, testGit)
  29. }
  30. func testGit(t *testing.T, u *url.URL) {
  31. username := "user2"
  32. baseAPITestContext := NewAPITestContext(t, username, "repo1")
  33. u.Path = baseAPITestContext.GitPath()
  34. forkedUserCtx := NewAPITestContext(t, "user4", "repo1")
  35. t.Run("HTTP", func(t *testing.T) {
  36. PrintCurrentTest(t)
  37. ensureAnonymousClone(t, u)
  38. httpContext := baseAPITestContext
  39. httpContext.Reponame = "repo-tmp-17"
  40. forkedUserCtx.Reponame = httpContext.Reponame
  41. dstPath, err := ioutil.TempDir("", httpContext.Reponame)
  42. assert.NoError(t, err)
  43. defer os.RemoveAll(dstPath)
  44. t.Run("CreateRepoInDifferentUser", doAPICreateRepository(forkedUserCtx, false))
  45. t.Run("AddUserAsCollaborator", doAPIAddCollaborator(forkedUserCtx, httpContext.Username, models.AccessModeRead))
  46. t.Run("ForkFromDifferentUser", doAPIForkRepository(httpContext, forkedUserCtx.Username))
  47. u.Path = httpContext.GitPath()
  48. u.User = url.UserPassword(username, userPassword)
  49. t.Run("Clone", doGitClone(dstPath, u))
  50. little, big := standardCommitAndPushTest(t, dstPath)
  51. littleLFS, bigLFS := lfsCommitAndPushTest(t, dstPath)
  52. rawTest(t, &httpContext, little, big, littleLFS, bigLFS)
  53. mediaTest(t, &httpContext, little, big, littleLFS, bigLFS)
  54. t.Run("BranchProtectMerge", doBranchProtectPRMerge(&httpContext, dstPath))
  55. t.Run("MergeFork", func(t *testing.T) {
  56. t.Run("CreatePRAndMerge", doMergeFork(httpContext, forkedUserCtx, "master", httpContext.Username+":master"))
  57. t.Run("DeleteRepository", doAPIDeleteRepository(httpContext))
  58. rawTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  59. mediaTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  60. })
  61. })
  62. t.Run("SSH", func(t *testing.T) {
  63. PrintCurrentTest(t)
  64. sshContext := baseAPITestContext
  65. sshContext.Reponame = "repo-tmp-18"
  66. keyname := "my-testing-key"
  67. forkedUserCtx.Reponame = sshContext.Reponame
  68. t.Run("CreateRepoInDifferentUser", doAPICreateRepository(forkedUserCtx, false))
  69. t.Run("AddUserAsCollaborator", doAPIAddCollaborator(forkedUserCtx, sshContext.Username, models.AccessModeRead))
  70. t.Run("ForkFromDifferentUser", doAPIForkRepository(sshContext, forkedUserCtx.Username))
  71. //Setup key the user ssh key
  72. withKeyFile(t, keyname, func(keyFile string) {
  73. t.Run("CreateUserKey", doAPICreateUserKey(sshContext, "test-key", keyFile))
  74. //Setup remote link
  75. //TODO: get url from api
  76. sshURL := createSSHUrl(sshContext.GitPath(), u)
  77. //Setup clone folder
  78. dstPath, err := ioutil.TempDir("", sshContext.Reponame)
  79. assert.NoError(t, err)
  80. defer os.RemoveAll(dstPath)
  81. t.Run("Clone", doGitClone(dstPath, sshURL))
  82. little, big := standardCommitAndPushTest(t, dstPath)
  83. littleLFS, bigLFS := lfsCommitAndPushTest(t, dstPath)
  84. rawTest(t, &sshContext, little, big, littleLFS, bigLFS)
  85. mediaTest(t, &sshContext, little, big, littleLFS, bigLFS)
  86. t.Run("BranchProtectMerge", doBranchProtectPRMerge(&sshContext, dstPath))
  87. t.Run("MergeFork", func(t *testing.T) {
  88. t.Run("CreatePRAndMerge", doMergeFork(sshContext, forkedUserCtx, "master", sshContext.Username+":master"))
  89. t.Run("DeleteRepository", doAPIDeleteRepository(sshContext))
  90. rawTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  91. mediaTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  92. })
  93. })
  94. })
  95. }
  96. func ensureAnonymousClone(t *testing.T, u *url.URL) {
  97. dstLocalPath, err := ioutil.TempDir("", "repo1")
  98. assert.NoError(t, err)
  99. defer os.RemoveAll(dstLocalPath)
  100. t.Run("CloneAnonymous", doGitClone(dstLocalPath, u))
  101. }
  102. func standardCommitAndPushTest(t *testing.T, dstPath string) (little, big string) {
  103. t.Run("Standard", func(t *testing.T) {
  104. PrintCurrentTest(t)
  105. little, big = commitAndPushTest(t, dstPath, "data-file-")
  106. })
  107. return
  108. }
  109. func lfsCommitAndPushTest(t *testing.T, dstPath string) (littleLFS, bigLFS string) {
  110. t.Run("LFS", func(t *testing.T) {
  111. PrintCurrentTest(t)
  112. setting.CheckLFSVersion()
  113. if !setting.LFS.StartServer {
  114. t.Skip()
  115. return
  116. }
  117. prefix := "lfs-data-file-"
  118. _, err := git.NewCommand("lfs").AddArguments("install").RunInDir(dstPath)
  119. assert.NoError(t, err)
  120. _, err = git.NewCommand("lfs").AddArguments("track", prefix+"*").RunInDir(dstPath)
  121. assert.NoError(t, err)
  122. err = git.AddChanges(dstPath, false, ".gitattributes")
  123. assert.NoError(t, err)
  124. oldGlobals := allowLFSFilters()
  125. err = git.CommitChanges(dstPath, git.CommitChangesOptions{
  126. Committer: &git.Signature{
  127. Email: "user2@example.com",
  128. Name: "User Two",
  129. When: time.Now(),
  130. },
  131. Author: &git.Signature{
  132. Email: "user2@example.com",
  133. Name: "User Two",
  134. When: time.Now(),
  135. },
  136. Message: fmt.Sprintf("Testing commit @ %v", time.Now()),
  137. })
  138. assert.NoError(t, err)
  139. git.GlobalCommandArgs = oldGlobals
  140. littleLFS, bigLFS = commitAndPushTest(t, dstPath, prefix)
  141. t.Run("Locks", func(t *testing.T) {
  142. PrintCurrentTest(t)
  143. lockTest(t, dstPath)
  144. })
  145. })
  146. return
  147. }
  148. func commitAndPushTest(t *testing.T, dstPath, prefix string) (little, big string) {
  149. t.Run("PushCommit", func(t *testing.T) {
  150. PrintCurrentTest(t)
  151. t.Run("Little", func(t *testing.T) {
  152. PrintCurrentTest(t)
  153. little = doCommitAndPush(t, littleSize, dstPath, prefix)
  154. })
  155. t.Run("Big", func(t *testing.T) {
  156. if testing.Short() {
  157. t.Skip("Skipping test in short mode.")
  158. return
  159. }
  160. PrintCurrentTest(t)
  161. big = doCommitAndPush(t, bigSize, dstPath, prefix)
  162. })
  163. })
  164. return
  165. }
  166. func rawTest(t *testing.T, ctx *APITestContext, little, big, littleLFS, bigLFS string) {
  167. t.Run("Raw", func(t *testing.T) {
  168. PrintCurrentTest(t)
  169. username := ctx.Username
  170. reponame := ctx.Reponame
  171. session := loginUser(t, username)
  172. // Request raw paths
  173. req := NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", little))
  174. resp := session.MakeRequest(t, req, http.StatusOK)
  175. assert.Equal(t, littleSize, resp.Body.Len())
  176. setting.CheckLFSVersion()
  177. if setting.LFS.StartServer {
  178. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", littleLFS))
  179. resp = session.MakeRequest(t, req, http.StatusOK)
  180. assert.NotEqual(t, littleSize, resp.Body.Len())
  181. assert.Contains(t, resp.Body.String(), models.LFSMetaFileIdentifier)
  182. }
  183. if !testing.Short() {
  184. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", big))
  185. resp = session.MakeRequest(t, req, http.StatusOK)
  186. assert.Equal(t, bigSize, resp.Body.Len())
  187. if setting.LFS.StartServer {
  188. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", bigLFS))
  189. resp = session.MakeRequest(t, req, http.StatusOK)
  190. assert.NotEqual(t, bigSize, resp.Body.Len())
  191. assert.Contains(t, resp.Body.String(), models.LFSMetaFileIdentifier)
  192. }
  193. }
  194. })
  195. }
  196. func mediaTest(t *testing.T, ctx *APITestContext, little, big, littleLFS, bigLFS string) {
  197. t.Run("Media", func(t *testing.T) {
  198. PrintCurrentTest(t)
  199. username := ctx.Username
  200. reponame := ctx.Reponame
  201. session := loginUser(t, username)
  202. // Request media paths
  203. req := NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", little))
  204. resp := session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  205. assert.Equal(t, littleSize, resp.Length)
  206. setting.CheckLFSVersion()
  207. if setting.LFS.StartServer {
  208. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", littleLFS))
  209. resp = session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  210. assert.Equal(t, littleSize, resp.Length)
  211. }
  212. if !testing.Short() {
  213. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", big))
  214. resp = session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  215. assert.Equal(t, bigSize, resp.Length)
  216. if setting.LFS.StartServer {
  217. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", bigLFS))
  218. resp = session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  219. assert.Equal(t, bigSize, resp.Length)
  220. }
  221. }
  222. })
  223. }
  224. func lockTest(t *testing.T, repoPath string) {
  225. lockFileTest(t, "README.md", repoPath)
  226. }
  227. func lockFileTest(t *testing.T, filename, repoPath string) {
  228. _, err := git.NewCommand("lfs").AddArguments("locks").RunInDir(repoPath)
  229. assert.NoError(t, err)
  230. _, err = git.NewCommand("lfs").AddArguments("lock", filename).RunInDir(repoPath)
  231. assert.NoError(t, err)
  232. _, err = git.NewCommand("lfs").AddArguments("locks").RunInDir(repoPath)
  233. assert.NoError(t, err)
  234. _, err = git.NewCommand("lfs").AddArguments("unlock", filename).RunInDir(repoPath)
  235. assert.NoError(t, err)
  236. }
  237. func doCommitAndPush(t *testing.T, size int, repoPath, prefix string) string {
  238. name, err := generateCommitWithNewData(size, repoPath, "user2@example.com", "User Two", prefix)
  239. assert.NoError(t, err)
  240. _, err = git.NewCommand("push", "origin", "master").RunInDir(repoPath) //Push
  241. assert.NoError(t, err)
  242. return name
  243. }
  244. func generateCommitWithNewData(size int, repoPath, email, fullName, prefix string) (string, error) {
  245. //Generate random file
  246. data := make([]byte, size)
  247. _, err := rand.Read(data)
  248. if err != nil {
  249. return "", err
  250. }
  251. tmpFile, err := ioutil.TempFile(repoPath, prefix)
  252. if err != nil {
  253. return "", err
  254. }
  255. defer tmpFile.Close()
  256. _, err = tmpFile.Write(data)
  257. if err != nil {
  258. return "", err
  259. }
  260. //Commit
  261. // Now here we should explicitly allow lfs filters to run
  262. oldGlobals := allowLFSFilters()
  263. err = git.AddChanges(repoPath, false, filepath.Base(tmpFile.Name()))
  264. if err != nil {
  265. return "", err
  266. }
  267. err = git.CommitChanges(repoPath, git.CommitChangesOptions{
  268. Committer: &git.Signature{
  269. Email: email,
  270. Name: fullName,
  271. When: time.Now(),
  272. },
  273. Author: &git.Signature{
  274. Email: email,
  275. Name: fullName,
  276. When: time.Now(),
  277. },
  278. Message: fmt.Sprintf("Testing commit @ %v", time.Now()),
  279. })
  280. git.GlobalCommandArgs = oldGlobals
  281. return filepath.Base(tmpFile.Name()), err
  282. }
  283. func doBranchProtectPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) {
  284. return func(t *testing.T) {
  285. PrintCurrentTest(t)
  286. t.Run("CreateBranchProtected", doGitCreateBranch(dstPath, "protected"))
  287. t.Run("PushProtectedBranch", doGitPushTestRepository(dstPath, "origin", "protected"))
  288. ctx := NewAPITestContext(t, baseCtx.Username, baseCtx.Reponame)
  289. t.Run("ProtectProtectedBranchNoWhitelist", doProtectBranch(ctx, "protected", ""))
  290. t.Run("GenerateCommit", func(t *testing.T) {
  291. _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-")
  292. assert.NoError(t, err)
  293. })
  294. t.Run("FailToPushToProtectedBranch", doGitPushTestRepositoryFail(dstPath, "origin", "protected"))
  295. t.Run("PushToUnprotectedBranch", doGitPushTestRepository(dstPath, "origin", "protected:unprotected"))
  296. var pr api.PullRequest
  297. var err error
  298. t.Run("CreatePullRequest", func(t *testing.T) {
  299. pr, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, "protected", "unprotected")(t)
  300. assert.NoError(t, err)
  301. })
  302. t.Run("MergePR", doAPIMergePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, pr.Index))
  303. t.Run("PullProtected", doGitPull(dstPath, "origin", "protected"))
  304. t.Run("ProtectProtectedBranchWhitelist", doProtectBranch(ctx, "protected", baseCtx.Username))
  305. t.Run("CheckoutMaster", doGitCheckoutBranch(dstPath, "master"))
  306. t.Run("CreateBranchForced", doGitCreateBranch(dstPath, "toforce"))
  307. t.Run("GenerateCommit", func(t *testing.T) {
  308. _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-")
  309. assert.NoError(t, err)
  310. })
  311. t.Run("FailToForcePushToProtectedBranch", doGitPushTestRepositoryFail(dstPath, "-f", "origin", "toforce:protected"))
  312. t.Run("MergeProtectedToToforce", doGitMerge(dstPath, "protected"))
  313. t.Run("PushToProtectedBranch", doGitPushTestRepository(dstPath, "origin", "toforce:protected"))
  314. t.Run("CheckoutMasterAgain", doGitCheckoutBranch(dstPath, "master"))
  315. }
  316. }
  317. func doProtectBranch(ctx APITestContext, branch string, userToWhitelist string) func(t *testing.T) {
  318. // We are going to just use the owner to set the protection.
  319. return func(t *testing.T) {
  320. csrf := GetCSRF(t, ctx.Session, fmt.Sprintf("/%s/%s/settings/branches", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame)))
  321. if userToWhitelist == "" {
  322. // Change branch to protected
  323. req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings/branches/%s", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), url.PathEscape(branch)), map[string]string{
  324. "_csrf": csrf,
  325. "protected": "on",
  326. })
  327. ctx.Session.MakeRequest(t, req, http.StatusFound)
  328. } else {
  329. user, err := models.GetUserByName(userToWhitelist)
  330. assert.NoError(t, err)
  331. // Change branch to protected
  332. req := NewRequestWithValues(t, "POST", fmt.Sprintf("/%s/%s/settings/branches/%s", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame), url.PathEscape(branch)), map[string]string{
  333. "_csrf": csrf,
  334. "protected": "on",
  335. "enable_whitelist": "on",
  336. "whitelist_users": strconv.FormatInt(user.ID, 10),
  337. })
  338. ctx.Session.MakeRequest(t, req, http.StatusFound)
  339. }
  340. // Check if master branch has been locked successfully
  341. flashCookie := ctx.Session.GetCookie("macaron_flash")
  342. assert.NotNil(t, flashCookie)
  343. assert.EqualValues(t, "success%3DBranch%2Bprotection%2Bfor%2Bbranch%2B%2527"+url.QueryEscape(branch)+"%2527%2Bhas%2Bbeen%2Bupdated.", flashCookie.Value)
  344. }
  345. }
  346. func doMergeFork(ctx, baseCtx APITestContext, baseBranch, headBranch string) func(t *testing.T) {
  347. return func(t *testing.T) {
  348. var pr api.PullRequest
  349. var err error
  350. t.Run("CreatePullRequest", func(t *testing.T) {
  351. pr, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, baseBranch, headBranch)(t)
  352. assert.NoError(t, err)
  353. })
  354. t.Run("MergePR", doAPIMergePullRequest(baseCtx, baseCtx.Username, baseCtx.Reponame, pr.Index))
  355. }
  356. }