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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  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. "code.gitea.io/gitea/routers/api/v1/utils"
  41. )
  42. func repoAssignment() macaron.Handler {
  43. return func(ctx *context.APIContext) {
  44. userName := ctx.Params(":username")
  45. repoName := ctx.Params(":reponame")
  46. var (
  47. owner *models.User
  48. err error
  49. )
  50. // Check if the user is the same as the repository owner.
  51. if ctx.IsSigned && ctx.User.LowerName == strings.ToLower(userName) {
  52. owner = ctx.User
  53. } else {
  54. owner, err = models.GetUserByName(userName)
  55. if err != nil {
  56. if models.IsErrUserNotExist(err) {
  57. ctx.Status(404)
  58. } else {
  59. ctx.Error(500, "GetUserByName", err)
  60. }
  61. return
  62. }
  63. }
  64. ctx.Repo.Owner = owner
  65. // Get repository.
  66. repo, err := models.GetRepositoryByName(owner.ID, repoName)
  67. if err != nil {
  68. if models.IsErrRepoNotExist(err) {
  69. redirectRepoID, err := models.LookupRepoRedirect(owner.ID, repoName)
  70. if err == nil {
  71. context.RedirectToRepo(ctx.Context, redirectRepoID)
  72. } else if models.IsErrRepoRedirectNotExist(err) {
  73. ctx.Status(404)
  74. } else {
  75. ctx.Error(500, "LookupRepoRedirect", err)
  76. }
  77. } else {
  78. ctx.Error(500, "GetRepositoryByName", err)
  79. }
  80. return
  81. }
  82. repo.Owner = owner
  83. if ctx.IsSigned && ctx.User.IsAdmin {
  84. ctx.Repo.AccessMode = models.AccessModeOwner
  85. } else {
  86. mode, err := models.AccessLevel(utils.UserID(ctx), repo)
  87. if err != nil {
  88. ctx.Error(500, "AccessLevel", err)
  89. return
  90. }
  91. ctx.Repo.AccessMode = mode
  92. }
  93. if !ctx.Repo.HasAccess() {
  94. ctx.Status(404)
  95. return
  96. }
  97. ctx.Repo.Repository = repo
  98. }
  99. }
  100. // Contexter middleware already checks token for user sign in process.
  101. func reqToken() macaron.Handler {
  102. return func(ctx *context.Context) {
  103. if !ctx.IsSigned {
  104. ctx.Error(401)
  105. return
  106. }
  107. }
  108. }
  109. func reqBasicAuth() macaron.Handler {
  110. return func(ctx *context.Context) {
  111. if !ctx.IsBasicAuth {
  112. ctx.Error(401)
  113. return
  114. }
  115. }
  116. }
  117. func reqAdmin() macaron.Handler {
  118. return func(ctx *context.Context) {
  119. if !ctx.IsSigned || !ctx.User.IsAdmin {
  120. ctx.Error(403)
  121. return
  122. }
  123. }
  124. }
  125. func reqRepoWriter() macaron.Handler {
  126. return func(ctx *context.Context) {
  127. if !ctx.Repo.IsWriter() {
  128. ctx.Error(403)
  129. return
  130. }
  131. }
  132. }
  133. func reqOrgMembership() macaron.Handler {
  134. return func(ctx *context.APIContext) {
  135. var orgID int64
  136. if ctx.Org.Organization != nil {
  137. orgID = ctx.Org.Organization.ID
  138. } else if ctx.Org.Team != nil {
  139. orgID = ctx.Org.Team.OrgID
  140. } else {
  141. ctx.Error(500, "", "reqOrgMembership: unprepared context")
  142. return
  143. }
  144. if !models.IsOrganizationMember(orgID, ctx.User.ID) {
  145. if ctx.Org.Organization != nil {
  146. ctx.Error(403, "", "Must be an organization member")
  147. } else {
  148. ctx.Status(404)
  149. }
  150. return
  151. }
  152. }
  153. }
  154. func reqOrgOwnership() macaron.Handler {
  155. return func(ctx *context.APIContext) {
  156. var orgID int64
  157. if ctx.Org.Organization != nil {
  158. orgID = ctx.Org.Organization.ID
  159. } else if ctx.Org.Team != nil {
  160. orgID = ctx.Org.Team.OrgID
  161. } else {
  162. ctx.Error(500, "", "reqOrgOwnership: unprepared context")
  163. return
  164. }
  165. if !models.IsOrganizationOwner(orgID, ctx.User.ID) {
  166. if ctx.Org.Organization != nil {
  167. ctx.Error(403, "", "Must be an organization owner")
  168. } else {
  169. ctx.Status(404)
  170. }
  171. return
  172. }
  173. }
  174. }
  175. func orgAssignment(args ...bool) macaron.Handler {
  176. var (
  177. assignOrg bool
  178. assignTeam bool
  179. )
  180. if len(args) > 0 {
  181. assignOrg = args[0]
  182. }
  183. if len(args) > 1 {
  184. assignTeam = args[1]
  185. }
  186. return func(ctx *context.APIContext) {
  187. ctx.Org = new(context.APIOrganization)
  188. var err error
  189. if assignOrg {
  190. ctx.Org.Organization, err = models.GetOrgByName(ctx.Params(":orgname"))
  191. if err != nil {
  192. if models.IsErrOrgNotExist(err) {
  193. ctx.Status(404)
  194. } else {
  195. ctx.Error(500, "GetOrgByName", err)
  196. }
  197. return
  198. }
  199. }
  200. if assignTeam {
  201. ctx.Org.Team, err = models.GetTeamByID(ctx.ParamsInt64(":teamid"))
  202. if err != nil {
  203. if models.IsErrUserNotExist(err) {
  204. ctx.Status(404)
  205. } else {
  206. ctx.Error(500, "GetTeamById", err)
  207. }
  208. return
  209. }
  210. }
  211. }
  212. }
  213. func mustEnableIssues(ctx *context.APIContext) {
  214. if !ctx.Repo.Repository.EnableUnit(models.UnitTypeIssues) {
  215. ctx.Status(404)
  216. return
  217. }
  218. }
  219. func mustAllowPulls(ctx *context.Context) {
  220. if !ctx.Repo.Repository.AllowsPulls() {
  221. ctx.Status(404)
  222. return
  223. }
  224. }
  225. // RegisterRoutes registers all v1 APIs routes to web application.
  226. // FIXME: custom form error response
  227. func RegisterRoutes(m *macaron.Macaron) {
  228. bind := binding.Bind
  229. m.Group("/v1", func() {
  230. // Miscellaneous
  231. m.Get("/version", misc.Version)
  232. m.Post("/markdown", bind(api.MarkdownOption{}), misc.Markdown)
  233. m.Post("/markdown/raw", misc.MarkdownRaw)
  234. // Users
  235. m.Group("/users", func() {
  236. m.Get("/search", user.Search)
  237. m.Group("/:username", func() {
  238. m.Get("", user.GetInfo)
  239. m.Get("/repos", user.ListUserRepos)
  240. m.Group("/tokens", func() {
  241. m.Combo("").Get(user.ListAccessTokens).
  242. Post(bind(api.CreateAccessTokenOption{}), user.CreateAccessToken)
  243. }, reqBasicAuth())
  244. })
  245. })
  246. m.Group("/users", func() {
  247. m.Group("/:username", func() {
  248. m.Get("/keys", user.ListPublicKeys)
  249. m.Get("/gpg_keys", user.ListGPGKeys)
  250. m.Get("/followers", user.ListFollowers)
  251. m.Group("/following", func() {
  252. m.Get("", user.ListFollowing)
  253. m.Get("/:target", user.CheckFollowing)
  254. })
  255. m.Get("/starred", user.GetStarredRepos)
  256. m.Get("/subscriptions", user.GetWatchedRepos)
  257. })
  258. }, reqToken())
  259. m.Group("/user", func() {
  260. m.Get("", user.GetAuthenticatedUser)
  261. m.Combo("/emails").Get(user.ListEmails).
  262. Post(bind(api.CreateEmailOption{}), user.AddEmail).
  263. Delete(bind(api.CreateEmailOption{}), user.DeleteEmail)
  264. m.Get("/followers", user.ListMyFollowers)
  265. m.Group("/following", func() {
  266. m.Get("", user.ListMyFollowing)
  267. m.Combo("/:username").Get(user.CheckMyFollowing).Put(user.Follow).Delete(user.Unfollow)
  268. })
  269. m.Group("/keys", func() {
  270. m.Combo("").Get(user.ListMyPublicKeys).
  271. Post(bind(api.CreateKeyOption{}), user.CreatePublicKey)
  272. m.Combo("/:id").Get(user.GetPublicKey).
  273. Delete(user.DeletePublicKey)
  274. })
  275. m.Group("/gpg_keys", func() {
  276. m.Combo("").Get(user.ListMyGPGKeys).
  277. Post(bind(api.CreateGPGKeyOption{}), user.CreateGPGKey)
  278. m.Combo("/:id").Get(user.GetGPGKey).
  279. Delete(user.DeleteGPGKey)
  280. })
  281. m.Combo("/repos").Get(user.ListMyRepos).
  282. Post(bind(api.CreateRepoOption{}), repo.Create)
  283. m.Group("/starred", func() {
  284. m.Get("", user.GetMyStarredRepos)
  285. m.Group("/:username/:reponame", func() {
  286. m.Get("", user.IsStarring)
  287. m.Put("", user.Star)
  288. m.Delete("", user.Unstar)
  289. }, repoAssignment())
  290. })
  291. m.Get("/subscriptions", user.GetMyWatchedRepos)
  292. }, reqToken())
  293. // Repositories
  294. m.Post("/org/:org/repos", reqToken(), bind(api.CreateRepoOption{}), repo.CreateOrgRepo)
  295. m.Group("/repos", func() {
  296. m.Get("/search", repo.Search)
  297. })
  298. m.Combo("/repositories/:id", reqToken()).Get(repo.GetByID)
  299. m.Group("/repos", func() {
  300. m.Post("/migrate", reqToken(), bind(auth.MigrateRepoForm{}), repo.Migrate)
  301. m.Group("/:username/:reponame", func() {
  302. m.Combo("").Get(repo.Get).Delete(reqToken(), repo.Delete)
  303. m.Group("/hooks", func() {
  304. m.Combo("").Get(repo.ListHooks).
  305. Post(bind(api.CreateHookOption{}), repo.CreateHook)
  306. m.Combo("/:id").Get(repo.GetHook).
  307. Patch(bind(api.EditHookOption{}), repo.EditHook).
  308. Delete(repo.DeleteHook)
  309. }, reqToken(), reqRepoWriter())
  310. m.Group("/collaborators", func() {
  311. m.Get("", repo.ListCollaborators)
  312. m.Combo("/:collaborator").Get(repo.IsCollaborator).
  313. Put(bind(api.AddCollaboratorOption{}), repo.AddCollaborator).
  314. Delete(repo.DeleteCollaborator)
  315. }, reqToken())
  316. m.Get("/raw/*", context.RepoRef(), repo.GetRawFile)
  317. m.Get("/archive/*", repo.GetArchive)
  318. m.Combo("/forks").Get(repo.ListForks).
  319. Post(reqToken(), bind(api.CreateForkOption{}), repo.CreateFork)
  320. m.Group("/branches", func() {
  321. m.Get("", repo.ListBranches)
  322. m.Get("/*", context.RepoRef(), repo.GetBranch)
  323. })
  324. m.Group("/keys", func() {
  325. m.Combo("").Get(repo.ListDeployKeys).
  326. Post(bind(api.CreateKeyOption{}), repo.CreateDeployKey)
  327. m.Combo("/:id").Get(repo.GetDeployKey).
  328. Delete(repo.DeleteDeploykey)
  329. }, reqToken())
  330. m.Group("/issues", func() {
  331. m.Combo("").Get(repo.ListIssues).
  332. Post(reqToken(), bind(api.CreateIssueOption{}), repo.CreateIssue)
  333. m.Group("/comments", func() {
  334. m.Get("", repo.ListRepoIssueComments)
  335. m.Combo("/:id", reqToken()).
  336. Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueComment)
  337. })
  338. m.Group("/:index", func() {
  339. m.Combo("").Get(repo.GetIssue).
  340. Patch(reqToken(), bind(api.EditIssueOption{}), repo.EditIssue)
  341. m.Group("/comments", func() {
  342. m.Combo("").Get(repo.ListIssueComments).
  343. Post(reqToken(), bind(api.CreateIssueCommentOption{}), repo.CreateIssueComment)
  344. m.Combo("/:id", reqToken()).Patch(bind(api.EditIssueCommentOption{}), repo.EditIssueComment).
  345. Delete(repo.DeleteIssueComment)
  346. })
  347. m.Group("/labels", func() {
  348. m.Combo("").Get(repo.ListIssueLabels).
  349. Post(reqToken(), bind(api.IssueLabelsOption{}), repo.AddIssueLabels).
  350. Put(reqToken(), bind(api.IssueLabelsOption{}), repo.ReplaceIssueLabels).
  351. Delete(reqToken(), repo.ClearIssueLabels)
  352. m.Delete("/:id", reqToken(), repo.DeleteIssueLabel)
  353. })
  354. })
  355. }, mustEnableIssues)
  356. m.Group("/labels", func() {
  357. m.Combo("").Get(repo.ListLabels).
  358. Post(reqToken(), bind(api.CreateLabelOption{}), repo.CreateLabel)
  359. m.Combo("/:id").Get(repo.GetLabel).
  360. Patch(reqToken(), bind(api.EditLabelOption{}), repo.EditLabel).
  361. Delete(reqToken(), repo.DeleteLabel)
  362. })
  363. m.Group("/milestones", func() {
  364. m.Combo("").Get(repo.ListMilestones).
  365. Post(reqToken(), reqRepoWriter(), bind(api.CreateMilestoneOption{}), repo.CreateMilestone)
  366. m.Combo("/:id").Get(repo.GetMilestone).
  367. Patch(reqToken(), reqRepoWriter(), bind(api.EditMilestoneOption{}), repo.EditMilestone).
  368. Delete(reqToken(), reqRepoWriter(), repo.DeleteMilestone)
  369. })
  370. m.Get("/stargazers", repo.ListStargazers)
  371. m.Get("/subscribers", repo.ListSubscribers)
  372. m.Group("/subscription", func() {
  373. m.Get("", user.IsWatching)
  374. m.Put("", reqToken(), user.Watch)
  375. m.Delete("", reqToken(), user.Unwatch)
  376. })
  377. m.Group("/releases", func() {
  378. m.Combo("").Get(repo.ListReleases).
  379. Post(reqToken(), bind(api.CreateReleaseOption{}), repo.CreateRelease)
  380. m.Combo("/:id").Get(repo.GetRelease).
  381. Patch(reqToken(), bind(api.EditReleaseOption{}), repo.EditRelease).
  382. Delete(reqToken(), repo.DeleteRelease)
  383. })
  384. m.Post("/mirror-sync", reqToken(), repo.MirrorSync)
  385. m.Get("/editorconfig/:filename", context.RepoRef(), repo.GetEditorconfig)
  386. m.Group("/pulls", func() {
  387. m.Combo("").Get(bind(api.ListPullRequestsOptions{}), repo.ListPullRequests).
  388. Post(reqToken(), reqRepoWriter(), bind(api.CreatePullRequestOption{}), repo.CreatePullRequest)
  389. m.Group("/:index", func() {
  390. m.Combo("").Get(repo.GetPullRequest).
  391. Patch(reqToken(), reqRepoWriter(), bind(api.EditPullRequestOption{}), repo.EditPullRequest)
  392. m.Combo("/merge").Get(repo.IsPullRequestMerged).
  393. Post(reqToken(), reqRepoWriter(), repo.MergePullRequest)
  394. })
  395. }, mustAllowPulls, context.ReferencesGitRepo())
  396. m.Group("/statuses", func() {
  397. m.Combo("/:sha").Get(repo.GetCommitStatuses).
  398. Post(reqToken(), reqRepoWriter(), bind(api.CreateStatusOption{}), repo.NewCommitStatus)
  399. })
  400. m.Group("/commits/:ref", func() {
  401. m.Get("/status", repo.GetCombinedCommitStatus)
  402. m.Get("/statuses", repo.GetCommitStatuses)
  403. })
  404. }, repoAssignment())
  405. })
  406. // Organizations
  407. m.Get("/user/orgs", reqToken(), org.ListMyOrgs)
  408. m.Get("/users/:username/orgs", org.ListUserOrgs)
  409. m.Group("/orgs/:orgname", func() {
  410. m.Combo("").Get(org.Get).
  411. Patch(reqToken(), reqOrgOwnership(), bind(api.EditOrgOption{}), org.Edit)
  412. m.Group("/members", func() {
  413. m.Get("", org.ListMembers)
  414. m.Combo("/:username").Get(org.IsMember).
  415. Delete(reqToken(), reqOrgOwnership(), org.DeleteMember)
  416. })
  417. m.Group("/public_members", func() {
  418. m.Get("", org.ListPublicMembers)
  419. m.Combo("/:username").Get(org.IsPublicMember).
  420. Put(reqToken(), reqOrgMembership(), org.PublicizeMember).
  421. Delete(reqToken(), reqOrgMembership(), org.ConcealMember)
  422. })
  423. m.Combo("/teams", reqToken(), reqOrgMembership()).Get(org.ListTeams).
  424. Post(bind(api.CreateTeamOption{}), org.CreateTeam)
  425. m.Group("/hooks", func() {
  426. m.Combo("").Get(org.ListHooks).
  427. Post(bind(api.CreateHookOption{}), org.CreateHook)
  428. m.Combo("/:id").Get(org.GetHook).
  429. Patch(reqOrgOwnership(), bind(api.EditHookOption{}), org.EditHook).
  430. Delete(reqOrgOwnership(), org.DeleteHook)
  431. }, reqToken(), reqOrgMembership())
  432. }, orgAssignment(true))
  433. m.Group("/teams/:teamid", func() {
  434. m.Combo("").Get(org.GetTeam).
  435. Patch(reqOrgOwnership(), bind(api.EditTeamOption{}), org.EditTeam).
  436. Delete(reqOrgOwnership(), org.DeleteTeam)
  437. m.Group("/members", func() {
  438. m.Get("", org.GetTeamMembers)
  439. m.Combo("/:username").
  440. Put(reqOrgOwnership(), org.AddTeamMember).
  441. Delete(reqOrgOwnership(), org.RemoveTeamMember)
  442. })
  443. m.Group("/repos", func() {
  444. m.Get("", org.GetTeamRepos)
  445. m.Combo("/:orgname/:reponame").
  446. Put(org.AddTeamRepository).
  447. Delete(org.RemoveTeamRepository)
  448. })
  449. }, orgAssignment(false, true), reqToken(), reqOrgMembership())
  450. m.Any("/*", func(ctx *context.Context) {
  451. ctx.Error(404)
  452. })
  453. m.Group("/admin", func() {
  454. m.Group("/users", func() {
  455. m.Post("", bind(api.CreateUserOption{}), admin.CreateUser)
  456. m.Group("/:username", func() {
  457. m.Combo("").Patch(bind(api.EditUserOption{}), admin.EditUser).
  458. Delete(admin.DeleteUser)
  459. m.Post("/keys", bind(api.CreateKeyOption{}), admin.CreatePublicKey)
  460. m.Post("/orgs", bind(api.CreateOrgOption{}), admin.CreateOrg)
  461. m.Post("/repos", bind(api.CreateRepoOption{}), admin.CreateRepo)
  462. })
  463. })
  464. }, reqAdmin())
  465. }, context.APIContexter())
  466. }