Skip to content

Commit

Permalink
parse: fix a panic when printing a level without initalizing a level …
Browse files Browse the repository at this point in the history
…formatter
  • Loading branch information
jrockway committed Jan 2, 2022
1 parent 84aa3aa commit 77c8785
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pkg/parse/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -445,7 +445,7 @@ func (s *InputSchema) ReadLine(l *line) error {
} else {
pushError(fmt.Errorf("no message key %q in incoming log", s.MessageKey))
}
if lvl, ok := l.fields[s.LevelKey]; ok {
if lvl, ok := l.fields[s.LevelKey]; s.LevelFormat != nil && ok {
if parsed, err := s.LevelFormat(lvl); err != nil {
pushError(fmt.Errorf("level key %q: %w", s.LevelKey, err))
} else {
Expand Down
50 changes: 50 additions & 0 deletions pkg/parse/parse_fuzz_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
//go:build go1.18
// +build go1.18

package parse

import (
"bytes"
"testing"

"github.com/logrusorgru/aurora/v3"
)

func FuzzReadLog(f *testing.F) {
f.Add([]byte(`{}`))
f.Add([]byte(`{"ts": 1234, "level": "info", "msg": "hello"}\n`))
f.Add([]byte(`{"ts": 1234, "level": "info", "msg": "hello"}\n` +
`{"ts": 1235, "level": "warn", "msg": "line 2"}`))
f.Add([]byte(`{"ts": 1234, "level": "info", "msg": "hello"}\n{}\n`))
jq, err := CompileJQ(".")
if err != nil {
f.Fatalf("jq: %v", err)
}

f.Fuzz(func(t *testing.T, in []byte) {
inbuf := bytes.NewReader(in)
ins := &InputSchema{
Strict: false,
}
errbuf := new(bytes.Buffer)
outs := &OutputSchema{
Formatter: &DefaultOutputFormatter{
Aurora: aurora.NewAurora(true),
},
EmitErrorFn: func(msg string) {
errbuf.WriteString(msg)
errbuf.WriteString("\n")
},
}
outbuf := new(bytes.Buffer)
if _, err := ReadLog(inbuf, outbuf, ins, outs, jq); err != nil {
t.Fatal(err)
}
if got, want := bytes.Count(outbuf.Bytes(), []byte("\n")), bytes.Count(in, []byte("\n")); got < want {
t.Errorf("output: line count:\n got: %v\n want: >=%v", got, want)
}
if errbuf.Len() > 0 {
t.Logf("errors: %v", errbuf.String())
}
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
go test fuzz v1
[]byte("{\"\":0}")

0 comments on commit 77c8785

Please sign in to comment.