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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484
  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. defer 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. t.Run("PushCreate", doPushCreate(httpContext, u))
  62. })
  63. t.Run("SSH", func(t *testing.T) {
  64. defer PrintCurrentTest(t)()
  65. sshContext := baseAPITestContext
  66. sshContext.Reponame = "repo-tmp-18"
  67. keyname := "my-testing-key"
  68. forkedUserCtx.Reponame = sshContext.Reponame
  69. t.Run("CreateRepoInDifferentUser", doAPICreateRepository(forkedUserCtx, false))
  70. t.Run("AddUserAsCollaborator", doAPIAddCollaborator(forkedUserCtx, sshContext.Username, models.AccessModeRead))
  71. t.Run("ForkFromDifferentUser", doAPIForkRepository(sshContext, forkedUserCtx.Username))
  72. //Setup key the user ssh key
  73. withKeyFile(t, keyname, func(keyFile string) {
  74. t.Run("CreateUserKey", doAPICreateUserKey(sshContext, "test-key", keyFile))
  75. //Setup remote link
  76. //TODO: get url from api
  77. sshURL := createSSHUrl(sshContext.GitPath(), u)
  78. //Setup clone folder
  79. dstPath, err := ioutil.TempDir("", sshContext.Reponame)
  80. assert.NoError(t, err)
  81. defer os.RemoveAll(dstPath)
  82. t.Run("Clone", doGitClone(dstPath, sshURL))
  83. little, big := standardCommitAndPushTest(t, dstPath)
  84. littleLFS, bigLFS := lfsCommitAndPushTest(t, dstPath)
  85. rawTest(t, &sshContext, little, big, littleLFS, bigLFS)
  86. mediaTest(t, &sshContext, little, big, littleLFS, bigLFS)
  87. t.Run("BranchProtectMerge", doBranchProtectPRMerge(&sshContext, dstPath))
  88. t.Run("MergeFork", func(t *testing.T) {
  89. t.Run("CreatePRAndMerge", doMergeFork(sshContext, forkedUserCtx, "master", sshContext.Username+":master"))
  90. t.Run("DeleteRepository", doAPIDeleteRepository(sshContext))
  91. rawTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  92. mediaTest(t, &forkedUserCtx, little, big, littleLFS, bigLFS)
  93. })
  94. t.Run("PushCreate", doPushCreate(sshContext, sshURL))
  95. })
  96. })
  97. }
  98. func ensureAnonymousClone(t *testing.T, u *url.URL) {
  99. dstLocalPath, err := ioutil.TempDir("", "repo1")
  100. assert.NoError(t, err)
  101. defer os.RemoveAll(dstLocalPath)
  102. t.Run("CloneAnonymous", doGitClone(dstLocalPath, u))
  103. }
  104. func standardCommitAndPushTest(t *testing.T, dstPath string) (little, big string) {
  105. t.Run("Standard", func(t *testing.T) {
  106. defer PrintCurrentTest(t)()
  107. little, big = commitAndPushTest(t, dstPath, "data-file-")
  108. })
  109. return
  110. }
  111. func lfsCommitAndPushTest(t *testing.T, dstPath string) (littleLFS, bigLFS string) {
  112. t.Run("LFS", func(t *testing.T) {
  113. defer PrintCurrentTest(t)()
  114. setting.CheckLFSVersion()
  115. if !setting.LFS.StartServer {
  116. t.Skip()
  117. return
  118. }
  119. prefix := "lfs-data-file-"
  120. _, err := git.NewCommand("lfs").AddArguments("install").RunInDir(dstPath)
  121. assert.NoError(t, err)
  122. _, err = git.NewCommand("lfs").AddArguments("track", prefix+"*").RunInDir(dstPath)
  123. assert.NoError(t, err)
  124. err = git.AddChanges(dstPath, false, ".gitattributes")
  125. assert.NoError(t, err)
  126. err = git.CommitChangesWithArgs(dstPath, allowLFSFilters(), git.CommitChangesOptions{
  127. Committer: &git.Signature{
  128. Email: "user2@example.com",
  129. Name: "User Two",
  130. When: time.Now(),
  131. },
  132. Author: &git.Signature{
  133. Email: "user2@example.com",
  134. Name: "User Two",
  135. When: time.Now(),
  136. },
  137. Message: fmt.Sprintf("Testing commit @ %v", time.Now()),
  138. })
  139. assert.NoError(t, err)
  140. littleLFS, bigLFS = commitAndPushTest(t, dstPath, prefix)
  141. t.Run("Locks", func(t *testing.T) {
  142. defer 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. defer PrintCurrentTest(t)()
  151. t.Run("Little", func(t *testing.T) {
  152. defer 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. defer 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. defer 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. defer 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. globalArgs := allowLFSFilters()
  263. err = git.AddChangesWithArgs(repoPath, globalArgs, false, filepath.Base(tmpFile.Name()))
  264. if err != nil {
  265. return "", err
  266. }
  267. err = git.CommitChangesWithArgs(repoPath, globalArgs, 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. 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. defer 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_push": "whitelist",
  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. }
  357. func doPushCreate(ctx APITestContext, u *url.URL) func(t *testing.T) {
  358. return func(t *testing.T) {
  359. defer PrintCurrentTest(t)()
  360. ctx.Reponame = fmt.Sprintf("repo-tmp-push-create-%s", u.Scheme)
  361. u.Path = ctx.GitPath()
  362. tmpDir, err := ioutil.TempDir("", ctx.Reponame)
  363. assert.NoError(t, err)
  364. _, err = git.NewCommand("clone", u.String()).RunInDir(tmpDir)
  365. assert.Error(t, err)
  366. err = git.InitRepository(tmpDir, false)
  367. assert.NoError(t, err)
  368. _, err = os.Create(filepath.Join(tmpDir, "test.txt"))
  369. assert.NoError(t, err)
  370. err = git.AddChanges(tmpDir, true)
  371. assert.NoError(t, err)
  372. err = git.CommitChanges(tmpDir, git.CommitChangesOptions{
  373. Committer: &git.Signature{
  374. Email: "user2@example.com",
  375. Name: "User Two",
  376. When: time.Now(),
  377. },
  378. Author: &git.Signature{
  379. Email: "user2@example.com",
  380. Name: "User Two",
  381. When: time.Now(),
  382. },
  383. Message: fmt.Sprintf("Testing push create @ %v", time.Now()),
  384. })
  385. assert.NoError(t, err)
  386. _, err = git.NewCommand("remote", "add", "origin", u.String()).RunInDir(tmpDir)
  387. assert.NoError(t, err)
  388. invalidCtx := ctx
  389. invalidCtx.Reponame = fmt.Sprintf("invalid/repo-tmp-push-create-%s", u.Scheme)
  390. u.Path = invalidCtx.GitPath()
  391. _, err = git.NewCommand("remote", "add", "invalid", u.String()).RunInDir(tmpDir)
  392. assert.NoError(t, err)
  393. // Push to create disabled
  394. setting.Repository.EnablePushCreateUser = false
  395. _, err = git.NewCommand("push", "origin", "master").RunInDir(tmpDir)
  396. assert.Error(t, err)
  397. // Push to create enabled
  398. setting.Repository.EnablePushCreateUser = true
  399. // Invalid repo
  400. _, err = git.NewCommand("push", "invalid", "master").RunInDir(tmpDir)
  401. assert.Error(t, err)
  402. // Valid repo
  403. _, err = git.NewCommand("push", "origin", "master").RunInDir(tmpDir)
  404. assert.NoError(t, err)
  405. // Fetch repo from database
  406. repo, err := models.GetRepositoryByOwnerAndName(ctx.Username, ctx.Reponame)
  407. assert.NoError(t, err)
  408. assert.False(t, repo.IsEmpty)
  409. assert.True(t, repo.IsPrivate)
  410. }
  411. }