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

serve.go 10KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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) error {
  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, "Failed to change directory %s: %v", workDir, err)
  52. }
  53. }
  54. setting.NewXORMLogService(true)
  55. return models.SetEngine()
  56. }
  57. func parseCmd(cmd string) (string, string) {
  58. ss := strings.SplitN(cmd, " ", 2)
  59. if len(ss) != 2 {
  60. return "", ""
  61. }
  62. return ss[0], strings.Replace(ss[1], "'/", "'", 1)
  63. }
  64. var (
  65. allowedCommands = map[string]models.AccessMode{
  66. "git-upload-pack": models.AccessModeRead,
  67. "git-upload-archive": models.AccessModeRead,
  68. "git-receive-pack": models.AccessModeWrite,
  69. lfsAuthenticateVerb: models.AccessModeNone,
  70. }
  71. )
  72. func fail(userMessage, logMessage string, args ...interface{}) {
  73. fmt.Fprintln(os.Stderr, "Gitea:", userMessage)
  74. if len(logMessage) > 0 {
  75. if !setting.ProdMode {
  76. fmt.Fprintf(os.Stderr, logMessage+"\n", args...)
  77. }
  78. log.GitLogger.Fatal(3, logMessage, args...)
  79. return
  80. }
  81. log.GitLogger.Close()
  82. os.Exit(1)
  83. }
  84. func handleUpdateTask(uuid string, user, repoUser *models.User, reponame string, isWiki bool) {
  85. task, err := models.GetUpdateTaskByUUID(uuid)
  86. if err != nil {
  87. if models.IsErrUpdateTaskNotExist(err) {
  88. log.GitLogger.Trace("No update task is presented: %s", uuid)
  89. return
  90. }
  91. log.GitLogger.Fatal(2, "GetUpdateTaskByUUID: %v", err)
  92. } else if err = models.DeleteUpdateTaskByUUID(uuid); err != nil {
  93. log.GitLogger.Fatal(2, "DeleteUpdateTaskByUUID: %v", err)
  94. }
  95. if isWiki {
  96. return
  97. }
  98. if err = models.PushUpdate(models.PushUpdateOptions{
  99. RefFullName: task.RefName,
  100. OldCommitID: task.OldCommitID,
  101. NewCommitID: task.NewCommitID,
  102. PusherID: user.ID,
  103. PusherName: user.Name,
  104. RepoUserName: repoUser.Name,
  105. RepoName: reponame,
  106. }); err != nil {
  107. log.GitLogger.Error(2, "Update: %v", err)
  108. }
  109. // Ask for running deliver hook and test pull request tasks.
  110. reqURL := setting.LocalURL + repoUser.Name + "/" + reponame + "/tasks/trigger?branch=" +
  111. strings.TrimPrefix(task.RefName, git.BranchPrefix) + "&secret=" + base.EncodeMD5(repoUser.Salt) + "&pusher=" + com.ToStr(user.ID)
  112. log.GitLogger.Trace("Trigger task: %s", reqURL)
  113. resp, err := httplib.Head(reqURL).SetTLSClientConfig(&tls.Config{
  114. InsecureSkipVerify: true,
  115. }).Response()
  116. if err == nil {
  117. resp.Body.Close()
  118. if resp.StatusCode/100 != 2 {
  119. log.GitLogger.Error(2, "Failed to trigger task: not 2xx response code")
  120. }
  121. } else {
  122. log.GitLogger.Error(2, "Failed to trigger task: %v", err)
  123. }
  124. }
  125. func runServ(c *cli.Context) error {
  126. if c.IsSet("config") {
  127. setting.CustomConf = c.String("config")
  128. }
  129. if err := setup("serv.log"); err != nil {
  130. fail("System init failed", fmt.Sprintf("setup: %v", err))
  131. }
  132. if setting.SSH.Disabled {
  133. println("Gitea: SSH has been disabled")
  134. return nil
  135. }
  136. if len(c.Args()) < 1 {
  137. fail("Not enough arguments", "Not enough arguments")
  138. }
  139. cmd := os.Getenv("SSH_ORIGINAL_COMMAND")
  140. if len(cmd) == 0 {
  141. println("Hi there, You've successfully authenticated, but Gitea does not provide shell access.")
  142. println("If this is unexpected, please log in with password and setup Gitea under another user.")
  143. return nil
  144. }
  145. verb, args := parseCmd(cmd)
  146. var lfsVerb string
  147. if verb == lfsAuthenticateVerb {
  148. if !setting.LFS.StartServer {
  149. fail("Unknown git command", "LFS authentication request over SSH denied, LFS support is disabled")
  150. }
  151. if strings.Contains(args, " ") {
  152. argsSplit := strings.SplitN(args, " ", 2)
  153. args = strings.TrimSpace(argsSplit[0])
  154. lfsVerb = strings.TrimSpace(argsSplit[1])
  155. }
  156. }
  157. repoPath := strings.ToLower(strings.Trim(args, "'"))
  158. rr := strings.SplitN(repoPath, "/", 2)
  159. if len(rr) != 2 {
  160. fail("Invalid repository path", "Invalid repository path: %v", args)
  161. }
  162. username := strings.ToLower(rr[0])
  163. reponame := strings.ToLower(strings.TrimSuffix(rr[1], ".git"))
  164. isWiki := false
  165. if strings.HasSuffix(reponame, ".wiki") {
  166. isWiki = true
  167. reponame = reponame[:len(reponame)-5]
  168. }
  169. repoUser, err := models.GetUserByName(username)
  170. if err != nil {
  171. if models.IsErrUserNotExist(err) {
  172. fail("Repository owner does not exist", "Unregistered owner: %s", username)
  173. }
  174. fail("Internal error", "Failed to get repository owner (%s): %v", username, err)
  175. }
  176. repo, err := models.GetRepositoryByName(repoUser.ID, reponame)
  177. if err != nil {
  178. if models.IsErrRepoNotExist(err) {
  179. fail(accessDenied, "Repository does not exist: %s/%s", repoUser.Name, reponame)
  180. }
  181. fail("Internal error", "Failed to get repository: %v", err)
  182. }
  183. requestedMode, has := allowedCommands[verb]
  184. if !has {
  185. fail("Unknown git command", "Unknown git command %s", verb)
  186. }
  187. if verb == lfsAuthenticateVerb {
  188. if lfsVerb == "upload" {
  189. requestedMode = models.AccessModeWrite
  190. } else {
  191. requestedMode = models.AccessModeRead
  192. }
  193. }
  194. // Prohibit push to mirror repositories.
  195. if requestedMode > models.AccessModeRead && repo.IsMirror {
  196. fail("mirror repository is read-only", "")
  197. }
  198. // Allow anonymous clone for public repositories.
  199. var (
  200. keyID int64
  201. user *models.User
  202. )
  203. if requestedMode == models.AccessModeWrite || repo.IsPrivate {
  204. keys := strings.Split(c.Args()[0], "-")
  205. if len(keys) != 2 {
  206. fail("Key ID format error", "Invalid key argument: %s", c.Args()[0])
  207. }
  208. key, err := models.GetPublicKeyByID(com.StrTo(keys[1]).MustInt64())
  209. if err != nil {
  210. fail("Invalid key ID", "Invalid key ID[%s]: %v", c.Args()[0], err)
  211. }
  212. keyID = key.ID
  213. // Check deploy key or user key.
  214. if key.Type == models.KeyTypeDeploy {
  215. if key.Mode < requestedMode {
  216. fail("Key permission denied", "Cannot push with deployment key: %d", key.ID)
  217. }
  218. // Check if this deploy key belongs to current repository.
  219. if !models.HasDeployKey(key.ID, repo.ID) {
  220. fail("Key access denied", "Deploy key access denied: [key_id: %d, repo_id: %d]", key.ID, repo.ID)
  221. }
  222. // Update deploy key activity.
  223. deployKey, err := models.GetDeployKeyByRepo(key.ID, repo.ID)
  224. if err != nil {
  225. fail("Internal error", "GetDeployKey: %v", err)
  226. }
  227. deployKey.Updated = time.Now()
  228. if err = models.UpdateDeployKey(deployKey); err != nil {
  229. fail("Internal error", "UpdateDeployKey: %v", err)
  230. }
  231. } else {
  232. user, err = models.GetUserByKeyID(key.ID)
  233. if err != nil {
  234. fail("internal error", "Failed to get user by key ID(%d): %v", keyID, err)
  235. }
  236. mode, err := models.AccessLevel(user, repo)
  237. if err != nil {
  238. fail("Internal error", "Failed to check access: %v", err)
  239. } else if mode < requestedMode {
  240. clientMessage := accessDenied
  241. if mode >= models.AccessModeRead {
  242. clientMessage = "You do not have sufficient authorization for this action"
  243. }
  244. fail(clientMessage,
  245. "User %s does not have level %v access to repository %s",
  246. user.Name, requestedMode, repoPath)
  247. }
  248. os.Setenv("GITEA_PUSHER_NAME", user.Name)
  249. }
  250. }
  251. //LFS token authentication
  252. if verb == lfsAuthenticateVerb {
  253. url := fmt.Sprintf("%s%s/%s.git/info/lfs", setting.AppURL, repoUser.Name, repo.Name)
  254. now := time.Now()
  255. token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
  256. "repo": repo.ID,
  257. "op": lfsVerb,
  258. "exp": now.Add(5 * time.Minute).Unix(),
  259. "nbf": now.Unix(),
  260. })
  261. // Sign and get the complete encoded token as a string using the secret
  262. tokenString, err := token.SignedString(setting.LFS.JWTSecretBytes)
  263. if err != nil {
  264. fail("Internal error", "Failed to sign JWT token: %v", err)
  265. }
  266. tokenAuthentication := &models.LFSTokenResponse{
  267. Header: make(map[string]string),
  268. Href: url,
  269. }
  270. tokenAuthentication.Header["Authorization"] = fmt.Sprintf("Bearer %s", tokenString)
  271. enc := json.NewEncoder(os.Stdout)
  272. err = enc.Encode(tokenAuthentication)
  273. if err != nil {
  274. fail("Internal error", "Failed to encode LFS json response: %v", err)
  275. }
  276. return nil
  277. }
  278. uuid := gouuid.NewV4().String()
  279. os.Setenv("GITEA_UUID", uuid)
  280. // Keep the old env variable name for backward compability
  281. os.Setenv("uuid", uuid)
  282. // Special handle for Windows.
  283. if setting.IsWindows {
  284. verb = strings.Replace(verb, "-", " ", 1)
  285. }
  286. var gitcmd *exec.Cmd
  287. verbs := strings.Split(verb, " ")
  288. if len(verbs) == 2 {
  289. gitcmd = exec.Command(verbs[0], verbs[1], repoPath)
  290. } else {
  291. gitcmd = exec.Command(verb, repoPath)
  292. }
  293. os.Setenv(models.ProtectedBranchAccessMode, requestedMode.String())
  294. os.Setenv(models.ProtectedBranchRepoID, fmt.Sprintf("%d", repo.ID))
  295. gitcmd.Dir = setting.RepoRootPath
  296. gitcmd.Stdout = os.Stdout
  297. gitcmd.Stdin = os.Stdin
  298. gitcmd.Stderr = os.Stderr
  299. if err = gitcmd.Run(); err != nil {
  300. fail("Internal error", "Failed to execute git command: %v", err)
  301. }
  302. if requestedMode == models.AccessModeWrite {
  303. handleUpdateTask(uuid, user, repoUser, reponame, isWiki)
  304. }
  305. // Update user key activity.
  306. if keyID > 0 {
  307. key, err := models.GetPublicKeyByID(keyID)
  308. if err != nil {
  309. fail("Internal error", "GetPublicKeyById: %v", err)
  310. }
  311. key.Updated = time.Now()
  312. if err = models.UpdatePublicKey(key); err != nil {
  313. fail("Internal error", "UpdatePublicKey: %v", err)
  314. }
  315. }
  316. return nil
  317. }