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.

api.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. // Copyright 2016 The Gogs Authors. All rights reserved.
  2. // Copyright 2019 The Gitea Authors. All rights reserved.
  3. // SPDX-License-Identifier: MIT
  4. package context
  5. import (
  6. "context"
  7. "fmt"
  8. "net/http"
  9. "net/url"
  10. "strings"
  11. repo_model "code.gitea.io/gitea/models/repo"
  12. "code.gitea.io/gitea/models/unit"
  13. user_model "code.gitea.io/gitea/models/user"
  14. mc "code.gitea.io/gitea/modules/cache"
  15. "code.gitea.io/gitea/modules/git"
  16. "code.gitea.io/gitea/modules/httpcache"
  17. "code.gitea.io/gitea/modules/log"
  18. "code.gitea.io/gitea/modules/setting"
  19. "code.gitea.io/gitea/modules/web"
  20. web_types "code.gitea.io/gitea/modules/web/types"
  21. "gitea.com/go-chi/cache"
  22. )
  23. // APIContext is a specific context for API service
  24. type APIContext struct {
  25. *Base
  26. Cache cache.Cache
  27. Doer *user_model.User // current signed-in user
  28. IsSigned bool
  29. IsBasicAuth bool
  30. ContextUser *user_model.User // the user which is being visited, in most cases it differs from Doer
  31. Repo *Repository
  32. Org *APIOrganization
  33. Package *Package
  34. }
  35. func init() {
  36. web.RegisterResponseStatusProvider[*APIContext](func(req *http.Request) web_types.ResponseStatusProvider {
  37. return req.Context().Value(apiContextKey).(*APIContext)
  38. })
  39. }
  40. // Currently, we have the following common fields in error response:
  41. // * message: the message for end users (it shouldn't be used for error type detection)
  42. // if we need to indicate some errors, we should introduce some new fields like ErrorCode or ErrorType
  43. // * url: the swagger document URL
  44. // APIError is error format response
  45. // swagger:response error
  46. type APIError struct {
  47. Message string `json:"message"`
  48. URL string `json:"url"`
  49. }
  50. // APIValidationError is error format response related to input validation
  51. // swagger:response validationError
  52. type APIValidationError struct {
  53. Message string `json:"message"`
  54. URL string `json:"url"`
  55. }
  56. // APIInvalidTopicsError is error format response to invalid topics
  57. // swagger:response invalidTopicsError
  58. type APIInvalidTopicsError struct {
  59. Message string `json:"message"`
  60. InvalidTopics []string `json:"invalidTopics"`
  61. }
  62. // APIEmpty is an empty response
  63. // swagger:response empty
  64. type APIEmpty struct{}
  65. // APIForbiddenError is a forbidden error response
  66. // swagger:response forbidden
  67. type APIForbiddenError struct {
  68. APIError
  69. }
  70. // APINotFound is a not found empty response
  71. // swagger:response notFound
  72. type APINotFound struct{}
  73. // APIConflict is a conflict empty response
  74. // swagger:response conflict
  75. type APIConflict struct{}
  76. // APIRedirect is a redirect response
  77. // swagger:response redirect
  78. type APIRedirect struct{}
  79. // APIString is a string response
  80. // swagger:response string
  81. type APIString string
  82. // ServerError responds with error message, status is 500
  83. func (ctx *APIContext) ServerError(title string, err error) {
  84. ctx.Error(http.StatusInternalServerError, title, err)
  85. }
  86. // Error responds with an error message to client with given obj as the message.
  87. // If status is 500, also it prints error to log.
  88. func (ctx *APIContext) Error(status int, title string, obj any) {
  89. var message string
  90. if err, ok := obj.(error); ok {
  91. message = err.Error()
  92. } else {
  93. message = fmt.Sprintf("%s", obj)
  94. }
  95. if status == http.StatusInternalServerError {
  96. log.ErrorWithSkip(1, "%s: %s", title, message)
  97. if setting.IsProd && !(ctx.Doer != nil && ctx.Doer.IsAdmin) {
  98. message = ""
  99. }
  100. }
  101. ctx.JSON(status, APIError{
  102. Message: message,
  103. URL: setting.API.SwaggerURL,
  104. })
  105. }
  106. // InternalServerError responds with an error message to the client with the error as a message
  107. // and the file and line of the caller.
  108. func (ctx *APIContext) InternalServerError(err error) {
  109. log.ErrorWithSkip(1, "InternalServerError: %v", err)
  110. var message string
  111. if !setting.IsProd || (ctx.Doer != nil && ctx.Doer.IsAdmin) {
  112. message = err.Error()
  113. }
  114. ctx.JSON(http.StatusInternalServerError, APIError{
  115. Message: message,
  116. URL: setting.API.SwaggerURL,
  117. })
  118. }
  119. type apiContextKeyType struct{}
  120. var apiContextKey = apiContextKeyType{}
  121. // GetAPIContext returns a context for API routes
  122. func GetAPIContext(req *http.Request) *APIContext {
  123. return req.Context().Value(apiContextKey).(*APIContext)
  124. }
  125. func genAPILinks(curURL *url.URL, total, pageSize, curPage int) []string {
  126. page := NewPagination(total, pageSize, curPage, 0)
  127. paginater := page.Paginater
  128. links := make([]string, 0, 4)
  129. if paginater.HasNext() {
  130. u := *curURL
  131. queries := u.Query()
  132. queries.Set("page", fmt.Sprintf("%d", paginater.Next()))
  133. u.RawQuery = queries.Encode()
  134. links = append(links, fmt.Sprintf("<%s%s>; rel=\"next\"", setting.AppURL, u.RequestURI()[1:]))
  135. }
  136. if !paginater.IsLast() {
  137. u := *curURL
  138. queries := u.Query()
  139. queries.Set("page", fmt.Sprintf("%d", paginater.TotalPages()))
  140. u.RawQuery = queries.Encode()
  141. links = append(links, fmt.Sprintf("<%s%s>; rel=\"last\"", setting.AppURL, u.RequestURI()[1:]))
  142. }
  143. if !paginater.IsFirst() {
  144. u := *curURL
  145. queries := u.Query()
  146. queries.Set("page", "1")
  147. u.RawQuery = queries.Encode()
  148. links = append(links, fmt.Sprintf("<%s%s>; rel=\"first\"", setting.AppURL, u.RequestURI()[1:]))
  149. }
  150. if paginater.HasPrevious() {
  151. u := *curURL
  152. queries := u.Query()
  153. queries.Set("page", fmt.Sprintf("%d", paginater.Previous()))
  154. u.RawQuery = queries.Encode()
  155. links = append(links, fmt.Sprintf("<%s%s>; rel=\"prev\"", setting.AppURL, u.RequestURI()[1:]))
  156. }
  157. return links
  158. }
  159. // SetLinkHeader sets pagination link header by given total number and page size.
  160. func (ctx *APIContext) SetLinkHeader(total, pageSize int) {
  161. links := genAPILinks(ctx.Req.URL, total, pageSize, ctx.FormInt("page"))
  162. if len(links) > 0 {
  163. ctx.RespHeader().Set("Link", strings.Join(links, ","))
  164. ctx.AppendAccessControlExposeHeaders("Link")
  165. }
  166. }
  167. // APIContexter returns apicontext as middleware
  168. func APIContexter() func(http.Handler) http.Handler {
  169. return func(next http.Handler) http.Handler {
  170. return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  171. base, baseCleanUp := NewBaseContext(w, req)
  172. ctx := &APIContext{
  173. Base: base,
  174. Cache: mc.GetCache(),
  175. Repo: &Repository{PullRequest: &PullRequest{}},
  176. Org: &APIOrganization{},
  177. }
  178. defer baseCleanUp()
  179. ctx.Base.AppendContextValue(apiContextKey, ctx)
  180. ctx.Base.AppendContextValueFunc(git.RepositoryContextKey, func() any { return ctx.Repo.GitRepo })
  181. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  182. if ctx.Req.Method == "POST" && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
  183. if err := ctx.Req.ParseMultipartForm(setting.Attachment.MaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  184. ctx.InternalServerError(err)
  185. return
  186. }
  187. }
  188. httpcache.SetCacheControlInHeader(ctx.Resp.Header(), 0, "no-transform")
  189. ctx.Resp.Header().Set(`X-Frame-Options`, setting.CORSConfig.XFrameOptions)
  190. next.ServeHTTP(ctx.Resp, ctx.Req)
  191. })
  192. }
  193. }
  194. // NotFound handles 404s for APIContext
  195. // String will replace message, errors will be added to a slice
  196. func (ctx *APIContext) NotFound(objs ...any) {
  197. message := ctx.Tr("error.not_found")
  198. var errors []string
  199. for _, obj := range objs {
  200. // Ignore nil
  201. if obj == nil {
  202. continue
  203. }
  204. if err, ok := obj.(error); ok {
  205. errors = append(errors, err.Error())
  206. } else {
  207. message = obj.(string)
  208. }
  209. }
  210. ctx.JSON(http.StatusNotFound, map[string]any{
  211. "message": message,
  212. "url": setting.API.SwaggerURL,
  213. "errors": errors,
  214. })
  215. }
  216. // ReferencesGitRepo injects the GitRepo into the Context
  217. // you can optional skip the IsEmpty check
  218. func ReferencesGitRepo(allowEmpty ...bool) func(ctx *APIContext) (cancel context.CancelFunc) {
  219. return func(ctx *APIContext) (cancel context.CancelFunc) {
  220. // Empty repository does not have reference information.
  221. if ctx.Repo.Repository.IsEmpty && !(len(allowEmpty) != 0 && allowEmpty[0]) {
  222. return nil
  223. }
  224. // For API calls.
  225. if ctx.Repo.GitRepo == nil {
  226. repoPath := repo_model.RepoPath(ctx.Repo.Owner.Name, ctx.Repo.Repository.Name)
  227. gitRepo, err := git.OpenRepository(ctx, repoPath)
  228. if err != nil {
  229. ctx.Error(http.StatusInternalServerError, "RepoRef Invalid repo "+repoPath, err)
  230. return cancel
  231. }
  232. ctx.Repo.GitRepo = gitRepo
  233. // We opened it, we should close it
  234. return func() {
  235. // If it's been set to nil then assume someone else has closed it.
  236. if ctx.Repo.GitRepo != nil {
  237. _ = ctx.Repo.GitRepo.Close()
  238. }
  239. }
  240. }
  241. return cancel
  242. }
  243. }
  244. // RepoRefForAPI handles repository reference names when the ref name is not explicitly given
  245. func RepoRefForAPI(next http.Handler) http.Handler {
  246. return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  247. ctx := GetAPIContext(req)
  248. if ctx.Repo.GitRepo == nil {
  249. ctx.InternalServerError(fmt.Errorf("no open git repo"))
  250. return
  251. }
  252. if ref := ctx.FormTrim("ref"); len(ref) > 0 {
  253. commit, err := ctx.Repo.GitRepo.GetCommit(ref)
  254. if err != nil {
  255. if git.IsErrNotExist(err) {
  256. ctx.NotFound()
  257. } else {
  258. ctx.Error(http.StatusInternalServerError, "GetCommit", err)
  259. }
  260. return
  261. }
  262. ctx.Repo.Commit = commit
  263. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  264. ctx.Repo.TreePath = ctx.Params("*")
  265. next.ServeHTTP(w, req)
  266. return
  267. }
  268. var err error
  269. refName := getRefName(ctx.Base, ctx.Repo, RepoRefAny)
  270. if ctx.Repo.GitRepo.IsBranchExist(refName) {
  271. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  272. if err != nil {
  273. ctx.InternalServerError(err)
  274. return
  275. }
  276. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  277. } else if ctx.Repo.GitRepo.IsTagExist(refName) {
  278. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName)
  279. if err != nil {
  280. ctx.InternalServerError(err)
  281. return
  282. }
  283. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  284. } else if len(refName) == git.SHAFullLength {
  285. ctx.Repo.CommitID = refName
  286. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
  287. if err != nil {
  288. ctx.NotFound("GetCommit", err)
  289. return
  290. }
  291. } else {
  292. ctx.NotFound(fmt.Errorf("not exist: '%s'", ctx.Params("*")))
  293. return
  294. }
  295. next.ServeHTTP(w, req)
  296. })
  297. }
  298. // HasAPIError returns true if error occurs in form validation.
  299. func (ctx *APIContext) HasAPIError() bool {
  300. hasErr, ok := ctx.Data["HasError"]
  301. if !ok {
  302. return false
  303. }
  304. return hasErr.(bool)
  305. }
  306. // GetErrMsg returns error message in form validation.
  307. func (ctx *APIContext) GetErrMsg() string {
  308. msg, _ := ctx.Data["ErrorMsg"].(string)
  309. if msg == "" {
  310. msg = "invalid form data"
  311. }
  312. return msg
  313. }
  314. // NotFoundOrServerError use error check function to determine if the error
  315. // is about not found. It responds with 404 status code for not found error,
  316. // or error context description for logging purpose of 500 server error.
  317. func (ctx *APIContext) NotFoundOrServerError(logMsg string, errCheck func(error) bool, logErr error) {
  318. if errCheck(logErr) {
  319. ctx.JSON(http.StatusNotFound, nil)
  320. return
  321. }
  322. ctx.Error(http.StatusInternalServerError, "NotFoundOrServerError", logMsg)
  323. }
  324. // IsUserSiteAdmin returns true if current user is a site admin
  325. func (ctx *APIContext) IsUserSiteAdmin() bool {
  326. return ctx.IsSigned && ctx.Doer.IsAdmin
  327. }
  328. // IsUserRepoAdmin returns true if current user is admin in current repo
  329. func (ctx *APIContext) IsUserRepoAdmin() bool {
  330. return ctx.Repo.IsAdmin()
  331. }
  332. // IsUserRepoWriter returns true if current user has write privilege in current repo
  333. func (ctx *APIContext) IsUserRepoWriter(unitTypes []unit.Type) bool {
  334. for _, unitType := range unitTypes {
  335. if ctx.Repo.CanWrite(unitType) {
  336. return true
  337. }
  338. }
  339. return false
  340. }