You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

369 lines
9.9 KiB

10 years ago
10 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
10 years ago
9 years ago
9 years ago
9 years ago
10 years ago
10 years ago
10 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
10 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
9 years ago
10 years ago
10 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
8 years ago
10 years ago
Git LFS support v2 (#122) * Import github.com/git-lfs/lfs-test-server as lfs module base Imported commit is 3968aac269a77b73924649b9412ae03f7ccd3198 Removed: Dockerfile CONTRIBUTING.md mgmt* script/ vendor/ kvlogger.go .dockerignore .gitignore README.md * Remove config, add JWT support from github.com/mgit-at/lfs-test-server Imported commit f0cdcc5a01599c5a955dc1bbf683bb4acecdba83 * Add LFS settings * Add LFS meta object model * Add LFS routes and initialization * Import github.com/dgrijalva/jwt-go into vendor/ * Adapt LFS module: handlers, routing, meta store * Move LFS routes to /user/repo/info/lfs/* * Add request header checks to LFS BatchHandler / PostHandler * Implement LFS basic authentication * Rework JWT secret generation / load * Implement LFS SSH token authentication with JWT Specification: https://github.com/github/git-lfs/tree/master/docs/api * Integrate LFS settings into install process * Remove LFS objects when repository is deleted Only removes objects from content store when deleted repo is the only referencing repository * Make LFS module stateless Fixes bug where LFS would not work after installation without restarting Gitea * Change 500 'Internal Server Error' to 400 'Bad Request' * Change sql query to xorm call * Remove unneeded type from LFS module * Change internal imports to code.gitea.io/gitea/ * Add Gitea authors copyright * Change basic auth realm to "gitea-lfs" * Add unique indexes to LFS model * Use xorm count function in LFS check on repository delete * Return io.ReadCloser from content store and close after usage * Add LFS info to runWeb() * Export LFS content store base path * LFS file download from UI * Work around git-lfs client issue with unauthenticated requests Returning a dummy Authorization header for unauthenticated requests lets git-lfs client skip asking for auth credentials See: https://github.com/github/git-lfs/issues/1088 * Fix unauthenticated UI downloads from public repositories * Authentication check order, Finish LFS file view logic * Ignore LFS hooks if installed for current OS user Fixes Gitea UI actions for repositories tracking LFS files. Checks for minimum needed git version by parsing the semantic version string. * Hide LFS metafile diff from commit view, marking as binary * Show LFS notice if file in commit view is tracked * Add notbefore/nbf JWT claim * Correct lint suggestions - comments for structs and functions - Add comments to LFS model - Function comment for GetRandomBytesAsBase64 - LFS server function comments and lint variable suggestion * Move secret generation code out of conditional Ensures no LFS code may run with an empty secret * Do not hand out JWT tokens if LFS server support is disabled
8 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Copyright 2016 The Gitea Authors. All rights reserved.
  3. // Use of this source code is governed by a MIT-style
  4. // license that can be found in the LICENSE file.
  5. package cmd
  6. import (
  7. "crypto/tls"
  8. "encoding/json"
  9. "fmt"
  10. "os"
  11. "os/exec"
  12. "path/filepath"
  13. "strings"
  14. "time"
  15. "code.gitea.io/git"
  16. "code.gitea.io/gitea/models"
  17. "code.gitea.io/gitea/modules/base"
  18. "code.gitea.io/gitea/modules/httplib"
  19. "code.gitea.io/gitea/modules/log"
  20. "code.gitea.io/gitea/modules/setting"
  21. "github.com/Unknwon/com"
  22. "github.com/dgrijalva/jwt-go"
  23. gouuid "github.com/satori/go.uuid"
  24. "github.com/urfave/cli"
  25. )
  26. const (
  27. accessDenied = "Repository does not exist or you do not have access"
  28. lfsAuthenticateVerb = "git-lfs-authenticate"
  29. )
  30. // CmdServ represents the available serv sub-command.
  31. var CmdServ = cli.Command{
  32. Name: "serv",
  33. Usage: "This command should only be called by SSH shell",
  34. Description: `Serv provide access auth for repositories`,
  35. Action: runServ,
  36. Flags: []cli.Flag{
  37. cli.StringFlag{
  38. Name: "config, c",
  39. Value: "custom/conf/app.ini",
  40. Usage: "Custom configuration file path",
  41. },
  42. },
  43. }
  44. func setup(logPath string) {
  45. setting.NewContext()
  46. log.NewGitLogger(filepath.Join(setting.LogRootPath, logPath))
  47. models.LoadConfigs()
  48. if setting.UseSQLite3 || setting.UseTiDB {
  49. workDir, _ := setting.WorkDir()
  50. if err := os.Chdir(workDir); err != nil {
  51. log.GitLogger.Fatal(4, "Fail to change directory %s: %v", workDir, err)
  52. }
  53. }
  54. models.SetEngine()
  55. }
  56. func parseCmd(cmd string) (string, string) {
  57. ss := strings.SplitN(cmd, " ", 2)
  58. if len(ss) != 2 {
  59. return "", ""
  60. }
  61. return ss[0], strings.Replace(ss[1], "'/", "'", 1)
  62. }
  63. var (
  64. allowedCommands = map[string]models.AccessMode{
  65. "git-upload-pack": models.AccessModeRead,
  66. "git-upload-archive": models.AccessModeRead,
  67. "git-receive-pack": models.AccessModeWrite,
  68. lfsAuthenticateVerb: models.AccessModeNone,
  69. }
  70. )
  71. func fail(userMessage, logMessage string, args ...interface{}) {
  72. fmt.Fprintln(os.Stderr, "Gitea:", userMessage)
  73. if len(logMessage) > 0 {
  74. if !setting.ProdMode {
  75. fmt.Fprintf(os.Stderr, logMessage+"\n", args...)
  76. }
  77. log.GitLogger.Fatal(3, logMessage, args...)
  78. return
  79. }
  80. log.GitLogger.Close()
  81. os.Exit(1)
  82. }
  83. func handleUpdateTask(uuid string, user, repoUser *models.User, reponame string, isWiki bool) {
  84. task, err := models.GetUpdateTaskByUUID(uuid)
  85. if err != nil {
  86. if models.IsErrUpdateTaskNotExist(err) {
  87. log.GitLogger.Trace("No update task is presented: %s", uuid)
  88. return
  89. }
  90. log.GitLogger.Fatal(2, "GetUpdateTaskByUUID: %v", err)
  91. } else if err = models.DeleteUpdateTaskByUUID(uuid); err != nil {
  92. log.GitLogger.Fatal(2, "DeleteUpdateTaskByUUID: %v", err)
  93. }
  94. if isWiki {
  95. return
  96. }
  97. if err = models.PushUpdate(models.PushUpdateOptions{
  98. RefFullName: task.RefName,
  99. OldCommitID: task.OldCommitID,
  100. NewCommitID: task.NewCommitID,
  101. PusherID: user.ID,
  102. PusherName: user.Name,
  103. RepoUserName: repoUser.Name,
  104. RepoName: reponame,
  105. }); err != nil {
  106. log.GitLogger.Error(2, "Update: %v", err)
  107. }
  108. // Ask for running deliver hook and test pull request tasks.
  109. reqURL := setting.LocalURL + repoUser.Name + "/" + reponame + "/tasks/trigger?branch=" +
  110. strings.TrimPrefix(task.RefName, git.BranchPrefix) + "&secret=" + base.EncodeMD5(repoUser.Salt) + "&pusher=" + com.ToStr(user.ID)
  111. log.GitLogger.Trace("Trigger task: %s", reqURL)
  112. resp, err := httplib.Head(reqURL).SetTLSClientConfig(&tls.Config{
  113. InsecureSkipVerify: true,
  114. }).Response()
  115. if err == nil {
  116. resp.Body.Close()
  117. if resp.StatusCode/100 != 2 {
  118. log.GitLogger.Error(2, "Fail to trigger task: not 2xx response code")
  119. }
  120. } else {
  121. log.GitLogger.Error(2, "Fail to trigger task: %v", err)
  122. }
  123. }
  124. func runServ(c *cli.Context) error {
  125. if c.IsSet("config") {
  126. setting.CustomConf = c.String("config")
  127. }
  128. setup("serv.log")
  129. if setting.SSH.Disabled {
  130. println("Gitea: SSH has been disabled")
  131. return nil
  132. }
  133. if len(c.Args()) < 1 {
  134. fail("Not enough arguments", "Not enough arguments")
  135. }
  136. cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
  137. if len(cmd) == 0 {
  138. println("Hi there, You've successfully authenticated, but Gitea does not provide shell access.")
  139. println("If this is unexpected, please log in with password and setup Gitea under another user.")
  140. return nil
  141. }
  142. verb, args := parseCmd(cmd)
  143. var lfsVerb string
  144. if verb == lfsAuthenticateVerb {
  145. if !setting.LFS.StartServer {
  146. fail("Unknown git command", "LFS authentication request over SSH denied, LFS support is disabled")
  147. }
  148. if strings.Contains(args, " ") {
  149. argsSplit := strings.SplitN(args, " ", 2)
  150. args = strings.TrimSpace(argsSplit[0])
  151. lfsVerb = strings.TrimSpace(argsSplit[1])
  152. }
  153. }
  154. repoPath := strings.ToLower(strings.Trim(args, "'"))
  155. rr := strings.SplitN(repoPath, "/", 2)
  156. if len(rr) != 2 {
  157. fail("Invalid repository path", "Invalid repository path: %v", args)
  158. }
  159. username := strings.ToLower(rr[0])
  160. reponame := strings.ToLower(strings.TrimSuffix(rr[1], ".git"))
  161. isWiki := false
  162. if strings.HasSuffix(reponame, ".wiki") {
  163. isWiki = true
  164. reponame = reponame[:len(reponame)-5]
  165. }
  166. repoUser, err := models.GetUserByName(username)
  167. if err != nil {
  168. if models.IsErrUserNotExist(err) {
  169. fail("Repository owner does not exist", "Unregistered owner: %s", username)
  170. }
  171. fail("Internal error", "Failed to get repository owner (%s): %v", username, err)
  172. }
  173. repo, err := models.GetRepositoryByName(repoUser.ID, reponame)
  174. if err != nil {
  175. if models.IsErrRepoNotExist(err) {
  176. fail(accessDenied, "Repository does not exist: %s/%s", repoUser.Name, reponame)
  177. }
  178. fail("Internal error", "Failed to get repository: %v", err)
  179. }
  180. requestedMode, has := allowedCommands[verb]
  181. if !has {
  182. fail("Unknown git command", "Unknown git command %s", verb)
  183. }
  184. if verb == lfsAuthenticateVerb {
  185. if lfsVerb == "upload" {
  186. requestedMode = models.AccessModeWrite
  187. } else {
  188. requestedMode = models.AccessModeRead
  189. }
  190. }
  191. // Prohibit push to mirror repositories.
  192. if requestedMode > models.AccessModeRead && repo.IsMirror {
  193. fail("mirror repository is read-only", "")
  194. }
  195. // Allow anonymous clone for public repositories.
  196. var (
  197. keyID int64
  198. user *models.User
  199. )
  200. if requestedMode == models.AccessModeWrite || repo.IsPrivate {
  201. keys := strings.Split(c.Args()[0], "-")
  202. if len(keys) != 2 {
  203. fail("Key ID format error", "Invalid key argument: %s", c.Args()[0])
  204. }
  205. key, err := models.GetPublicKeyByID(com.StrTo(keys[1]).MustInt64())
  206. if err != nil {
  207. fail("Invalid key ID", "Invalid key ID[%s]: %v", c.Args()[0], err)
  208. }
  209. keyID = key.ID
  210. // Check deploy key or user key.
  211. if key.Type == models.KeyTypeDeploy {
  212. if key.Mode < requestedMode {
  213. fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
  214. }
  215. // Check if this deploy key belongs to current repository.
  216. if !models.HasDeployKey(key.ID, repo.ID) {
  217. fail("Key access denied", "Deploy key access denied: [key_id: %d, repo_id: %d]", key.ID, repo.ID)
  218. }
  219. // Update deploy key activity.
  220. deployKey, err := models.GetDeployKeyByRepo(key.ID, repo.ID)
  221. if err != nil {
  222. fail("Internal error", "GetDeployKey: %v", err)
  223. }
  224. deployKey.Updated = time.Now()
  225. if err = models.UpdateDeployKey(deployKey); err != nil {
  226. fail("Internal error", "UpdateDeployKey: %v", err)
  227. }
  228. } else {
  229. user, err = models.GetUserByKeyID(key.ID)
  230. if err != nil {
  231. fail("internal error", "Failed to get user by key ID(%d): %v", keyID, err)
  232. }
  233. mode, err := models.AccessLevel(user, repo)
  234. if err != nil {
  235. fail("Internal error", "Fail to check access: %v", err)
  236. } else if mode < requestedMode {
  237. clientMessage := accessDenied
  238. if mode >= models.AccessModeRead {
  239. clientMessage = "You do not have sufficient authorization for this action"
  240. }
  241. fail(clientMessage,
  242. "User %s does not have level %v access to repository %s",
  243. user.Name, requestedMode, repoPath)
  244. }
  245. os.Setenv("GITEA_PUSHER_NAME", user.Name)
  246. }
  247. }
  248. //LFS token authentication
  249. if verb == lfsAuthenticateVerb {
  250. url := fmt.Sprintf("%s%s/%s.git/info/lfs", setting.AppURL, repoUser.Name, repo.Name)
  251. now := time.Now()
  252. token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
  253. "repo": repo.ID,
  254. "op": lfsVerb,
  255. "exp": now.Add(5 * time.Minute).Unix(),
  256. "nbf": now.Unix(),
  257. })
  258. // Sign and get the complete encoded token as a string using the secret
  259. tokenString, err := token.SignedString(setting.LFS.JWTSecretBytes)
  260. if err != nil {
  261. fail("Internal error", "Failed to sign JWT token: %v", err)
  262. }
  263. tokenAuthentication := &models.LFSTokenResponse{
  264. Header: make(map[string]string),
  265. Href: url,
  266. }
  267. tokenAuthentication.Header["Authorization"] = fmt.Sprintf("Bearer %s", tokenString)
  268. enc := json.NewEncoder(os.Stdout)
  269. err = enc.Encode(tokenAuthentication)
  270. if err != nil {
  271. fail("Internal error", "Failed to encode LFS json response: %v", err)
  272. }
  273. return nil
  274. }
  275. uuid := gouuid.NewV4().String()
  276. os.Setenv("GITEA_UUID", uuid)
  277. // Keep the old env variable name for backward compability
  278. os.Setenv("uuid", uuid)
  279. // Special handle for Windows.
  280. if setting.IsWindows {
  281. verb = strings.Replace(verb, "-", " ", 1)
  282. }
  283. var gitcmd *exec.Cmd
  284. verbs := strings.Split(verb, " ")
  285. if len(verbs) == 2 {
  286. gitcmd = exec.Command(verbs[0], verbs[1], repoPath)
  287. } else {
  288. gitcmd = exec.Command(verb, repoPath)
  289. }
  290. gitcmd.Dir = setting.RepoRootPath
  291. gitcmd.Stdout = os.Stdout
  292. gitcmd.Stdin = os.Stdin
  293. gitcmd.Stderr = os.Stderr
  294. if err = gitcmd.Run(); err != nil {
  295. fail("Internal error", "Failed to execute git command: %v", err)
  296. }
  297. if requestedMode == models.AccessModeWrite {
  298. handleUpdateTask(uuid, user, repoUser, reponame, isWiki)
  299. }
  300. // Update user key activity.
  301. if keyID > 0 {
  302. key, err := models.GetPublicKeyByID(keyID)
  303. if err != nil {
  304. fail("Internal error", "GetPublicKeyById: %v", err)
  305. }
  306. key.Updated = time.Now()
  307. if err = models.UpdatePublicKey(key); err != nil {
  308. fail("Internal error", "UpdatePublicKey: %v", err)
  309. }
  310. }
  311. return nil
  312. }