repo_editor.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. // Copyright 2016 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 database
  5. import (
  6. "fmt"
  7. "io"
  8. "mime/multipart"
  9. "os"
  10. "os/exec"
  11. "path"
  12. "path/filepath"
  13. "strings"
  14. "time"
  15. "github.com/pkg/errors"
  16. gouuid "github.com/satori/go.uuid"
  17. "github.com/unknwon/com"
  18. "github.com/gogs/git-module"
  19. "gogs.io/gogs/internal/conf"
  20. "gogs.io/gogs/internal/cryptoutil"
  21. dberrors "gogs.io/gogs/internal/database/errors"
  22. "gogs.io/gogs/internal/gitutil"
  23. "gogs.io/gogs/internal/osutil"
  24. "gogs.io/gogs/internal/pathutil"
  25. "gogs.io/gogs/internal/process"
  26. "gogs.io/gogs/internal/tool"
  27. )
  28. const (
  29. EnvAuthUserID = "GOGS_AUTH_USER_ID"
  30. EnvAuthUserName = "GOGS_AUTH_USER_NAME"
  31. EnvAuthUserEmail = "GOGS_AUTH_USER_EMAIL"
  32. EnvRepoOwnerName = "GOGS_REPO_OWNER_NAME"
  33. EnvRepoOwnerSaltMd5 = "GOGS_REPO_OWNER_SALT_MD5"
  34. EnvRepoID = "GOGS_REPO_ID"
  35. EnvRepoName = "GOGS_REPO_NAME"
  36. EnvRepoCustomHooksPath = "GOGS_REPO_CUSTOM_HOOKS_PATH"
  37. )
  38. type ComposeHookEnvsOptions struct {
  39. AuthUser *User
  40. OwnerName string
  41. OwnerSalt string
  42. RepoID int64
  43. RepoName string
  44. RepoPath string
  45. }
  46. func ComposeHookEnvs(opts ComposeHookEnvsOptions) []string {
  47. envs := []string{
  48. "SSH_ORIGINAL_COMMAND=1",
  49. EnvAuthUserID + "=" + com.ToStr(opts.AuthUser.ID),
  50. EnvAuthUserName + "=" + opts.AuthUser.Name,
  51. EnvAuthUserEmail + "=" + opts.AuthUser.Email,
  52. EnvRepoOwnerName + "=" + opts.OwnerName,
  53. EnvRepoOwnerSaltMd5 + "=" + cryptoutil.MD5(opts.OwnerSalt),
  54. EnvRepoID + "=" + com.ToStr(opts.RepoID),
  55. EnvRepoName + "=" + opts.RepoName,
  56. EnvRepoCustomHooksPath + "=" + filepath.Join(opts.RepoPath, "custom_hooks"),
  57. }
  58. return envs
  59. }
  60. // ___________ .___.__ __ ___________.__.__
  61. // \_ _____/ __| _/|__|/ |_ \_ _____/|__| | ____
  62. // | __)_ / __ | | \ __\ | __) | | | _/ __ \
  63. // | \/ /_/ | | || | | \ | | |_\ ___/
  64. // /_______ /\____ | |__||__| \___ / |__|____/\___ >
  65. // \/ \/ \/ \/
  66. // discardLocalRepoBranchChanges discards local commits/changes of
  67. // given branch to make sure it is even to remote branch.
  68. func discardLocalRepoBranchChanges(localPath, branch string) error {
  69. if !com.IsExist(localPath) {
  70. return nil
  71. }
  72. // No need to check if nothing in the repository.
  73. if !git.RepoHasBranch(localPath, branch) {
  74. return nil
  75. }
  76. rev := "origin/" + branch
  77. if err := git.Reset(localPath, rev, git.ResetOptions{Hard: true}); err != nil {
  78. return fmt.Errorf("reset [revision: %s]: %v", rev, err)
  79. }
  80. return nil
  81. }
  82. func (r *Repository) DiscardLocalRepoBranchChanges(branch string) error {
  83. return discardLocalRepoBranchChanges(r.LocalCopyPath(), branch)
  84. }
  85. // CheckoutNewBranch checks out to a new branch from the a branch name.
  86. func (r *Repository) CheckoutNewBranch(oldBranch, newBranch string) error {
  87. if err := git.Checkout(r.LocalCopyPath(), newBranch, git.CheckoutOptions{
  88. BaseBranch: oldBranch,
  89. Timeout: time.Duration(conf.Git.Timeout.Pull) * time.Second,
  90. }); err != nil {
  91. return fmt.Errorf("checkout [base: %s, new: %s]: %v", oldBranch, newBranch, err)
  92. }
  93. return nil
  94. }
  95. // hasSymlinkInPath returns true if there is any symlink in path hierarchy using
  96. // the given base and relative path.
  97. func hasSymlinkInPath(base, relPath string) bool {
  98. parts := strings.Split(filepath.ToSlash(relPath), "/")
  99. for i := range parts {
  100. filePath := path.Join(append([]string{base}, parts[:i+1]...)...)
  101. if osutil.IsSymlink(filePath) {
  102. return true
  103. }
  104. }
  105. return false
  106. }
  107. type UpdateRepoFileOptions struct {
  108. OldBranch string
  109. NewBranch string
  110. OldTreeName string
  111. NewTreeName string
  112. Message string
  113. Content string
  114. IsNewFile bool
  115. }
  116. // UpdateRepoFile adds or updates a file in repository.
  117. func (r *Repository) UpdateRepoFile(doer *User, opts UpdateRepoFileOptions) error {
  118. // 🚨 SECURITY: Prevent uploading files into the ".git" directory.
  119. if isRepositoryGitPath(opts.NewTreeName) {
  120. return errors.Errorf("bad tree path %q", opts.NewTreeName)
  121. }
  122. repoWorkingPool.CheckIn(com.ToStr(r.ID))
  123. defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
  124. if err := r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  125. return fmt.Errorf("discard local repo branch[%s] changes: %v", opts.OldBranch, err)
  126. } else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  127. return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
  128. }
  129. localPath := r.LocalCopyPath()
  130. // 🚨 SECURITY: Prevent touching files in surprising places, reject operations
  131. // that involve symlinks.
  132. if hasSymlinkInPath(localPath, opts.OldTreeName) || hasSymlinkInPath(localPath, opts.NewTreeName) {
  133. return errors.New("cannot update file with symbolic link in path")
  134. }
  135. repoPath := r.RepoPath()
  136. if opts.OldBranch != opts.NewBranch {
  137. // Directly return error if new branch already exists in the server
  138. if git.RepoHasBranch(repoPath, opts.NewBranch) {
  139. return dberrors.BranchAlreadyExists{Name: opts.NewBranch}
  140. }
  141. // Otherwise, delete branch from local copy in case out of sync
  142. if git.RepoHasBranch(localPath, opts.NewBranch) {
  143. if err := git.DeleteBranch(localPath, opts.NewBranch, git.DeleteBranchOptions{
  144. Force: true,
  145. }); err != nil {
  146. return fmt.Errorf("delete branch %q: %v", opts.NewBranch, err)
  147. }
  148. }
  149. if err := r.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  150. return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
  151. }
  152. }
  153. oldFilePath := path.Join(localPath, opts.OldTreeName)
  154. newFilePath := path.Join(localPath, opts.NewTreeName)
  155. // Prompt the user if the meant-to-be new file already exists.
  156. if osutil.IsExist(newFilePath) && opts.IsNewFile {
  157. return ErrRepoFileAlreadyExist{newFilePath}
  158. }
  159. if err := os.MkdirAll(path.Dir(newFilePath), os.ModePerm); err != nil {
  160. return errors.Wrapf(err, "create parent directories of %q", newFilePath)
  161. }
  162. if osutil.IsFile(oldFilePath) && opts.OldTreeName != opts.NewTreeName {
  163. if err := git.Move(localPath, opts.OldTreeName, opts.NewTreeName); err != nil {
  164. return errors.Wrapf(err, "git mv %q %q", opts.OldTreeName, opts.NewTreeName)
  165. }
  166. }
  167. if err := os.WriteFile(newFilePath, []byte(opts.Content), 0o600); err != nil {
  168. return fmt.Errorf("write file: %v", err)
  169. }
  170. if err := git.Add(localPath, git.AddOptions{All: true}); err != nil {
  171. return fmt.Errorf("git add --all: %v", err)
  172. }
  173. err := git.CreateCommit(
  174. localPath,
  175. &git.Signature{
  176. Name: doer.DisplayName(),
  177. Email: doer.Email,
  178. When: time.Now(),
  179. },
  180. opts.Message,
  181. )
  182. if err != nil {
  183. return fmt.Errorf("commit changes on %q: %v", localPath, err)
  184. }
  185. err = git.Push(localPath, "origin", opts.NewBranch,
  186. git.PushOptions{
  187. CommandOptions: git.CommandOptions{
  188. Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
  189. AuthUser: doer,
  190. OwnerName: r.MustOwner().Name,
  191. OwnerSalt: r.MustOwner().Salt,
  192. RepoID: r.ID,
  193. RepoName: r.Name,
  194. RepoPath: r.RepoPath(),
  195. }),
  196. },
  197. },
  198. )
  199. if err != nil {
  200. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  201. }
  202. return nil
  203. }
  204. // GetDiffPreview produces and returns diff result of a file which is not yet committed.
  205. func (r *Repository) GetDiffPreview(branch, treePath, content string) (*gitutil.Diff, error) {
  206. // 🚨 SECURITY: Prevent uploading files into the ".git" directory.
  207. if isRepositoryGitPath(treePath) {
  208. return nil, errors.Errorf("bad tree path %q", treePath)
  209. }
  210. repoWorkingPool.CheckIn(com.ToStr(r.ID))
  211. defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
  212. if err := r.DiscardLocalRepoBranchChanges(branch); err != nil {
  213. return nil, fmt.Errorf("discard local repo branch[%s] changes: %v", branch, err)
  214. } else if err = r.UpdateLocalCopyBranch(branch); err != nil {
  215. return nil, fmt.Errorf("update local copy branch[%s]: %v", branch, err)
  216. }
  217. localPath := r.LocalCopyPath()
  218. filePath := path.Join(localPath, treePath)
  219. // 🚨 SECURITY: Prevent touching files in surprising places, reject operations
  220. // that involve symlinks.
  221. if hasSymlinkInPath(localPath, treePath) {
  222. return nil, errors.New("cannot update file with symbolic link in path")
  223. }
  224. if err := os.MkdirAll(path.Dir(filePath), os.ModePerm); err != nil {
  225. return nil, errors.Wrap(err, "create parent directories")
  226. } else if err = os.WriteFile(filePath, []byte(content), 0o600); err != nil {
  227. return nil, fmt.Errorf("write file: %v", err)
  228. }
  229. // 🚨 SECURITY: Prevent including unintended options in the path to the Git command.
  230. cmd := exec.Command("git", "diff", "--end-of-options", treePath)
  231. cmd.Dir = localPath
  232. cmd.Stderr = os.Stderr
  233. stdout, err := cmd.StdoutPipe()
  234. if err != nil {
  235. return nil, fmt.Errorf("get stdout pipe: %v", err)
  236. }
  237. if err = cmd.Start(); err != nil {
  238. return nil, fmt.Errorf("start: %v", err)
  239. }
  240. pid := process.Add(fmt.Sprintf("GetDiffPreview [repo_path: %s]", r.RepoPath()), cmd)
  241. defer process.Remove(pid)
  242. diff, err := gitutil.ParseDiff(stdout, conf.Git.MaxDiffFiles, conf.Git.MaxDiffLines, conf.Git.MaxDiffLineChars)
  243. if err != nil {
  244. return nil, fmt.Errorf("parse diff: %v", err)
  245. }
  246. if err = cmd.Wait(); err != nil {
  247. return nil, fmt.Errorf("wait: %v", err)
  248. }
  249. return diff, nil
  250. }
  251. // ________ .__ __ ___________.__.__
  252. // \______ \ ____ | | _____/ |_ ____ \_ _____/|__| | ____
  253. // | | \_/ __ \| | _/ __ \ __\/ __ \ | __) | | | _/ __ \
  254. // | ` \ ___/| |_\ ___/| | \ ___/ | \ | | |_\ ___/
  255. // /_______ /\___ >____/\___ >__| \___ > \___ / |__|____/\___ >
  256. // \/ \/ \/ \/ \/ \/
  257. //
  258. type DeleteRepoFileOptions struct {
  259. LastCommitID string
  260. OldBranch string
  261. NewBranch string
  262. TreePath string
  263. Message string
  264. }
  265. func (r *Repository) DeleteRepoFile(doer *User, opts DeleteRepoFileOptions) (err error) {
  266. // 🚨 SECURITY: Prevent uploading files into the ".git" directory.
  267. if isRepositoryGitPath(opts.TreePath) {
  268. return errors.Errorf("bad tree path %q", opts.TreePath)
  269. }
  270. repoWorkingPool.CheckIn(com.ToStr(r.ID))
  271. defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
  272. if err = r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  273. return fmt.Errorf("discard local r branch[%s] changes: %v", opts.OldBranch, err)
  274. } else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  275. return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
  276. }
  277. localPath := r.LocalCopyPath()
  278. // 🚨 SECURITY: Prevent touching files in surprising places, reject operations
  279. // that involve symlinks.
  280. if hasSymlinkInPath(localPath, opts.TreePath) {
  281. return errors.New("cannot update file with symbolic link in path")
  282. }
  283. if opts.OldBranch != opts.NewBranch {
  284. if err := r.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  285. return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
  286. }
  287. }
  288. filePath := path.Join(localPath, opts.TreePath)
  289. if err = os.Remove(filePath); err != nil {
  290. return fmt.Errorf("remove file %q: %v", opts.TreePath, err)
  291. }
  292. if err = git.Add(localPath, git.AddOptions{All: true}); err != nil {
  293. return fmt.Errorf("git add --all: %v", err)
  294. }
  295. err = git.CreateCommit(
  296. localPath,
  297. &git.Signature{
  298. Name: doer.DisplayName(),
  299. Email: doer.Email,
  300. When: time.Now(),
  301. },
  302. opts.Message,
  303. )
  304. if err != nil {
  305. return fmt.Errorf("commit changes to %q: %v", localPath, err)
  306. }
  307. err = git.Push(localPath, "origin", opts.NewBranch,
  308. git.PushOptions{
  309. CommandOptions: git.CommandOptions{
  310. Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
  311. AuthUser: doer,
  312. OwnerName: r.MustOwner().Name,
  313. OwnerSalt: r.MustOwner().Salt,
  314. RepoID: r.ID,
  315. RepoName: r.Name,
  316. RepoPath: r.RepoPath(),
  317. }),
  318. },
  319. },
  320. )
  321. if err != nil {
  322. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  323. }
  324. return nil
  325. }
  326. // ____ ___ .__ .___ ___________.___.__
  327. // | | \______ | | _________ __| _/ \_ _____/| | | ____ ______
  328. // | | /\____ \| | / _ \__ \ / __ | | __) | | | _/ __ \ / ___/
  329. // | | / | |_> > |_( <_> ) __ \_/ /_/ | | \ | | |_\ ___/ \___ \
  330. // |______/ | __/|____/\____(____ /\____ | \___ / |___|____/\___ >____ >
  331. // |__| \/ \/ \/ \/ \/
  332. //
  333. // Upload represent a uploaded file to a repo to be deleted when moved
  334. type Upload struct {
  335. ID int64
  336. UUID string `xorm:"uuid UNIQUE"`
  337. Name string
  338. }
  339. // UploadLocalPath returns where uploads is stored in local file system based on given UUID.
  340. func UploadLocalPath(uuid string) string {
  341. return path.Join(conf.Repository.Upload.TempPath, uuid[0:1], uuid[1:2], uuid)
  342. }
  343. // LocalPath returns where uploads are temporarily stored in local file system.
  344. func (upload *Upload) LocalPath() string {
  345. return UploadLocalPath(upload.UUID)
  346. }
  347. // NewUpload creates a new upload object.
  348. func NewUpload(name string, buf []byte, file multipart.File) (_ *Upload, err error) {
  349. if tool.IsMaliciousPath(name) {
  350. return nil, fmt.Errorf("malicious path detected: %s", name)
  351. }
  352. upload := &Upload{
  353. UUID: gouuid.NewV4().String(),
  354. Name: name,
  355. }
  356. localPath := upload.LocalPath()
  357. if err = os.MkdirAll(path.Dir(localPath), os.ModePerm); err != nil {
  358. return nil, fmt.Errorf("mkdir all: %v", err)
  359. }
  360. fw, err := os.Create(localPath)
  361. if err != nil {
  362. return nil, fmt.Errorf("create: %v", err)
  363. }
  364. defer func() { _ = fw.Close() }()
  365. if _, err = fw.Write(buf); err != nil {
  366. return nil, fmt.Errorf("write: %v", err)
  367. } else if _, err = io.Copy(fw, file); err != nil {
  368. return nil, fmt.Errorf("copy: %v", err)
  369. }
  370. if _, err := x.Insert(upload); err != nil {
  371. return nil, err
  372. }
  373. return upload, nil
  374. }
  375. func GetUploadByUUID(uuid string) (*Upload, error) {
  376. upload := &Upload{UUID: uuid}
  377. has, err := x.Get(upload)
  378. if err != nil {
  379. return nil, err
  380. } else if !has {
  381. return nil, ErrUploadNotExist{0, uuid}
  382. }
  383. return upload, nil
  384. }
  385. func GetUploadsByUUIDs(uuids []string) ([]*Upload, error) {
  386. if len(uuids) == 0 {
  387. return []*Upload{}, nil
  388. }
  389. // Silently drop invalid uuids.
  390. uploads := make([]*Upload, 0, len(uuids))
  391. return uploads, x.In("uuid", uuids).Find(&uploads)
  392. }
  393. func DeleteUploads(uploads ...*Upload) (err error) {
  394. if len(uploads) == 0 {
  395. return nil
  396. }
  397. sess := x.NewSession()
  398. defer sess.Close()
  399. if err = sess.Begin(); err != nil {
  400. return err
  401. }
  402. ids := make([]int64, len(uploads))
  403. for i := 0; i < len(uploads); i++ {
  404. ids[i] = uploads[i].ID
  405. }
  406. if _, err = sess.In("id", ids).Delete(new(Upload)); err != nil {
  407. return fmt.Errorf("delete uploads: %v", err)
  408. }
  409. for _, upload := range uploads {
  410. localPath := upload.LocalPath()
  411. if !osutil.IsFile(localPath) {
  412. continue
  413. }
  414. if err := os.Remove(localPath); err != nil {
  415. return fmt.Errorf("remove upload: %v", err)
  416. }
  417. }
  418. return sess.Commit()
  419. }
  420. func DeleteUpload(u *Upload) error {
  421. return DeleteUploads(u)
  422. }
  423. func DeleteUploadByUUID(uuid string) error {
  424. upload, err := GetUploadByUUID(uuid)
  425. if err != nil {
  426. if IsErrUploadNotExist(err) {
  427. return nil
  428. }
  429. return fmt.Errorf("get upload by UUID[%s]: %v", uuid, err)
  430. }
  431. if err := DeleteUpload(upload); err != nil {
  432. return fmt.Errorf("delete upload: %v", err)
  433. }
  434. return nil
  435. }
  436. type UploadRepoFileOptions struct {
  437. LastCommitID string
  438. OldBranch string
  439. NewBranch string
  440. TreePath string
  441. Message string
  442. Files []string // In UUID format
  443. }
  444. // isRepositoryGitPath returns true if given path is or resides inside ".git"
  445. // path of the repository.
  446. //
  447. // TODO(unknwon): Move to repoutil during refactoring for this file.
  448. func isRepositoryGitPath(path string) bool {
  449. path = strings.ToLower(path)
  450. return strings.HasSuffix(path, ".git") ||
  451. strings.Contains(path, ".git/") ||
  452. strings.Contains(path, `.git\`) ||
  453. // Windows treats ".git." the same as ".git"
  454. strings.HasSuffix(path, ".git.") ||
  455. strings.Contains(path, ".git./") ||
  456. strings.Contains(path, `.git.\`)
  457. }
  458. func (r *Repository) UploadRepoFiles(doer *User, opts UploadRepoFileOptions) error {
  459. if len(opts.Files) == 0 {
  460. return nil
  461. }
  462. // 🚨 SECURITY: Prevent uploading files into the ".git" directory.
  463. if isRepositoryGitPath(opts.TreePath) {
  464. return errors.Errorf("bad tree path %q", opts.TreePath)
  465. }
  466. uploads, err := GetUploadsByUUIDs(opts.Files)
  467. if err != nil {
  468. return fmt.Errorf("get uploads by UUIDs[%v]: %v", opts.Files, err)
  469. }
  470. repoWorkingPool.CheckIn(com.ToStr(r.ID))
  471. defer repoWorkingPool.CheckOut(com.ToStr(r.ID))
  472. if err = r.DiscardLocalRepoBranchChanges(opts.OldBranch); err != nil {
  473. return fmt.Errorf("discard local r branch[%s] changes: %v", opts.OldBranch, err)
  474. } else if err = r.UpdateLocalCopyBranch(opts.OldBranch); err != nil {
  475. return fmt.Errorf("update local copy branch[%s]: %v", opts.OldBranch, err)
  476. }
  477. if opts.OldBranch != opts.NewBranch {
  478. if err = r.CheckoutNewBranch(opts.OldBranch, opts.NewBranch); err != nil {
  479. return fmt.Errorf("checkout new branch[%s] from old branch[%s]: %v", opts.NewBranch, opts.OldBranch, err)
  480. }
  481. }
  482. localPath := r.LocalCopyPath()
  483. dirPath := path.Join(localPath, opts.TreePath)
  484. if err = os.MkdirAll(dirPath, os.ModePerm); err != nil {
  485. return err
  486. }
  487. // Copy uploaded files into repository
  488. for _, upload := range uploads {
  489. tmpPath := upload.LocalPath()
  490. if !osutil.IsFile(tmpPath) {
  491. continue
  492. }
  493. // 🚨 SECURITY: Prevent path traversal.
  494. upload.Name = pathutil.Clean(upload.Name)
  495. // 🚨 SECURITY: Prevent uploading files into the ".git" directory.
  496. if isRepositoryGitPath(upload.Name) {
  497. continue
  498. }
  499. targetPath := path.Join(dirPath, upload.Name)
  500. // 🚨 SECURITY: Prevent updating files in surprising place, check if the target
  501. // is a symlink.
  502. if osutil.IsSymlink(targetPath) {
  503. return fmt.Errorf("cannot overwrite symbolic link: %s", upload.Name)
  504. }
  505. if err = com.Copy(tmpPath, targetPath); err != nil {
  506. return fmt.Errorf("copy: %v", err)
  507. }
  508. }
  509. if err = git.Add(localPath, git.AddOptions{All: true}); err != nil {
  510. return fmt.Errorf("git add --all: %v", err)
  511. }
  512. err = git.CreateCommit(
  513. localPath,
  514. &git.Signature{
  515. Name: doer.DisplayName(),
  516. Email: doer.Email,
  517. When: time.Now(),
  518. },
  519. opts.Message,
  520. )
  521. if err != nil {
  522. return fmt.Errorf("commit changes on %q: %v", localPath, err)
  523. }
  524. err = git.Push(localPath, "origin", opts.NewBranch,
  525. git.PushOptions{
  526. CommandOptions: git.CommandOptions{
  527. Envs: ComposeHookEnvs(ComposeHookEnvsOptions{
  528. AuthUser: doer,
  529. OwnerName: r.MustOwner().Name,
  530. OwnerSalt: r.MustOwner().Salt,
  531. RepoID: r.ID,
  532. RepoName: r.Name,
  533. RepoPath: r.RepoPath(),
  534. }),
  535. },
  536. },
  537. )
  538. if err != nil {
  539. return fmt.Errorf("git push origin %s: %v", opts.NewBranch, err)
  540. }
  541. return DeleteUploads(uploads...)
  542. }