repo_editor.go 19 KB

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