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