route.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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.
  31. func authenticate() macaron.Handler {
  32. askCredentials := func(w http.ResponseWriter) {
  33. w.Header().Set("LFS-Authenticate", `Basic realm="Git LFS"`)
  34. responseJSON(w, http.StatusUnauthorized, responseError{
  35. Message: "Credentials needed",
  36. })
  37. }
  38. return func(c *macaron.Context) {
  39. username, password := authutil.DecodeBasic(c.Req.Header)
  40. if username == "" {
  41. askCredentials(c.Resp)
  42. return
  43. }
  44. user, err := db.Users.Authenticate(username, password, -1)
  45. if err != nil && !db.IsErrUserNotExist(err) {
  46. c.Status(http.StatusInternalServerError)
  47. log.Error("Failed to authenticate user [name: %s]: %v", username, err)
  48. return
  49. }
  50. if err == nil && user.IsEnabledTwoFactor() {
  51. c.Error(http.StatusBadRequest, `Users with 2FA enabled are not allowed to authenticate via username and password.`)
  52. return
  53. }
  54. // If username and password authentication failed, try again using username as an access token.
  55. if db.IsErrUserNotExist(err) {
  56. token, err := db.AccessTokens.GetBySHA(username)
  57. if err != nil {
  58. if db.IsErrAccessTokenNotExist(err) {
  59. askCredentials(c.Resp)
  60. } else {
  61. c.Status(http.StatusInternalServerError)
  62. log.Error("Failed to get access token [sha: %s]: %v", username, err)
  63. }
  64. return
  65. }
  66. token.Updated = time.Now()
  67. if err = db.AccessTokens.Save(token); err != nil {
  68. log.Error("Failed to update access token: %v", err)
  69. }
  70. user, err = db.Users.GetByID(token.UserID)
  71. if err != nil {
  72. // Once we found the token, we're supposed to find its related user,
  73. // thus any error is unexpected.
  74. c.Status(http.StatusInternalServerError)
  75. log.Error("Failed to get user: %v", err)
  76. return
  77. }
  78. }
  79. log.Trace("[LFS] Authenticated user: %s", user.Name)
  80. c.Map(user)
  81. }
  82. }
  83. // authorize tries to authorize the user to the context repository with given access mode.
  84. func authorize(mode db.AccessMode) macaron.Handler {
  85. return func(c *macaron.Context, user *db.User) {
  86. username := c.Params(":username")
  87. reponame := strings.TrimSuffix(c.Params(":reponame"), ".git")
  88. owner, err := db.Users.GetByUsername(username)
  89. if err != nil {
  90. if db.IsErrUserNotExist(err) {
  91. c.Status(http.StatusNotFound)
  92. } else {
  93. c.Status(http.StatusInternalServerError)
  94. log.Error("Failed to get user [name: %s]: %v", username, err)
  95. }
  96. return
  97. }
  98. repo, err := db.Repos.GetByName(owner.ID, reponame)
  99. if err != nil {
  100. if db.IsErrRepoNotExist(err) {
  101. c.Status(http.StatusNotFound)
  102. } else {
  103. c.Status(http.StatusInternalServerError)
  104. log.Error("Failed to get repository [owner_id: %d, name: %s]: %v", owner.ID, reponame, err)
  105. }
  106. return
  107. }
  108. if !db.Perms.Authorize(user.ID, repo, mode) {
  109. c.Status(http.StatusNotFound)
  110. return
  111. }
  112. c.Map(owner)
  113. c.Map(repo)
  114. }
  115. }
  116. // verifyHeader checks if the HTTP header contains given value.
  117. // When not, response given "failCode" as status code.
  118. func verifyHeader(key, value string, failCode int) macaron.Handler {
  119. return func(c *macaron.Context) {
  120. if !strings.Contains(c.Req.Header.Get(key), value) {
  121. c.Status(failCode)
  122. return
  123. }
  124. }
  125. }
  126. // verifyOID checks if the ":oid" URL parameter is valid.
  127. func verifyOID() macaron.Handler {
  128. return func(c *macaron.Context) {
  129. oid := lfsutil.OID(c.Params(":oid"))
  130. if !lfsutil.ValidOID(oid) {
  131. c.Error(http.StatusBadRequest, "Invalid oid")
  132. return
  133. }
  134. c.Map(oid)
  135. }
  136. }