route.go 5.4 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/db"
  14. "gogs.io/gogs/internal/lfsutil"
  15. )
  16. // RegisterRoutes registers LFS routes using given router, and inherits all groups and middleware.
  17. func RegisterRoutes(r *macaron.Router) {
  18. verifyAccept := verifyHeader("Accept", contentType, http.StatusNotAcceptable)
  19. verifyContentTypeJSON := verifyHeader("Content-Type", contentType, http.StatusBadRequest)
  20. verifyContentTypeStream := verifyHeader("Content-Type", "application/octet-stream", http.StatusBadRequest)
  21. r.Group("", func() {
  22. r.Post("/objects/batch", authorize(db.AccessModeRead), verifyAccept, verifyContentTypeJSON, serveBatch)
  23. r.Group("/objects/basic", func() {
  24. basic := &basicHandler{
  25. defaultStorage: lfsutil.Storage(conf.LFS.Storage),
  26. storagers: map[lfsutil.Storage]lfsutil.Storager{
  27. lfsutil.StorageLocal: &lfsutil.LocalStorage{Root: conf.LFS.ObjectsPath},
  28. },
  29. }
  30. r.Combo("/:oid", verifyOID()).
  31. Get(authorize(db.AccessModeRead), basic.serveDownload).
  32. Put(authorize(db.AccessModeWrite), verifyContentTypeStream, basic.serveUpload)
  33. r.Post("/verify", authorize(db.AccessModeWrite), verifyAccept, verifyContentTypeJSON, basic.serveVerify)
  34. })
  35. }, authenticate())
  36. }
  37. // authenticate tries to authenticate user via HTTP Basic Auth. It first tries to authenticate
  38. // as plain username and password, then use username as access token if previous step failed.
  39. func authenticate() macaron.Handler {
  40. askCredentials := func(w http.ResponseWriter) {
  41. w.Header().Set("Lfs-Authenticate", `Basic realm="Git LFS"`)
  42. responseJSON(w, http.StatusUnauthorized, responseError{
  43. Message: "Credentials needed",
  44. })
  45. }
  46. return func(c *macaron.Context) {
  47. username, password := authutil.DecodeBasic(c.Req.Header)
  48. if username == "" {
  49. askCredentials(c.Resp)
  50. return
  51. }
  52. user, err := db.Users.Authenticate(username, password, -1)
  53. if err != nil && !auth.IsErrBadCredentials(err) {
  54. internalServerError(c.Resp)
  55. log.Error("Failed to authenticate user [name: %s]: %v", username, err)
  56. return
  57. }
  58. if err == nil && user.IsEnabledTwoFactor() {
  59. c.Error(http.StatusBadRequest, "Users with 2FA enabled are not allowed to authenticate via username and password.")
  60. return
  61. }
  62. // If username and password authentication failed, try again using username as an access token.
  63. if auth.IsErrBadCredentials(err) {
  64. token, err := db.AccessTokens.GetBySHA(username)
  65. if err != nil {
  66. if db.IsErrAccessTokenNotExist(err) {
  67. askCredentials(c.Resp)
  68. } else {
  69. internalServerError(c.Resp)
  70. log.Error("Failed to get access token [sha: %s]: %v", username, err)
  71. }
  72. return
  73. }
  74. if err = db.AccessTokens.Save(token); err != nil {
  75. log.Error("Failed to update access token: %v", err)
  76. }
  77. user, err = db.Users.GetByID(token.UserID)
  78. if err != nil {
  79. // Once we found the token, we're supposed to find its related user,
  80. // thus any error is unexpected.
  81. internalServerError(c.Resp)
  82. log.Error("Failed to get user [id: %d]: %v", token.UserID, err)
  83. return
  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(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(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(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. }