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.

410 lines
14 KiB

Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
Sign merges, CRUD, Wiki and Repository initialisation with gpg key (#7631) This PR fixes #7598 by providing a configurable way of signing commits across the Gitea instance. Per repository configurability and import/generation of trusted secure keys is not provided by this PR - from a security PoV that's probably impossible to do properly. Similarly web-signing, that is asking the user to sign something, is not implemented - this could be done at a later stage however. ## Features - [x] If commit.gpgsign is set in .gitconfig sign commits and files created through repofiles. (merges should already have been signed.) - [x] Verify commits signed with the default gpg as valid - [x] Signer, Committer and Author can all be different - [x] Allow signer to be arbitrarily different - We still require the key to have an activated email on Gitea. A more complete implementation would be to use a keyserver and mark external-or-unactivated with an "unknown" trust level icon. - [x] Add a signing-key.gpg endpoint to get the default gpg pub key if available - Rather than add a fake web-flow user I've added this as an endpoint on /api/v1/signing-key.gpg - [x] Try to match the default key with a user on gitea - this is done at verification time - [x] Make things configurable? - app.ini configuration done - [x] when checking commits are signed need to check if they're actually verifiable too - [x] Add documentation I have decided that adjusting the docker to create a default gpg key is not the correct thing to do and therefore have not implemented this.
5 years ago
  1. // Copyright 2019 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. "net/url"
  7. "path/filepath"
  8. "testing"
  9. "time"
  10. "code.gitea.io/gitea/models"
  11. "code.gitea.io/gitea/modules/git"
  12. "code.gitea.io/gitea/modules/repofiles"
  13. "code.gitea.io/gitea/modules/setting"
  14. api "code.gitea.io/gitea/modules/structs"
  15. "code.gitea.io/gitea/modules/test"
  16. "github.com/stretchr/testify/assert"
  17. )
  18. func getCreateRepoFileOptions(repo *models.Repository) *repofiles.UpdateRepoFileOptions {
  19. return &repofiles.UpdateRepoFileOptions{
  20. OldBranch: repo.DefaultBranch,
  21. NewBranch: repo.DefaultBranch,
  22. TreePath: "new/file.txt",
  23. Message: "Creates new/file.txt",
  24. Content: "This is a NEW file",
  25. IsNewFile: true,
  26. Author: nil,
  27. Committer: nil,
  28. }
  29. }
  30. func getUpdateRepoFileOptions(repo *models.Repository) *repofiles.UpdateRepoFileOptions {
  31. return &repofiles.UpdateRepoFileOptions{
  32. OldBranch: repo.DefaultBranch,
  33. NewBranch: repo.DefaultBranch,
  34. TreePath: "README.md",
  35. Message: "Updates README.md",
  36. SHA: "4b4851ad51df6a7d9f25c979345979eaeb5b349f",
  37. Content: "This is UPDATED content for the README file",
  38. IsNewFile: false,
  39. Author: nil,
  40. Committer: nil,
  41. }
  42. }
  43. func getExpectedFileResponseForRepofilesCreate(commitID string) *api.FileResponse {
  44. treePath := "new/file.txt"
  45. encoding := "base64"
  46. content := "VGhpcyBpcyBhIE5FVyBmaWxl"
  47. selfURL := setting.AppURL + "api/v1/repos/user2/repo1/contents/" + treePath + "?ref=master"
  48. htmlURL := setting.AppURL + "user2/repo1/src/branch/master/" + treePath
  49. gitURL := setting.AppURL + "api/v1/repos/user2/repo1/git/blobs/103ff9234cefeee5ec5361d22b49fbb04d385885"
  50. downloadURL := setting.AppURL + "user2/repo1/raw/branch/master/" + treePath
  51. return &api.FileResponse{
  52. Content: &api.ContentsResponse{
  53. Name: filepath.Base(treePath),
  54. Path: treePath,
  55. SHA: "103ff9234cefeee5ec5361d22b49fbb04d385885",
  56. Type: "file",
  57. Size: 18,
  58. Encoding: &encoding,
  59. Content: &content,
  60. URL: &selfURL,
  61. HTMLURL: &htmlURL,
  62. GitURL: &gitURL,
  63. DownloadURL: &downloadURL,
  64. Links: &api.FileLinksResponse{
  65. Self: &selfURL,
  66. GitURL: &gitURL,
  67. HTMLURL: &htmlURL,
  68. },
  69. },
  70. Commit: &api.FileCommitResponse{
  71. CommitMeta: api.CommitMeta{
  72. URL: setting.AppURL + "api/v1/repos/user2/repo1/git/commits/" + commitID,
  73. SHA: commitID,
  74. },
  75. HTMLURL: setting.AppURL + "user2/repo1/commit/" + commitID,
  76. Author: &api.CommitUser{
  77. Identity: api.Identity{
  78. Name: "User Two",
  79. Email: "user2@noreply.example.org",
  80. },
  81. Date: time.Now().UTC().Format(time.RFC3339),
  82. },
  83. Committer: &api.CommitUser{
  84. Identity: api.Identity{
  85. Name: "User Two",
  86. Email: "user2@noreply.example.org",
  87. },
  88. Date: time.Now().UTC().Format(time.RFC3339),
  89. },
  90. Parents: []*api.CommitMeta{
  91. {
  92. URL: setting.AppURL + "api/v1/repos/user2/repo1/git/commits/65f1bf27bc3bf70f64657658635e66094edbcb4d",
  93. SHA: "65f1bf27bc3bf70f64657658635e66094edbcb4d",
  94. },
  95. },
  96. Message: "Updates README.md\n",
  97. Tree: &api.CommitMeta{
  98. URL: setting.AppURL + "api/v1/repos/user2/repo1/git/trees/f93e3a1a1525fb5b91020da86e44810c87a2d7bc",
  99. SHA: "f93e3a1a1525fb5b91020git dda86e44810c87a2d7bc",
  100. },
  101. },
  102. Verification: &api.PayloadCommitVerification{
  103. Verified: false,
  104. Reason: "gpg.error.not_signed_commit",
  105. Signature: "",
  106. Payload: "",
  107. },
  108. }
  109. }
  110. func getExpectedFileResponseForRepofilesUpdate(commitID, filename string) *api.FileResponse {
  111. encoding := "base64"
  112. content := "VGhpcyBpcyBVUERBVEVEIGNvbnRlbnQgZm9yIHRoZSBSRUFETUUgZmlsZQ=="
  113. selfURL := setting.AppURL + "api/v1/repos/user2/repo1/contents/" + filename + "?ref=master"
  114. htmlURL := setting.AppURL + "user2/repo1/src/branch/master/" + filename
  115. gitURL := setting.AppURL + "api/v1/repos/user2/repo1/git/blobs/dbf8d00e022e05b7e5cf7e535de857de57925647"
  116. downloadURL := setting.AppURL + "user2/repo1/raw/branch/master/" + filename
  117. return &api.FileResponse{
  118. Content: &api.ContentsResponse{
  119. Name: filename,
  120. Path: filename,
  121. SHA: "dbf8d00e022e05b7e5cf7e535de857de57925647",
  122. Type: "file",
  123. Size: 43,
  124. Encoding: &encoding,
  125. Content: &content,
  126. URL: &selfURL,
  127. HTMLURL: &htmlURL,
  128. GitURL: &gitURL,
  129. DownloadURL: &downloadURL,
  130. Links: &api.FileLinksResponse{
  131. Self: &selfURL,
  132. GitURL: &gitURL,
  133. HTMLURL: &htmlURL,
  134. },
  135. },
  136. Commit: &api.FileCommitResponse{
  137. CommitMeta: api.CommitMeta{
  138. URL: setting.AppURL + "api/v1/repos/user2/repo1/git/commits/" + commitID,
  139. SHA: commitID,
  140. },
  141. HTMLURL: setting.AppURL + "user2/repo1/commit/" + commitID,
  142. Author: &api.CommitUser{
  143. Identity: api.Identity{
  144. Name: "User Two",
  145. Email: "user2@noreply.example.org",
  146. },
  147. Date: time.Now().UTC().Format(time.RFC3339),
  148. },
  149. Committer: &api.CommitUser{
  150. Identity: api.Identity{
  151. Name: "User Two",
  152. Email: "user2@noreply.example.org",
  153. },
  154. Date: time.Now().UTC().Format(time.RFC3339),
  155. },
  156. Parents: []*api.CommitMeta{
  157. {
  158. URL: setting.AppURL + "api/v1/repos/user2/repo1/git/commits/65f1bf27bc3bf70f64657658635e66094edbcb4d",
  159. SHA: "65f1bf27bc3bf70f64657658635e66094edbcb4d",
  160. },
  161. },
  162. Message: "Updates README.md\n",
  163. Tree: &api.CommitMeta{
  164. URL: setting.AppURL + "api/v1/repos/user2/repo1/git/trees/f93e3a1a1525fb5b91020da86e44810c87a2d7bc",
  165. SHA: "f93e3a1a1525fb5b91020da86e44810c87a2d7bc",
  166. },
  167. },
  168. Verification: &api.PayloadCommitVerification{
  169. Verified: false,
  170. Reason: "gpg.error.not_signed_commit",
  171. Signature: "",
  172. Payload: "",
  173. },
  174. }
  175. }
  176. func TestCreateOrUpdateRepoFileForCreate(t *testing.T) {
  177. // setup
  178. onGiteaRun(t, func(t *testing.T, u *url.URL) {
  179. ctx := test.MockContext(t, "user2/repo1")
  180. ctx.SetParams(":id", "1")
  181. test.LoadRepo(t, ctx, 1)
  182. test.LoadRepoCommit(t, ctx)
  183. test.LoadUser(t, ctx, 2)
  184. test.LoadGitRepo(t, ctx)
  185. defer ctx.Repo.GitRepo.Close()
  186. repo := ctx.Repo.Repository
  187. doer := ctx.User
  188. opts := getCreateRepoFileOptions(repo)
  189. // test
  190. fileResponse, err := repofiles.CreateOrUpdateRepoFile(repo, doer, opts)
  191. // asserts
  192. assert.Nil(t, err)
  193. gitRepo, _ := git.OpenRepository(repo.RepoPath())
  194. defer gitRepo.Close()
  195. commitID, _ := gitRepo.GetBranchCommitID(opts.NewBranch)
  196. expectedFileResponse := getExpectedFileResponseForRepofilesCreate(commitID)
  197. assert.NotNil(t, expectedFileResponse)
  198. if expectedFileResponse != nil {
  199. assert.EqualValues(t, expectedFileResponse.Content, fileResponse.Content)
  200. assert.EqualValues(t, expectedFileResponse.Commit.SHA, fileResponse.Commit.SHA)
  201. assert.EqualValues(t, expectedFileResponse.Commit.HTMLURL, fileResponse.Commit.HTMLURL)
  202. assert.EqualValues(t, expectedFileResponse.Commit.Author.Email, fileResponse.Commit.Author.Email)
  203. assert.EqualValues(t, expectedFileResponse.Commit.Author.Name, fileResponse.Commit.Author.Name)
  204. }
  205. })
  206. }
  207. func TestCreateOrUpdateRepoFileForUpdate(t *testing.T) {
  208. // setup
  209. onGiteaRun(t, func(t *testing.T, u *url.URL) {
  210. ctx := test.MockContext(t, "user2/repo1")
  211. ctx.SetParams(":id", "1")
  212. test.LoadRepo(t, ctx, 1)
  213. test.LoadRepoCommit(t, ctx)
  214. test.LoadUser(t, ctx, 2)
  215. test.LoadGitRepo(t, ctx)
  216. defer ctx.Repo.GitRepo.Close()
  217. repo := ctx.Repo.Repository
  218. doer := ctx.User
  219. opts := getUpdateRepoFileOptions(repo)
  220. // test
  221. fileResponse, err := repofiles.CreateOrUpdateRepoFile(repo, doer, opts)
  222. // asserts
  223. assert.Nil(t, err)
  224. gitRepo, _ := git.OpenRepository(repo.RepoPath())
  225. defer gitRepo.Close()
  226. commitID, _ := gitRepo.GetBranchCommitID(opts.NewBranch)
  227. expectedFileResponse := getExpectedFileResponseForRepofilesUpdate(commitID, opts.TreePath)
  228. assert.EqualValues(t, expectedFileResponse.Content, fileResponse.Content)
  229. assert.EqualValues(t, expectedFileResponse.Commit.SHA, fileResponse.Commit.SHA)
  230. assert.EqualValues(t, expectedFileResponse.Commit.HTMLURL, fileResponse.Commit.HTMLURL)
  231. assert.EqualValues(t, expectedFileResponse.Commit.Author.Email, fileResponse.Commit.Author.Email)
  232. assert.EqualValues(t, expectedFileResponse.Commit.Author.Name, fileResponse.Commit.Author.Name)
  233. })
  234. }
  235. func TestCreateOrUpdateRepoFileForUpdateWithFileMove(t *testing.T) {
  236. // setup
  237. onGiteaRun(t, func(t *testing.T, u *url.URL) {
  238. ctx := test.MockContext(t, "user2/repo1")
  239. ctx.SetParams(":id", "1")
  240. test.LoadRepo(t, ctx, 1)
  241. test.LoadRepoCommit(t, ctx)
  242. test.LoadUser(t, ctx, 2)
  243. test.LoadGitRepo(t, ctx)
  244. defer ctx.Repo.GitRepo.Close()
  245. repo := ctx.Repo.Repository
  246. doer := ctx.User
  247. opts := getUpdateRepoFileOptions(repo)
  248. opts.FromTreePath = "README.md"
  249. opts.TreePath = "README_new.md" // new file name, README_new.md
  250. // test
  251. fileResponse, err := repofiles.CreateOrUpdateRepoFile(repo, doer, opts)
  252. // asserts
  253. assert.Nil(t, err)
  254. gitRepo, _ := git.OpenRepository(repo.RepoPath())
  255. defer gitRepo.Close()
  256. commit, _ := gitRepo.GetBranchCommit(opts.NewBranch)
  257. expectedFileResponse := getExpectedFileResponseForRepofilesUpdate(commit.ID.String(), opts.TreePath)
  258. // assert that the old file no longer exists in the last commit of the branch
  259. fromEntry, err := commit.GetTreeEntryByPath(opts.FromTreePath)
  260. switch err.(type) {
  261. case git.ErrNotExist:
  262. // correct, continue
  263. default:
  264. t.Fatalf("expected git.ErrNotExist, got:%v", err)
  265. }
  266. toEntry, err := commit.GetTreeEntryByPath(opts.TreePath)
  267. assert.Nil(t, err)
  268. assert.Nil(t, fromEntry) // Should no longer exist here
  269. assert.NotNil(t, toEntry) // Should exist here
  270. // assert SHA has remained the same but paths use the new file name
  271. assert.EqualValues(t, expectedFileResponse.Content.SHA, fileResponse.Content.SHA)
  272. assert.EqualValues(t, expectedFileResponse.Content.Name, fileResponse.Content.Name)
  273. assert.EqualValues(t, expectedFileResponse.Content.Path, fileResponse.Content.Path)
  274. assert.EqualValues(t, expectedFileResponse.Content.URL, fileResponse.Content.URL)
  275. assert.EqualValues(t, expectedFileResponse.Commit.SHA, fileResponse.Commit.SHA)
  276. assert.EqualValues(t, expectedFileResponse.Commit.HTMLURL, fileResponse.Commit.HTMLURL)
  277. })
  278. }
  279. // Test opts with branch names removed, should get same results as above test
  280. func TestCreateOrUpdateRepoFileWithoutBranchNames(t *testing.T) {
  281. // setup
  282. onGiteaRun(t, func(t *testing.T, u *url.URL) {
  283. ctx := test.MockContext(t, "user2/repo1")
  284. ctx.SetParams(":id", "1")
  285. test.LoadRepo(t, ctx, 1)
  286. test.LoadRepoCommit(t, ctx)
  287. test.LoadUser(t, ctx, 2)
  288. test.LoadGitRepo(t, ctx)
  289. defer ctx.Repo.GitRepo.Close()
  290. repo := ctx.Repo.Repository
  291. doer := ctx.User
  292. opts := getUpdateRepoFileOptions(repo)
  293. opts.OldBranch = ""
  294. opts.NewBranch = ""
  295. // test
  296. fileResponse, err := repofiles.CreateOrUpdateRepoFile(repo, doer, opts)
  297. // asserts
  298. assert.Nil(t, err)
  299. gitRepo, _ := git.OpenRepository(repo.RepoPath())
  300. defer gitRepo.Close()
  301. commitID, _ := gitRepo.GetBranchCommitID(repo.DefaultBranch)
  302. expectedFileResponse := getExpectedFileResponseForRepofilesUpdate(commitID, opts.TreePath)
  303. assert.EqualValues(t, expectedFileResponse.Content, fileResponse.Content)
  304. })
  305. }
  306. func TestCreateOrUpdateRepoFileErrors(t *testing.T) {
  307. // setup
  308. onGiteaRun(t, func(t *testing.T, u *url.URL) {
  309. ctx := test.MockContext(t, "user2/repo1")
  310. ctx.SetParams(":id", "1")
  311. test.LoadRepo(t, ctx, 1)
  312. test.LoadRepoCommit(t, ctx)
  313. test.LoadUser(t, ctx, 2)
  314. test.LoadGitRepo(t, ctx)
  315. defer ctx.Repo.GitRepo.Close()
  316. repo := ctx.Repo.Repository
  317. doer := ctx.User
  318. t.Run("bad branch", func(t *testing.T) {
  319. opts := getUpdateRepoFileOptions(repo)
  320. opts.OldBranch = "bad_branch"
  321. fileResponse, err := repofiles.CreateOrUpdateRepoFile(repo, doer, opts)
  322. assert.Error(t, err)
  323. assert.Nil(t, fileResponse)
  324. expectedError := "branch does not exist [name: " + opts.OldBranch + "]"
  325. assert.EqualError(t, err, expectedError)
  326. })
  327. t.Run("bad SHA", func(t *testing.T) {
  328. opts := getUpdateRepoFileOptions(repo)
  329. origSHA := opts.SHA
  330. opts.SHA = "bad_sha"
  331. fileResponse, err := repofiles.CreateOrUpdateRepoFile(repo, doer, opts)
  332. assert.Nil(t, fileResponse)
  333. assert.Error(t, err)
  334. expectedError := "sha does not match [given: " + opts.SHA + ", expected: " + origSHA + "]"
  335. assert.EqualError(t, err, expectedError)
  336. })
  337. t.Run("new branch already exists", func(t *testing.T) {
  338. opts := getUpdateRepoFileOptions(repo)
  339. opts.NewBranch = "develop"
  340. fileResponse, err := repofiles.CreateOrUpdateRepoFile(repo, doer, opts)
  341. assert.Nil(t, fileResponse)
  342. assert.Error(t, err)
  343. expectedError := "branch already exists [name: " + opts.NewBranch + "]"
  344. assert.EqualError(t, err, expectedError)
  345. })
  346. t.Run("treePath is empty:", func(t *testing.T) {
  347. opts := getUpdateRepoFileOptions(repo)
  348. opts.TreePath = ""
  349. fileResponse, err := repofiles.CreateOrUpdateRepoFile(repo, doer, opts)
  350. assert.Nil(t, fileResponse)
  351. assert.Error(t, err)
  352. expectedError := "path contains a malformed path component [path: ]"
  353. assert.EqualError(t, err, expectedError)
  354. })
  355. t.Run("treePath is a git directory:", func(t *testing.T) {
  356. opts := getUpdateRepoFileOptions(repo)
  357. opts.TreePath = ".git"
  358. fileResponse, err := repofiles.CreateOrUpdateRepoFile(repo, doer, opts)
  359. assert.Nil(t, fileResponse)
  360. assert.Error(t, err)
  361. expectedError := "path contains a malformed path component [path: " + opts.TreePath + "]"
  362. assert.EqualError(t, err, expectedError)
  363. })
  364. t.Run("create file that already exists", func(t *testing.T) {
  365. opts := getCreateRepoFileOptions(repo)
  366. opts.TreePath = "README.md" //already exists
  367. fileResponse, err := repofiles.CreateOrUpdateRepoFile(repo, doer, opts)
  368. assert.Nil(t, fileResponse)
  369. assert.Error(t, err)
  370. expectedError := "repository file already exists [path: " + opts.TreePath + "]"
  371. assert.EqualError(t, err, expectedError)
  372. })
  373. })
  374. }