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.

323 lines
8.5 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
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
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
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
  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. "encoding/json"
  8. "fmt"
  9. "os"
  10. "os/exec"
  11. "path/filepath"
  12. "strings"
  13. "time"
  14. "code.gitea.io/gitea/models"
  15. "code.gitea.io/gitea/modules/log"
  16. "code.gitea.io/gitea/modules/setting"
  17. "github.com/Unknwon/com"
  18. "github.com/dgrijalva/jwt-go"
  19. "github.com/urfave/cli"
  20. )
  21. const (
  22. accessDenied = "Repository does not exist or you do not have access"
  23. lfsAuthenticateVerb = "git-lfs-authenticate"
  24. )
  25. // CmdServ represents the available serv sub-command.
  26. var CmdServ = cli.Command{
  27. Name: "serv",
  28. Usage: "This command should only be called by SSH shell",
  29. Description: `Serv provide access auth for repositories`,
  30. Action: runServ,
  31. Flags: []cli.Flag{
  32. cli.StringFlag{
  33. Name: "config, c",
  34. Value: "custom/conf/app.ini",
  35. Usage: "Custom configuration file path",
  36. },
  37. },
  38. }
  39. func setup(logPath string) error {
  40. setting.NewContext()
  41. log.NewGitLogger(filepath.Join(setting.LogRootPath, logPath))
  42. models.LoadConfigs()
  43. if setting.UseSQLite3 || setting.UseTiDB {
  44. workDir, _ := setting.WorkDir()
  45. if err := os.Chdir(workDir); err != nil {
  46. log.GitLogger.Fatal(4, "Failed to change directory %s: %v", workDir, err)
  47. }
  48. }
  49. setting.NewXORMLogService(true)
  50. return models.SetEngine()
  51. }
  52. func parseCmd(cmd string) (string, string) {
  53. ss := strings.SplitN(cmd, " ", 2)
  54. if len(ss) != 2 {
  55. return "", ""
  56. }
  57. return ss[0], strings.Replace(ss[1], "'/", "'", 1)
  58. }
  59. var (
  60. allowedCommands = map[string]models.AccessMode{
  61. "git-upload-pack": models.AccessModeRead,
  62. "git-upload-archive": models.AccessModeRead,
  63. "git-receive-pack": models.AccessModeWrite,
  64. lfsAuthenticateVerb: models.AccessModeNone,
  65. }
  66. )
  67. func fail(userMessage, logMessage string, args ...interface{}) {
  68. fmt.Fprintln(os.Stderr, "Gitea:", userMessage)
  69. if len(logMessage) > 0 {
  70. if !setting.ProdMode {
  71. fmt.Fprintf(os.Stderr, logMessage+"\n", args...)
  72. }
  73. log.GitLogger.Fatal(3, logMessage, args...)
  74. return
  75. }
  76. log.GitLogger.Close()
  77. os.Exit(1)
  78. }
  79. func runServ(c *cli.Context) error {
  80. if c.IsSet("config") {
  81. setting.CustomConf = c.String("config")
  82. }
  83. if err := setup("serv.log"); err != nil {
  84. fail("System init failed", fmt.Sprintf("setup: %v", err))
  85. }
  86. if setting.SSH.Disabled {
  87. println("Gitea: SSH has been disabled")
  88. return nil
  89. }
  90. if len(c.Args()) < 1 {
  91. fail("Not enough arguments", "Not enough arguments")
  92. }
  93. cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
  94. if len(cmd) == 0 {
  95. println("Hi there, You've successfully authenticated, but Gitea does not provide shell access.")
  96. println("If this is unexpected, please log in with password and setup Gitea under another user.")
  97. return nil
  98. }
  99. verb, args := parseCmd(cmd)
  100. var lfsVerb string
  101. if verb == lfsAuthenticateVerb {
  102. if !setting.LFS.StartServer {
  103. fail("Unknown git command", "LFS authentication request over SSH denied, LFS support is disabled")
  104. }
  105. if strings.Contains(args, " ") {
  106. argsSplit := strings.SplitN(args, " ", 2)
  107. args = strings.TrimSpace(argsSplit[0])
  108. lfsVerb = strings.TrimSpace(argsSplit[1])
  109. }
  110. }
  111. repoPath := strings.ToLower(strings.Trim(args, "'"))
  112. rr := strings.SplitN(repoPath, "/", 2)
  113. if len(rr) != 2 {
  114. fail("Invalid repository path", "Invalid repository path: %v", args)
  115. }
  116. username := strings.ToLower(rr[0])
  117. reponame := strings.ToLower(strings.TrimSuffix(rr[1], ".git"))
  118. isWiki := false
  119. if strings.HasSuffix(reponame, ".wiki") {
  120. isWiki = true
  121. reponame = reponame[:len(reponame)-5]
  122. }
  123. os.Setenv(models.EnvRepoUsername, username)
  124. if isWiki {
  125. os.Setenv(models.EnvRepoIsWiki, "true")
  126. } else {
  127. os.Setenv(models.EnvRepoIsWiki, "false")
  128. }
  129. os.Setenv(models.EnvRepoName, reponame)
  130. repoUser, err := models.GetUserByName(username)
  131. if err != nil {
  132. if models.IsErrUserNotExist(err) {
  133. fail("Repository owner does not exist", "Unregistered owner: %s", username)
  134. }
  135. fail("Internal error", "Failed to get repository owner (%s): %v", username, err)
  136. }
  137. os.Setenv(models.EnvRepoUserSalt, repoUser.Salt)
  138. repo, err := models.GetRepositoryByName(repoUser.ID, reponame)
  139. if err != nil {
  140. if models.IsErrRepoNotExist(err) {
  141. fail(accessDenied, "Repository does not exist: %s/%s", repoUser.Name, reponame)
  142. }
  143. fail("Internal error", "Failed to get repository: %v", err)
  144. }
  145. requestedMode, has := allowedCommands[verb]
  146. if !has {
  147. fail("Unknown git command", "Unknown git command %s", verb)
  148. }
  149. if verb == lfsAuthenticateVerb {
  150. if lfsVerb == "upload" {
  151. requestedMode = models.AccessModeWrite
  152. } else {
  153. requestedMode = models.AccessModeRead
  154. }
  155. }
  156. // Prohibit push to mirror repositories.
  157. if requestedMode > models.AccessModeRead && repo.IsMirror {
  158. fail("mirror repository is read-only", "")
  159. }
  160. // Allow anonymous clone for public repositories.
  161. var (
  162. keyID int64
  163. user *models.User
  164. )
  165. if requestedMode == models.AccessModeWrite || repo.IsPrivate {
  166. keys := strings.Split(c.Args()[0], "-")
  167. if len(keys) != 2 {
  168. fail("Key ID format error", "Invalid key argument: %s", c.Args()[0])
  169. }
  170. key, err := models.GetPublicKeyByID(com.StrTo(keys[1]).MustInt64())
  171. if err != nil {
  172. fail("Invalid key ID", "Invalid key ID[%s]: %v", c.Args()[0], err)
  173. }
  174. keyID = key.ID
  175. // Check deploy key or user key.
  176. if key.Type == models.KeyTypeDeploy {
  177. if key.Mode < requestedMode {
  178. fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
  179. }
  180. // Check if this deploy key belongs to current repository.
  181. if !models.HasDeployKey(key.ID, repo.ID) {
  182. fail("Key access denied", "Deploy key access denied: [key_id: %d, repo_id: %d]", key.ID, repo.ID)
  183. }
  184. // Update deploy key activity.
  185. deployKey, err := models.GetDeployKeyByRepo(key.ID, repo.ID)
  186. if err != nil {
  187. fail("Internal error", "GetDeployKey: %v", err)
  188. }
  189. deployKey.Updated = time.Now()
  190. if err = models.UpdateDeployKey(deployKey); err != nil {
  191. fail("Internal error", "UpdateDeployKey: %v", err)
  192. }
  193. } else {
  194. user, err = models.GetUserByKeyID(key.ID)
  195. if err != nil {
  196. fail("internal error", "Failed to get user by key ID(%d): %v", keyID, err)
  197. }
  198. mode, err := models.AccessLevel(user, repo)
  199. if err != nil {
  200. fail("Internal error", "Failed to check access: %v", err)
  201. } else if mode < requestedMode {
  202. clientMessage := accessDenied
  203. if mode >= models.AccessModeRead {
  204. clientMessage = "You do not have sufficient authorization for this action"
  205. }
  206. fail(clientMessage,
  207. "User %s does not have level %v access to repository %s",
  208. user.Name, requestedMode, repoPath)
  209. }
  210. os.Setenv(models.EnvPusherName, user.Name)
  211. os.Setenv(models.EnvPusherID, fmt.Sprintf("%d", user.ID))
  212. }
  213. }
  214. //LFS token authentication
  215. if verb == lfsAuthenticateVerb {
  216. url := fmt.Sprintf("%s%s/%s.git/info/lfs", setting.AppURL, repoUser.Name, repo.Name)
  217. now := time.Now()
  218. token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
  219. "repo": repo.ID,
  220. "op": lfsVerb,
  221. "exp": now.Add(5 * time.Minute).Unix(),
  222. "nbf": now.Unix(),
  223. })
  224. // Sign and get the complete encoded token as a string using the secret
  225. tokenString, err := token.SignedString(setting.LFS.JWTSecretBytes)
  226. if err != nil {
  227. fail("Internal error", "Failed to sign JWT token: %v", err)
  228. }
  229. tokenAuthentication := &models.LFSTokenResponse{
  230. Header: make(map[string]string),
  231. Href: url,
  232. }
  233. tokenAuthentication.Header["Authorization"] = fmt.Sprintf("Bearer %s", tokenString)
  234. enc := json.NewEncoder(os.Stdout)
  235. err = enc.Encode(tokenAuthentication)
  236. if err != nil {
  237. fail("Internal error", "Failed to encode LFS json response: %v", err)
  238. }
  239. return nil
  240. }
  241. // Special handle for Windows.
  242. if setting.IsWindows {
  243. verb = strings.Replace(verb, "-", " ", 1)
  244. }
  245. var gitcmd *exec.Cmd
  246. verbs := strings.Split(verb, " ")
  247. if len(verbs) == 2 {
  248. gitcmd = exec.Command(verbs[0], verbs[1], repoPath)
  249. } else {
  250. gitcmd = exec.Command(verb, repoPath)
  251. }
  252. os.Setenv(models.ProtectedBranchRepoID, fmt.Sprintf("%d", repo.ID))
  253. gitcmd.Dir = setting.RepoRootPath
  254. gitcmd.Stdout = os.Stdout
  255. gitcmd.Stdin = os.Stdin
  256. gitcmd.Stderr = os.Stderr
  257. if err = gitcmd.Run(); err != nil {
  258. fail("Internal error", "Failed to execute git command: %v", err)
  259. }
  260. // Update user key activity.
  261. if keyID > 0 {
  262. key, err := models.GetPublicKeyByID(keyID)
  263. if err != nil {
  264. fail("Internal error", "GetPublicKeyById: %v", err)
  265. }
  266. key.Updated = time.Now()
  267. if err = models.UpdatePublicKey(key); err != nil {
  268. fail("Internal error", "UpdatePublicKey: %v", err)
  269. }
  270. }
  271. return nil
  272. }