Fork to maintain patches against the official gitea for https://code.ceondo.com https://github.com/go-gitea/gitea

serv.go 8.8KB

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