route.go 4.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159
  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/context"
  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. r.Combo("/:oid", verifyOID()).
  25. Get(authorize(db.AccessModeRead), serveBasicDownload).
  26. Put(authorize(db.AccessModeWrite), verifyContentTypeStream, serveBasicUpload)
  27. r.Post("/verify", authorize(db.AccessModeWrite), verifyAccept, verifyContentTypeJSON, serveBasicVerify)
  28. })
  29. }, authenticate())
  30. }
  31. // authenticate tries to authenticate user via HTTP Basic Auth.
  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 *context.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. c.Status(http.StatusInternalServerError)
  48. log.Error("Failed to authenticate user [name: %s]: %v", username, err)
  49. return
  50. }
  51. if err == nil && user.IsEnabledTwoFactor() {
  52. c.PlainText(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. c.Status(http.StatusInternalServerError)
  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. c.Status(http.StatusInternalServerError)
  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 *context.Context, user *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. c.Status(http.StatusInternalServerError)
  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. c.Status(http.StatusInternalServerError)
  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(user.ID, repo, mode) {
  110. c.Status(http.StatusNotFound)
  111. return
  112. }
  113. c.Map(owner)
  114. c.Map(repo)
  115. }
  116. }
  117. // verifyHeader checks if the HTTP header value is matching.
  118. // When not, response given "failCode" as status code.
  119. func verifyHeader(key, value string, failCode int) macaron.Handler {
  120. return func(c *context.Context) {
  121. if 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 *context.Context) {
  130. oid := lfsutil.OID(c.Params(":oid"))
  131. if !lfsutil.ValidOID(oid) {
  132. c.PlainText(http.StatusBadRequest, "Invalid oid")
  133. return
  134. }
  135. c.Map(oid)
  136. }
  137. }