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