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 12KB

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