Skip to content

Commit 30515f2

Browse files
author
Gusted
authored
Make ParsePatch more robust (#17573)
1 parent 69b61d4 commit 30515f2

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

services/gitdiff/gitdiff.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -839,7 +839,12 @@ parsingLoop:
839839
case strings.HasPrefix(line, "--- "):
840840
// Handle ambiguous filenames
841841
if curFile.IsAmbiguous {
842-
if len(line) > 6 && line[4] == 'a' {
842+
// The shortest string that can end up here is:
843+
// "--- a\t\n" without the qoutes.
844+
// This line has a len() of 7 but doesn't contain a oldName.
845+
// So the amount that the line need is at least 8 or more.
846+
// The code will otherwise panic for a out-of-bounds.
847+
if len(line) > 7 && line[4] == 'a' {
843848
curFile.OldName = line[6 : len(line)-1]
844849
if line[len(line)-2] == '\t' {
845850
curFile.OldName = curFile.OldName[:len(curFile.OldName)-1]
@@ -1194,6 +1199,11 @@ func readFileName(rd *strings.Reader) (string, bool) {
11941199
_ = rd.UnreadByte()
11951200
if char == '"' {
11961201
fmt.Fscanf(rd, "%q ", &name)
1202+
if len(name) == 0 {
1203+
log.Error("Reader has no file name: %v", rd)
1204+
return "", true
1205+
}
1206+
11971207
if name[0] == '\\' {
11981208
name = name[1:]
11991209
}

services/gitdiff/gitdiff_test.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -541,3 +541,22 @@ func TestDiffToHTML_14231(t *testing.T) {
541541

542542
assertEqual(t, expected, output)
543543
}
544+
545+
func TestNoCrashes(t *testing.T) {
546+
type testcase struct {
547+
gitdiff string
548+
}
549+
550+
tests := []testcase{
551+
{
552+
gitdiff: "diff --git \n--- a\t\n",
553+
},
554+
{
555+
gitdiff: "diff --git \"0\n",
556+
},
557+
}
558+
for _, testcase := range tests {
559+
// It shouldn't crash, so don't care about the output.
560+
ParsePatch(setting.Git.MaxGitDiffLines, setting.Git.MaxGitDiffLineCharacters, setting.Git.MaxGitDiffFiles, strings.NewReader(testcase.gitdiff))
561+
}
562+
}

0 commit comments

Comments
 (0)