You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

api.go 15 kB

Add basic integration test infrastructure (and new endpoint `/api/v1/version` for testing it) (#741) * Implement '/api/v1/version' * Cleanup and various fixes * Enhance run.sh * Add install_test.go * Add parameter utils.Config for testing handlers * Re-organize TestVersion.go * Rename functions * handling process cleanup properly * Fix missing function renaming * Cleanup the 'retry' logic * Cleanup * Remove unneeded logging code * Logging messages tweaking * Logging message tweaking * Fix logging messages * Use 'const' instead of hardwired numbers * We don't really need retries anymore * Move constant ServerHttpPort to install_test.go * Restore mistakenly removed constant * Add required comments to make the linter happy. * Fix comments and naming to address linter's complaints * Detect Gitea executale version automatically * Remove tests/run.sh, `go test` suffices. * Make `make build` a prerequisite of `make test` * Do not sleep before trying * Speedup the server pinging loop * Use defined const instead of hardwired numbers * Remove redundant error handling * Use a dedicated target for running code.gitea.io/tests * Do not make 'test' depend on 'build' target * Rectify the excluded package list * Remove redundant 'exit 1' * Change the API to allow passing test.T to test handlers * Make testing.T an embedded field * Use assert.Equal to comparing results * Add copyright info * Parametrized logging output * Use tmpdir instead * Eliminate redundant casting * Remove unneeded variable * Fix last commit * Add missing copyright info * Replace fmt.Fprintf with fmt.Fprint * rename the xtest to integration-test * Use Symlink instead of hard-link for cross-device linking * Turn debugging logs on * Follow the existing framework for APIs * Output logs only if test.v is true * Re-order import statements * Enhance the error message * Fix comment which breaks the linter's rule * Rename 'integration-test' to 'e2e-test' for saving keystrokes * Add comment to avoid possible confusion * Rename tests -> integration-tests Also change back the Makefile to use `make integration-test`. * Use tests/integration for now * tests/integration -> integrations Slightly flattened directory hierarchy is better. * Update Makefile accordingly * Fix a missing change in Makefile * govendor update code.gitea.io/sdk/gitea * Fix comment of struct fields * Fix conditional nonsense * Fix missing updates regarding version string changes * Make variable naming more consistent * Check http status code * Rectify error messages
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509
  1. // Copyright 2015 The Gogs 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 v1 Gitea API.
  5. //
  6. // This provide API interface to communicate with this Gitea instance.
  7. //
  8. // Terms Of Service:
  9. //
  10. // there are no TOS at this moment, use at your own risk we take no responsibility
  11. //
  12. // Schemes: http, https
  13. // BasePath: /api/v1
  14. // Version: 1.1.1
  15. // License: MIT http://opensource.org/licenses/MIT
  16. //
  17. // Consumes:
  18. // - application/json
  19. // - text/plain
  20. //
  21. // Produces:
  22. // - application/json
  23. // - text/html
  24. //
  25. // swagger:meta
  26. package v1
  27. import (
  28. "strings"
  29. "github.com/go-macaron/binding"
  30. "gopkg.in/macaron.v1"
  31. api "code.gitea.io/sdk/gitea"
  32. "code.gitea.io/gitea/models"
  33. "code.gitea.io/gitea/modules/auth"
  34. "code.gitea.io/gitea/modules/context"
  35. "code.gitea.io/gitea/routers/api/v1/admin"
  36. "code.gitea.io/gitea/routers/api/v1/misc"
  37. "code.gitea.io/gitea/routers/api/v1/org"
  38. "code.gitea.io/gitea/routers/api/v1/repo"
  39. "code.gitea.io/gitea/routers/api/v1/user"
  40. )
  41. func repoAssignment() macaron.Handler {
  42. return func(ctx *context.APIContext) {
  43. userName := ctx.Params(":username")
  44. repoName := ctx.Params(":reponame")
  45. var (
  46. owner *models.User
  47. err error
  48. )
  49. // Check if the user is the same as the repository owner.
  50. if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) {
  51. owner = ctx.User
  52. } else {
  53. owner, err = models.GetUserByName(userName)
  54. if err != nil {
  55. if models.IsErrUserNotExist(err) {
  56. ctx.Status(404)
  57. } else {
  58. ctx.Error(500, "GetUserByName", err)
  59. }
  60. return
  61. }
  62. }
  63. ctx.Repo.Owner = owner
  64. // Get repository.
  65. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  66. if err != nil {
  67. if models.IsErrRepoNotExist(err) {
  68. redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName)
  69. if err == nil {
  70. context.RedirectToRepo(ctx.Context, redirectRepoID)
  71. } else if models.IsErrRepoRedirectNotExist(err) {
  72. ctx.Status(404)
  73. } else {
  74. ctx.Error(500, "LookupRepoRedirect", err)
  75. }
  76. } else {
  77. ctx.Error(500, "GetRepositoryByName", err)
  78. }
  79. return
  80. }
  81. repo.Owner = owner
  82. if ctx.IsSigned && ctx.User.IsAdmin {
  83. ctx.Repo.AccessMode = models.AccessModeOwner
  84. } else {
  85. mode, err := models.AccessLevel(ctx.User.ID, repo)
  86. if err != nil {
  87. ctx.Error(500, "AccessLevel", err)
  88. return
  89. }
  90. ctx.Repo.AccessMode = mode
  91. }
  92. if !ctx.Repo.HasAccess() {
  93. ctx.Status(404)
  94. return
  95. }
  96. ctx.Repo.Repository = repo
  97. }
  98. }
  99. // Contexter middleware already checks token for user sign in process.
  100. func reqToken() macaron.Handler {
  101. return func(ctx *context.Context) {
  102. if !ctx.IsSigned {
  103. ctx.Error(401)
  104. return
  105. }
  106. }
  107. }
  108. func reqBasicAuth() macaron.Handler {
  109. return func(ctx *context.Context) {
  110. if !ctx.IsBasicAuth {
  111. ctx.Error(401)
  112. return
  113. }
  114. }
  115. }
  116. func reqAdmin() macaron.Handler {
  117. return func(ctx *context.Context) {
  118. if !ctx.IsSigned || !ctx.User.IsAdmin {
  119. ctx.Error(403)
  120. return
  121. }
  122. }
  123. }
  124. func reqRepoWriter() macaron.Handler {
  125. return func(ctx *context.Context) {
  126. if !ctx.Repo.IsWriter() {
  127. ctx.Error(403)
  128. return
  129. }
  130. }
  131. }
  132. func reqOrgMembership() macaron.Handler {
  133. return func(ctx *context.APIContext) {
  134. var orgID int64
  135. if ctx.Org.Organization != nil {
  136. orgID = ctx.Org.Organization.ID
  137. } else if ctx.Org.Team != nil {
  138. orgID = ctx.Org.Team.OrgID
  139. } else {
  140. ctx.Error(500, "", "reqOrgMembership: unprepared context")
  141. return
  142. }
  143. if !models.IsOrganizationMember(orgID, ctx.User.ID) {
  144. if ctx.Org.Organization != nil {
  145. ctx.Error(403, "", "Must be an organization member")
  146. } else {
  147. ctx.Status(404)
  148. }
  149. return
  150. }
  151. }
  152. }
  153. func reqOrgOwnership() macaron.Handler {
  154. return func(ctx *context.APIContext) {
  155. var orgID int64
  156. if ctx.Org.Organization != nil {
  157. orgID = ctx.Org.Organization.ID
  158. } else if ctx.Org.Team != nil {
  159. orgID = ctx.Org.Team.OrgID
  160. } else {
  161. ctx.Error(500, "", "reqOrgOwnership: unprepared context")
  162. return
  163. }
  164. if !models.IsOrganizationOwner(orgID, ctx.User.ID) {
  165. if ctx.Org.Organization != nil {
  166. ctx.Error(403, "", "Must be an organization owner")
  167. } else {
  168. ctx.Status(404)
  169. }
  170. return
  171. }
  172. }
  173. }
  174. func orgAssignment(args ...bool) macaron.Handler {
  175. var (
  176. assignOrg bool
  177. assignTeam bool
  178. )
  179. if len(args) > 0 {
  180. assignOrg = args[0]
  181. }
  182. if len(args) > 1 {
  183. assignTeam = args[1]
  184. }
  185. return func(ctx *context.APIContext) {
  186. ctx.Org = new(context.APIOrganization)
  187. var err error
  188. if assignOrg {
  189. ctx.Org.Organization, err = models.GetUserByName(ctx.Params(":orgname"))
  190. if err != nil {
  191. if models.IsErrUserNotExist(err) {
  192. ctx.Status(404)
  193. } else {
  194. ctx.Error(500, "GetUserByName", err)
  195. }
  196. return
  197. }
  198. }
  199. if assignTeam {
  200. ctx.Org.Team, err = models.GetTeamByID(ctx.ParamsInt64(":teamid"))
  201. if err != nil {
  202. if models.IsErrUserNotExist(err) {
  203. ctx.Status(404)
  204. } else {
  205. ctx.Error(500, "GetTeamById", err)
  206. }
  207. return
  208. }
  209. }
  210. }
  211. }
  212. func mustEnableIssues(ctx *context.APIContext) {
  213. if !ctx.Repo.Repository.EnableUnit(models.UnitTypeIssues) {
  214. ctx.Status(404)
  215. return
  216. }
  217. }
  218. func mustAllowPulls(ctx *context.Context) {
  219. if !ctx.Repo.Repository.AllowsPulls() {
  220. ctx.Status(404)
  221. return
  222. }
  223. }
  224. // RegisterRoutes registers all v1 APIs routes to web application.
  225. // FIXME: custom form error response
  226. func RegisterRoutes(m *macaron.Macaron) {
  227. bind := binding.Bind
  228. m.Group("/v1", func() {
  229. // Miscellaneous
  230. m.Get("/version", misc.Version)
  231. m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown)
  232. m.Post("/markdown/raw", misc.MarkdownRaw)
  233. // Users
  234. m.Group("/users", func() {
  235. m.Get("/search", user.Search)
  236. m.Group("/:username", func() {
  237. m.Get("", user.GetInfo)
  238. m.Get("/repos", user.ListUserRepos)
  239. m.Group("/tokens", func() {
  240. m.Combo("").Get(user.ListAccessTokens).
  241. Post(bind(api.CreateAccessTokenOption{}), user.CreateAccessToken)
  242. }, reqBasicAuth())
  243. })
  244. })
  245. m.Group("/users", func() {
  246. m.Group("/:username", func() {
  247. m.Get("/keys", user.ListPublicKeys)
  248. m.Get("/gpg_keys", user.ListGPGKeys)
  249. m.Get("/followers", user.ListFollowers)
  250. m.Group("/following", func() {
  251. m.Get("", user.ListFollowing)
  252. m.Get("/:target", user.CheckFollowing)
  253. })
  254. m.Get("/starred", user.GetStarredRepos)
  255. m.Get("/subscriptions", user.GetWatchedRepos)
  256. })
  257. }, reqToken())
  258. m.Group("/user", func() {
  259. m.Get("", user.GetAuthenticatedUser)
  260. m.Combo("/emails").Get(user.ListEmails).
  261. Post(bind(api.CreateEmailOption{}), user.AddEmail).
  262. Delete(bind(api.CreateEmailOption{}), user.DeleteEmail)
  263. m.Get("/followers", user.ListMyFollowers)
  264. m.Group("/following", func() {
  265. m.Get("", user.ListMyFollowing)
  266. m.Combo("/:username").Get(user.CheckMyFollowing).Put(user.Follow).Delete(user.Unfollow)
  267. })
  268. m.Group("/keys", func() {
  269. m.Combo("").Get(user.ListMyPublicKeys).
  270. Post(bind(api.CreateKeyOption{}), user.CreatePublicKey)
  271. m.Combo("/:id").Get(user.GetPublicKey).
  272. Delete(user.DeletePublicKey)
  273. })
  274. m.Group("/gpg_keys", func() {
  275. m.Combo("").Get(user.ListMyGPGKeys).
  276. Post(bind(api.CreateGPGKeyOption{}), user.CreateGPGKey)
  277. m.Combo("/:id").Get(user.GetGPGKey).
  278. Delete(user.DeleteGPGKey)
  279. })
  280. m.Combo("/repos").Get(user.ListMyRepos).
  281. Post(bind(api.CreateRepoOption{}), repo.Create)
  282. m.Group("/starred", func() {
  283. m.Get("", user.GetMyStarredRepos)
  284. m.Group("/:username/:reponame", func() {
  285. m.Get("", user.IsStarring)
  286. m.Put("", user.Star)
  287. m.Delete("", user.Unstar)
  288. }, repoAssignment())
  289. })
  290. m.Get("/subscriptions", user.GetMyWatchedRepos)
  291. }, reqToken())
  292. // Repositories
  293. m.Post("/org/:org/repos", reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepo)
  294. m.Group("/repos", func() {
  295. m.Get("/search", repo.Search)
  296. })
  297. m.Combo("/repositories/:id", reqToken()).Get(repo.GetByID)
  298. m.Group("/repos", func() {
  299. m.Post("/migrate", bind(auth.MigrateRepoForm{}), repo.Migrate)
  300. m.Group("/:username/:reponame", func() {
  301. m.Combo("").Get(repo.Get).Delete(repo.Delete)
  302. m.Group("/hooks", func() {
  303. m.Combo("").Get(repo.ListHooks).
  304. Post(bind(api.CreateHookOption{}), repo.CreateHook)
  305. m.Combo("/:id").Get(repo.GetHook).
  306. Patch(bind(api.EditHookOption{}), repo.EditHook).
  307. Delete(repo.DeleteHook)
  308. }, reqRepoWriter())
  309. m.Group("/collaborators", func() {
  310. m.Get("", repo.ListCollaborators)
  311. m.Combo("/:collaborator").Get(repo.IsCollaborator).
  312. Put(bind(api.AddCollaboratorOption{}), repo.AddCollaborator).
  313. Delete(repo.DeleteCollaborator)
  314. })
  315. m.Get("/raw/*", context.RepoRef(), repo.GetRawFile)
  316. m.Get("/archive/*", repo.GetArchive)
  317. m.Combo("/forks").Get(repo.ListForks).
  318. Post(bind(api.CreateForkOption{}), repo.CreateFork)
  319. m.Group("/branches", func() {
  320. m.Get("", repo.ListBranches)
  321. m.Get("/:branchname", repo.GetBranch)
  322. })
  323. m.Group("/keys", func() {
  324. m.Combo("").Get(repo.ListDeployKeys).
  325. Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey)
  326. m.Combo("/:id").Get(repo.GetDeployKey).
  327. Delete(repo.DeleteDeploykey)
  328. })
  329. m.Group("/issues", func() {
  330. m.Combo("").Get(repo.ListIssues).Post(bind(api.CreateIssueOption{}), repo.CreateIssue)
  331. m.Group("/comments", func() {
  332. m.Get("", repo.ListRepoIssueComments)
  333. m.Combo("/:id").Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueComment)
  334. })
  335. m.Group("/:index", func() {
  336. m.Combo("").Get(repo.GetIssue).Patch(bind(api.EditIssueOption{}), repo.EditIssue)
  337. m.Group("/comments", func() {
  338. m.Combo("").Get(repo.ListIssueComments).Post(bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment)
  339. m.Combo("/:id").Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueComment).
  340. Delete(repo.DeleteIssueComment)
  341. })
  342. m.Group("/labels", func() {
  343. m.Combo("").Get(repo.ListIssueLabels).
  344. Post(bind(api.IssueLabelsOption{}), repo.AddIssueLabels).
  345. Put(bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels).
  346. Delete(repo.ClearIssueLabels)
  347. m.Delete("/:id", repo.DeleteIssueLabel)
  348. })
  349. })
  350. }, mustEnableIssues)
  351. m.Group("/labels", func() {
  352. m.Combo("").Get(repo.ListLabels).
  353. Post(bind(api.CreateLabelOption{}), repo.CreateLabel)
  354. m.Combo("/:id").Get(repo.GetLabel).Patch(bind(api.EditLabelOption{}), repo.EditLabel).
  355. Delete(repo.DeleteLabel)
  356. })
  357. m.Group("/milestones", func() {
  358. m.Combo("").Get(repo.ListMilestones).
  359. Post(reqRepoWriter(), bind(api.CreateMilestoneOption{}), repo.CreateMilestone)
  360. m.Combo("/:id").Get(repo.GetMilestone).
  361. Patch(reqRepoWriter(), bind(api.EditMilestoneOption{}), repo.EditMilestone).
  362. Delete(reqRepoWriter(), repo.DeleteMilestone)
  363. })
  364. m.Get("/stargazers", repo.ListStargazers)
  365. m.Get("/subscribers", repo.ListSubscribers)
  366. m.Group("/subscription", func() {
  367. m.Get("", user.IsWatching)
  368. m.Put("", user.Watch)
  369. m.Delete("", user.Unwatch)
  370. })
  371. m.Group("/releases", func() {
  372. m.Combo("").Get(repo.ListReleases).
  373. Post(bind(api.CreateReleaseOption{}), repo.CreateRelease)
  374. m.Combo("/:id").Get(repo.GetRelease).
  375. Patch(bind(api.EditReleaseOption{}), repo.EditRelease).
  376. Delete(repo.DeleteRelease)
  377. })
  378. m.Post("/mirror-sync", repo.MirrorSync)
  379. m.Get("/editorconfig/:filename", context.RepoRef(), repo.GetEditorconfig)
  380. m.Group("/pulls", func() {
  381. m.Combo("").Get(bind(api.ListPullRequestsOptions{}), repo.ListPullRequests).Post(reqRepoWriter(), bind(api.CreatePullRequestOption{}), repo.CreatePullRequest)
  382. m.Group("/:index", func() {
  383. m.Combo("").Get(repo.GetPullRequest).Patch(reqRepoWriter(), bind(api.EditPullRequestOption{}), repo.EditPullRequest)
  384. m.Combo("/merge").Get(repo.IsPullRequestMerged).Post(reqRepoWriter(), repo.MergePullRequest)
  385. })
  386. }, mustAllowPulls, context.ReferencesGitRepo())
  387. m.Group("/statuses", func() {
  388. m.Combo("/:sha").Get(repo.GetCommitStatuses).Post(reqRepoWriter(), bind(api.CreateStatusOption{}), repo.NewCommitStatus)
  389. })
  390. m.Group("/commits/:ref", func() {
  391. m.Get("/status", repo.GetCombinedCommitStatus)
  392. m.Get("/statuses", repo.GetCommitStatuses)
  393. })
  394. }, repoAssignment())
  395. }, reqToken())
  396. // Organizations
  397. m.Get("/user/orgs", reqToken(), org.ListMyOrgs)
  398. m.Get("/users/:username/orgs", org.ListUserOrgs)
  399. m.Group("/orgs/:orgname", func() {
  400. m.Combo("").Get(org.Get).
  401. Patch(reqToken(), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit)
  402. m.Group("/members", func() {
  403. m.Get("", org.ListMembers)
  404. m.Combo("/:username").Get(org.IsMember).
  405. Delete(reqToken(), reqOrgOwnership(), org.DeleteMember)
  406. })
  407. m.Group("/public_members", func() {
  408. m.Get("", org.ListPublicMembers)
  409. m.Combo("/:username").Get(org.IsPublicMember).
  410. Put(reqToken(), reqOrgMembership(), org.PublicizeMember).
  411. Delete(reqToken(), reqOrgMembership(), org.ConcealMember)
  412. })
  413. m.Combo("/teams", reqToken(), reqOrgMembership()).Get(org.ListTeams).
  414. Post(bind(api.CreateTeamOption{}), org.CreateTeam)
  415. m.Group("/hooks", func() {
  416. m.Combo("").Get(org.ListHooks).
  417. Post(bind(api.CreateHookOption{}), org.CreateHook)
  418. m.Combo("/:id").Get(org.GetHook).
  419. Patch(reqOrgOwnership(), bind(api.EditHookOption{}), org.EditHook).
  420. Delete(reqOrgOwnership(), org.DeleteHook)
  421. }, reqToken(), reqOrgMembership())
  422. }, orgAssignment(true))
  423. m.Group("/teams/:teamid", func() {
  424. m.Combo("").Get(org.GetTeam).
  425. Patch(reqOrgOwnership(), bind(api.EditTeamOption{}), org.EditTeam).
  426. Delete(reqOrgOwnership(), org.DeleteTeam)
  427. m.Group("/members", func() {
  428. m.Get("", org.GetTeamMembers)
  429. m.Combo("/:username").
  430. Put(reqOrgOwnership(), org.AddTeamMember).
  431. Delete(reqOrgOwnership(), org.RemoveTeamMember)
  432. })
  433. m.Group("/repos", func() {
  434. m.Get("", org.GetTeamRepos)
  435. m.Combo("/:orgname/:reponame").
  436. Put(org.AddTeamRepository).
  437. Delete(org.RemoveTeamRepository)
  438. })
  439. }, orgAssignment(false, true), reqToken(), reqOrgMembership())
  440. m.Any("/*", func(ctx *context.Context) {
  441. ctx.Error(404)
  442. })
  443. m.Group("/admin", func() {
  444. m.Group("/users", func() {
  445. m.Post("", bind(api.CreateUserOption{}), admin.CreateUser)
  446. m.Group("/:username", func() {
  447. m.Combo("").Patch(bind(api.EditUserOption{}), admin.EditUser).
  448. Delete(admin.DeleteUser)
  449. m.Post("/keys", bind(api.CreateKeyOption{}), admin.CreatePublicKey)
  450. m.Post("/orgs", bind(api.CreateOrgOption{}), admin.CreateOrg)
  451. m.Post("/repos", bind(api.CreateRepoOption{}), admin.CreateRepo)
  452. })
  453. })
  454. }, reqAdmin())
  455. }, context.APIContexter())
  456. }