route.go 5.1 KB

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