diff --git a/models/migrations/v1_12/v128.go b/models/migrations/v1_12/v128.go index 44d44a26c549f..85a524f347cea 100644 --- a/models/migrations/v1_12/v128.go +++ b/models/migrations/v1_12/v128.go @@ -85,14 +85,14 @@ func FixMergeBase(x *xorm.Engine) error { pr.MergeBase, _, err = git.NewCommand(git.DefaultContext, "merge-base").AddDashesAndList(pr.BaseBranch, gitRefName).RunStdString(&git.RunOpts{Dir: repoPath}) if err != nil { var err2 error - pr.MergeBase, _, err2 = git.NewCommand(git.DefaultContext, "rev-parse").AddDynamicArguments(git.BranchPrefix + pr.BaseBranch).RunStdString(&git.RunOpts{Dir: repoPath}) + pr.MergeBase, _, err2 = git.NewCommand(git.DefaultContext, "rev-parse").AddUntrustedArguments(git.BranchPrefix + pr.BaseBranch).RunStdString(&git.RunOpts{Dir: repoPath}) if err2 != nil { log.Error("Unable to get merge base for PR ID %d, Index %d in %s/%s. Error: %v & %v", pr.ID, pr.Index, baseRepo.OwnerName, baseRepo.Name, err, err2) continue } } } else { - parentsString, _, err := git.NewCommand(git.DefaultContext, "rev-list", "--parents", "-n", "1").AddDynamicArguments(pr.MergedCommitID).RunStdString(&git.RunOpts{Dir: repoPath}) + parentsString, _, err := git.NewCommand(git.DefaultContext, "rev-list", "--parents", "-n", "1").AddUntrustedArguments(pr.MergedCommitID).RunStdString(&git.RunOpts{Dir: repoPath}) if err != nil { log.Error("Unable to get parents for merged PR ID %d, Index %d in %s/%s. Error: %v", pr.ID, pr.Index, baseRepo.OwnerName, baseRepo.Name, err) continue diff --git a/models/migrations/v1_12/v134.go b/models/migrations/v1_12/v134.go index 3d1c82f09e164..ebd252eb72ec8 100644 --- a/models/migrations/v1_12/v134.go +++ b/models/migrations/v1_12/v134.go @@ -79,7 +79,7 @@ func RefixMergeBase(x *xorm.Engine) error { gitRefName := fmt.Sprintf("refs/pull/%d/head", pr.Index) - parentsString, _, err := git.NewCommand(git.DefaultContext, "rev-list", "--parents", "-n", "1").AddDynamicArguments(pr.MergedCommitID).RunStdString(&git.RunOpts{Dir: repoPath}) + parentsString, _, err := git.NewCommand(git.DefaultContext, "rev-list", "--parents", "-n", "1").AddUntrustedArguments(pr.MergedCommitID).RunStdString(&git.RunOpts{Dir: repoPath}) if err != nil { log.Error("Unable to get parents for merged PR ID %d, Index %d in %s/%s. Error: %v", pr.ID, pr.Index, baseRepo.OwnerName, baseRepo.Name, err) continue diff --git a/modules/doctor/mergebase.go b/modules/doctor/mergebase.go index e79369e581c1e..5aa3654c60db8 100644 --- a/modules/doctor/mergebase.go +++ b/modules/doctor/mergebase.go @@ -45,14 +45,14 @@ func checkPRMergeBase(ctx context.Context, logger log.Logger, autofix bool) erro pr.MergeBase, _, err = git.NewCommand(ctx, "merge-base").AddDashesAndList(pr.BaseBranch, pr.GetGitRefName()).RunStdString(&git.RunOpts{Dir: repoPath}) if err != nil { var err2 error - pr.MergeBase, _, err2 = git.NewCommand(ctx, "rev-parse").AddDynamicArguments(git.BranchPrefix + pr.BaseBranch).RunStdString(&git.RunOpts{Dir: repoPath}) + pr.MergeBase, _, err2 = git.NewCommand(ctx, "rev-parse").AddUntrustedArguments(git.BranchPrefix + pr.BaseBranch).RunStdString(&git.RunOpts{Dir: repoPath}) if err2 != nil { logger.Warn("Unable to get merge base for PR ID %d, #%d onto %s in %s/%s. Error: %v & %v", pr.ID, pr.Index, pr.BaseBranch, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, err, err2) return nil } } } else { - parentsString, _, err := git.NewCommand(ctx, "rev-list", "--parents", "-n", "1").AddDynamicArguments(pr.MergedCommitID).RunStdString(&git.RunOpts{Dir: repoPath}) + parentsString, _, err := git.NewCommand(ctx, "rev-list", "--parents", "-n", "1").AddUntrustedArguments(pr.MergedCommitID).RunStdString(&git.RunOpts{Dir: repoPath}) if err != nil { logger.Warn("Unable to get parents for merged PR ID %d, #%d onto %s in %s/%s. Error: %v", pr.ID, pr.Index, pr.BaseBranch, pr.BaseRepo.OwnerName, pr.BaseRepo.Name, err) return nil diff --git a/modules/git/blame.go b/modules/git/blame.go index 3b6e4c95db9f9..08516bc169b93 100644 --- a/modules/git/blame.go +++ b/modules/git/blame.go @@ -104,7 +104,7 @@ func (r *BlameReader) Close() error { // CreateBlameReader creates reader for given repository, commit and file func CreateBlameReader(ctx context.Context, repoPath, commitID, file string) (*BlameReader, error) { cmd := NewCommandContextNoGlobals(ctx, "blame", "--porcelain"). - AddDynamicArguments(commitID). + AddUntrustedArguments(commitID). AddDashesAndList(file). SetDescription(fmt.Sprintf("GetBlame [repo_path: %s]", repoPath)) reader, stdout, err := os.Pipe() diff --git a/modules/git/command.go b/modules/git/command.go index d88fcd1a8c807..30544eb60723e 100644 --- a/modules/git/command.go +++ b/modules/git/command.go @@ -52,7 +52,7 @@ func (c *Command) String() string { } // NewCommand creates and returns a new Git Command based on given command and arguments. -// Each argument should be safe to be trusted. User-provided arguments should be passed to AddDynamicArguments instead. +// Each argument should be safe to be trusted. User-provided arguments should be passed to AddUntrustedArguments instead. func NewCommand(ctx context.Context, args ...CmdArg) *Command { // Make an explicit copy of globalCommandArgs, otherwise append might overwrite it cargs := make([]string, 0, len(globalCommandArgs)+len(args)) @@ -71,13 +71,13 @@ func NewCommand(ctx context.Context, args ...CmdArg) *Command { } // NewCommandNoGlobals creates and returns a new Git Command based on given command and arguments only with the specify args and don't care global command args -// Each argument should be safe to be trusted. User-provided arguments should be passed to AddDynamicArguments instead. +// Each argument should be safe to be trusted. User-provided arguments should be passed to AddUntrustedArguments instead. func NewCommandNoGlobals(args ...CmdArg) *Command { return NewCommandContextNoGlobals(DefaultContext, args...) } // NewCommandContextNoGlobals creates and returns a new Git Command based on given command and arguments only with the specify args and don't care global command args -// Each argument should be safe to be trusted. User-provided arguments should be passed to AddDynamicArguments instead. +// Each argument should be safe to be trusted. User-provided arguments should be passed to AddUntrustedArguments instead. func NewCommandContextNoGlobals(ctx context.Context, args ...CmdArg) *Command { cargs := make([]string, 0, len(args)) for _, arg := range args { @@ -103,18 +103,19 @@ func (c *Command) SetDescription(desc string) *Command { return c } -// AddArguments adds new git argument(s) to the command. Each argument must be safe to be trusted. -// User-provided arguments should be passed to AddDynamicArguments instead. -func (c *Command) AddArguments(args ...CmdArg) *Command { +// AddTrustedArguments adds new git argument(s) to the command. +// Each argument must be safe to be trusted, so only string literals should be passed. +// User-provided arguments should be passed to AddUntrustedArguments instead. +func (c *Command) AddTrustedArguments(args ...CmdArg) *Command { for _, arg := range args { c.args = append(c.args, string(arg)) } return c } -// AddDynamicArguments adds new dynamic argument(s) to the command. -// The arguments may come from user input and can not be trusted, so no leading '-' is allowed to avoid passing options -func (c *Command) AddDynamicArguments(args ...string) *Command { +// AddUntrustedArguments adds new argument(s) to the command. +// The arguments should be user-supplied and hence cannot be trusted, so no leading '-' is allowed to avoid passing options +func (c *Command) AddUntrustedArguments(args ...string) *Command { for _, arg := range args { if arg != "" && arg[0] == '-' { c.brokenArgs = append(c.brokenArgs, arg) diff --git a/modules/git/command_test.go b/modules/git/command_test.go index 2dca2d0d344d0..e4d92d48f4277 100644 --- a/modules/git/command_test.go +++ b/modules/git/command_test.go @@ -27,15 +27,15 @@ func TestRunWithContextStd(t *testing.T) { } cmd = NewCommand(context.Background()) - cmd.AddDynamicArguments("-test") + cmd.AddUntrustedArguments("-test") assert.ErrorIs(t, cmd.Run(&RunOpts{}), ErrBrokenCommand) cmd = NewCommand(context.Background()) - cmd.AddDynamicArguments("--test") + cmd.AddUntrustedArguments("--test") assert.ErrorIs(t, cmd.Run(&RunOpts{}), ErrBrokenCommand) subCmd := "version" - cmd = NewCommand(context.Background()).AddDynamicArguments(subCmd) // for test purpose only, the sub-command should never be dynamic for production + cmd = NewCommand(context.Background()).AddUntrustedArguments(subCmd) // for test purpose only, the sub-command should never be dynamic for production stdout, stderr, err = cmd.RunStdString(&RunOpts{}) assert.NoError(t, err) assert.Empty(t, stderr) diff --git a/modules/git/commit.go b/modules/git/commit.go index 14710de612153..8b14efdb147e3 100644 --- a/modules/git/commit.go +++ b/modules/git/commit.go @@ -94,7 +94,7 @@ func AddChanges(repoPath string, all bool, files ...string) error { func AddChangesWithArgs(repoPath string, globalArgs []CmdArg, all bool, files ...string) error { cmd := NewCommandNoGlobals(append(globalArgs, "add")...) if all { - cmd.AddArguments("--all") + cmd.AddTrustedArguments("--all") } cmd.AddDashesAndList(files...) _, _, err := cmd.RunStdString(&RunOpts{Dir: repoPath}) @@ -121,17 +121,17 @@ func CommitChanges(repoPath string, opts CommitChangesOptions) error { func CommitChangesWithArgs(repoPath string, args []CmdArg, opts CommitChangesOptions) error { cmd := NewCommandNoGlobals(args...) if opts.Committer != nil { - cmd.AddArguments("-c", CmdArg("user.name="+opts.Committer.Name), "-c", CmdArg("user.email="+opts.Committer.Email)) + cmd.AddTrustedArguments("-c", CmdArg("user.name="+opts.Committer.Name), "-c", CmdArg("user.email="+opts.Committer.Email)) } - cmd.AddArguments("commit") + cmd.AddTrustedArguments("commit") if opts.Author == nil { opts.Author = opts.Committer } if opts.Author != nil { - cmd.AddArguments(CmdArg(fmt.Sprintf("--author='%s <%s>'", opts.Author.Name, opts.Author.Email))) + cmd.AddTrustedArguments(CmdArg(fmt.Sprintf("--author='%s <%s>'", opts.Author.Name, opts.Author.Email))) } - cmd.AddArguments("-m").AddDynamicArguments(opts.Message) + cmd.AddTrustedArguments("-m").AddUntrustedArguments(opts.Message) _, _, err := cmd.RunStdString(&RunOpts{Dir: repoPath}) // No stderr but exit status 1 means nothing to commit. @@ -145,9 +145,9 @@ func CommitChangesWithArgs(repoPath string, args []CmdArg, opts CommitChangesOpt func AllCommitsCount(ctx context.Context, repoPath string, hidePRRefs bool, files ...string) (int64, error) { cmd := NewCommand(ctx, "rev-list") if hidePRRefs { - cmd.AddArguments("--exclude=" + PullPrefix + "*") + cmd.AddTrustedArguments("--exclude=" + PullPrefix + "*") } - cmd.AddArguments("--all", "--count") + cmd.AddTrustedArguments("--all", "--count") if len(files) > 0 { cmd.AddDashesAndList(files...) } @@ -163,7 +163,7 @@ func AllCommitsCount(ctx context.Context, repoPath string, hidePRRefs bool, file // CommitsCountFiles returns number of total commits of until given revision. func CommitsCountFiles(ctx context.Context, repoPath string, revision, relpath []string) (int64, error) { cmd := NewCommand(ctx, "rev-list", "--count") - cmd.AddDynamicArguments(revision...) + cmd.AddUntrustedArguments(revision...) if len(relpath) > 0 { cmd.AddDashesAndList(relpath...) } @@ -205,7 +205,7 @@ func (c *Commit) HasPreviousCommit(commitHash SHA1) (bool, error) { return false, nil } - _, _, err := NewCommand(c.repo.Ctx, "merge-base", "--is-ancestor").AddDynamicArguments(that, this).RunStdString(&RunOpts{Dir: c.repo.Path}) + _, _, err := NewCommand(c.repo.Ctx, "merge-base", "--is-ancestor").AddUntrustedArguments(that, this).RunStdString(&RunOpts{Dir: c.repo.Path}) if err == nil { return true, nil } @@ -390,9 +390,9 @@ func (c *Commit) GetSubModule(entryname string) (*SubModule, error) { func (c *Commit) GetBranchName() (string, error) { cmd := NewCommand(c.repo.Ctx, "name-rev") if CheckGitVersionAtLeast("2.13.0") == nil { - cmd.AddArguments("--exclude", "refs/tags/*") + cmd.AddTrustedArguments("--exclude", "refs/tags/*") } - cmd.AddArguments("--name-only", "--no-undefined").AddDynamicArguments(c.ID.String()) + cmd.AddTrustedArguments("--name-only", "--no-undefined").AddUntrustedArguments(c.ID.String()) data, _, err := cmd.RunStdString(&RunOpts{Dir: c.repo.Path}) if err != nil { // handle special case where git can not describe commit @@ -419,7 +419,7 @@ func (c *Commit) LoadBranchName() (err error) { // GetTagName gets the current tag name for given commit func (c *Commit) GetTagName() (string, error) { - data, _, err := NewCommand(c.repo.Ctx, "describe", "--exact-match", "--tags", "--always").AddDynamicArguments(c.ID.String()).RunStdString(&RunOpts{Dir: c.repo.Path}) + data, _, err := NewCommand(c.repo.Ctx, "describe", "--exact-match", "--tags", "--always").AddUntrustedArguments(c.ID.String()).RunStdString(&RunOpts{Dir: c.repo.Path}) if err != nil { // handle special case where there is no tag for this commit if strings.Contains(err.Error(), "no tag exactly matches") { @@ -496,7 +496,7 @@ func GetCommitFileStatus(ctx context.Context, repoPath, commitID string) (*Commi }() stderr := new(bytes.Buffer) - err := NewCommand(ctx, "log", "--name-status", "-c", "--pretty=format:", "--parents", "--no-renames", "-z", "-1").AddDynamicArguments(commitID).Run(&RunOpts{ + err := NewCommand(ctx, "log", "--name-status", "-c", "--pretty=format:", "--parents", "--no-renames", "-z", "-1").AddUntrustedArguments(commitID).Run(&RunOpts{ Dir: repoPath, Stdout: w, Stderr: stderr, @@ -512,7 +512,7 @@ func GetCommitFileStatus(ctx context.Context, repoPath, commitID string) (*Commi // GetFullCommitID returns full length (40) of commit ID by given short SHA in a repository. func GetFullCommitID(ctx context.Context, repoPath, shortID string) (string, error) { - commitID, _, err := NewCommand(ctx, "rev-parse").AddDynamicArguments(shortID).RunStdString(&RunOpts{Dir: repoPath}) + commitID, _, err := NewCommand(ctx, "rev-parse").AddUntrustedArguments(shortID).RunStdString(&RunOpts{Dir: repoPath}) if err != nil { if strings.Contains(err.Error(), "exit status 128") { return "", ErrNotExist{shortID, ""} diff --git a/modules/git/diff.go b/modules/git/diff.go index 10ef3d83fba98..6edd45ad52b05 100644 --- a/modules/git/diff.go +++ b/modules/git/diff.go @@ -34,7 +34,7 @@ func GetRawDiff(repo *Repository, commitID string, diffType RawDiffType, writer // GetReverseRawDiff dumps the reverse diff results of repository in given commit ID to io.Writer. func GetReverseRawDiff(ctx context.Context, repoPath, commitID string, writer io.Writer) error { stderr := new(bytes.Buffer) - cmd := NewCommand(ctx, "show", "--pretty=format:revert %H%n", "-R").AddDynamicArguments(commitID) + cmd := NewCommand(ctx, "show", "--pretty=format:revert %H%n", "-R").AddUntrustedArguments(commitID) if err := cmd.Run(&RunOpts{ Dir: repoPath, Stdout: writer, @@ -60,23 +60,23 @@ func GetRepoRawDiffForFile(repo *Repository, startCommit, endCommit string, diff switch diffType { case RawDiffNormal: if len(startCommit) != 0 { - cmd.AddArguments("diff", "-M").AddDynamicArguments(startCommit, endCommit).AddDashesAndList(files...) + cmd.AddTrustedArguments("diff", "-M").AddUntrustedArguments(startCommit, endCommit).AddDashesAndList(files...) } else if commit.ParentCount() == 0 { - cmd.AddArguments("show").AddDynamicArguments(endCommit).AddDashesAndList(files...) + cmd.AddTrustedArguments("show").AddUntrustedArguments(endCommit).AddDashesAndList(files...) } else { c, _ := commit.Parent(0) - cmd.AddArguments("diff", "-M").AddDynamicArguments(c.ID.String(), endCommit).AddDashesAndList(files...) + cmd.AddTrustedArguments("diff", "-M").AddUntrustedArguments(c.ID.String(), endCommit).AddDashesAndList(files...) } case RawDiffPatch: if len(startCommit) != 0 { query := fmt.Sprintf("%s...%s", endCommit, startCommit) - cmd.AddArguments("format-patch", "--no-signature", "--stdout", "--root").AddDynamicArguments(query).AddDashesAndList(files...) + cmd.AddTrustedArguments("format-patch", "--no-signature", "--stdout", "--root").AddUntrustedArguments(query).AddDashesAndList(files...) } else if commit.ParentCount() == 0 { - cmd.AddArguments("format-patch", "--no-signature", "--stdout", "--root").AddDynamicArguments(endCommit).AddDashesAndList(files...) + cmd.AddTrustedArguments("format-patch", "--no-signature", "--stdout", "--root").AddUntrustedArguments(endCommit).AddDashesAndList(files...) } else { c, _ := commit.Parent(0) query := fmt.Sprintf("%s...%s", endCommit, c.ID.String()) - cmd.AddArguments("format-patch", "--no-signature", "--stdout").AddDynamicArguments(query).AddDashesAndList(files...) + cmd.AddTrustedArguments("format-patch", "--no-signature", "--stdout").AddUntrustedArguments(query).AddDashesAndList(files...) } default: return fmt.Errorf("invalid diffType: %s", diffType) @@ -285,7 +285,7 @@ func GetAffectedFiles(repo *Repository, oldCommitID, newCommitID string, env []s affectedFiles := make([]string, 0, 32) // Run `git diff --name-only` to get the names of the changed files - err = NewCommand(repo.Ctx, "diff", "--name-only").AddDynamicArguments(oldCommitID, newCommitID). + err = NewCommand(repo.Ctx, "diff", "--name-only").AddUntrustedArguments(oldCommitID, newCommitID). Run(&RunOpts{ Env: env, Dir: repo.Path, diff --git a/modules/git/git.go b/modules/git/git.go index f5919d82dcae1..4ab48505c28ff 100644 --- a/modules/git/git.go +++ b/modules/git/git.go @@ -312,7 +312,7 @@ func CheckGitVersionAtLeast(atLeast string) error { } func configSet(key, value string) error { - stdout, _, err := NewCommand(DefaultContext, "config", "--get").AddDynamicArguments(key).RunStdString(nil) + stdout, _, err := NewCommand(DefaultContext, "config", "--get").AddUntrustedArguments(key).RunStdString(nil) if err != nil && !err.IsExitCode(1) { return fmt.Errorf("failed to get git config %s, err: %w", key, err) } @@ -322,7 +322,7 @@ func configSet(key, value string) error { return nil } - _, _, err = NewCommand(DefaultContext, "config", "--global").AddDynamicArguments(key, value).RunStdString(nil) + _, _, err = NewCommand(DefaultContext, "config", "--global").AddUntrustedArguments(key, value).RunStdString(nil) if err != nil { return fmt.Errorf("failed to set git global config %s, err: %w", key, err) } @@ -331,14 +331,14 @@ func configSet(key, value string) error { } func configSetNonExist(key, value string) error { - _, _, err := NewCommand(DefaultContext, "config", "--get").AddDynamicArguments(key).RunStdString(nil) + _, _, err := NewCommand(DefaultContext, "config", "--get").AddUntrustedArguments(key).RunStdString(nil) if err == nil { // already exist return nil } if err.IsExitCode(1) { // not exist, set new config - _, _, err = NewCommand(DefaultContext, "config", "--global").AddDynamicArguments(key, value).RunStdString(nil) + _, _, err = NewCommand(DefaultContext, "config", "--global").AddUntrustedArguments(key, value).RunStdString(nil) if err != nil { return fmt.Errorf("failed to set git global config %s, err: %w", key, err) } @@ -349,14 +349,14 @@ func configSetNonExist(key, value string) error { } func configAddNonExist(key, value string) error { - _, _, err := NewCommand(DefaultContext, "config", "--get").AddDynamicArguments(key, regexp.QuoteMeta(value)).RunStdString(nil) + _, _, err := NewCommand(DefaultContext, "config", "--get").AddUntrustedArguments(key, regexp.QuoteMeta(value)).RunStdString(nil) if err == nil { // already exist return nil } if err.IsExitCode(1) { // not exist, add new config - _, _, err = NewCommand(DefaultContext, "config", "--global", "--add").AddDynamicArguments(key, value).RunStdString(nil) + _, _, err = NewCommand(DefaultContext, "config", "--global", "--add").AddUntrustedArguments(key, value).RunStdString(nil) if err != nil { return fmt.Errorf("failed to add git global config %s, err: %w", key, err) } @@ -366,10 +366,10 @@ func configAddNonExist(key, value string) error { } func configUnsetAll(key, value string) error { - _, _, err := NewCommand(DefaultContext, "config", "--get").AddDynamicArguments(key).RunStdString(nil) + _, _, err := NewCommand(DefaultContext, "config", "--get").AddUntrustedArguments(key).RunStdString(nil) if err == nil { // exist, need to remove - _, _, err = NewCommand(DefaultContext, "config", "--global", "--unset-all").AddDynamicArguments(key, regexp.QuoteMeta(value)).RunStdString(nil) + _, _, err = NewCommand(DefaultContext, "config", "--global", "--unset-all").AddUntrustedArguments(key, regexp.QuoteMeta(value)).RunStdString(nil) if err != nil { return fmt.Errorf("failed to unset git global config %s, err: %w", key, err) } @@ -384,5 +384,5 @@ func configUnsetAll(key, value string) error { // Fsck verifies the connectivity and validity of the objects in the database func Fsck(ctx context.Context, repoPath string, timeout time.Duration, args ...CmdArg) error { - return NewCommand(ctx, "fsck").AddArguments(args...).Run(&RunOpts{Timeout: timeout, Dir: repoPath}) + return NewCommand(ctx, "fsck").AddTrustedArguments(args...).Run(&RunOpts{Timeout: timeout, Dir: repoPath}) } diff --git a/modules/git/log_name_status.go b/modules/git/log_name_status.go index fe3b6598d7d8a..7c87d8db66c11 100644 --- a/modules/git/log_name_status.go +++ b/modules/git/log_name_status.go @@ -35,7 +35,7 @@ func LogNameStatusRepo(ctx context.Context, repository, head, treepath string, p } cmd := NewCommand(ctx) - cmd.AddArguments("log", "--name-status", "-c", "--format=commit%x00%H %P%x00", "--parents", "--no-renames", "-t", "-z").AddDynamicArguments(head) + cmd.AddTrustedArguments("log", "--name-status", "-c", "--format=commit%x00%H %P%x00", "--parents", "--no-renames", "-t", "-z").AddUntrustedArguments(head) var files []string if len(paths) < 70 { diff --git a/modules/git/pipeline/revlist.go b/modules/git/pipeline/revlist.go index 09bb2c8b3c844..25ca6389ace49 100644 --- a/modules/git/pipeline/revlist.go +++ b/modules/git/pipeline/revlist.go @@ -42,7 +42,7 @@ func RevListObjects(ctx context.Context, revListWriter *io.PipeWriter, wg *sync. defer revListWriter.Close() stderr := new(bytes.Buffer) var errbuf strings.Builder - cmd := git.NewCommand(ctx, "rev-list", "--objects").AddDynamicArguments(headSHA).AddArguments("--not").AddDynamicArguments(baseSHA) + cmd := git.NewCommand(ctx, "rev-list", "--objects").AddUntrustedArguments(headSHA).AddTrustedArguments("--not").AddUntrustedArguments(baseSHA) if err := cmd.Run(&git.RunOpts{ Dir: tmpBasePath, Stdout: revListWriter, diff --git a/modules/git/remote.go b/modules/git/remote.go index 3585313f6ae38..04894781faae7 100644 --- a/modules/git/remote.go +++ b/modules/git/remote.go @@ -13,9 +13,9 @@ import ( func GetRemoteAddress(ctx context.Context, repoPath, remoteName string) (string, error) { var cmd *Command if CheckGitVersionAtLeast("2.7") == nil { - cmd = NewCommand(ctx, "remote", "get-url").AddDynamicArguments(remoteName) + cmd = NewCommand(ctx, "remote", "get-url").AddUntrustedArguments(remoteName) } else { - cmd = NewCommand(ctx, "config", "--get").AddDynamicArguments("remote." + remoteName + ".url") + cmd = NewCommand(ctx, "config", "--get").AddUntrustedArguments("remote." + remoteName + ".url") } result, _, err := cmd.RunStdString(&RunOpts{Dir: repoPath}) diff --git a/modules/git/repo.go b/modules/git/repo.go index 4ba40d20af0d5..16a121eeaab2a 100644 --- a/modules/git/repo.go +++ b/modules/git/repo.go @@ -58,7 +58,7 @@ func (repo *Repository) parsePrettyFormatLogToList(logs []byte) ([]*Commit, erro // IsRepoURLAccessible checks if given repository URL is accessible. func IsRepoURLAccessible(ctx context.Context, url string) bool { - _, _, err := NewCommand(ctx, "ls-remote", "-q", "-h").AddDynamicArguments(url, "HEAD").RunStdString(nil) + _, _, err := NewCommand(ctx, "ls-remote", "-q", "-h").AddUntrustedArguments(url, "HEAD").RunStdString(nil) return err == nil } @@ -71,7 +71,7 @@ func InitRepository(ctx context.Context, repoPath string, bare bool) error { cmd := NewCommand(ctx, "init") if bare { - cmd.AddArguments("--bare") + cmd.AddTrustedArguments("--bare") } _, _, err = cmd.RunStdString(&RunOpts{Dir: repoPath}) return err @@ -121,33 +121,33 @@ func CloneWithArgs(ctx context.Context, args []CmdArg, from, to string, opts Clo return err } - cmd := NewCommandContextNoGlobals(ctx, args...).AddArguments("clone") + cmd := NewCommandContextNoGlobals(ctx, args...).AddTrustedArguments("clone") if opts.SkipTLSVerify { - cmd.AddArguments("-c", "http.sslVerify=false") + cmd.AddTrustedArguments("-c", "http.sslVerify=false") } if opts.Mirror { - cmd.AddArguments("--mirror") + cmd.AddTrustedArguments("--mirror") } if opts.Bare { - cmd.AddArguments("--bare") + cmd.AddTrustedArguments("--bare") } if opts.Quiet { - cmd.AddArguments("--quiet") + cmd.AddTrustedArguments("--quiet") } if opts.Shared { - cmd.AddArguments("-s") + cmd.AddTrustedArguments("-s") } if opts.NoCheckout { - cmd.AddArguments("--no-checkout") + cmd.AddTrustedArguments("--no-checkout") } if opts.Depth > 0 { - cmd.AddArguments("--depth").AddDynamicArguments(strconv.Itoa(opts.Depth)) + cmd.AddTrustedArguments("--depth").AddUntrustedArguments(strconv.Itoa(opts.Depth)) } if opts.Filter != "" { - cmd.AddArguments("--filter").AddDynamicArguments(opts.Filter) + cmd.AddTrustedArguments("--filter").AddUntrustedArguments(opts.Filter) } if len(opts.Branch) > 0 { - cmd.AddArguments("-b").AddDynamicArguments(opts.Branch) + cmd.AddTrustedArguments("-b").AddUntrustedArguments(opts.Branch) } cmd.AddDashesAndList(from, to) @@ -195,10 +195,10 @@ type PushOptions struct { func Push(ctx context.Context, repoPath string, opts PushOptions) error { cmd := NewCommand(ctx, "push") if opts.Force { - cmd.AddArguments("-f") + cmd.AddTrustedArguments("-f") } if opts.Mirror { - cmd.AddArguments("--mirror") + cmd.AddTrustedArguments("--mirror") } remoteBranchArgs := []string{opts.Remote} if len(opts.Branch) > 0 { @@ -275,7 +275,7 @@ type DivergeObject struct { func checkDivergence(ctx context.Context, repoPath, baseBranch, targetBranch string) (int, error) { branches := fmt.Sprintf("%s..%s", baseBranch, targetBranch) - cmd := NewCommand(ctx, "rev-list", "--count").AddDynamicArguments(branches) + cmd := NewCommand(ctx, "rev-list", "--count").AddUntrustedArguments(branches) stdout, _, err := cmd.RunStdString(&RunOpts{Dir: repoPath}) if err != nil { return -1, err @@ -318,7 +318,7 @@ func (repo *Repository) CreateBundle(ctx context.Context, commit string, out io. return err } - _, _, err = NewCommand(ctx, "reset", "--soft").AddDynamicArguments(commit).RunStdString(&RunOpts{Dir: tmp, Env: env}) + _, _, err = NewCommand(ctx, "reset", "--soft").AddUntrustedArguments(commit).RunStdString(&RunOpts{Dir: tmp, Env: env}) if err != nil { return err } @@ -329,7 +329,7 @@ func (repo *Repository) CreateBundle(ctx context.Context, commit string, out io. } tmpFile := filepath.Join(tmp, "bundle") - _, _, err = NewCommand(ctx, "bundle", "create").AddDynamicArguments(tmpFile, "bundle", "HEAD").RunStdString(&RunOpts{Dir: tmp, Env: env}) + _, _, err = NewCommand(ctx, "bundle", "create").AddUntrustedArguments(tmpFile, "bundle", "HEAD").RunStdString(&RunOpts{Dir: tmp, Env: env}) if err != nil { return err } diff --git a/modules/git/repo_archive.go b/modules/git/repo_archive.go index cff9724f00543..0a9ae81f4b7a2 100644 --- a/modules/git/repo_archive.go +++ b/modules/git/repo_archive.go @@ -57,10 +57,10 @@ func (repo *Repository) CreateArchive(ctx context.Context, format ArchiveType, t cmd := NewCommand(ctx, "archive") if usePrefix { - cmd.AddArguments(CmdArg("--prefix=" + filepath.Base(strings.TrimSuffix(repo.Path, ".git")) + "/")) + cmd.AddTrustedArguments(CmdArg("--prefix=" + filepath.Base(strings.TrimSuffix(repo.Path, ".git")) + "/")) } - cmd.AddArguments(CmdArg("--format=" + format.String())) - cmd.AddDynamicArguments(commitID) + cmd.AddTrustedArguments(CmdArg("--format=" + format.String())) + cmd.AddUntrustedArguments(commitID) var stderr strings.Builder err := cmd.Run(&RunOpts{ diff --git a/modules/git/repo_attribute.go b/modules/git/repo_attribute.go index 404d9e502c042..a8ce345890269 100644 --- a/modules/git/repo_attribute.go +++ b/modules/git/repo_attribute.go @@ -44,17 +44,17 @@ func (repo *Repository) CheckAttribute(opts CheckAttributeOpts) (map[string]map[ cmd := NewCommand(repo.Ctx, "check-attr", "-z") if opts.AllAttributes { - cmd.AddArguments("-a") + cmd.AddTrustedArguments("-a") } else { for _, attribute := range opts.Attributes { if attribute != "" { - cmd.AddArguments(attribute) + cmd.AddTrustedArguments(attribute) } } } if opts.CachedOnly { - cmd.AddArguments("--cached") + cmd.AddTrustedArguments("--cached") } cmd.AddDashesAndList(opts.Filenames...) diff --git a/modules/git/repo_blame.go b/modules/git/repo_blame.go index 7f44735f9f907..fd372d4dfe546 100644 --- a/modules/git/repo_blame.go +++ b/modules/git/repo_blame.go @@ -14,8 +14,8 @@ func (repo *Repository) FileBlame(revision, path, file string) ([]byte, error) { // LineBlame returns the latest commit at the given line func (repo *Repository) LineBlame(revision, path, file string, line uint) (*Commit, error) { res, _, err := NewCommand(repo.Ctx, "blame"). - AddArguments(CmdArg(fmt.Sprintf("-L %d,%d", line, line))). - AddArguments("-p").AddDynamicArguments(revision). + AddTrustedArguments(CmdArg(fmt.Sprintf("-L %d,%d", line, line))). + AddTrustedArguments("-p").AddUntrustedArguments(revision). AddDashesAndList(file).RunStdString(&RunOpts{Dir: path}) if err != nil { return nil, err diff --git a/modules/git/repo_branch.go b/modules/git/repo_branch.go index 14dcf14d8a0da..24ea809650df5 100644 --- a/modules/git/repo_branch.go +++ b/modules/git/repo_branch.go @@ -65,7 +65,7 @@ func (repo *Repository) GetHEADBranch() (*Branch, error) { // SetDefaultBranch sets default branch of repository. func (repo *Repository) SetDefaultBranch(name string) error { - _, _, err := NewCommand(repo.Ctx, "symbolic-ref", "HEAD").AddDynamicArguments(BranchPrefix + name).RunStdString(&RunOpts{Dir: repo.Path}) + _, _, err := NewCommand(repo.Ctx, "symbolic-ref", "HEAD").AddUntrustedArguments(BranchPrefix + name).RunStdString(&RunOpts{Dir: repo.Path}) return err } @@ -135,9 +135,9 @@ func (repo *Repository) DeleteBranch(name string, opts DeleteBranchOptions) erro cmd := NewCommand(repo.Ctx, "branch") if opts.Force { - cmd.AddArguments("-D") + cmd.AddTrustedArguments("-D") } else { - cmd.AddArguments("-d") + cmd.AddTrustedArguments("-d") } cmd.AddDashesAndList(name) @@ -160,9 +160,9 @@ func (repo *Repository) CreateBranch(branch, oldbranchOrCommit string) error { func (repo *Repository) AddRemote(name, url string, fetch bool) error { cmd := NewCommand(repo.Ctx, "remote", "add") if fetch { - cmd.AddArguments("-f") + cmd.AddTrustedArguments("-f") } - cmd.AddDynamicArguments(name, url) + cmd.AddUntrustedArguments(name, url) _, _, err := cmd.RunStdString(&RunOpts{Dir: repo.Path}) return err @@ -170,7 +170,7 @@ func (repo *Repository) AddRemote(name, url string, fetch bool) error { // RemoveRemote removes a remote from repository. func (repo *Repository) RemoveRemote(name string) error { - _, _, err := NewCommand(repo.Ctx, "remote", "rm").AddDynamicArguments(name).RunStdString(&RunOpts{Dir: repo.Path}) + _, _, err := NewCommand(repo.Ctx, "remote", "rm").AddUntrustedArguments(name).RunStdString(&RunOpts{Dir: repo.Path}) return err } @@ -181,6 +181,6 @@ func (branch *Branch) GetCommit() (*Commit, error) { // RenameBranch rename a branch func (repo *Repository) RenameBranch(from, to string) error { - _, _, err := NewCommand(repo.Ctx, "branch", "-m").AddDynamicArguments(from, to).RunStdString(&RunOpts{Dir: repo.Path}) + _, _, err := NewCommand(repo.Ctx, "branch", "-m").AddUntrustedArguments(from, to).RunStdString(&RunOpts{Dir: repo.Path}) return err } diff --git a/modules/git/repo_commit.go b/modules/git/repo_commit.go index 8343e34843534..b6cf90d612d52 100644 --- a/modules/git/repo_commit.go +++ b/modules/git/repo_commit.go @@ -60,7 +60,7 @@ func (repo *Repository) getCommitByPathWithID(id SHA1, relpath string) (*Commit, relpath = `\` + relpath } - stdout, _, runErr := NewCommand(repo.Ctx, "log", "-1", prettyLogFormat).AddDynamicArguments(id.String()).AddDashesAndList(relpath).RunStdString(&RunOpts{Dir: repo.Path}) + stdout, _, runErr := NewCommand(repo.Ctx, "log", "-1", prettyLogFormat).AddUntrustedArguments(id.String()).AddDashesAndList(relpath).RunStdString(&RunOpts{Dir: repo.Path}) if runErr != nil { return nil, runErr } @@ -89,8 +89,8 @@ func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error) { func (repo *Repository) commitsByRange(id SHA1, page, pageSize int) ([]*Commit, error) { stdout, _, err := NewCommand(repo.Ctx, "log"). - AddArguments(CmdArg("--skip="+strconv.Itoa((page-1)*pageSize)), CmdArg("--max-count="+strconv.Itoa(pageSize)), prettyLogFormat). - AddDynamicArguments(id.String()). + AddTrustedArguments(CmdArg("--skip="+strconv.Itoa((page-1)*pageSize)), CmdArg("--max-count="+strconv.Itoa(pageSize)), prettyLogFormat). + AddUntrustedArguments(id.String()). RunStdBytes(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err @@ -100,7 +100,7 @@ func (repo *Repository) commitsByRange(id SHA1, page, pageSize int) ([]*Commit, func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) ([]*Commit, error) { // create new git log command with limit of 100 commis - cmd := NewCommand(repo.Ctx, "log", "-100", prettyLogFormat).AddDynamicArguments(id.String()) + cmd := NewCommand(repo.Ctx, "log", "-100", prettyLogFormat).AddUntrustedArguments(id.String()) // ignore case args := []CmdArg{"-i"} @@ -130,19 +130,19 @@ func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) ([]*Co // https://git-scm.com/docs/git-log#Documentation/git-log.txt---all // note this is done only for command created above if opts.All { - cmd.AddArguments("--all") + cmd.AddTrustedArguments("--all") } // add remaining keywords from search string // note this is done only for command created above if len(opts.Keywords) > 0 { for _, v := range opts.Keywords { - cmd.AddArguments(CmdArg("--grep=" + v)) + cmd.AddTrustedArguments(CmdArg("--grep=" + v)) } } // search for commits matching given constraints and keywords in commit msg - cmd.AddArguments(args...) + cmd.AddTrustedArguments(args...) stdout, _, err := cmd.RunStdBytes(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err @@ -160,9 +160,9 @@ func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) ([]*Co // create new git log command with 1 commit limit hashCmd := NewCommand(repo.Ctx, "log", "-1", prettyLogFormat) // add previous arguments except for --grep and --all - hashCmd.AddArguments(args...) + hashCmd.AddTrustedArguments(args...) // add keyword as - hashCmd.AddDynamicArguments(v) + hashCmd.AddUntrustedArguments(v) // search with given constraints for commit matching sha hash of v hashMatching, _, err := hashCmd.RunStdBytes(&RunOpts{Dir: repo.Path}) @@ -179,7 +179,7 @@ func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) ([]*Co } func (repo *Repository) getFilesChanged(id1, id2 string) ([]string, error) { - stdout, _, err := NewCommand(repo.Ctx, "diff", "--name-only").AddDynamicArguments(id1, id2).RunStdBytes(&RunOpts{Dir: repo.Path}) + stdout, _, err := NewCommand(repo.Ctx, "diff", "--name-only").AddUntrustedArguments(id1, id2).RunStdBytes(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err } @@ -189,7 +189,7 @@ func (repo *Repository) getFilesChanged(id1, id2 string) ([]string, error) { // FileChangedBetweenCommits Returns true if the file changed between commit IDs id1 and id2 // You must ensure that id1 and id2 are valid commit ids. func (repo *Repository) FileChangedBetweenCommits(filename, id1, id2 string) (bool, error) { - stdout, _, err := NewCommand(repo.Ctx, "diff", "--name-only", "-z").AddDynamicArguments(id1, id2).AddDashesAndList(filename).RunStdBytes(&RunOpts{Dir: repo.Path}) + stdout, _, err := NewCommand(repo.Ctx, "diff", "--name-only", "-z").AddUntrustedArguments(id1, id2).AddDashesAndList(filename).RunStdBytes(&RunOpts{Dir: repo.Path}) if err != nil { return false, err } @@ -213,9 +213,9 @@ func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) ( go func() { stderr := strings.Builder{} gitCmd := NewCommand(repo.Ctx, "rev-list"). - AddArguments(CmdArg("--max-count=" + strconv.Itoa(setting.Git.CommitsRangeSize*page))). - AddArguments(CmdArg("--skip=" + strconv.Itoa(skip))) - gitCmd.AddDynamicArguments(revision) + AddTrustedArguments(CmdArg("--max-count=" + strconv.Itoa(setting.Git.CommitsRangeSize*page))). + AddTrustedArguments(CmdArg("--skip=" + strconv.Itoa(skip))) + gitCmd.AddUntrustedArguments(revision) gitCmd.AddDashesAndList(file) err := gitCmd.Run(&RunOpts{ Dir: repo.Path, @@ -257,11 +257,11 @@ func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) ( // FilesCountBetween return the number of files changed between two commits func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error) { - stdout, _, err := NewCommand(repo.Ctx, "diff", "--name-only").AddDynamicArguments(startCommitID + "..." + endCommitID).RunStdString(&RunOpts{Dir: repo.Path}) + stdout, _, err := NewCommand(repo.Ctx, "diff", "--name-only").AddUntrustedArguments(startCommitID + "..." + endCommitID).RunStdString(&RunOpts{Dir: repo.Path}) if err != nil && strings.Contains(err.Error(), "no merge base") { // git >= 2.28 now returns an error if startCommitID and endCommitID have become unrelated. // previously it would return the results of git diff --name-only startCommitID endCommitID so let's try that... - stdout, _, err = NewCommand(repo.Ctx, "diff", "--name-only").AddDynamicArguments(startCommitID, endCommitID).RunStdString(&RunOpts{Dir: repo.Path}) + stdout, _, err = NewCommand(repo.Ctx, "diff", "--name-only").AddUntrustedArguments(startCommitID, endCommitID).RunStdString(&RunOpts{Dir: repo.Path}) } if err != nil { return 0, err @@ -275,13 +275,13 @@ func (repo *Repository) CommitsBetween(last, before *Commit) ([]*Commit, error) var stdout []byte var err error if before == nil { - stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path}) + stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddUntrustedArguments(last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path}) } else { - stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(before.ID.String() + ".." + last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path}) + stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddUntrustedArguments(before.ID.String() + ".." + last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path}) if err != nil && strings.Contains(err.Error(), "no merge base") { // future versions of git >= 2.28 are likely to return an error if before and last have become unrelated. // previously it would return the results of git rev-list before last so let's try that... - stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(before.ID.String(), last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path}) + stdout, _, err = NewCommand(repo.Ctx, "rev-list").AddUntrustedArguments(before.ID.String(), last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path}) } } if err != nil { @@ -298,19 +298,19 @@ func (repo *Repository) CommitsBetweenLimit(last, before *Commit, limit, skip in stdout, _, err = NewCommand(repo.Ctx, "rev-list", "--max-count", CmdArg(strconv.Itoa(limit)), "--skip", CmdArg(strconv.Itoa(skip))). - AddDynamicArguments(last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path}) + AddUntrustedArguments(last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path}) } else { stdout, _, err = NewCommand(repo.Ctx, "rev-list", "--max-count", CmdArg(strconv.Itoa(limit)), "--skip", CmdArg(strconv.Itoa(skip))). - AddDynamicArguments(before.ID.String() + ".." + last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path}) + AddUntrustedArguments(before.ID.String() + ".." + last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path}) if err != nil && strings.Contains(err.Error(), "no merge base") { // future versions of git >= 2.28 are likely to return an error if before and last have become unrelated. // previously it would return the results of git rev-list --max-count n before last so let's try that... stdout, _, err = NewCommand(repo.Ctx, "rev-list", "--max-count", CmdArg(strconv.Itoa(limit)), "--skip", CmdArg(strconv.Itoa(skip))). - AddDynamicArguments(before.ID.String(), last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path}) + AddUntrustedArguments(before.ID.String(), last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path}) } } if err != nil { @@ -351,9 +351,9 @@ func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) { func (repo *Repository) commitsBefore(id SHA1, limit int) ([]*Commit, error) { cmd := NewCommand(repo.Ctx, "log") if limit > 0 { - cmd.AddArguments(CmdArg("-"+strconv.Itoa(limit)), prettyLogFormat).AddDynamicArguments(id.String()) + cmd.AddTrustedArguments(CmdArg("-"+strconv.Itoa(limit)), prettyLogFormat).AddUntrustedArguments(id.String()) } else { - cmd.AddArguments(prettyLogFormat).AddDynamicArguments(id.String()) + cmd.AddTrustedArguments(prettyLogFormat).AddUntrustedArguments(id.String()) } stdout, _, runErr := cmd.RunStdBytes(&RunOpts{Dir: repo.Path}) @@ -396,7 +396,7 @@ func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) stdout, _, err := NewCommand(repo.Ctx, "for-each-ref", CmdArg("--count="+strconv.Itoa(limit)), "--format=%(refname:strip=2)", "--contains"). - AddDynamicArguments(commit.ID.String(), BranchPrefix). + AddUntrustedArguments(commit.ID.String(), BranchPrefix). RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err @@ -406,7 +406,7 @@ func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) return branches, nil } - stdout, _, err := NewCommand(repo.Ctx, "branch", "--contains").AddDynamicArguments(commit.ID.String()).RunStdString(&RunOpts{Dir: repo.Path}) + stdout, _, err := NewCommand(repo.Ctx, "branch", "--contains").AddUntrustedArguments(commit.ID.String()).RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err } @@ -445,7 +445,7 @@ func (repo *Repository) GetCommitsFromIDs(commitIDs []string) []*Commit { // IsCommitInBranch check if the commit is on the branch func (repo *Repository) IsCommitInBranch(commitID, branch string) (r bool, err error) { - stdout, _, err := NewCommand(repo.Ctx, "branch", "--contains").AddDynamicArguments(commitID, branch).RunStdString(&RunOpts{Dir: repo.Path}) + stdout, _, err := NewCommand(repo.Ctx, "branch", "--contains").AddUntrustedArguments(commitID, branch).RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { return false, err } diff --git a/modules/git/repo_commit_gogit.go b/modules/git/repo_commit_gogit.go index 72de158e6e11c..85bbbdc744913 100644 --- a/modules/git/repo_commit_gogit.go +++ b/modules/git/repo_commit_gogit.go @@ -48,7 +48,7 @@ func (repo *Repository) ConvertToSHA1(commitID string) (SHA1, error) { } } - actualCommitID, _, err := NewCommand(repo.Ctx, "rev-parse", "--verify").AddDynamicArguments(commitID).RunStdString(&RunOpts{Dir: repo.Path}) + actualCommitID, _, err := NewCommand(repo.Ctx, "rev-parse", "--verify").AddUntrustedArguments(commitID).RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { if strings.Contains(err.Error(), "unknown revision or path") || strings.Contains(err.Error(), "fatal: Needed a single revision") { diff --git a/modules/git/repo_commit_nogogit.go b/modules/git/repo_commit_nogogit.go index 7373d01c8efbe..f309e009a7a89 100644 --- a/modules/git/repo_commit_nogogit.go +++ b/modules/git/repo_commit_nogogit.go @@ -16,7 +16,7 @@ import ( // ResolveReference resolves a name to a reference func (repo *Repository) ResolveReference(name string) (string, error) { - stdout, _, err := NewCommand(repo.Ctx, "show-ref", "--hash").AddDynamicArguments(name).RunStdString(&RunOpts{Dir: repo.Path}) + stdout, _, err := NewCommand(repo.Ctx, "show-ref", "--hash").AddUntrustedArguments(name).RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { if strings.Contains(err.Error(), "not a valid ref") { return "", ErrNotExist{name, ""} @@ -49,19 +49,19 @@ func (repo *Repository) GetRefCommitID(name string) (string, error) { // SetReference sets the commit ID string of given reference (e.g. branch or tag). func (repo *Repository) SetReference(name, commitID string) error { - _, _, err := NewCommand(repo.Ctx, "update-ref").AddDynamicArguments(name, commitID).RunStdString(&RunOpts{Dir: repo.Path}) + _, _, err := NewCommand(repo.Ctx, "update-ref").AddUntrustedArguments(name, commitID).RunStdString(&RunOpts{Dir: repo.Path}) return err } // RemoveReference removes the given reference (e.g. branch or tag). func (repo *Repository) RemoveReference(name string) error { - _, _, err := NewCommand(repo.Ctx, "update-ref", "--no-deref", "-d").AddDynamicArguments(name).RunStdString(&RunOpts{Dir: repo.Path}) + _, _, err := NewCommand(repo.Ctx, "update-ref", "--no-deref", "-d").AddUntrustedArguments(name).RunStdString(&RunOpts{Dir: repo.Path}) return err } // IsCommitExist returns true if given commit exists in current repository. func (repo *Repository) IsCommitExist(name string) bool { - _, _, err := NewCommand(repo.Ctx, "cat-file", "-e").AddDynamicArguments(name).RunStdString(&RunOpts{Dir: repo.Path}) + _, _, err := NewCommand(repo.Ctx, "cat-file", "-e").AddUntrustedArguments(name).RunStdString(&RunOpts{Dir: repo.Path}) return err == nil } diff --git a/modules/git/repo_compare.go b/modules/git/repo_compare.go index b1b55c88a4446..09974114f42c2 100644 --- a/modules/git/repo_compare.go +++ b/modules/git/repo_compare.go @@ -39,7 +39,7 @@ func (repo *Repository) GetMergeBase(tmpRemote, base, head string) (string, stri if tmpRemote != "origin" { tmpBaseName := RemotePrefix + tmpRemote + "/tmp_" + base // Fetch commit into a temporary branch in order to be able to handle commits and tags - _, _, err := NewCommand(repo.Ctx, "fetch", "--no-tags").AddDynamicArguments(tmpRemote).AddDashesAndList(base + ":" + tmpBaseName).RunStdString(&RunOpts{Dir: repo.Path}) + _, _, err := NewCommand(repo.Ctx, "fetch", "--no-tags").AddUntrustedArguments(tmpRemote).AddDashesAndList(base + ":" + tmpBaseName).RunStdString(&RunOpts{Dir: repo.Path}) if err == nil { base = tmpBaseName } @@ -93,7 +93,7 @@ func (repo *Repository) GetCompareInfo(basePath, baseBranch, headBranch string, // We have a common base - therefore we know that ... should work if !fileOnly { var logs []byte - logs, _, err = NewCommand(repo.Ctx, "log").AddDynamicArguments(baseCommitID + separator + headBranch).AddArguments(prettyLogFormat).RunStdBytes(&RunOpts{Dir: repo.Path}) + logs, _, err = NewCommand(repo.Ctx, "log").AddUntrustedArguments(baseCommitID + separator + headBranch).AddTrustedArguments(prettyLogFormat).RunStdBytes(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err } @@ -146,7 +146,7 @@ func (repo *Repository) GetDiffNumChangedFiles(base, head string, directComparis separator = ".." } - if err := NewCommand(repo.Ctx, "diff", "-z", "--name-only").AddDynamicArguments(base + separator + head). + if err := NewCommand(repo.Ctx, "diff", "-z", "--name-only").AddUntrustedArguments(base + separator + head). Run(&RunOpts{ Dir: repo.Path, Stdout: w, @@ -157,7 +157,7 @@ func (repo *Repository) GetDiffNumChangedFiles(base, head string, directComparis // previously it would return the results of git diff -z --name-only base head so let's try that... w = &lineCountWriter{} stderr.Reset() - if err = NewCommand(repo.Ctx, "diff", "-z", "--name-only").AddDynamicArguments(base, head).Run(&RunOpts{ + if err = NewCommand(repo.Ctx, "diff", "-z", "--name-only").AddUntrustedArguments(base, head).Run(&RunOpts{ Dir: repo.Path, Stdout: w, Stderr: stderr, @@ -246,7 +246,7 @@ func (repo *Repository) GetDiffOrPatch(base, head string, w io.Writer, patch, bi // GetDiff generates and returns patch data between given revisions, optimized for human readability func (repo *Repository) GetDiff(base, head string, w io.Writer) error { - return NewCommand(repo.Ctx, "diff", "-p").AddDynamicArguments(base, head).Run(&RunOpts{ + return NewCommand(repo.Ctx, "diff", "-p").AddUntrustedArguments(base, head).Run(&RunOpts{ Dir: repo.Path, Stdout: w, }) @@ -254,7 +254,7 @@ func (repo *Repository) GetDiff(base, head string, w io.Writer) error { // GetDiffBinary generates and returns patch data between given revisions, including binary diffs. func (repo *Repository) GetDiffBinary(base, head string, w io.Writer) error { - return NewCommand(repo.Ctx, "diff", "-p", "--binary", "--histogram").AddDynamicArguments(base, head).Run(&RunOpts{ + return NewCommand(repo.Ctx, "diff", "-p", "--binary", "--histogram").AddUntrustedArguments(base, head).Run(&RunOpts{ Dir: repo.Path, Stdout: w, }) @@ -263,14 +263,14 @@ func (repo *Repository) GetDiffBinary(base, head string, w io.Writer) error { // GetPatch generates and returns format-patch data between given revisions, able to be used with `git apply` func (repo *Repository) GetPatch(base, head string, w io.Writer) error { stderr := new(bytes.Buffer) - err := NewCommand(repo.Ctx, "format-patch", "--binary", "--stdout").AddDynamicArguments(base + "..." + head). + err := NewCommand(repo.Ctx, "format-patch", "--binary", "--stdout").AddUntrustedArguments(base + "..." + head). Run(&RunOpts{ Dir: repo.Path, Stdout: w, Stderr: stderr, }) if err != nil && bytes.Contains(stderr.Bytes(), []byte("no merge base")) { - return NewCommand(repo.Ctx, "format-patch", "--binary", "--stdout").AddDynamicArguments(base, head). + return NewCommand(repo.Ctx, "format-patch", "--binary", "--stdout").AddUntrustedArguments(base, head). Run(&RunOpts{ Dir: repo.Path, Stdout: w, @@ -281,7 +281,7 @@ func (repo *Repository) GetPatch(base, head string, w io.Writer) error { // GetFilesChangedBetween returns a list of all files that have been changed between the given commits func (repo *Repository) GetFilesChangedBetween(base, head string) ([]string, error) { - stdout, _, err := NewCommand(repo.Ctx, "diff", "--name-only").AddDynamicArguments(base + ".." + head).RunStdString(&RunOpts{Dir: repo.Path}) + stdout, _, err := NewCommand(repo.Ctx, "diff", "--name-only").AddUntrustedArguments(base + ".." + head).RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err } @@ -291,7 +291,7 @@ func (repo *Repository) GetFilesChangedBetween(base, head string) ([]string, err // GetDiffFromMergeBase generates and return patch data from merge base to head func (repo *Repository) GetDiffFromMergeBase(base, head string, w io.Writer) error { stderr := new(bytes.Buffer) - err := NewCommand(repo.Ctx, "diff", "-p", "--binary").AddDynamicArguments(base + "..." + head). + err := NewCommand(repo.Ctx, "diff", "-p", "--binary").AddUntrustedArguments(base + "..." + head). Run(&RunOpts{ Dir: repo.Path, Stdout: w, diff --git a/modules/git/repo_index.go b/modules/git/repo_index.go index 5ff2a2e4fc9d2..f176d2d712e25 100644 --- a/modules/git/repo_index.go +++ b/modules/git/repo_index.go @@ -17,7 +17,7 @@ import ( // ReadTreeToIndex reads a treeish to the index func (repo *Repository) ReadTreeToIndex(treeish string, indexFilename ...string) error { if len(treeish) != SHAFullLength { - res, _, err := NewCommand(repo.Ctx, "rev-parse", "--verify").AddDynamicArguments(treeish).RunStdString(&RunOpts{Dir: repo.Path}) + res, _, err := NewCommand(repo.Ctx, "rev-parse", "--verify").AddUntrustedArguments(treeish).RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { return err } @@ -37,7 +37,7 @@ func (repo *Repository) readTreeToIndex(id SHA1, indexFilename ...string) error if len(indexFilename) > 0 { env = append(os.Environ(), "GIT_INDEX_FILE="+indexFilename[0]) } - _, _, err := NewCommand(repo.Ctx, "read-tree").AddDynamicArguments(id.String()).RunStdString(&RunOpts{Dir: repo.Path, Env: env}) + _, _, err := NewCommand(repo.Ctx, "read-tree").AddUntrustedArguments(id.String()).RunStdString(&RunOpts{Dir: repo.Path, Env: env}) if err != nil { return err } @@ -110,7 +110,7 @@ func (repo *Repository) RemoveFilesFromIndex(filenames ...string) error { // AddObjectToIndex adds the provided object hash to the index at the provided filename func (repo *Repository) AddObjectToIndex(mode string, object SHA1, filename string) error { - cmd := NewCommand(repo.Ctx, "update-index", "--add", "--replace", "--cacheinfo").AddDynamicArguments(mode, object.String(), filename) + cmd := NewCommand(repo.Ctx, "update-index", "--add", "--replace", "--cacheinfo").AddUntrustedArguments(mode, object.String(), filename) _, _, err := cmd.RunStdString(&RunOpts{Dir: repo.Path}) return err } diff --git a/modules/git/repo_stats.go b/modules/git/repo_stats.go index d6e91f25a9a60..dfae1fe85bc6a 100644 --- a/modules/git/repo_stats.go +++ b/modules/git/repo_stats.go @@ -62,9 +62,9 @@ func (repo *Repository) GetCodeActivityStats(fromTime time.Time, branch string) gitCmd := NewCommand(repo.Ctx, "log", "--numstat", "--no-merges", "--pretty=format:---%n%h%n%aN%n%aE%n", "--date=iso", CmdArg(fmt.Sprintf("--since='%s'", since))) if len(branch) == 0 { - gitCmd.AddArguments("--branches=*") + gitCmd.AddTrustedArguments("--branches=*") } else { - gitCmd.AddArguments("--first-parent").AddDynamicArguments(branch) + gitCmd.AddTrustedArguments("--first-parent").AddUntrustedArguments(branch) } stderr := new(strings.Builder) diff --git a/modules/git/repo_tag.go b/modules/git/repo_tag.go index 8aa06545d4cb1..ae568cab887c6 100644 --- a/modules/git/repo_tag.go +++ b/modules/git/repo_tag.go @@ -30,7 +30,7 @@ func (repo *Repository) CreateTag(name, revision string) error { // CreateAnnotatedTag create one annotated tag in the repository func (repo *Repository) CreateAnnotatedTag(name, message, revision string) error { - _, _, err := NewCommand(repo.Ctx, "tag", "-a", "-m").AddDynamicArguments(message).AddDashesAndList(name, revision).RunStdString(&RunOpts{Dir: repo.Path}) + _, _, err := NewCommand(repo.Ctx, "tag", "-a", "-m").AddUntrustedArguments(message).AddDashesAndList(name, revision).RunStdString(&RunOpts{Dir: repo.Path}) return err } diff --git a/modules/git/repo_tree.go b/modules/git/repo_tree.go index 5fea5c0aea4bd..778ae9a7e8770 100644 --- a/modules/git/repo_tree.go +++ b/modules/git/repo_tree.go @@ -34,10 +34,10 @@ func (repo *Repository) CommitTree(author, committer *Signature, tree *Tree, opt "GIT_COMMITTER_EMAIL="+committer.Email, "GIT_COMMITTER_DATE="+commitTimeStr, ) - cmd := NewCommand(repo.Ctx, "commit-tree").AddDynamicArguments(tree.ID.String()) + cmd := NewCommand(repo.Ctx, "commit-tree").AddUntrustedArguments(tree.ID.String()) for _, parent := range opts.Parents { - cmd.AddArguments("-p").AddDynamicArguments(parent) + cmd.AddTrustedArguments("-p").AddUntrustedArguments(parent) } messageBytes := new(bytes.Buffer) @@ -45,11 +45,11 @@ func (repo *Repository) CommitTree(author, committer *Signature, tree *Tree, opt _, _ = messageBytes.WriteString("\n") if opts.KeyID != "" || opts.AlwaysSign { - cmd.AddArguments(CmdArg(fmt.Sprintf("-S%s", opts.KeyID))) + cmd.AddTrustedArguments(CmdArg(fmt.Sprintf("-S%s", opts.KeyID))) } if opts.NoGPGSign { - cmd.AddArguments("--no-gpg-sign") + cmd.AddTrustedArguments("--no-gpg-sign") } stdout := new(bytes.Buffer) diff --git a/modules/git/repo_tree_gogit.go b/modules/git/repo_tree_gogit.go index a7b1081b15f18..9c7e2cb54445d 100644 --- a/modules/git/repo_tree_gogit.go +++ b/modules/git/repo_tree_gogit.go @@ -20,7 +20,7 @@ func (repo *Repository) getTree(id SHA1) (*Tree, error) { // GetTree find the tree object in the repository. func (repo *Repository) GetTree(idStr string) (*Tree, error) { if len(idStr) != SHAFullLength { - res, _, err := NewCommand(repo.Ctx, "rev-parse", "--verify").AddDynamicArguments(idStr).RunStdString(&RunOpts{Dir: repo.Path}) + res, _, err := NewCommand(repo.Ctx, "rev-parse", "--verify").AddUntrustedArguments(idStr).RunStdString(&RunOpts{Dir: repo.Path}) if err != nil { return nil, err } diff --git a/modules/git/tree_nogogit.go b/modules/git/tree_nogogit.go index 185317e7a7096..b5d9b984bff2a 100644 --- a/modules/git/tree_nogogit.go +++ b/modules/git/tree_nogogit.go @@ -79,7 +79,7 @@ func (t *Tree) ListEntries() (Entries, error) { } } - stdout, _, runErr := NewCommand(t.repo.Ctx, "ls-tree", "-l").AddDynamicArguments(t.ID.String()).RunStdBytes(&RunOpts{Dir: t.repo.Path}) + stdout, _, runErr := NewCommand(t.repo.Ctx, "ls-tree", "-l").AddUntrustedArguments(t.ID.String()).RunStdBytes(&RunOpts{Dir: t.repo.Path}) if runErr != nil { if strings.Contains(runErr.Error(), "fatal: Not a valid object name") || strings.Contains(runErr.Error(), "fatal: not a tree object") { return nil, ErrNotExist{ diff --git a/modules/gitgraph/graph.go b/modules/gitgraph/graph.go index baedfe5980632..031a1a334f2bc 100644 --- a/modules/gitgraph/graph.go +++ b/modules/gitgraph/graph.go @@ -26,14 +26,14 @@ func GetCommitGraph(r *git.Repository, page, maxAllowedColors int, hidePRRefs bo graphCmd := git.NewCommand(r.Ctx, "log", "--graph", "--date-order", "--decorate=full") if hidePRRefs { - graphCmd.AddArguments("--exclude=" + git.PullPrefix + "*") + graphCmd.AddTrustedArguments("--exclude=" + git.PullPrefix + "*") } if len(branches) == 0 { - graphCmd.AddArguments("--all") + graphCmd.AddTrustedArguments("--all") } - graphCmd.AddArguments( + graphCmd.AddTrustedArguments( "-C", "-M", git.CmdArg(fmt.Sprintf("-n %d", setting.UI.GraphMaxCommitNum*page)), @@ -41,7 +41,7 @@ func GetCommitGraph(r *git.Repository, page, maxAllowedColors int, hidePRRefs bo git.CmdArg(fmt.Sprintf("--pretty=format:%s", format))) if len(branches) > 0 { - graphCmd.AddDynamicArguments(branches...) + graphCmd.AddUntrustedArguments(branches...) } if len(files) > 0 { graphCmd.AddDashesAndList(files...) diff --git a/modules/indexer/code/bleve.go b/modules/indexer/code/bleve.go index 6ee2639d34f98..287bc1773d151 100644 --- a/modules/indexer/code/bleve.go +++ b/modules/indexer/code/bleve.go @@ -193,7 +193,7 @@ func (b *BleveIndexer) addUpdate(ctx context.Context, batchWriter git.WriteClose var err error if !update.Sized { var stdout string - stdout, _, err = git.NewCommand(ctx, "cat-file", "-s").AddDynamicArguments(update.BlobSha).RunStdString(&git.RunOpts{Dir: repo.RepoPath()}) + stdout, _, err = git.NewCommand(ctx, "cat-file", "-s").AddUntrustedArguments(update.BlobSha).RunStdString(&git.RunOpts{Dir: repo.RepoPath()}) if err != nil { return err } diff --git a/modules/indexer/code/elastic_search.go b/modules/indexer/code/elastic_search.go index 68c80967585d6..0291676585887 100644 --- a/modules/indexer/code/elastic_search.go +++ b/modules/indexer/code/elastic_search.go @@ -222,7 +222,7 @@ func (b *ElasticSearchIndexer) addUpdate(ctx context.Context, batchWriter git.Wr var err error if !update.Sized { var stdout string - stdout, _, err = git.NewCommand(ctx, "cat-file", "-s").AddDynamicArguments(update.BlobSha).RunStdString(&git.RunOpts{Dir: repo.RepoPath()}) + stdout, _, err = git.NewCommand(ctx, "cat-file", "-s").AddUntrustedArguments(update.BlobSha).RunStdString(&git.RunOpts{Dir: repo.RepoPath()}) if err != nil { return nil, err } diff --git a/modules/indexer/code/git.go b/modules/indexer/code/git.go index bbcc6ba487190..ea0fa60cd73c3 100644 --- a/modules/indexer/code/git.go +++ b/modules/indexer/code/git.go @@ -28,7 +28,7 @@ type repoChanges struct { } func getDefaultBranchSha(ctx context.Context, repo *repo_model.Repository) (string, error) { - stdout, _, err := git.NewCommand(ctx, "show-ref", "-s").AddDynamicArguments(git.BranchPrefix + repo.DefaultBranch).RunStdString(&git.RunOpts{Dir: repo.RepoPath()}) + stdout, _, err := git.NewCommand(ctx, "show-ref", "-s").AddUntrustedArguments(git.BranchPrefix + repo.DefaultBranch).RunStdString(&git.RunOpts{Dir: repo.RepoPath()}) if err != nil { return "", err } @@ -91,7 +91,7 @@ func parseGitLsTreeOutput(stdout []byte) ([]fileUpdate, error) { // genesisChanges get changes to add repo to the indexer for the first time func genesisChanges(ctx context.Context, repo *repo_model.Repository, revision string) (*repoChanges, error) { var changes repoChanges - stdout, _, runErr := git.NewCommand(ctx, "ls-tree", "--full-tree", "-l", "-r").AddDynamicArguments(revision).RunStdBytes(&git.RunOpts{Dir: repo.RepoPath()}) + stdout, _, runErr := git.NewCommand(ctx, "ls-tree", "--full-tree", "-l", "-r").AddUntrustedArguments(revision).RunStdBytes(&git.RunOpts{Dir: repo.RepoPath()}) if runErr != nil { return nil, runErr } @@ -103,7 +103,7 @@ func genesisChanges(ctx context.Context, repo *repo_model.Repository, revision s // nonGenesisChanges get changes since the previous indexer update func nonGenesisChanges(ctx context.Context, repo *repo_model.Repository, revision string) (*repoChanges, error) { - diffCmd := git.NewCommand(ctx, "diff", "--name-status").AddDynamicArguments(repo.CodeIndexerStatus.CommitSha, revision) + diffCmd := git.NewCommand(ctx, "diff", "--name-status").AddUntrustedArguments(repo.CodeIndexerStatus.CommitSha, revision) stdout, _, runErr := diffCmd.RunStdString(&git.RunOpts{Dir: repo.RepoPath()}) if runErr != nil { // previous commit sha may have been removed by a force push, so @@ -168,7 +168,7 @@ func nonGenesisChanges(ctx context.Context, repo *repo_model.Repository, revisio } } - cmd := git.NewCommand(ctx, "ls-tree", "--full-tree", "-l").AddDynamicArguments(revision). + cmd := git.NewCommand(ctx, "ls-tree", "--full-tree", "-l").AddUntrustedArguments(revision). AddDashesAndList(updatedFilenames...) lsTreeStdout, _, err := cmd.RunStdBytes(&git.RunOpts{Dir: repo.RepoPath()}) if err != nil { diff --git a/modules/repository/generate.go b/modules/repository/generate.go index b6a1d7b43ef09..431d25baf898b 100644 --- a/modules/repository/generate.go +++ b/modules/repository/generate.go @@ -210,7 +210,7 @@ func generateRepoCommit(ctx context.Context, repo, templateRepo, generateRepo *r } repoPath := repo.RepoPath() - if stdout, _, err := git.NewCommand(ctx, "remote", "add", "origin").AddDynamicArguments(repoPath). + if stdout, _, err := git.NewCommand(ctx, "remote", "add", "origin").AddUntrustedArguments(repoPath). SetDescription(fmt.Sprintf("generateRepoCommit (git remote add): %s to %s", templateRepoPath, tmpDir)). RunStdString(&git.RunOpts{Dir: tmpDir, Env: env}); err != nil { log.Error("Unable to add %v as remote origin to temporary repo to %s: stdout %s\nError: %v", repo, tmpDir, stdout, err) diff --git a/modules/repository/init.go b/modules/repository/init.go index 2b0d0be7bc99c..dd46c04228f16 100644 --- a/modules/repository/init.go +++ b/modules/repository/init.go @@ -227,7 +227,7 @@ func prepareRepoCommit(ctx context.Context, repo *repo_model.Repository, tmpDir, ) // Clone to temporary path and do the init commit. - if stdout, _, err := git.NewCommand(ctx, "clone").AddDynamicArguments(repoPath, tmpDir). + if stdout, _, err := git.NewCommand(ctx, "clone").AddUntrustedArguments(repoPath, tmpDir). SetDescription(fmt.Sprintf("prepareRepoCommit (git clone): %s to %s", repoPath, tmpDir)). RunStdString(&git.RunOpts{Dir: "", Env: env}); err != nil { log.Error("Failed to clone from %v into %s: stdout: %s\nError: %v", repo, tmpDir, stdout, err) @@ -323,7 +323,7 @@ func initRepoCommit(ctx context.Context, tmpPath string, repo *repo_model.Reposi sign, keyID, signer, _ := asymkey_service.SignInitialCommit(ctx, tmpPath, u) if sign { - cmd.AddArguments(git.CmdArg("-S" + keyID)) + cmd.AddTrustedArguments(git.CmdArg("-S" + keyID)) if repo.GetTrustModel() == repo_model.CommitterTrustModel || repo.GetTrustModel() == repo_model.CollaboratorCommitterTrustModel { // need to set the committer to the KeyID owner @@ -331,7 +331,7 @@ func initRepoCommit(ctx context.Context, tmpPath string, repo *repo_model.Reposi committerEmail = signer.Email } } else { - cmd.AddArguments("--no-gpg-sign") + cmd.AddTrustedArguments("--no-gpg-sign") } env = append(env, @@ -350,7 +350,7 @@ func initRepoCommit(ctx context.Context, tmpPath string, repo *repo_model.Reposi defaultBranch = setting.Repository.DefaultBranch } - if stdout, _, err := git.NewCommand(ctx, "push", "origin").AddDynamicArguments("HEAD:" + defaultBranch). + if stdout, _, err := git.NewCommand(ctx, "push", "origin").AddUntrustedArguments("HEAD:" + defaultBranch). SetDescription(fmt.Sprintf("initRepoCommit (git push): %s", tmpPath)). RunStdString(&git.RunOpts{Dir: tmpPath, Env: InternalPushingEnvironment(u, repo)}); err != nil { log.Error("Failed to push back to HEAD: Stdout: %s\nError: %v", stdout, err) diff --git a/modules/repository/push.go b/modules/repository/push.go index 1fa711b359c34..0917669cd125c 100644 --- a/modules/repository/push.go +++ b/modules/repository/push.go @@ -103,7 +103,7 @@ func IsForcePush(ctx context.Context, opts *PushUpdateOptions) (bool, error) { return false, nil } - output, _, err := git.NewCommand(ctx, "rev-list", "--max-count=1").AddDynamicArguments(opts.OldCommitID, "^"+opts.NewCommitID). + output, _, err := git.NewCommand(ctx, "rev-list", "--max-count=1").AddUntrustedArguments(opts.OldCommitID, "^"+opts.NewCommitID). RunStdString(&git.RunOpts{Dir: repo_model.RepoPath(opts.RepoUserName, opts.RepoName)}) if err != nil { return false, err diff --git a/routers/private/hook_pre_receive.go b/routers/private/hook_pre_receive.go index 8468227077fdf..da12409c5fee8 100644 --- a/routers/private/hook_pre_receive.go +++ b/routers/private/hook_pre_receive.go @@ -186,7 +186,7 @@ func preReceiveBranch(ctx *preReceiveContext, oldCommitID, newCommitID, refFullN // 2. Disallow force pushes to protected branches if git.EmptySHA != oldCommitID { - output, _, err := git.NewCommand(ctx, "rev-list", "--max-count=1").AddDynamicArguments(oldCommitID, "^"+newCommitID).RunStdString(&git.RunOpts{Dir: repo.RepoPath(), Env: ctx.env}) + output, _, err := git.NewCommand(ctx, "rev-list", "--max-count=1").AddUntrustedArguments(oldCommitID, "^"+newCommitID).RunStdString(&git.RunOpts{Dir: repo.RepoPath(), Env: ctx.env}) if err != nil { log.Error("Unable to detect force push between: %s and %s in %-v Error: %v", oldCommitID, newCommitID, repo, err) ctx.JSON(http.StatusInternalServerError, private.Response{ diff --git a/routers/private/hook_verification.go b/routers/private/hook_verification.go index 7b9550dfddddf..19ac7fb52d631 100644 --- a/routers/private/hook_verification.go +++ b/routers/private/hook_verification.go @@ -43,7 +43,7 @@ func verifyCommits(oldCommitID, newCommitID string, repo *git.Repository, env [] }() // This is safe as force pushes are already forbidden - err = git.NewCommand(repo.Ctx, "rev-list").AddDynamicArguments(oldCommitID + "..." + newCommitID). + err = git.NewCommand(repo.Ctx, "rev-list").AddUntrustedArguments(oldCommitID + "..." + newCommitID). Run(&git.RunOpts{ Env: env, Dir: repo.Path, @@ -90,7 +90,7 @@ func readAndVerifyCommit(sha string, repo *git.Repository, env []string) error { }() hash := git.MustIDFromString(sha) - return git.NewCommand(repo.Ctx, "cat-file", "commit").AddDynamicArguments(sha). + return git.NewCommand(repo.Ctx, "cat-file", "commit").AddUntrustedArguments(sha). Run(&git.RunOpts{ Env: env, Dir: repo.Path, diff --git a/routers/web/repo/http.go b/routers/web/repo/http.go index b2a49e3e3a103..695a1bbf8096f 100644 --- a/routers/web/repo/http.go +++ b/routers/web/repo/http.go @@ -397,7 +397,7 @@ func (h *serviceHandler) sendFile(contentType, file string) { var safeGitProtocolHeader = regexp.MustCompile(`^[0-9a-zA-Z]+=[0-9a-zA-Z]+(:[0-9a-zA-Z]+=[0-9a-zA-Z]+)*$`) func getGitConfig(ctx gocontext.Context, option, dir string) string { - out, _, err := git.NewCommand(ctx, "config").AddDynamicArguments(option).RunStdString(&git.RunOpts{Dir: dir}) + out, _, err := git.NewCommand(ctx, "config").AddUntrustedArguments(option).RunStdString(&git.RunOpts{Dir: dir}) if err != nil { log.Error("%v - %s", err, out) } @@ -470,7 +470,7 @@ func serviceRPC(ctx gocontext.Context, h serviceHandler, service string) { } var stderr bytes.Buffer - cmd := git.NewCommand(h.r.Context(), git.CmdArgCheck(service), "--stateless-rpc").AddDynamicArguments(h.dir) + cmd := git.NewCommand(h.r.Context(), git.CmdArgCheck(service), "--stateless-rpc").AddUntrustedArguments(h.dir) cmd.SetDescription(fmt.Sprintf("%s %s %s [repo_path: %s]", git.GitExecutable, service, "--stateless-rpc", h.dir)) if err := cmd.Run(&git.RunOpts{ Dir: h.dir, diff --git a/routers/web/repo/pull.go b/routers/web/repo/pull.go index c2208120fcf24..63ee43f27e943 100644 --- a/routers/web/repo/pull.go +++ b/routers/web/repo/pull.go @@ -371,7 +371,7 @@ func PrepareMergedViewPullInfo(ctx *context.Context, issue *issues_model.Issue) } if commitSHA != "" { // Get immediate parent of the first commit in the patch, grab history back - parentCommit, _, err = git.NewCommand(ctx, "rev-list", "-1", "--skip=1").AddDynamicArguments(commitSHA).RunStdString(&git.RunOpts{Dir: ctx.Repo.GitRepo.Path}) + parentCommit, _, err = git.NewCommand(ctx, "rev-list", "-1", "--skip=1").AddUntrustedArguments(commitSHA).RunStdString(&git.RunOpts{Dir: ctx.Repo.GitRepo.Path}) if err == nil { parentCommit = strings.TrimSpace(parentCommit) } diff --git a/services/agit/agit.go b/services/agit/agit.go index b61cb6f3f5692..fbb6be987ebb0 100644 --- a/services/agit/agit.go +++ b/services/agit/agit.go @@ -178,7 +178,7 @@ func ProcReceive(ctx context.Context, repo *repo_model.Repository, gitRepo *git. } if !forcePush { - output, _, err := git.NewCommand(ctx, "rev-list", "--max-count=1").AddDynamicArguments(oldCommitID, "^"+opts.NewCommitIDs[i]).RunStdString(&git.RunOpts{Dir: repo.RepoPath(), Env: os.Environ()}) + output, _, err := git.NewCommand(ctx, "rev-list", "--max-count=1").AddUntrustedArguments(oldCommitID, "^"+opts.NewCommitIDs[i]).RunStdString(&git.RunOpts{Dir: repo.RepoPath(), Env: os.Environ()}) if err != nil { return nil, fmt.Errorf("Fail to detect force push: %w", err) } else if len(output) > 0 { diff --git a/services/migrations/dump.go b/services/migrations/dump.go index cc8518d4a25c6..0fbb0b919e5e5 100644 --- a/services/migrations/dump.go +++ b/services/migrations/dump.go @@ -490,7 +490,7 @@ func (g *RepositoryDumper) handlePullRequest(pr *base.PullRequest) error { if pr.Head.CloneURL == "" || pr.Head.Ref == "" { // Set head information if pr.Head.SHA is available if pr.Head.SHA != "" { - _, _, err = git.NewCommand(g.ctx, "update-ref", "--no-deref").AddDynamicArguments(pr.GetGitRefName(), pr.Head.SHA).RunStdString(&git.RunOpts{Dir: g.gitPath()}) + _, _, err = git.NewCommand(g.ctx, "update-ref", "--no-deref").AddUntrustedArguments(pr.GetGitRefName(), pr.Head.SHA).RunStdString(&git.RunOpts{Dir: g.gitPath()}) if err != nil { log.Error("PR #%d in %s/%s unable to update-ref for pr HEAD: %v", pr.Number, g.repoOwner, g.repoName, err) } @@ -520,7 +520,7 @@ func (g *RepositoryDumper) handlePullRequest(pr *base.PullRequest) error { if !ok { // Set head information if pr.Head.SHA is available if pr.Head.SHA != "" { - _, _, err = git.NewCommand(g.ctx, "update-ref", "--no-deref").AddDynamicArguments(pr.GetGitRefName(), pr.Head.SHA).RunStdString(&git.RunOpts{Dir: g.gitPath()}) + _, _, err = git.NewCommand(g.ctx, "update-ref", "--no-deref").AddUntrustedArguments(pr.GetGitRefName(), pr.Head.SHA).RunStdString(&git.RunOpts{Dir: g.gitPath()}) if err != nil { log.Error("PR #%d in %s/%s unable to update-ref for pr HEAD: %v", pr.Number, g.repoOwner, g.repoName, err) } @@ -579,7 +579,7 @@ func (g *RepositoryDumper) handlePullRequest(pr *base.PullRequest) error { pr.Head.SHA = headSha } if pr.Head.SHA != "" { - _, _, err = git.NewCommand(g.ctx, "update-ref", "--no-deref").AddDynamicArguments(pr.GetGitRefName(), pr.Head.SHA).RunStdString(&git.RunOpts{Dir: g.gitPath()}) + _, _, err = git.NewCommand(g.ctx, "update-ref", "--no-deref").AddUntrustedArguments(pr.GetGitRefName(), pr.Head.SHA).RunStdString(&git.RunOpts{Dir: g.gitPath()}) if err != nil { log.Error("unable to set %s as the local head for PR #%d from %s in %s/%s. Error: %v", pr.Head.SHA, pr.Number, pr.Head.Ref, g.repoOwner, g.repoName, err) } diff --git a/services/migrations/gitea_uploader.go b/services/migrations/gitea_uploader.go index 20370d99f9824..dbd8eb9d272cf 100644 --- a/services/migrations/gitea_uploader.go +++ b/services/migrations/gitea_uploader.go @@ -654,7 +654,7 @@ func (g *GiteaLocalUploader) updateGitForPullRequest(pr *base.PullRequest) (head pr.Head.SHA = headSha } - _, _, err = git.NewCommand(g.ctx, "update-ref", "--no-deref").AddDynamicArguments(pr.GetGitRefName(), pr.Head.SHA).RunStdString(&git.RunOpts{Dir: g.repo.RepoPath()}) + _, _, err = git.NewCommand(g.ctx, "update-ref", "--no-deref").AddUntrustedArguments(pr.GetGitRefName(), pr.Head.SHA).RunStdString(&git.RunOpts{Dir: g.repo.RepoPath()}) if err != nil { return "", err } @@ -671,13 +671,13 @@ func (g *GiteaLocalUploader) updateGitForPullRequest(pr *base.PullRequest) (head // The SHA is empty log.Warn("Empty reference, no pull head for PR #%d in %s/%s", pr.Number, g.repoOwner, g.repoName) } else { - _, _, err = git.NewCommand(g.ctx, "rev-list", "--quiet", "-1").AddDynamicArguments(pr.Head.SHA).RunStdString(&git.RunOpts{Dir: g.repo.RepoPath()}) + _, _, err = git.NewCommand(g.ctx, "rev-list", "--quiet", "-1").AddUntrustedArguments(pr.Head.SHA).RunStdString(&git.RunOpts{Dir: g.repo.RepoPath()}) if err != nil { // Git update-ref remove bad references with a relative path log.Warn("Deprecated local head %s for PR #%d in %s/%s, removing %s", pr.Head.SHA, pr.Number, g.repoOwner, g.repoName, pr.GetGitRefName()) } else { // set head information - _, _, err = git.NewCommand(g.ctx, "update-ref", "--no-deref").AddDynamicArguments(pr.GetGitRefName(), pr.Head.SHA).RunStdString(&git.RunOpts{Dir: g.repo.RepoPath()}) + _, _, err = git.NewCommand(g.ctx, "update-ref", "--no-deref").AddUntrustedArguments(pr.GetGitRefName(), pr.Head.SHA).RunStdString(&git.RunOpts{Dir: g.repo.RepoPath()}) if err != nil { log.Error("unable to set %s as the local head for PR #%d from %s in %s/%s. Error: %v", pr.Head.SHA, pr.Number, pr.Head.Ref, g.repoOwner, g.repoName, err) } diff --git a/services/migrations/gitea_uploader_test.go b/services/migrations/gitea_uploader_test.go index 6a942b9b57637..b53605dbf6f34 100644 --- a/services/migrations/gitea_uploader_test.go +++ b/services/migrations/gitea_uploader_test.go @@ -233,7 +233,7 @@ func TestGiteaUploadUpdateGitForPullRequest(t *testing.T) { fromRepo := unittest.AssertExistsAndLoadBean(t, &repo_model.Repository{ID: 1}) baseRef := "master" assert.NoError(t, git.InitRepository(git.DefaultContext, fromRepo.RepoPath(), false)) - err := git.NewCommand(git.DefaultContext, "symbolic-ref").AddDynamicArguments("HEAD", git.BranchPrefix+baseRef).Run(&git.RunOpts{Dir: fromRepo.RepoPath()}) + err := git.NewCommand(git.DefaultContext, "symbolic-ref").AddUntrustedArguments("HEAD", git.BranchPrefix+baseRef).Run(&git.RunOpts{Dir: fromRepo.RepoPath()}) assert.NoError(t, err) assert.NoError(t, os.WriteFile(filepath.Join(fromRepo.RepoPath(), "README.md"), []byte(fmt.Sprintf("# Testing Repository\n\nOriginally created in: %s", fromRepo.RepoPath())), 0o644)) assert.NoError(t, git.AddChanges(fromRepo.RepoPath(), true)) @@ -257,7 +257,7 @@ func TestGiteaUploadUpdateGitForPullRequest(t *testing.T) { // fromRepo branch1 // headRef := "branch1" - _, _, err = git.NewCommand(git.DefaultContext, "checkout", "-b").AddDynamicArguments(headRef).RunStdString(&git.RunOpts{Dir: fromRepo.RepoPath()}) + _, _, err = git.NewCommand(git.DefaultContext, "checkout", "-b").AddUntrustedArguments(headRef).RunStdString(&git.RunOpts{Dir: fromRepo.RepoPath()}) assert.NoError(t, err) assert.NoError(t, os.WriteFile(filepath.Join(fromRepo.RepoPath(), "README.md"), []byte("SOMETHING"), 0o644)) assert.NoError(t, git.AddChanges(fromRepo.RepoPath(), true)) @@ -281,7 +281,7 @@ func TestGiteaUploadUpdateGitForPullRequest(t *testing.T) { assert.NoError(t, git.CloneWithArgs(git.DefaultContext, nil, fromRepo.RepoPath(), forkRepo.RepoPath(), git.CloneRepoOptions{ Branch: headRef, })) - _, _, err = git.NewCommand(git.DefaultContext, "checkout", "-b").AddDynamicArguments(forkHeadRef).RunStdString(&git.RunOpts{Dir: forkRepo.RepoPath()}) + _, _, err = git.NewCommand(git.DefaultContext, "checkout", "-b").AddUntrustedArguments(forkHeadRef).RunStdString(&git.RunOpts{Dir: forkRepo.RepoPath()}) assert.NoError(t, err) assert.NoError(t, os.WriteFile(filepath.Join(forkRepo.RepoPath(), "README.md"), []byte(fmt.Sprintf("# branch2 %s", forkRepo.RepoPath())), 0o644)) assert.NoError(t, git.AddChanges(forkRepo.RepoPath(), true)) diff --git a/services/mirror/mirror_pull.go b/services/mirror/mirror_pull.go index 98e8d122a5dfa..7fdbb2611053c 100644 --- a/services/mirror/mirror_pull.go +++ b/services/mirror/mirror_pull.go @@ -32,12 +32,12 @@ func UpdateAddress(ctx context.Context, m *repo_model.Mirror, addr string) error remoteName := m.GetRemoteName() repoPath := m.GetRepository().RepoPath() // Remove old remote - _, _, err := git.NewCommand(ctx, "remote", "rm").AddDynamicArguments(remoteName).RunStdString(&git.RunOpts{Dir: repoPath}) + _, _, err := git.NewCommand(ctx, "remote", "rm").AddUntrustedArguments(remoteName).RunStdString(&git.RunOpts{Dir: repoPath}) if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") { return err } - cmd := git.NewCommand(ctx, "remote", "add").AddDynamicArguments(remoteName).AddArguments("--mirror=fetch").AddDynamicArguments(addr) + cmd := git.NewCommand(ctx, "remote", "add").AddUntrustedArguments(remoteName).AddTrustedArguments("--mirror=fetch").AddUntrustedArguments(addr) if strings.Contains(addr, "://") && strings.Contains(addr, "@") { cmd.SetDescription(fmt.Sprintf("remote add %s --mirror=fetch %s [repo_path: %s]", remoteName, util.SanitizeCredentialURLs(addr), repoPath)) } else { @@ -52,12 +52,12 @@ func UpdateAddress(ctx context.Context, m *repo_model.Mirror, addr string) error wikiPath := m.Repo.WikiPath() wikiRemotePath := repo_module.WikiRemoteURL(ctx, addr) // Remove old remote of wiki - _, _, err = git.NewCommand(ctx, "remote", "rm").AddDynamicArguments(remoteName).RunStdString(&git.RunOpts{Dir: wikiPath}) + _, _, err = git.NewCommand(ctx, "remote", "rm").AddUntrustedArguments(remoteName).RunStdString(&git.RunOpts{Dir: wikiPath}) if err != nil && !strings.HasPrefix(err.Error(), "exit status 128 - fatal: No such remote ") { return err } - cmd = git.NewCommand(ctx, "remote", "add").AddDynamicArguments(remoteName).AddArguments("--mirror=fetch").AddDynamicArguments(wikiRemotePath) + cmd = git.NewCommand(ctx, "remote", "add").AddUntrustedArguments(remoteName).AddTrustedArguments("--mirror=fetch").AddUntrustedArguments(wikiRemotePath) if strings.Contains(wikiRemotePath, "://") && strings.Contains(wikiRemotePath, "@") { cmd.SetDescription(fmt.Sprintf("remote add %s --mirror=fetch %s [repo_path: %s]", remoteName, util.SanitizeCredentialURLs(wikiRemotePath), wikiPath)) } else { @@ -168,7 +168,7 @@ func pruneBrokenReferences(ctx context.Context, stderrBuilder.Reset() stdoutBuilder.Reset() - pruneErr := git.NewCommand(ctx, "remote", "prune").AddDynamicArguments(m.GetRemoteName()). + pruneErr := git.NewCommand(ctx, "remote", "prune").AddUntrustedArguments(m.GetRemoteName()). SetDescription(fmt.Sprintf("Mirror.runSync %ssPrune references: %s ", wiki, m.Repo.FullName())). Run(&git.RunOpts{ Timeout: timeout, @@ -308,7 +308,7 @@ func runSync(ctx context.Context, m *repo_model.Mirror) ([]*mirrorSyncResult, bo log.Trace("SyncMirrors [repo: %-v Wiki]: running git remote update...", m.Repo) stderrBuilder.Reset() stdoutBuilder.Reset() - if err := git.NewCommand(ctx, "remote", "update", "--prune").AddDynamicArguments(m.GetRemoteName()). + if err := git.NewCommand(ctx, "remote", "update", "--prune").AddUntrustedArguments(m.GetRemoteName()). SetDescription(fmt.Sprintf("Mirror.runSync Wiki: %s ", m.Repo.FullName())). Run(&git.RunOpts{ Timeout: timeout, @@ -335,7 +335,7 @@ func runSync(ctx context.Context, m *repo_model.Mirror) ([]*mirrorSyncResult, bo stderrBuilder.Reset() stdoutBuilder.Reset() - if err = git.NewCommand(ctx, "remote", "update", "--prune").AddDynamicArguments(m.GetRemoteName()). + if err = git.NewCommand(ctx, "remote", "update", "--prune").AddUntrustedArguments(m.GetRemoteName()). SetDescription(fmt.Sprintf("Mirror.runSync Wiki: %s ", m.Repo.FullName())). Run(&git.RunOpts{ Timeout: timeout, diff --git a/services/mirror/mirror_push.go b/services/mirror/mirror_push.go index c0c68a3f54161..eccee70d2c0e2 100644 --- a/services/mirror/mirror_push.go +++ b/services/mirror/mirror_push.go @@ -28,7 +28,7 @@ var stripExitStatus = regexp.MustCompile(`exit status \d+ - `) // AddPushMirrorRemote registers the push mirror remote. func AddPushMirrorRemote(ctx context.Context, m *repo_model.PushMirror, addr string) error { addRemoteAndConfig := func(addr, path string) error { - cmd := git.NewCommand(ctx, "remote", "add", "--mirror=push").AddDynamicArguments(m.RemoteName, addr) + cmd := git.NewCommand(ctx, "remote", "add", "--mirror=push").AddUntrustedArguments(m.RemoteName, addr) if strings.Contains(addr, "://") && strings.Contains(addr, "@") { cmd.SetDescription(fmt.Sprintf("remote add %s --mirror=push %s [repo_path: %s]", m.RemoteName, util.SanitizeCredentialURLs(addr), path)) } else { @@ -64,7 +64,7 @@ func AddPushMirrorRemote(ctx context.Context, m *repo_model.PushMirror, addr str // RemovePushMirrorRemote removes the push mirror remote. func RemovePushMirrorRemote(ctx context.Context, m *repo_model.PushMirror) error { - cmd := git.NewCommand(ctx, "remote", "rm").AddDynamicArguments(m.RemoteName) + cmd := git.NewCommand(ctx, "remote", "rm").AddUntrustedArguments(m.RemoteName) _ = m.GetRepository() if _, _, err := cmd.RunStdString(&git.RunOpts{Dir: m.Repo.RepoPath()}); err != nil { diff --git a/services/pull/check.go b/services/pull/check.go index db86378909c49..16628dfbe384e 100644 --- a/services/pull/check.go +++ b/services/pull/check.go @@ -186,7 +186,7 @@ func getMergeCommit(ctx context.Context, pr *issues_model.PullRequest) (*git.Com headFile := pr.GetGitRefName() // Check if a pull request is merged into BaseBranch - _, _, err = git.NewCommand(ctx, "merge-base", "--is-ancestor").AddDynamicArguments(headFile, pr.BaseBranch). + _, _, err = git.NewCommand(ctx, "merge-base", "--is-ancestor").AddUntrustedArguments(headFile, pr.BaseBranch). RunStdString(&git.RunOpts{Dir: pr.BaseRepo.RepoPath(), Env: []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()}}) if err != nil { // Errors are signaled by a non-zero status that is not 1 @@ -207,7 +207,7 @@ func getMergeCommit(ctx context.Context, pr *issues_model.PullRequest) (*git.Com cmd := commitID[:git.SHAFullLength] + ".." + pr.BaseBranch // Get the commit from BaseBranch where the pull request got merged - mergeCommit, _, err := git.NewCommand(ctx, "rev-list", "--ancestry-path", "--merges", "--reverse").AddDynamicArguments(cmd). + mergeCommit, _, err := git.NewCommand(ctx, "rev-list", "--ancestry-path", "--merges", "--reverse").AddUntrustedArguments(cmd). RunStdString(&git.RunOpts{Dir: "", Env: []string{"GIT_INDEX_FILE=" + indexTmpPath, "GIT_DIR=" + pr.BaseRepo.RepoPath()}}) if err != nil { return nil, fmt.Errorf("git rev-list --ancestry-path --merges --reverse: %w", err) diff --git a/services/pull/merge.go b/services/pull/merge.go index bdd2cb0e8651f..1dd55858a29a5 100644 --- a/services/pull/merge.go +++ b/services/pull/merge.go @@ -255,7 +255,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode stagingBranch := "staging" if expectedHeadCommitID != "" { - trackingCommitID, _, err := git.NewCommand(ctx, "show-ref", "--hash").AddDynamicArguments(git.BranchPrefix + trackingBranch).RunStdString(&git.RunOpts{Dir: tmpBasePath}) + trackingCommitID, _, err := git.NewCommand(ctx, "show-ref", "--hash").AddUntrustedArguments(git.BranchPrefix + trackingBranch).RunStdString(&git.RunOpts{Dir: tmpBasePath}) if err != nil { log.Error("show-ref[%s] --hash refs/heads/trackingn: %v", tmpBasePath, git.BranchPrefix+trackingBranch, err) return "", fmt.Errorf("getDiffTree: %w", err) @@ -294,7 +294,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode } // Switch off LFS process (set required, clean and smudge here also) - if err := gitConfigCommand().AddArguments("filter.lfs.process", ""). + if err := gitConfigCommand().AddTrustedArguments("filter.lfs.process", ""). Run(&git.RunOpts{ Dir: tmpBasePath, Stdout: &outbuf, @@ -306,7 +306,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode outbuf.Reset() errbuf.Reset() - if err := gitConfigCommand().AddArguments("filter.lfs.required", "false"). + if err := gitConfigCommand().AddTrustedArguments("filter.lfs.required", "false"). Run(&git.RunOpts{ Dir: tmpBasePath, Stdout: &outbuf, @@ -318,7 +318,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode outbuf.Reset() errbuf.Reset() - if err := gitConfigCommand().AddArguments("filter.lfs.clean", ""). + if err := gitConfigCommand().AddTrustedArguments("filter.lfs.clean", ""). Run(&git.RunOpts{ Dir: tmpBasePath, Stdout: &outbuf, @@ -330,7 +330,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode outbuf.Reset() errbuf.Reset() - if err := gitConfigCommand().AddArguments("filter.lfs.smudge", ""). + if err := gitConfigCommand().AddTrustedArguments("filter.lfs.smudge", ""). Run(&git.RunOpts{ Dir: tmpBasePath, Stdout: &outbuf, @@ -342,7 +342,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode outbuf.Reset() errbuf.Reset() - if err := gitConfigCommand().AddArguments("core.sparseCheckout", "true"). + if err := gitConfigCommand().AddTrustedArguments("core.sparseCheckout", "true"). Run(&git.RunOpts{ Dir: tmpBasePath, Stdout: &outbuf, @@ -397,7 +397,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode // Merge commits. switch mergeStyle { case repo_model.MergeStyleMerge: - cmd := git.NewCommand(ctx, "merge", "--no-ff", "--no-commit").AddDynamicArguments(trackingBranch) + cmd := git.NewCommand(ctx, "merge", "--no-ff", "--no-commit").AddUntrustedArguments(trackingBranch) if err := runMergeCommand(pr, mergeStyle, cmd, tmpBasePath); err != nil { log.Error("Unable to merge tracking into base: %v", err) return "", err @@ -413,7 +413,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode fallthrough case repo_model.MergeStyleRebaseMerge: // Checkout head branch - if err := git.NewCommand(ctx, "checkout", "-b").AddDynamicArguments(stagingBranch, trackingBranch). + if err := git.NewCommand(ctx, "checkout", "-b").AddUntrustedArguments(stagingBranch, trackingBranch). Run(&git.RunOpts{ Dir: tmpBasePath, Stdout: &outbuf, @@ -426,7 +426,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode errbuf.Reset() // Rebase before merging - if err := git.NewCommand(ctx, "rebase").AddDynamicArguments(baseBranch). + if err := git.NewCommand(ctx, "rebase").AddUntrustedArguments(baseBranch). Run(&git.RunOpts{ Dir: tmpBasePath, Stdout: &outbuf, @@ -479,7 +479,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode } // Checkout base branch again - if err := git.NewCommand(ctx, "checkout").AddDynamicArguments(baseBranch). + if err := git.NewCommand(ctx, "checkout").AddUntrustedArguments(baseBranch). Run(&git.RunOpts{ Dir: tmpBasePath, Stdout: &outbuf, @@ -493,11 +493,11 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode cmd := git.NewCommand(ctx, "merge") if mergeStyle == repo_model.MergeStyleRebase { - cmd.AddArguments("--ff-only") + cmd.AddTrustedArguments("--ff-only") } else { - cmd.AddArguments("--no-ff", "--no-commit") + cmd.AddTrustedArguments("--no-ff", "--no-commit") } - cmd.AddDynamicArguments(stagingBranch) + cmd.AddUntrustedArguments(stagingBranch) // Prepare merge with commit if err := runMergeCommand(pr, mergeStyle, cmd, tmpBasePath); err != nil { @@ -512,7 +512,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode } case repo_model.MergeStyleSquash: // Merge with squash - cmd := git.NewCommand(ctx, "merge", "--squash").AddDynamicArguments(trackingBranch) + cmd := git.NewCommand(ctx, "merge", "--squash").AddUntrustedArguments(trackingBranch) if err := runMergeCommand(pr, mergeStyle, cmd, tmpBasePath); err != nil { log.Error("Unable to merge --squash tracking into base: %v", err) return "", err @@ -524,7 +524,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode } sig := pr.Issue.Poster.NewGitSig() if signArg == "" { - if err := git.NewCommand(ctx, "commit", git.CmdArg(fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email)), "-m").AddDynamicArguments(message). + if err := git.NewCommand(ctx, "commit", git.CmdArg(fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email)), "-m").AddUntrustedArguments(message). Run(&git.RunOpts{ Env: env, Dir: tmpBasePath, @@ -540,9 +540,9 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode message += fmt.Sprintf("\nCo-authored-by: %s\nCo-committed-by: %s\n", sig.String(), sig.String()) } if err := git.NewCommand(ctx, "commit"). - AddArguments(signArg). - AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email))). - AddArguments("-m").AddDynamicArguments(message). + AddTrustedArguments(signArg). + AddTrustedArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email))). + AddTrustedArguments("-m").AddUntrustedArguments(message). Run(&git.RunOpts{ Env: env, Dir: tmpBasePath, @@ -605,7 +605,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode pr.HeadRepo.Name, pr.ID, ) - pushCmd = git.NewCommand(ctx, "push", "-f", "head_repo").AddDynamicArguments(stagingBranch + ":" + git.BranchPrefix + pr.HeadBranch) + pushCmd = git.NewCommand(ctx, "push", "-f", "head_repo").AddUntrustedArguments(stagingBranch + ":" + git.BranchPrefix + pr.HeadBranch) } else { env = repo_module.FullPushingEnvironment( headUser, @@ -614,7 +614,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode pr.BaseRepo.Name, pr.ID, ) - pushCmd = git.NewCommand(ctx, "push", "origin").AddDynamicArguments(baseBranch + ":" + git.BranchPrefix + pr.BaseBranch) + pushCmd = git.NewCommand(ctx, "push", "origin").AddUntrustedArguments(baseBranch + ":" + git.BranchPrefix + pr.BaseBranch) } // Push back to upstream. @@ -652,7 +652,7 @@ func rawMerge(ctx context.Context, pr *issues_model.PullRequest, doer *user_mode func commitAndSignNoAuthor(ctx context.Context, pr *issues_model.PullRequest, message string, signArg git.CmdArg, tmpBasePath string, env []string) error { var outbuf, errbuf strings.Builder if signArg == "" { - if err := git.NewCommand(ctx, "commit", "-m").AddDynamicArguments(message). + if err := git.NewCommand(ctx, "commit", "-m").AddUntrustedArguments(message). Run(&git.RunOpts{ Env: env, Dir: tmpBasePath, @@ -663,7 +663,7 @@ func commitAndSignNoAuthor(ctx context.Context, pr *issues_model.PullRequest, me return fmt.Errorf("git commit [%s:%s -> %s:%s]: %w\n%s\n%s", pr.HeadRepo.FullName(), pr.HeadBranch, pr.BaseRepo.FullName(), pr.BaseBranch, err, outbuf.String(), errbuf.String()) } } else { - if err := git.NewCommand(ctx, "commit").AddArguments(signArg).AddArguments("-m").AddDynamicArguments(message). + if err := git.NewCommand(ctx, "commit").AddTrustedArguments(signArg).AddTrustedArguments("-m").AddUntrustedArguments(message). Run(&git.RunOpts{ Env: env, Dir: tmpBasePath, @@ -716,7 +716,7 @@ func getDiffTree(ctx context.Context, repoPath, baseBranch, headBranch string) ( getDiffTreeFromBranch := func(repoPath, baseBranch, headBranch string) (string, error) { var outbuf, errbuf strings.Builder // Compute the diff-tree for sparse-checkout - if err := git.NewCommand(ctx, "diff-tree", "--no-commit-id", "--name-only", "-r", "-z", "--root").AddDynamicArguments(baseBranch, headBranch). + if err := git.NewCommand(ctx, "diff-tree", "--no-commit-id", "--name-only", "-r", "-z", "--root").AddUntrustedArguments(baseBranch, headBranch). Run(&git.RunOpts{ Dir: repoPath, Stdout: &outbuf, diff --git a/services/pull/patch.go b/services/pull/patch.go index 26a72a7371bf1..792d4cd593dd2 100644 --- a/services/pull/patch.go +++ b/services/pull/patch.go @@ -181,7 +181,7 @@ func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, g } // Need to get the objects from the object db to attempt to merge - root, _, err := git.NewCommand(ctx, "unpack-file").AddDynamicArguments(file.stage1.sha).RunStdString(&git.RunOpts{Dir: tmpBasePath}) + root, _, err := git.NewCommand(ctx, "unpack-file").AddUntrustedArguments(file.stage1.sha).RunStdString(&git.RunOpts{Dir: tmpBasePath}) if err != nil { return fmt.Errorf("unable to get root object: %s at path: %s for merging. Error: %w", file.stage1.sha, file.stage1.path, err) } @@ -190,7 +190,7 @@ func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, g _ = util.Remove(filepath.Join(tmpBasePath, root)) }() - base, _, err := git.NewCommand(ctx, "unpack-file").AddDynamicArguments(file.stage2.sha).RunStdString(&git.RunOpts{Dir: tmpBasePath}) + base, _, err := git.NewCommand(ctx, "unpack-file").AddUntrustedArguments(file.stage2.sha).RunStdString(&git.RunOpts{Dir: tmpBasePath}) if err != nil { return fmt.Errorf("unable to get base object: %s at path: %s for merging. Error: %w", file.stage2.sha, file.stage2.path, err) } @@ -198,7 +198,7 @@ func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, g defer func() { _ = util.Remove(base) }() - head, _, err := git.NewCommand(ctx, "unpack-file").AddDynamicArguments(file.stage3.sha).RunStdString(&git.RunOpts{Dir: tmpBasePath}) + head, _, err := git.NewCommand(ctx, "unpack-file").AddUntrustedArguments(file.stage3.sha).RunStdString(&git.RunOpts{Dir: tmpBasePath}) if err != nil { return fmt.Errorf("unable to get head object:%s at path: %s for merging. Error: %w", file.stage3.sha, file.stage3.path, err) } @@ -208,13 +208,13 @@ func attemptMerge(ctx context.Context, file *unmergedFile, tmpBasePath string, g }() // now git merge-file annoyingly takes a different order to the merge-tree ... - _, _, conflictErr := git.NewCommand(ctx, "merge-file").AddDynamicArguments(base, root, head).RunStdString(&git.RunOpts{Dir: tmpBasePath}) + _, _, conflictErr := git.NewCommand(ctx, "merge-file").AddUntrustedArguments(base, root, head).RunStdString(&git.RunOpts{Dir: tmpBasePath}) if conflictErr != nil { return &errMergeConflict{file.stage2.path} } // base now contains the merged data - hash, _, err := git.NewCommand(ctx, "hash-object", "-w", "--path").AddDynamicArguments(file.stage2.path, base).RunStdString(&git.RunOpts{Dir: tmpBasePath}) + hash, _, err := git.NewCommand(ctx, "hash-object", "-w", "--path").AddUntrustedArguments(file.stage2.path, base).RunStdString(&git.RunOpts{Dir: tmpBasePath}) if err != nil { return err } @@ -238,7 +238,7 @@ func AttemptThreeWayMerge(ctx context.Context, gitPath string, gitRepo *git.Repo defer cancel() // First we use read-tree to do a simple three-way merge - if _, _, err := git.NewCommand(ctx, "read-tree", "-m").AddDynamicArguments(base, ours, theirs).RunStdString(&git.RunOpts{Dir: gitPath}); err != nil { + if _, _, err := git.NewCommand(ctx, "read-tree", "-m").AddUntrustedArguments(base, ours, theirs).RunStdString(&git.RunOpts{Dir: gitPath}); err != nil { log.Error("Unable to run read-tree -m! Error: %v", err) return false, nil, fmt.Errorf("unable to run read-tree -m! Error: %w", err) } diff --git a/services/pull/pull.go b/services/pull/pull.go index 08f70a5e4ef02..d1c1a6501f280 100644 --- a/services/pull/pull.go +++ b/services/pull/pull.go @@ -489,7 +489,7 @@ func UpdateRef(ctx context.Context, pr *issues_model.PullRequest) (err error) { return err } - _, _, err = git.NewCommand(ctx, "update-ref").AddDynamicArguments(pr.GetGitRefName(), pr.HeadCommitID).RunStdString(&git.RunOpts{Dir: pr.BaseRepo.RepoPath()}) + _, _, err = git.NewCommand(ctx, "update-ref").AddUntrustedArguments(pr.GetGitRefName(), pr.HeadCommitID).RunStdString(&git.RunOpts{Dir: pr.BaseRepo.RepoPath()}) if err != nil { log.Error("Unable to update ref in base repository for PR[%d] Error: %v", pr.ID, err) } diff --git a/services/pull/temp_repo.go b/services/pull/temp_repo.go index d49a15cea00ad..bf735c8ca4dfe 100644 --- a/services/pull/temp_repo.go +++ b/services/pull/temp_repo.go @@ -93,7 +93,7 @@ func createTemporaryRepo(ctx context.Context, pr *issues_model.PullRequest) (str } var outbuf, errbuf strings.Builder - if err := git.NewCommand(ctx, "remote", "add", "-t").AddDynamicArguments(pr.BaseBranch).AddArguments("-m").AddDynamicArguments(pr.BaseBranch).AddDynamicArguments("origin", baseRepoPath). + if err := git.NewCommand(ctx, "remote", "add", "-t").AddUntrustedArguments(pr.BaseBranch).AddTrustedArguments("-m").AddUntrustedArguments(pr.BaseBranch).AddUntrustedArguments("origin", baseRepoPath). Run(&git.RunOpts{ Dir: tmpBasePath, Stdout: &outbuf, @@ -123,7 +123,7 @@ func createTemporaryRepo(ctx context.Context, pr *issues_model.PullRequest) (str outbuf.Reset() errbuf.Reset() - if err := git.NewCommand(ctx, "symbolic-ref").AddDynamicArguments("HEAD", git.BranchPrefix+baseBranch). + if err := git.NewCommand(ctx, "symbolic-ref").AddUntrustedArguments("HEAD", git.BranchPrefix+baseBranch). Run(&git.RunOpts{ Dir: tmpBasePath, Stdout: &outbuf, @@ -146,7 +146,7 @@ func createTemporaryRepo(ctx context.Context, pr *issues_model.PullRequest) (str return "", fmt.Errorf("Unable to head base repository to temporary repo [%s -> tmpBasePath]: %w", pr.HeadRepo.FullName(), err) } - if err := git.NewCommand(ctx, "remote", "add").AddDynamicArguments(remoteRepoName, headRepoPath). + if err := git.NewCommand(ctx, "remote", "add").AddUntrustedArguments(remoteRepoName, headRepoPath). Run(&git.RunOpts{ Dir: tmpBasePath, Stdout: &outbuf, @@ -171,7 +171,7 @@ func createTemporaryRepo(ctx context.Context, pr *issues_model.PullRequest) (str } else { headBranch = pr.GetGitRefName() } - if err := git.NewCommand(ctx, "fetch", "--no-tags").AddDynamicArguments(remoteRepoName, headBranch+":"+trackingBranch). + if err := git.NewCommand(ctx, "fetch", "--no-tags").AddUntrustedArguments(remoteRepoName, headBranch+":"+trackingBranch). Run(&git.RunOpts{ Dir: tmpBasePath, Stdout: &outbuf, diff --git a/services/repository/files/temp_repo.go b/services/repository/files/temp_repo.go index 1f3375cdcc83c..49567db4c6a0a 100644 --- a/services/repository/files/temp_repo.go +++ b/services/repository/files/temp_repo.go @@ -52,7 +52,7 @@ func (t *TemporaryUploadRepository) Close() { // Clone the base repository to our path and set branch as the HEAD func (t *TemporaryUploadRepository) Clone(branch string) error { - if _, _, err := git.NewCommand(t.ctx, "clone", "-s", "--bare", "-b").AddDynamicArguments(branch, t.repo.RepoPath(), t.basePath).RunStdString(nil); err != nil { + if _, _, err := git.NewCommand(t.ctx, "clone", "-s", "--bare", "-b").AddUntrustedArguments(branch, t.repo.RepoPath(), t.basePath).RunStdString(nil); err != nil { stderr := err.Error() if matched, _ := regexp.MatchString(".*Remote branch .* not found in upstream origin.*", stderr); matched { return git.ErrBranchNotExist{ @@ -169,7 +169,7 @@ func (t *TemporaryUploadRepository) HashObject(content io.Reader) (string, error // AddObjectToIndex adds the provided object hash to the index with the provided mode and path func (t *TemporaryUploadRepository) AddObjectToIndex(mode, objectHash, objectPath string) error { - if _, _, err := git.NewCommand(t.ctx, "update-index", "--add", "--replace", "--cacheinfo").AddDynamicArguments(mode, objectHash, objectPath).RunStdString(&git.RunOpts{Dir: t.basePath}); err != nil { + if _, _, err := git.NewCommand(t.ctx, "update-index", "--add", "--replace", "--cacheinfo").AddUntrustedArguments(mode, objectHash, objectPath).RunStdString(&git.RunOpts{Dir: t.basePath}); err != nil { stderr := err.Error() if matched, _ := regexp.MatchString(".*Invalid path '.*", stderr); matched { return models.ErrFilePathInvalid{ @@ -203,7 +203,7 @@ func (t *TemporaryUploadRepository) GetLastCommitByRef(ref string) (string, erro if ref == "" { ref = "HEAD" } - stdout, _, err := git.NewCommand(t.ctx, "rev-parse").AddDynamicArguments(ref).RunStdString(&git.RunOpts{Dir: t.basePath}) + stdout, _, err := git.NewCommand(t.ctx, "rev-parse").AddUntrustedArguments(ref).RunStdString(&git.RunOpts{Dir: t.basePath}) if err != nil { log.Error("Unable to get last ref for %s in temporary repo: %s(%s): Error: %v", ref, t.repo.FullName(), t.basePath, err) return "", fmt.Errorf("Unable to rev-parse %s in temporary repo for: %s Error: %w", ref, t.repo.FullName(), err) diff --git a/services/repository/fork.go b/services/repository/fork.go index ad534be887f1b..d927a23471d1f 100644 --- a/services/repository/fork.go +++ b/services/repository/fork.go @@ -136,7 +136,7 @@ func ForkRepository(ctx context.Context, doer, owner *user_model.User, opts Fork repoPath := repo_model.RepoPath(owner.Name, repo.Name) if stdout, _, err := git.NewCommand(txCtx, - "clone", "--bare").AddDynamicArguments(oldRepoPath, repoPath). + "clone", "--bare").AddUntrustedArguments(oldRepoPath, repoPath). SetDescription(fmt.Sprintf("ForkRepository(git clone): %s to %s", opts.BaseRepo.FullName(), repo.FullName())). RunStdBytes(&git.RunOpts{Timeout: 10 * time.Minute}); err != nil { log.Error("Fork Repository (git clone) Failed for %v (from %v):\nStdout: %s\nError: %v", repo, opts.BaseRepo, stdout, err) diff --git a/tests/integration/api_repo_git_tags_test.go b/tests/integration/api_repo_git_tags_test.go index b29fc45cf5531..52cbe3073ff94 100644 --- a/tests/integration/api_repo_git_tags_test.go +++ b/tests/integration/api_repo_git_tags_test.go @@ -29,8 +29,8 @@ func TestAPIGitTags(t *testing.T) { token := getTokenForLoggedInUser(t, session) // Set up git config for the tagger - _ = git.NewCommand(git.DefaultContext, "config", "user.name").AddDynamicArguments(user.Name).Run(&git.RunOpts{Dir: repo.RepoPath()}) - _ = git.NewCommand(git.DefaultContext, "config", "user.email").AddDynamicArguments(user.Email).Run(&git.RunOpts{Dir: repo.RepoPath()}) + _ = git.NewCommand(git.DefaultContext, "config", "user.name").AddUntrustedArguments(user.Name).Run(&git.RunOpts{Dir: repo.RepoPath()}) + _ = git.NewCommand(git.DefaultContext, "config", "user.email").AddUntrustedArguments(user.Email).Run(&git.RunOpts{Dir: repo.RepoPath()}) gitRepo, _ := git.OpenRepository(git.DefaultContext, repo.RepoPath()) defer gitRepo.Close() diff --git a/tests/integration/git_helper_for_declarative_test.go b/tests/integration/git_helper_for_declarative_test.go index 9e3ff9c4484d3..a384536395c16 100644 --- a/tests/integration/git_helper_for_declarative_test.go +++ b/tests/integration/git_helper_for_declarative_test.go @@ -149,7 +149,7 @@ func doGitInitTestRepository(dstPath string) func(*testing.T) { func doGitAddRemote(dstPath, remoteName string, u *url.URL) func(*testing.T) { return func(t *testing.T) { - _, _, err := git.NewCommand(git.DefaultContext, "remote", "add").AddDynamicArguments(remoteName, u.String()).RunStdString(&git.RunOpts{Dir: dstPath}) + _, _, err := git.NewCommand(git.DefaultContext, "remote", "add").AddUntrustedArguments(remoteName, u.String()).RunStdString(&git.RunOpts{Dir: dstPath}) assert.NoError(t, err) } } @@ -170,7 +170,7 @@ func doGitPushTestRepositoryFail(dstPath string, args ...git.CmdArg) func(*testi func doGitCreateBranch(dstPath, branch string) func(*testing.T) { return func(t *testing.T) { - _, _, err := git.NewCommand(git.DefaultContext, "checkout", "-b").AddDynamicArguments(branch).RunStdString(&git.RunOpts{Dir: dstPath}) + _, _, err := git.NewCommand(git.DefaultContext, "checkout", "-b").AddUntrustedArguments(branch).RunStdString(&git.RunOpts{Dir: dstPath}) assert.NoError(t, err) } } diff --git a/tests/integration/git_test.go b/tests/integration/git_test.go index a11bad21b7b08..01660c87cb65a 100644 --- a/tests/integration/git_test.go +++ b/tests/integration/git_test.go @@ -149,9 +149,9 @@ func lfsCommitAndPushTest(t *testing.T, dstPath string) (littleLFS, bigLFS strin t.Run("LFS", func(t *testing.T) { defer tests.PrintCurrentTest(t)() prefix := "lfs-data-file-" - err := git.NewCommand(git.DefaultContext, "lfs").AddArguments("install").Run(&git.RunOpts{Dir: dstPath}) + err := git.NewCommand(git.DefaultContext, "lfs").AddTrustedArguments("install").Run(&git.RunOpts{Dir: dstPath}) assert.NoError(t, err) - _, _, err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("track").AddDynamicArguments(prefix + "*").RunStdString(&git.RunOpts{Dir: dstPath}) + _, _, err = git.NewCommand(git.DefaultContext, "lfs").AddTrustedArguments("track").AddUntrustedArguments(prefix + "*").RunStdString(&git.RunOpts{Dir: dstPath}) assert.NoError(t, err) err = git.AddChanges(dstPath, false, ".gitattributes") assert.NoError(t, err) @@ -277,13 +277,13 @@ func lockTest(t *testing.T, repoPath string) { } func lockFileTest(t *testing.T, filename, repoPath string) { - _, _, err := git.NewCommand(git.DefaultContext, "lfs").AddArguments("locks").RunStdString(&git.RunOpts{Dir: repoPath}) + _, _, err := git.NewCommand(git.DefaultContext, "lfs").AddTrustedArguments("locks").RunStdString(&git.RunOpts{Dir: repoPath}) assert.NoError(t, err) - _, _, err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("lock").AddDynamicArguments(filename).RunStdString(&git.RunOpts{Dir: repoPath}) + _, _, err = git.NewCommand(git.DefaultContext, "lfs").AddTrustedArguments("lock").AddUntrustedArguments(filename).RunStdString(&git.RunOpts{Dir: repoPath}) assert.NoError(t, err) - _, _, err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("locks").RunStdString(&git.RunOpts{Dir: repoPath}) + _, _, err = git.NewCommand(git.DefaultContext, "lfs").AddTrustedArguments("locks").RunStdString(&git.RunOpts{Dir: repoPath}) assert.NoError(t, err) - _, _, err = git.NewCommand(git.DefaultContext, "lfs").AddArguments("unlock").AddDynamicArguments(filename).RunStdString(&git.RunOpts{Dir: repoPath}) + _, _, err = git.NewCommand(git.DefaultContext, "lfs").AddTrustedArguments("unlock").AddUntrustedArguments(filename).RunStdString(&git.RunOpts{Dir: repoPath}) assert.NoError(t, err) } @@ -736,7 +736,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB }) t.Run("Push", func(t *testing.T) { - err := git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master", "-o").AddDynamicArguments("topic=" + headBranch).Run(&git.RunOpts{Dir: dstPath}) + err := git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master", "-o").AddUntrustedArguments("topic=" + headBranch).Run(&git.RunOpts{Dir: dstPath}) if !assert.NoError(t, err) { return } @@ -757,7 +757,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB assert.Contains(t, "Testing commit 1", prMsg.Body) assert.Equal(t, commit, prMsg.Head.Sha) - _, _, err = git.NewCommand(git.DefaultContext, "push", "origin").AddDynamicArguments("HEAD:refs/for/master/test/" + headBranch).RunStdString(&git.RunOpts{Dir: dstPath}) + _, _, err = git.NewCommand(git.DefaultContext, "push", "origin").AddUntrustedArguments("HEAD:refs/for/master/test/" + headBranch).RunStdString(&git.RunOpts{Dir: dstPath}) if !assert.NoError(t, err) { return } @@ -810,7 +810,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB }) t.Run("Push2", func(t *testing.T) { - err := git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master", "-o").AddDynamicArguments("topic=" + headBranch).Run(&git.RunOpts{Dir: dstPath}) + err := git.NewCommand(git.DefaultContext, "push", "origin", "HEAD:refs/for/master", "-o").AddUntrustedArguments("topic=" + headBranch).Run(&git.RunOpts{Dir: dstPath}) if !assert.NoError(t, err) { return } @@ -822,7 +822,7 @@ func doCreateAgitFlowPull(dstPath string, ctx *APITestContext, baseBranch, headB assert.Equal(t, false, prMsg.HasMerged) assert.Equal(t, commit, prMsg.Head.Sha) - _, _, err = git.NewCommand(git.DefaultContext, "push", "origin").AddDynamicArguments("HEAD:refs/for/master/test/" + headBranch).RunStdString(&git.RunOpts{Dir: dstPath}) + _, _, err = git.NewCommand(git.DefaultContext, "push", "origin").AddUntrustedArguments("HEAD:refs/for/master/test/" + headBranch).RunStdString(&git.RunOpts{Dir: dstPath}) if !assert.NoError(t, err) { return } diff --git a/tests/integration/pull_merge_test.go b/tests/integration/pull_merge_test.go index 491fc0e0aafec..634d55a4277dc 100644 --- a/tests/integration/pull_merge_test.go +++ b/tests/integration/pull_merge_test.go @@ -310,7 +310,7 @@ func TestCantMergeUnrelated(t *testing.T) { _, _ = messageBytes.WriteString("\n") stdout.Reset() - err = git.NewCommand(git.DefaultContext, "commit-tree").AddDynamicArguments(treeSha). + err = git.NewCommand(git.DefaultContext, "commit-tree").AddUntrustedArguments(treeSha). Run(&git.RunOpts{ Env: env, Dir: path, @@ -320,7 +320,7 @@ func TestCantMergeUnrelated(t *testing.T) { assert.NoError(t, err) commitSha := strings.TrimSpace(stdout.String()) - _, _, err = git.NewCommand(git.DefaultContext, "branch", "unrelated").AddDynamicArguments(commitSha).RunStdString(&git.RunOpts{Dir: path}) + _, _, err = git.NewCommand(git.DefaultContext, "branch", "unrelated").AddUntrustedArguments(commitSha).RunStdString(&git.RunOpts{Dir: path}) assert.NoError(t, err) testEditFileToNewBranch(t, session, "user1", "repo1", "master", "conflict", "README.md", "Hello, World (Edited Once)\n")