gitea源码

api.go 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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. "errors"
  7. "fmt"
  8. "net/http"
  9. "net/url"
  10. "slices"
  11. "strconv"
  12. "strings"
  13. "code.gitea.io/gitea/models/unit"
  14. user_model "code.gitea.io/gitea/models/user"
  15. "code.gitea.io/gitea/modules/cache"
  16. "code.gitea.io/gitea/modules/git"
  17. "code.gitea.io/gitea/modules/gitrepo"
  18. "code.gitea.io/gitea/modules/httpcache"
  19. "code.gitea.io/gitea/modules/log"
  20. "code.gitea.io/gitea/modules/setting"
  21. "code.gitea.io/gitea/modules/util"
  22. "code.gitea.io/gitea/modules/web"
  23. web_types "code.gitea.io/gitea/modules/web/types"
  24. )
  25. // APIContext is a specific context for API service
  26. // ATTENTION: This struct should never be manually constructed in routes/services,
  27. // it has many internal details which should be carefully prepared by the framework.
  28. // If it is abused, it would cause strange bugs like panic/resource-leak.
  29. type APIContext struct {
  30. *Base
  31. Cache cache.StringCache
  32. Doer *user_model.User // current signed-in user
  33. IsSigned bool
  34. IsBasicAuth bool
  35. ContextUser *user_model.User // the user which is being visited, in most cases it differs from Doer
  36. Repo *Repository
  37. Org *APIOrganization
  38. Package *Package
  39. PublicOnly bool // Whether the request is for a public endpoint
  40. }
  41. func init() {
  42. web.RegisterResponseStatusProvider[*APIContext](func(req *http.Request) web_types.ResponseStatusProvider {
  43. return req.Context().Value(apiContextKey).(*APIContext)
  44. })
  45. }
  46. // Currently, we have the following common fields in error response:
  47. // * message: the message for end users (it shouldn't be used for error type detection)
  48. // if we need to indicate some errors, we should introduce some new fields like ErrorCode or ErrorType
  49. // * url: the swagger document URL
  50. // APIError is error format response
  51. // swagger:response error
  52. type APIError struct {
  53. Message string `json:"message"`
  54. URL string `json:"url"`
  55. }
  56. // APIValidationError is error format response related to input validation
  57. // swagger:response validationError
  58. type APIValidationError struct {
  59. Message string `json:"message"`
  60. URL string `json:"url"`
  61. }
  62. // APIInvalidTopicsError is error format response to invalid topics
  63. // swagger:response invalidTopicsError
  64. type APIInvalidTopicsError struct {
  65. Message string `json:"message"`
  66. InvalidTopics []string `json:"invalidTopics"`
  67. }
  68. // APIEmpty is an empty response
  69. // swagger:response empty
  70. type APIEmpty struct{}
  71. // APIForbiddenError is a forbidden error response
  72. // swagger:response forbidden
  73. type APIForbiddenError struct {
  74. APIError
  75. }
  76. // APINotFound is a not found empty response
  77. // swagger:response notFound
  78. type APINotFound struct{}
  79. // APIConflict is a conflict empty response
  80. // swagger:response conflict
  81. type APIConflict struct{}
  82. // APIRedirect is a redirect response
  83. // swagger:response redirect
  84. type APIRedirect struct{}
  85. // APIString is a string response
  86. // swagger:response string
  87. type APIString string
  88. // APIRepoArchivedError is an error that is raised when an archived repo should be modified
  89. // swagger:response repoArchivedError
  90. type APIRepoArchivedError struct {
  91. APIError
  92. }
  93. // APIErrorInternal responds with error message, status is 500
  94. func (ctx *APIContext) APIErrorInternal(err error) {
  95. ctx.apiErrorInternal(1, err)
  96. }
  97. func (ctx *APIContext) apiErrorInternal(skip int, err error) {
  98. log.ErrorWithSkip(skip+1, "InternalServerError: %v", err)
  99. var message string
  100. if !setting.IsProd || (ctx.Doer != nil && ctx.Doer.IsAdmin) {
  101. message = err.Error()
  102. }
  103. ctx.JSON(http.StatusInternalServerError, APIError{
  104. Message: message,
  105. URL: setting.API.SwaggerURL,
  106. })
  107. }
  108. // APIError responds with an error message to client with given obj as the message.
  109. // If status is 500, also it prints error to log.
  110. func (ctx *APIContext) APIError(status int, obj any) {
  111. var message string
  112. if err, ok := obj.(error); ok {
  113. message = err.Error()
  114. } else {
  115. message = fmt.Sprintf("%s", obj)
  116. }
  117. if status == http.StatusInternalServerError {
  118. log.ErrorWithSkip(1, "APIError: %s", message)
  119. if setting.IsProd && !(ctx.Doer != nil && ctx.Doer.IsAdmin) {
  120. message = ""
  121. }
  122. }
  123. ctx.JSON(status, APIError{
  124. Message: message,
  125. URL: setting.API.SwaggerURL,
  126. })
  127. }
  128. type apiContextKeyType struct{}
  129. var apiContextKey = apiContextKeyType{}
  130. // GetAPIContext returns a context for API routes
  131. func GetAPIContext(req *http.Request) *APIContext {
  132. return req.Context().Value(apiContextKey).(*APIContext)
  133. }
  134. func genAPILinks(curURL *url.URL, total, pageSize, curPage int) []string {
  135. page := NewPagination(total, pageSize, curPage, 0)
  136. paginater := page.Paginater
  137. links := make([]string, 0, 4)
  138. if paginater.HasNext() {
  139. u := *curURL
  140. queries := u.Query()
  141. queries.Set("page", strconv.Itoa(paginater.Next()))
  142. u.RawQuery = queries.Encode()
  143. links = append(links, fmt.Sprintf("<%s%s>; rel=\"next\"", setting.AppURL, u.RequestURI()[1:]))
  144. }
  145. if !paginater.IsLast() {
  146. u := *curURL
  147. queries := u.Query()
  148. queries.Set("page", strconv.Itoa(paginater.TotalPages()))
  149. u.RawQuery = queries.Encode()
  150. links = append(links, fmt.Sprintf("<%s%s>; rel=\"last\"", setting.AppURL, u.RequestURI()[1:]))
  151. }
  152. if !paginater.IsFirst() {
  153. u := *curURL
  154. queries := u.Query()
  155. queries.Set("page", "1")
  156. u.RawQuery = queries.Encode()
  157. links = append(links, fmt.Sprintf("<%s%s>; rel=\"first\"", setting.AppURL, u.RequestURI()[1:]))
  158. }
  159. if paginater.HasPrevious() {
  160. u := *curURL
  161. queries := u.Query()
  162. queries.Set("page", strconv.Itoa(paginater.Previous()))
  163. u.RawQuery = queries.Encode()
  164. links = append(links, fmt.Sprintf("<%s%s>; rel=\"prev\"", setting.AppURL, u.RequestURI()[1:]))
  165. }
  166. return links
  167. }
  168. // SetLinkHeader sets pagination link header by given total number and page size.
  169. func (ctx *APIContext) SetLinkHeader(total, pageSize int) {
  170. links := genAPILinks(ctx.Req.URL, total, pageSize, ctx.FormInt("page"))
  171. if len(links) > 0 {
  172. ctx.RespHeader().Set("Link", strings.Join(links, ","))
  173. ctx.AppendAccessControlExposeHeaders("Link")
  174. }
  175. }
  176. // APIContexter returns APIContext middleware
  177. func APIContexter() func(http.Handler) http.Handler {
  178. return func(next http.Handler) http.Handler {
  179. return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  180. base := NewBaseContext(w, req)
  181. ctx := &APIContext{
  182. Base: base,
  183. Cache: cache.GetCache(),
  184. Repo: &Repository{PullRequest: &PullRequest{}},
  185. Org: &APIOrganization{},
  186. }
  187. ctx.SetContextValue(apiContextKey, ctx)
  188. // If request sends files, parse them here otherwise the Query() can't be parsed and the CsrfToken will be invalid.
  189. if ctx.Req.Method == http.MethodPost && strings.Contains(ctx.Req.Header.Get("Content-Type"), "multipart/form-data") {
  190. if err := ctx.Req.ParseMultipartForm(setting.Attachment.MaxSize << 20); err != nil && !strings.Contains(err.Error(), "EOF") { // 32MB max size
  191. ctx.APIErrorInternal(err)
  192. return
  193. }
  194. }
  195. httpcache.SetCacheControlInHeader(ctx.Resp.Header(), &httpcache.CacheControlOptions{NoTransform: true})
  196. ctx.Resp.Header().Set(`X-Frame-Options`, setting.CORSConfig.XFrameOptions)
  197. next.ServeHTTP(ctx.Resp, ctx.Req)
  198. })
  199. }
  200. }
  201. // APIErrorNotFound handles 404s for APIContext
  202. // String will replace message, errors will be added to a slice
  203. func (ctx *APIContext) APIErrorNotFound(objs ...any) {
  204. var message string
  205. var errs []string
  206. for _, obj := range objs {
  207. // Ignore nil
  208. if obj == nil {
  209. continue
  210. }
  211. if err, ok := obj.(error); ok {
  212. errs = append(errs, err.Error())
  213. } else {
  214. message = obj.(string)
  215. }
  216. }
  217. ctx.JSON(http.StatusNotFound, map[string]any{
  218. "message": util.IfZero(message, "not found"), // do not use locale in API
  219. "url": setting.API.SwaggerURL,
  220. "errors": errs,
  221. })
  222. }
  223. // ReferencesGitRepo injects the GitRepo into the Context
  224. // you can optional skip the IsEmpty check
  225. func ReferencesGitRepo(allowEmpty ...bool) func(ctx *APIContext) {
  226. return func(ctx *APIContext) {
  227. // Empty repository does not have reference information.
  228. if ctx.Repo.Repository.IsEmpty && !(len(allowEmpty) != 0 && allowEmpty[0]) {
  229. return
  230. }
  231. // For API calls.
  232. if ctx.Repo.GitRepo == nil {
  233. var err error
  234. ctx.Repo.GitRepo, err = gitrepo.RepositoryFromRequestContextOrOpen(ctx, ctx.Repo.Repository)
  235. if err != nil {
  236. ctx.APIErrorInternal(err)
  237. return
  238. }
  239. }
  240. }
  241. }
  242. // RepoRefForAPI handles repository reference names when the ref name is not explicitly given
  243. func RepoRefForAPI(next http.Handler) http.Handler {
  244. return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
  245. ctx := GetAPIContext(req)
  246. if ctx.Repo.Repository.IsEmpty {
  247. ctx.APIErrorNotFound("repository is empty")
  248. return
  249. }
  250. if ctx.Repo.GitRepo == nil {
  251. panic("no GitRepo, forgot to call the middleware?") // it is a programming error
  252. }
  253. refName, refType, _ := getRefNameLegacy(ctx.Base, ctx.Repo, ctx.PathParam("*"), ctx.FormTrim("ref"))
  254. var err error
  255. switch refType {
  256. case git.RefTypeBranch:
  257. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetBranchCommit(refName)
  258. case git.RefTypeTag:
  259. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetTagCommit(refName)
  260. case git.RefTypeCommit:
  261. ctx.Repo.Commit, err = ctx.Repo.GitRepo.GetCommit(refName)
  262. }
  263. if ctx.Repo.Commit == nil || errors.Is(err, util.ErrNotExist) {
  264. ctx.APIErrorNotFound("unable to find a git ref")
  265. return
  266. } else if err != nil {
  267. ctx.APIErrorInternal(err)
  268. return
  269. }
  270. ctx.Repo.CommitID = ctx.Repo.Commit.ID.String()
  271. next.ServeHTTP(w, req)
  272. })
  273. }
  274. // HasAPIError returns true if error occurs in form validation.
  275. func (ctx *APIContext) HasAPIError() bool {
  276. hasErr, ok := ctx.Data["HasError"]
  277. if !ok {
  278. return false
  279. }
  280. return hasErr.(bool)
  281. }
  282. // GetErrMsg returns error message in form validation.
  283. func (ctx *APIContext) GetErrMsg() string {
  284. msg, _ := ctx.Data["ErrorMsg"].(string)
  285. if msg == "" {
  286. msg = "invalid form data"
  287. }
  288. return msg
  289. }
  290. // NotFoundOrServerError use error check function to determine if the error
  291. // is about not found. It responds with 404 status code for not found error,
  292. // or error context description for logging purpose of 500 server error.
  293. func (ctx *APIContext) NotFoundOrServerError(err error) {
  294. if errors.Is(err, util.ErrNotExist) {
  295. ctx.JSON(http.StatusNotFound, nil)
  296. return
  297. }
  298. ctx.APIErrorInternal(err)
  299. }
  300. // IsUserSiteAdmin returns true if current user is a site admin
  301. func (ctx *APIContext) IsUserSiteAdmin() bool {
  302. return ctx.IsSigned && ctx.Doer.IsAdmin
  303. }
  304. // IsUserRepoAdmin returns true if current user is admin in current repo
  305. func (ctx *APIContext) IsUserRepoAdmin() bool {
  306. return ctx.Repo.IsAdmin()
  307. }
  308. // IsUserRepoWriter returns true if current user has "write" privilege in current repo
  309. func (ctx *APIContext) IsUserRepoWriter(unitTypes []unit.Type) bool {
  310. return slices.ContainsFunc(unitTypes, ctx.Repo.CanWrite)
  311. }