route.go 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  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. "time"
  9. "gopkg.in/macaron.v1"
  10. log "unknwon.dev/clog/v2"
  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 && !db.IsErrUserNotExist(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 db.IsErrUserNotExist(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. token.Updated = time.Now()
  75. if err = db.AccessTokens.Save(token); err != nil {
  76. log.Error("Failed to update access token: %v", err)
  77. }
  78. user, err = db.Users.GetByID(token.UserID)
  79. if err != nil {
  80. // Once we found the token, we're supposed to find its related user,
  81. // thus any error is unexpected.
  82. internalServerError(c.Resp)
  83. log.Error("Failed to get user [id: %d]: %v", token.UserID, err)
  84. return
  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 db.AccessMode) macaron.Handler {
  93. return func(c *macaron.Context, actor *db.User) {
  94. username := c.Params(":username")
  95. reponame := strings.TrimSuffix(c.Params(":reponame"), ".git")
  96. owner, err := db.Users.GetByUsername(username)
  97. if err != nil {
  98. if db.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 := db.Repos.GetByName(owner.ID, reponame)
  107. if err != nil {
  108. if db.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 !db.Perms.Authorize(actor.ID, repo, mode) {
  117. c.Status(http.StatusNotFound)
  118. return
  119. }
  120. c.Map(owner) // NOTE: Override actor
  121. c.Map(repo)
  122. }
  123. }
  124. // verifyHeader checks if the HTTP header contains given value.
  125. // When not, response given "failCode" as status code.
  126. func verifyHeader(key, value string, failCode int) macaron.Handler {
  127. return func(c *macaron.Context) {
  128. if !strings.Contains(c.Req.Header.Get(key), value) {
  129. c.Status(failCode)
  130. return
  131. }
  132. }
  133. }
  134. // verifyOID checks if the ":oid" URL parameter is valid.
  135. func verifyOID() macaron.Handler {
  136. return func(c *macaron.Context) {
  137. oid := lfsutil.OID(c.Params(":oid"))
  138. if !lfsutil.ValidOID(oid) {
  139. responseJSON(c.Resp, http.StatusBadRequest, responseError{
  140. Message: "Invalid oid",
  141. })
  142. return
  143. }
  144. c.Map(oid)
  145. }
  146. }
  147. func internalServerError(w http.ResponseWriter) {
  148. responseJSON(w, http.StatusInternalServerError, responseError{
  149. Message: "Internal server error",
  150. })
  151. }