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

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