repo_editor.go 19 KB

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