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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  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. git.GlobalCommandArgs = oldGlobals
  139. littleLFS, bigLFS = commitAndPushTest(t, dstPath, prefix)
  140. t.Run("Locks", func(t *testing.T) {
  141. PrintCurrentTest(t)
  142. lockTest(t, dstPath)
  143. })
  144. })
  145. return
  146. }
  147. func commitAndPushTest(t *testing.T, dstPath, prefix string) (little, big string) {
  148. t.Run("PushCommit", func(t *testing.T) {
  149. PrintCurrentTest(t)
  150. t.Run("Little", func(t *testing.T) {
  151. PrintCurrentTest(t)
  152. little = doCommitAndPush(t, littleSize, dstPath, prefix)
  153. })
  154. t.Run("Big", func(t *testing.T) {
  155. if testing.Short() {
  156. t.Skip("Skipping test in short mode.")
  157. return
  158. }
  159. PrintCurrentTest(t)
  160. big = doCommitAndPush(t, bigSize, dstPath, prefix)
  161. })
  162. })
  163. return
  164. }
  165. func rawTest(t *testing.T, ctx *APITestContext, little, big, littleLFS, bigLFS string) {
  166. t.Run("Raw", func(t *testing.T) {
  167. PrintCurrentTest(t)
  168. username := ctx.Username
  169. reponame := ctx.Reponame
  170. session := loginUser(t, username)
  171. // Request raw paths
  172. req := NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", little))
  173. resp := session.MakeRequest(t, req, http.StatusOK)
  174. assert.Equal(t, littleSize, resp.Body.Len())
  175. setting.CheckLFSVersion()
  176. if setting.LFS.StartServer {
  177. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", littleLFS))
  178. resp = session.MakeRequest(t, req, http.StatusOK)
  179. assert.NotEqual(t, littleSize, resp.Body.Len())
  180. assert.Contains(t, resp.Body.String(), models.LFSMetaFileIdentifier)
  181. }
  182. if !testing.Short() {
  183. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", big))
  184. resp = session.MakeRequest(t, req, http.StatusOK)
  185. assert.Equal(t, bigSize, resp.Body.Len())
  186. if setting.LFS.StartServer {
  187. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/raw/branch/master/", bigLFS))
  188. resp = session.MakeRequest(t, req, http.StatusOK)
  189. assert.NotEqual(t, bigSize, resp.Body.Len())
  190. assert.Contains(t, resp.Body.String(), models.LFSMetaFileIdentifier)
  191. }
  192. }
  193. })
  194. }
  195. func mediaTest(t *testing.T, ctx *APITestContext, little, big, littleLFS, bigLFS string) {
  196. t.Run("Media", func(t *testing.T) {
  197. PrintCurrentTest(t)
  198. username := ctx.Username
  199. reponame := ctx.Reponame
  200. session := loginUser(t, username)
  201. // Request media paths
  202. req := NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", little))
  203. resp := session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  204. assert.Equal(t, littleSize, resp.Length)
  205. setting.CheckLFSVersion()
  206. if setting.LFS.StartServer {
  207. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", littleLFS))
  208. resp = session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  209. assert.Equal(t, littleSize, resp.Length)
  210. }
  211. if !testing.Short() {
  212. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", big))
  213. resp = session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  214. assert.Equal(t, bigSize, resp.Length)
  215. if setting.LFS.StartServer {
  216. req = NewRequest(t, "GET", path.Join("/", username, reponame, "/media/branch/master/", bigLFS))
  217. resp = session.MakeRequestNilResponseRecorder(t, req, http.StatusOK)
  218. assert.Equal(t, bigSize, resp.Length)
  219. }
  220. }
  221. })
  222. }
  223. func lockTest(t *testing.T, repoPath string) {
  224. lockFileTest(t, "README.md", repoPath)
  225. }
  226. func lockFileTest(t *testing.T, filename, repoPath string) {
  227. _, err := git.NewCommand("lfs").AddArguments("locks").RunInDir(repoPath)
  228. assert.NoError(t, err)
  229. _, err = git.NewCommand("lfs").AddArguments("lock", filename).RunInDir(repoPath)
  230. assert.NoError(t, err)
  231. _, err = git.NewCommand("lfs").AddArguments("locks").RunInDir(repoPath)
  232. assert.NoError(t, err)
  233. _, err = git.NewCommand("lfs").AddArguments("unlock", filename).RunInDir(repoPath)
  234. assert.NoError(t, err)
  235. }
  236. func doCommitAndPush(t *testing.T, size int, repoPath, prefix string) string {
  237. name, err := generateCommitWithNewData(size, repoPath, "user2@example.com", "User Two", prefix)
  238. assert.NoError(t, err)
  239. _, err = git.NewCommand("push", "origin", "master").RunInDir(repoPath) //Push
  240. assert.NoError(t, err)
  241. return name
  242. }
  243. func generateCommitWithNewData(size int, repoPath, email, fullName, prefix string) (string, error) {
  244. //Generate random file
  245. data := make([]byte, size)
  246. _, err := rand.Read(data)
  247. if err != nil {
  248. return "", err
  249. }
  250. tmpFile, err := ioutil.TempFile(repoPath, prefix)
  251. if err != nil {
  252. return "", err
  253. }
  254. defer tmpFile.Close()
  255. _, err = tmpFile.Write(data)
  256. if err != nil {
  257. return "", err
  258. }
  259. //Commit
  260. // Now here we should explicitly allow lfs filters to run
  261. oldGlobals := allowLFSFilters()
  262. err = git.AddChanges(repoPath, false, filepath.Base(tmpFile.Name()))
  263. if err != nil {
  264. return "", err
  265. }
  266. err = git.CommitChanges(repoPath, git.CommitChangesOptions{
  267. Committer: &git.Signature{
  268. Email: email,
  269. Name: fullName,
  270. When: time.Now(),
  271. },
  272. Author: &git.Signature{
  273. Email: email,
  274. Name: fullName,
  275. When: time.Now(),
  276. },
  277. Message: fmt.Sprintf("Testing commit @ %v", time.Now()),
  278. })
  279. git.GlobalCommandArgs = oldGlobals
  280. return filepath.Base(tmpFile.Name()), err
  281. }
  282. func doBranchProtectPRMerge(baseCtx *APITestContext, dstPath string) func(t *testing.T) {
  283. return func(t *testing.T) {
  284. PrintCurrentTest(t)
  285. t.Run("CreateBranchProtected", doGitCreateBranch(dstPath, "protected"))
  286. t.Run("PushProtectedBranch", doGitPushTestRepository(dstPath, "origin", "protected"))
  287. ctx := NewAPITestContext(t, baseCtx.Username, baseCtx.Reponame)
  288. t.Run("ProtectProtectedBranchNoWhitelist", doProtectBranch(ctx, "protected", ""))
  289. t.Run("GenerateCommit", func(t *testing.T) {
  290. _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-")
  291. assert.NoError(t, err)
  292. })
  293. t.Run("FailToPushToProtectedBranch", doGitPushTestRepositoryFail(dstPath, "origin", "protected"))
  294. t.Run("PushToUnprotectedBranch", doGitPushTestRepository(dstPath, "origin", "protected:unprotected"))
  295. var pr api.PullRequest
  296. var err error
  297. t.Run("CreatePullRequest", func(t *testing.T) {
  298. pr, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, "protected", "unprotected")(t)
  299. assert.NoError(t, err)
  300. })
  301. t.Run("MergePR", doAPIMergePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, pr.Index))
  302. t.Run("PullProtected", doGitPull(dstPath, "origin", "protected"))
  303. t.Run("ProtectProtectedBranchWhitelist", doProtectBranch(ctx, "protected", baseCtx.Username))
  304. t.Run("CheckoutMaster", doGitCheckoutBranch(dstPath, "master"))
  305. t.Run("CreateBranchForced", doGitCreateBranch(dstPath, "toforce"))
  306. t.Run("GenerateCommit", func(t *testing.T) {
  307. _, err := generateCommitWithNewData(littleSize, dstPath, "user2@example.com", "User Two", "branch-data-file-")
  308. assert.NoError(t, err)
  309. })
  310. t.Run("FailToForcePushToProtectedBranch", doGitPushTestRepositoryFail(dstPath, "-f", "origin", "toforce:protected"))
  311. t.Run("MergeProtectedToToforce", doGitMerge(dstPath, "protected"))
  312. t.Run("PushToProtectedBranch", doGitPushTestRepository(dstPath, "origin", "toforce:protected"))
  313. t.Run("CheckoutMasterAgain", doGitCheckoutBranch(dstPath, "master"))
  314. }
  315. }
  316. func doProtectBranch(ctx APITestContext, branch string, userToWhitelist string) func(t *testing.T) {
  317. // We are going to just use the owner to set the protection.
  318. return func(t *testing.T) {
  319. csrf := GetCSRF(t, ctx.Session, fmt.Sprintf("/%s/%s/settings/branches", url.PathEscape(ctx.Username), url.PathEscape(ctx.Reponame)))
  320. if userToWhitelist == "" {
  321. // Change branch to protected
  322. 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{
  323. "_csrf": csrf,
  324. "protected": "on",
  325. })
  326. ctx.Session.MakeRequest(t, req, http.StatusFound)
  327. } else {
  328. user, err := models.GetUserByName(userToWhitelist)
  329. assert.NoError(t, err)
  330. // Change branch to protected
  331. 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{
  332. "_csrf": csrf,
  333. "protected": "on",
  334. "enable_whitelist": "on",
  335. "whitelist_users": strconv.FormatInt(user.ID, 10),
  336. })
  337. ctx.Session.MakeRequest(t, req, http.StatusFound)
  338. }
  339. // Check if master branch has been locked successfully
  340. flashCookie := ctx.Session.GetCookie("macaron_flash")
  341. assert.NotNil(t, flashCookie)
  342. assert.EqualValues(t, "success%3DBranch%2Bprotection%2Bfor%2Bbranch%2B%2527"+url.QueryEscape(branch)+"%2527%2Bhas%2Bbeen%2Bupdated.", flashCookie.Value)
  343. }
  344. }
  345. func doMergeFork(ctx, baseCtx APITestContext, baseBranch, headBranch string) func(t *testing.T) {
  346. return func(t *testing.T) {
  347. var pr api.PullRequest
  348. var err error
  349. t.Run("CreatePullRequest", func(t *testing.T) {
  350. pr, err = doAPICreatePullRequest(ctx, baseCtx.Username, baseCtx.Reponame, baseBranch, headBranch)(t)
  351. assert.NoError(t, err)
  352. })
  353. t.Run("MergePR", doAPIMergePullRequest(baseCtx, baseCtx.Username, baseCtx.Reponame, pr.Index))
  354. }
  355. }