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

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