route.go 5.6 KB

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