route.go 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. // Copyright 2020 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package lfs
  5. import (
  6. "net/http"
  7. "strings"
  8. "gopkg.in/macaron.v1"
  9. log "unknwon.dev/clog/v2"
  10. "gogs.io/gogs/internal/auth"
  11. "gogs.io/gogs/internal/authutil"
  12. "gogs.io/gogs/internal/conf"
  13. "gogs.io/gogs/internal/context"
  14. "gogs.io/gogs/internal/database"
  15. "gogs.io/gogs/internal/lfsutil"
  16. )
  17. // RegisterRoutes registers LFS routes using given router, and inherits all
  18. // groups and middleware.
  19. func RegisterRoutes(r *macaron.Router) {
  20. verifyAccept := verifyHeader("Accept", contentType, http.StatusNotAcceptable)
  21. verifyContentTypeJSON := verifyHeader("Content-Type", contentType, http.StatusBadRequest)
  22. verifyContentTypeStream := verifyHeader("Content-Type", "application/octet-stream", http.StatusBadRequest)
  23. store := NewStore()
  24. r.Group("", func() {
  25. r.Post("/objects/batch", authorize(store, database.AccessModeRead), verifyAccept, verifyContentTypeJSON, serveBatch(store))
  26. r.Group("/objects/basic", func() {
  27. basic := &basicHandler{
  28. store: store,
  29. defaultStorage: lfsutil.Storage(conf.LFS.Storage),
  30. storagers: map[lfsutil.Storage]lfsutil.Storager{
  31. lfsutil.StorageLocal: &lfsutil.LocalStorage{Root: conf.LFS.ObjectsPath},
  32. },
  33. }
  34. r.Combo("/:oid", verifyOID()).
  35. Get(authorize(store, database.AccessModeRead), basic.serveDownload).
  36. Put(authorize(store, database.AccessModeWrite), verifyContentTypeStream, basic.serveUpload)
  37. r.Post("/verify", authorize(store, database.AccessModeWrite), verifyAccept, verifyContentTypeJSON, basic.serveVerify)
  38. })
  39. }, authenticate(store))
  40. }
  41. // authenticate tries to authenticate user via HTTP Basic Auth. It first tries to authenticate
  42. // as plain username and password, then use username as access token if previous step failed.
  43. func authenticate(store Store) macaron.Handler {
  44. askCredentials := func(w http.ResponseWriter) {
  45. w.Header().Set("Lfs-Authenticate", `Basic realm="Git LFS"`)
  46. responseJSON(w, http.StatusUnauthorized, responseError{
  47. Message: "Credentials needed",
  48. })
  49. }
  50. return func(c *macaron.Context) {
  51. username, password := authutil.DecodeBasic(c.Req.Header)
  52. if username == "" {
  53. askCredentials(c.Resp)
  54. return
  55. }
  56. user, err := store.AuthenticateUser(c.Req.Context(), username, password, -1)
  57. if err != nil && !auth.IsErrBadCredentials(err) {
  58. internalServerError(c.Resp)
  59. log.Error("Failed to authenticate user [name: %s]: %v", username, err)
  60. return
  61. }
  62. if err == nil && store.IsTwoFactorEnabled(c.Req.Context(), user.ID) {
  63. c.Error(http.StatusBadRequest, "Users with 2FA enabled are not allowed to authenticate via username and password.")
  64. return
  65. }
  66. // If username and password combination failed, try again using either username
  67. // or password as the token.
  68. if auth.IsErrBadCredentials(err) {
  69. user, err = context.AuthenticateByToken(store, c.Req.Context(), username)
  70. if err != nil && !database.IsErrAccessTokenNotExist(err) {
  71. internalServerError(c.Resp)
  72. log.Error("Failed to authenticate by access token via username: %v", err)
  73. return
  74. } else if database.IsErrAccessTokenNotExist(err) {
  75. // Try again using the password field as the token.
  76. user, err = context.AuthenticateByToken(store, c.Req.Context(), password)
  77. if err != nil {
  78. if database.IsErrAccessTokenNotExist(err) {
  79. askCredentials(c.Resp)
  80. } else {
  81. c.Status(http.StatusInternalServerError)
  82. log.Error("Failed to authenticate by access token via password: %v", err)
  83. }
  84. return
  85. }
  86. }
  87. }
  88. log.Trace("[LFS] Authenticated user: %s", user.Name)
  89. c.Map(user)
  90. }
  91. }
  92. // authorize tries to authorize the user to the context repository with given access mode.
  93. func authorize(store Store, mode database.AccessMode) macaron.Handler {
  94. return func(c *macaron.Context, actor *database.User) {
  95. username := c.Params(":username")
  96. reponame := strings.TrimSuffix(c.Params(":reponame"), ".git")
  97. owner, err := store.GetUserByUsername(c.Req.Context(), username)
  98. if err != nil {
  99. if database.IsErrUserNotExist(err) {
  100. c.Status(http.StatusNotFound)
  101. } else {
  102. internalServerError(c.Resp)
  103. log.Error("Failed to get user [name: %s]: %v", username, err)
  104. }
  105. return
  106. }
  107. repo, err := store.GetRepositoryByName(c.Req.Context(), owner.ID, reponame)
  108. if err != nil {
  109. if database.IsErrRepoNotExist(err) {
  110. c.Status(http.StatusNotFound)
  111. } else {
  112. internalServerError(c.Resp)
  113. log.Error("Failed to get repository [owner_id: %d, name: %s]: %v", owner.ID, reponame, err)
  114. }
  115. return
  116. }
  117. if !store.AuthorizeRepositoryAccess(c.Req.Context(), actor.ID, repo.ID, mode,
  118. database.AccessModeOptions{
  119. OwnerID: repo.OwnerID,
  120. Private: repo.IsPrivate,
  121. },
  122. ) {
  123. c.Status(http.StatusNotFound)
  124. return
  125. }
  126. log.Trace("[LFS] Authorized user %q to %q", actor.Name, username+"/"+reponame)
  127. c.Map(owner) // NOTE: Override actor
  128. c.Map(repo)
  129. }
  130. }
  131. // verifyHeader checks if the HTTP header contains given value.
  132. // When not, response given "failCode" as status code.
  133. func verifyHeader(key, value string, failCode int) macaron.Handler {
  134. return func(c *macaron.Context) {
  135. vals := c.Req.Header.Values(key)
  136. for _, val := range vals {
  137. if strings.Contains(val, value) {
  138. return
  139. }
  140. }
  141. log.Trace("[LFS] HTTP header %q does not contain value %q", key, value)
  142. c.Status(failCode)
  143. }
  144. }
  145. // verifyOID checks if the ":oid" URL parameter is valid.
  146. func verifyOID() macaron.Handler {
  147. return func(c *macaron.Context) {
  148. oid := lfsutil.OID(c.Params(":oid"))
  149. if !lfsutil.ValidOID(oid) {
  150. responseJSON(c.Resp, http.StatusBadRequest, responseError{
  151. Message: "Invalid oid",
  152. })
  153. return
  154. }
  155. c.Map(oid)
  156. }
  157. }
  158. func internalServerError(w http.ResponseWriter) {
  159. responseJSON(w, http.StatusInternalServerError, responseError{
  160. Message: "Internal server error",
  161. })
  162. }