Refactor git command package to improve security and maintainability (#22678)
This PR follows #21535 (and replace #22592) ## Review without space diff https://github.com/go-gitea/gitea/pull/22678/files?diff=split&w=1 ## Purpose of this PR 1. Make git module command completely safe (risky user inputs won't be passed as argument option anymore) 2. Avoid low-level mistakes like https://github.com/go-gitea/gitea/pull/22098#discussion_r1045234918 3. Remove deprecated and dirty `CmdArgCheck` function, hide the `CmdArg` type 4. Simplify code when using git command ## The main idea of this PR * Move the `git.CmdArg` to the `internal` package, then no other package except `git` could use it. Then developers could never do `AddArguments(git.CmdArg(userInput))` any more. * Introduce `git.ToTrustedCmdArgs`, it's for user-provided and already trusted arguments. It's only used in a few cases, for example: use git arguments from config file, help unit test with some arguments. * Introduce `AddOptionValues` and `AddOptionFormat`, they make code more clear and simple: * Before: `AddArguments("-m").AddDynamicArguments(message)` * After: `AddOptionValues("-m", message)` * - * Before: `AddArguments(git.CmdArg(fmt.Sprintf("--author='%s <%s>'", sig.Name, sig.Email)))` * After: `AddOptionFormat("--author='%s <%s>'", sig.Name, sig.Email)` ## FAQ ### Why these changes were not done in #21535 ? #21535 is mainly a search&replace, it did its best to not change too much logic. Making the framework better needs a lot of changes, so this separate PR is needed as the second step. ### The naming of `AddOptionXxx` According to git's manual, the `--xxx` part is called `option`. ### How can it guarantee that `internal.CmdArg` won't be not misused? Go's specification guarantees that. Trying to access other package's internal package causes compilation error. And, `golangci-lint` also denies the git/internal package. Only the `git/command.go` can use it carefully. ### There is still a `ToTrustedCmdArgs`, will it still allow developers to make mistakes and pass untrusted arguments? Generally speaking, no. Because when using `ToTrustedCmdArgs`, the code will be very complex (see the changes for examples). Then developers and reviewers can know that something might be unreasonable. ### Why there was a `CmdArgCheck` and why it's removed? At the moment of #21535, to reduce unnecessary changes, `CmdArgCheck` was introduced as a hacky patch. Now, almost all code could be written as `cmd := NewCommand(); cmd.AddXxx(...)`, then there is no need for `CmdArgCheck` anymore. ### Why many codes for `signArg == ""` is deleted? Because in the old code, `signArg` could never be empty string, it's either `-S[key-id]` or `--no-gpg-sign`. So the `signArg == ""` is just dead code. --------- Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
This commit is contained in:
parent
3c5655ce18
commit
6bc3079c00
42 changed files with 382 additions and 385 deletions
|
@ -89,7 +89,7 @@ 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).
|
||||
AddOptionFormat("--skip=%d", (page-1)*pageSize).AddOptionFormat("--max-count=%d", pageSize).AddArguments(prettyLogFormat).
|
||||
AddDynamicArguments(id.String()).
|
||||
RunStdBytes(&RunOpts{Dir: repo.Path})
|
||||
if err != nil {
|
||||
|
@ -99,32 +99,36 @@ 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
|
||||
// add common arguments to git command
|
||||
addCommonSearchArgs := func(c *Command) {
|
||||
// ignore case
|
||||
c.AddArguments("-i")
|
||||
|
||||
// add authors if present in search query
|
||||
if len(opts.Authors) > 0 {
|
||||
for _, v := range opts.Authors {
|
||||
c.AddOptionFormat("--author=%s", v)
|
||||
}
|
||||
}
|
||||
|
||||
// add committers if present in search query
|
||||
if len(opts.Committers) > 0 {
|
||||
for _, v := range opts.Committers {
|
||||
c.AddOptionFormat("--committer=%s", v)
|
||||
}
|
||||
}
|
||||
|
||||
// add time constraints if present in search query
|
||||
if len(opts.After) > 0 {
|
||||
c.AddOptionFormat("--after=%s", opts.After)
|
||||
}
|
||||
if len(opts.Before) > 0 {
|
||||
c.AddOptionFormat("--before=%s", opts.Before)
|
||||
}
|
||||
}
|
||||
|
||||
// create new git log command with limit of 100 commits
|
||||
cmd := NewCommand(repo.Ctx, "log", "-100", prettyLogFormat).AddDynamicArguments(id.String())
|
||||
// ignore case
|
||||
args := []CmdArg{"-i"}
|
||||
|
||||
// add authors if present in search query
|
||||
if len(opts.Authors) > 0 {
|
||||
for _, v := range opts.Authors {
|
||||
args = append(args, CmdArg("--author="+v))
|
||||
}
|
||||
}
|
||||
|
||||
// add committers if present in search query
|
||||
if len(opts.Committers) > 0 {
|
||||
for _, v := range opts.Committers {
|
||||
args = append(args, CmdArg("--committer="+v))
|
||||
}
|
||||
}
|
||||
|
||||
// add time constraints if present in search query
|
||||
if len(opts.After) > 0 {
|
||||
args = append(args, CmdArg("--after="+opts.After))
|
||||
}
|
||||
if len(opts.Before) > 0 {
|
||||
args = append(args, CmdArg("--before="+opts.Before))
|
||||
}
|
||||
|
||||
// pretend that all refs along with HEAD were listed on command line as <commis>
|
||||
// https://git-scm.com/docs/git-log#Documentation/git-log.txt---all
|
||||
|
@ -137,12 +141,12 @@ func (repo *Repository) searchCommits(id SHA1, opts SearchCommitsOptions) ([]*Co
|
|||
// 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.AddOptionFormat("--grep=%s", v)
|
||||
}
|
||||
}
|
||||
|
||||
// search for commits matching given constraints and keywords in commit msg
|
||||
cmd.AddArguments(args...)
|
||||
addCommonSearchArgs(cmd)
|
||||
stdout, _, err := cmd.RunStdBytes(&RunOpts{Dir: repo.Path})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -160,7 +164,7 @@ 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...)
|
||||
addCommonSearchArgs(hashCmd)
|
||||
// add keyword as <commit>
|
||||
hashCmd.AddDynamicArguments(v)
|
||||
|
||||
|
@ -213,8 +217,8 @@ 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)))
|
||||
AddOptionFormat("--max-count=%d", setting.Git.CommitsRangeSize*page).
|
||||
AddOptionFormat("--skip=%d", skip)
|
||||
gitCmd.AddDynamicArguments(revision)
|
||||
gitCmd.AddDashesAndList(file)
|
||||
err := gitCmd.Run(&RunOpts{
|
||||
|
@ -295,21 +299,21 @@ func (repo *Repository) CommitsBetweenLimit(last, before *Commit, limit, skip in
|
|||
var stdout []byte
|
||||
var err error
|
||||
if before == nil {
|
||||
stdout, _, err = NewCommand(repo.Ctx, "rev-list",
|
||||
"--max-count", CmdArg(strconv.Itoa(limit)),
|
||||
"--skip", CmdArg(strconv.Itoa(skip))).
|
||||
stdout, _, err = NewCommand(repo.Ctx, "rev-list").
|
||||
AddOptionValues("--max-count", strconv.Itoa(limit)).
|
||||
AddOptionValues("--skip", strconv.Itoa(skip)).
|
||||
AddDynamicArguments(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))).
|
||||
stdout, _, err = NewCommand(repo.Ctx, "rev-list").
|
||||
AddOptionValues("--max-count", strconv.Itoa(limit)).
|
||||
AddOptionValues("--skip", strconv.Itoa(skip)).
|
||||
AddDynamicArguments(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))).
|
||||
stdout, _, err = NewCommand(repo.Ctx, "rev-list").
|
||||
AddOptionValues("--max-count", strconv.Itoa(limit)).
|
||||
AddOptionValues("--skip", strconv.Itoa(skip)).
|
||||
AddDynamicArguments(before.ID.String(), last.ID.String()).RunStdBytes(&RunOpts{Dir: repo.Path})
|
||||
}
|
||||
}
|
||||
|
@ -349,12 +353,11 @@ func (repo *Repository) CommitsCountBetween(start, end string) (int64, error) {
|
|||
|
||||
// commitsBefore the limit is depth, not total number of returned commits.
|
||||
func (repo *Repository) commitsBefore(id SHA1, limit int) ([]*Commit, error) {
|
||||
cmd := NewCommand(repo.Ctx, "log")
|
||||
cmd := NewCommand(repo.Ctx, "log", prettyLogFormat)
|
||||
if limit > 0 {
|
||||
cmd.AddArguments(CmdArg("-"+strconv.Itoa(limit)), prettyLogFormat).AddDynamicArguments(id.String())
|
||||
} else {
|
||||
cmd.AddArguments(prettyLogFormat).AddDynamicArguments(id.String())
|
||||
cmd.AddOptionFormat("-%d", limit)
|
||||
}
|
||||
cmd.AddDynamicArguments(id.String())
|
||||
|
||||
stdout, _, runErr := cmd.RunStdBytes(&RunOpts{Dir: repo.Path})
|
||||
if runErr != nil {
|
||||
|
@ -393,10 +396,9 @@ func (repo *Repository) getCommitsBeforeLimit(id SHA1, num int) ([]*Commit, erro
|
|||
|
||||
func (repo *Repository) getBranches(commit *Commit, limit int) ([]string, error) {
|
||||
if CheckGitVersionAtLeast("2.7.0") == nil {
|
||||
stdout, _, err := NewCommand(repo.Ctx, "for-each-ref",
|
||||
CmdArg("--count="+strconv.Itoa(limit)),
|
||||
"--format=%(refname:strip=2)", "--contains").
|
||||
AddDynamicArguments(commit.ID.String(), BranchPrefix).
|
||||
stdout, _, err := NewCommand(repo.Ctx, "for-each-ref", "--format=%(refname:strip=2)").
|
||||
AddOptionFormat("--count=%d", limit).
|
||||
AddOptionValues("--contains", commit.ID.String(), BranchPrefix).
|
||||
RunStdString(&RunOpts{Dir: repo.Path})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
@ -406,7 +408,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").AddOptionValues("--contains", commit.ID.String()).RunStdString(&RunOpts{Dir: repo.Path})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue