route.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  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/db"
  13. "gogs.io/gogs/internal/lfsutil"
  14. )
  15. // RegisterRoutes registers LFS routes using given router, and inherits all groups and middleware.
  16. func RegisterRoutes(r *macaron.Router) {
  17. verifyAccept := verifyHeader("Accept", contentType, http.StatusNotAcceptable)
  18. verifyContentTypeJSON := verifyHeader("Content-Type", contentType, http.StatusBadRequest)
  19. verifyContentTypeStream := verifyHeader("Content-Type", "application/octet-stream", http.StatusBadRequest)
  20. r.Group("", func() {
  21. r.Post("/objects/batch", authorize(db.AccessModeRead), verifyAccept, verifyContentTypeJSON, serveBatch)
  22. r.Group("/objects/basic", func() {
  23. r.Combo("/:oid", verifyOID()).
  24. Get(authorize(db.AccessModeRead), serveBasicDownload).
  25. Put(authorize(db.AccessModeWrite), verifyContentTypeStream, serveBasicUpload)
  26. r.Post("/verify", authorize(db.AccessModeWrite), verifyAccept, verifyContentTypeJSON, serveBasicVerify)
  27. })
  28. }, authenticate())
  29. }
  30. // authenticate tries to authenticate user via HTTP Basic Auth. It first tries to authenticate
  31. // as plain username and password, then use username as access token if previous step failed.
  32. func authenticate() macaron.Handler {
  33. askCredentials := func(w http.ResponseWriter) {
  34. w.Header().Set("Lfs-Authenticate", `Basic realm="Git LFS"`)
  35. responseJSON(w, http.StatusUnauthorized, responseError{
  36. Message: "Credentials needed",
  37. })
  38. }
  39. return func(c *macaron.Context) {
  40. username, password := authutil.DecodeBasic(c.Req.Header)
  41. if username == "" {
  42. askCredentials(c.Resp)
  43. return
  44. }
  45. user, err := db.Users.Authenticate(username, password, -1)
  46. if err != nil && !db.IsErrUserNotExist(err) {
  47. internalServerError(c.Resp)
  48. log.Error("Failed to authenticate user [name: %s]: %v", username, err)
  49. return
  50. }
  51. if err == nil && user.IsEnabledTwoFactor() {
  52. c.Error(http.StatusBadRequest, "Users with 2FA enabled are not allowed to authenticate via username and password.")
  53. return
  54. }
  55. // If username and password authentication failed, try again using username as an access token.
  56. if db.IsErrUserNotExist(err) {
  57. token, err := db.AccessTokens.GetBySHA(username)
  58. if err != nil {
  59. if db.IsErrAccessTokenNotExist(err) {
  60. askCredentials(c.Resp)
  61. } else {
  62. internalServerError(c.Resp)
  63. log.Error("Failed to get access token [sha: %s]: %v", username, err)
  64. }
  65. return
  66. }
  67. token.Updated = time.Now()
  68. if err = db.AccessTokens.Save(token); err != nil {
  69. log.Error("Failed to update access token: %v", err)
  70. }
  71. user, err = db.Users.GetByID(token.UserID)
  72. if err != nil {
  73. // Once we found the token, we're supposed to find its related user,
  74. // thus any error is unexpected.
  75. internalServerError(c.Resp)
  76. log.Error("Failed to get user: %v", err)
  77. return
  78. }
  79. }
  80. log.Trace("[LFS] Authenticated user: %s", user.Name)
  81. c.Map(user)
  82. }
  83. }
  84. // authorize tries to authorize the user to the context repository with given access mode.
  85. func authorize(mode db.AccessMode) macaron.Handler {
  86. return func(c *macaron.Context, actor *db.User) {
  87. username := c.Params(":username")
  88. reponame := strings.TrimSuffix(c.Params(":reponame"), ".git")
  89. owner, err := db.Users.GetByUsername(username)
  90. if err != nil {
  91. if db.IsErrUserNotExist(err) {
  92. c.Status(http.StatusNotFound)
  93. } else {
  94. internalServerError(c.Resp)
  95. log.Error("Failed to get user [name: %s]: %v", username, err)
  96. }
  97. return
  98. }
  99. repo, err := db.Repos.GetByName(owner.ID, reponame)
  100. if err != nil {
  101. if db.IsErrRepoNotExist(err) {
  102. c.Status(http.StatusNotFound)
  103. } else {
  104. internalServerError(c.Resp)
  105. log.Error("Failed to get repository [owner_id: %d, name: %s]: %v", owner.ID, reponame, err)
  106. }
  107. return
  108. }
  109. if !db.Perms.Authorize(actor.ID, repo, mode) {
  110. c.Status(http.StatusNotFound)
  111. return
  112. }
  113. c.Map(owner) // NOTE: Override actor
  114. c.Map(repo)
  115. }
  116. }
  117. // verifyHeader checks if the HTTP header contains given value.
  118. // When not, response given "failCode" as status code.
  119. func verifyHeader(key, value string, failCode int) macaron.Handler {
  120. return func(c *macaron.Context) {
  121. if !strings.Contains(c.Req.Header.Get(key), value) {
  122. c.Status(failCode)
  123. return
  124. }
  125. }
  126. }
  127. // verifyOID checks if the ":oid" URL parameter is valid.
  128. func verifyOID() macaron.Handler {
  129. return func(c *macaron.Context) {
  130. oid := lfsutil.OID(c.Params(":oid"))
  131. if !lfsutil.ValidOID(oid) {
  132. responseJSON(c.Resp, http.StatusBadRequest, responseError{
  133. Message: "Invalid oid",
  134. })
  135. return
  136. }
  137. c.Map(oid)
  138. }
  139. }
  140. func internalServerError(w http.ResponseWriter) {
  141. responseJSON(w, http.StatusInternalServerError, responseError{
  142. Message: "Internal server error",
  143. })
  144. }