route.go 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  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(database.AccessModeRead), verifyAccept, verifyContentTypeJSON, serveBatch)
  26. r.Group("/objects/basic", func() {
  27. basic := &basicHandler{
  28. defaultStorage: lfsutil.Storage(conf.LFS.Storage),
  29. storagers: map[lfsutil.Storage]lfsutil.Storager{
  30. lfsutil.StorageLocal: &lfsutil.LocalStorage{Root: conf.LFS.ObjectsPath},
  31. },
  32. }
  33. r.Combo("/:oid", verifyOID()).
  34. Get(authorize(database.AccessModeRead), basic.serveDownload).
  35. Put(authorize(database.AccessModeWrite), verifyContentTypeStream, basic.serveUpload)
  36. r.Post("/verify", authorize(database.AccessModeWrite), verifyAccept, verifyContentTypeJSON, basic.serveVerify)
  37. })
  38. }, authenticate(store))
  39. }
  40. // authenticate tries to authenticate user via HTTP Basic Auth. It first tries to authenticate
  41. // as plain username and password, then use username as access token if previous step failed.
  42. func authenticate(store Store) macaron.Handler {
  43. askCredentials := func(w http.ResponseWriter) {
  44. w.Header().Set("Lfs-Authenticate", `Basic realm="Git LFS"`)
  45. responseJSON(w, http.StatusUnauthorized, responseError{
  46. Message: "Credentials needed",
  47. })
  48. }
  49. return func(c *macaron.Context) {
  50. username, password := authutil.DecodeBasic(c.Req.Header)
  51. if username == "" {
  52. askCredentials(c.Resp)
  53. return
  54. }
  55. user, err := database.Users.Authenticate(c.Req.Context(), username, password, -1)
  56. if err != nil && !auth.IsErrBadCredentials(err) {
  57. internalServerError(c.Resp)
  58. log.Error("Failed to authenticate user [name: %s]: %v", username, err)
  59. return
  60. }
  61. if err == nil && database.TwoFactors.IsEnabled(c.Req.Context(), user.ID) {
  62. c.Error(http.StatusBadRequest, "Users with 2FA enabled are not allowed to authenticate via username and password.")
  63. return
  64. }
  65. // If username and password combination failed, try again using either username
  66. // or password as the token.
  67. if auth.IsErrBadCredentials(err) {
  68. user, err = context.AuthenticateByToken(store, c.Req.Context(), username)
  69. if err != nil && !database.IsErrAccessTokenNotExist(err) {
  70. internalServerError(c.Resp)
  71. log.Error("Failed to authenticate by access token via username: %v", err)
  72. return
  73. } else if database.IsErrAccessTokenNotExist(err) {
  74. // Try again using the password field as the token.
  75. user, err = context.AuthenticateByToken(store, c.Req.Context(), password)
  76. if err != nil {
  77. if database.IsErrAccessTokenNotExist(err) {
  78. askCredentials(c.Resp)
  79. } else {
  80. c.Status(http.StatusInternalServerError)
  81. log.Error("Failed to authenticate by access token via password: %v", err)
  82. }
  83. return
  84. }
  85. }
  86. }
  87. log.Trace("[LFS] Authenticated user: %s", user.Name)
  88. c.Map(user)
  89. }
  90. }
  91. // authorize tries to authorize the user to the context repository with given access mode.
  92. func authorize(mode database.AccessMode) macaron.Handler {
  93. return func(c *macaron.Context, actor *database.User) {
  94. username := c.Params(":username")
  95. reponame := strings.TrimSuffix(c.Params(":reponame"), ".git")
  96. owner, err := database.Users.GetByUsername(c.Req.Context(), username)
  97. if err != nil {
  98. if database.IsErrUserNotExist(err) {
  99. c.Status(http.StatusNotFound)
  100. } else {
  101. internalServerError(c.Resp)
  102. log.Error("Failed to get user [name: %s]: %v", username, err)
  103. }
  104. return
  105. }
  106. repo, err := database.Repos.GetByName(c.Req.Context(), owner.ID, reponame)
  107. if err != nil {
  108. if database.IsErrRepoNotExist(err) {
  109. c.Status(http.StatusNotFound)
  110. } else {
  111. internalServerError(c.Resp)
  112. log.Error("Failed to get repository [owner_id: %d, name: %s]: %v", owner.ID, reponame, err)
  113. }
  114. return
  115. }
  116. if !database.Perms.Authorize(c.Req.Context(), actor.ID, repo.ID, mode,
  117. database.AccessModeOptions{
  118. OwnerID: repo.OwnerID,
  119. Private: repo.IsPrivate,
  120. },
  121. ) {
  122. c.Status(http.StatusNotFound)
  123. return
  124. }
  125. log.Trace("[LFS] Authorized user %q to %q", actor.Name, username+"/"+reponame)
  126. c.Map(owner) // NOTE: Override actor
  127. c.Map(repo)
  128. }
  129. }
  130. // verifyHeader checks if the HTTP header contains given value.
  131. // When not, response given "failCode" as status code.
  132. func verifyHeader(key, value string, failCode int) macaron.Handler {
  133. return func(c *macaron.Context) {
  134. vals := c.Req.Header.Values(key)
  135. for _, val := range vals {
  136. if strings.Contains(val, value) {
  137. return
  138. }
  139. }
  140. log.Trace("[LFS] HTTP header %q does not contain value %q", key, value)
  141. c.Status(failCode)
  142. }
  143. }
  144. // verifyOID checks if the ":oid" URL parameter is valid.
  145. func verifyOID() macaron.Handler {
  146. return func(c *macaron.Context) {
  147. oid := lfsutil.OID(c.Params(":oid"))
  148. if !lfsutil.ValidOID(oid) {
  149. responseJSON(c.Resp, http.StatusBadRequest, responseError{
  150. Message: "Invalid oid",
  151. })
  152. return
  153. }
  154. c.Map(oid)
  155. }
  156. }
  157. func internalServerError(w http.ResponseWriter) {
  158. responseJSON(w, http.StatusInternalServerError, responseError{
  159. Message: "Internal server error",
  160. })
  161. }